Java Code Examples for org.wso2.balana.attr.BagAttribute

The following examples show how to use org.wso2.balana.attr.BagAttribute. These examples are extracted from open source projects. 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
@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 2
Source Project: balana   Source File: SampleAttributeFinderModule.java    License: 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 3
Source Project: balana   Source File: SampleAttributeFinderModule.java    License: 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 4
Source Project: balana   Source File: SampleAttributeFinderModule.java    License: 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 5
Source Project: balana   Source File: SampleAttributeFinderModule.java    License: 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 6
Source Project: balana   Source File: ConditionBagFunction.java    License: 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 inputs, EvaluationCtx context) {

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

    // *-is-in takes a bag and an element of baseType and
    // returns a single boolean value
    AttributeValue item = (AttributeValue) (argValues[0]);
    BagAttribute bag = (BagAttribute) (argValues[1]);

    return new EvaluationResult(BooleanAttribute.getInstance(bag.contains(item)));
}
 
Example 7
Source Project: balana   Source File: HigherOrderFunction.java    License: 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 8
Source Project: balana   Source File: CurrentEnvModule.java    License: 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 9
/**
 * This method is introduced in order to check whether the user is local or federated. If it is a
 * federated user, obtaining user attributes from userstore will be prevented.
 *
 * @param attributeType The type of the required attribute.
 * @param attributeId   The unique id of the required attribute.
 * @param category      The category of the required attribute.
 * @param issuer        The attribute issuer.
 * @param evaluationCtx The evaluation context object.
 * @return return the set of values for the required attribute.
 * @throws Exception throws if fails.
 */
@Override
public Set<String> getAttributeValues(URI attributeType, URI attributeId, URI category,
                                      String issuer, EvaluationCtx evaluationCtx) throws Exception {

    Set<String> values = null;
    EvaluationResult userType = evaluationCtx.getAttribute(new URI(StringAttribute.identifier), new URI(
            PDPConstants.USER_TYPE_ID), issuer, new URI(PDPConstants.USER_CATEGORY));
    String userTypeId = null;
    if (userType != null && userType.getAttributeValue() != null && userType.getAttributeValue().isBag()) {
        BagAttribute bagAttribute = (BagAttribute) userType.getAttributeValue();
        if (bagAttribute.size() > 0) {
            userTypeId = ((AttributeValue) bagAttribute.iterator().next()).encode();
            if (log.isDebugEnabled()) {
                log.debug(String.format("The user type of the user is %s", userTypeId));
            }
        }
    }

    if (!StringUtils.equalsIgnoreCase(userTypeId, FEDERATED_USER_DOMAIN)) {
        // If the user is not a federated user, user attributes should be be populated from local userstore.
        values = super.getAttributeValues(attributeType, attributeId, category, issuer, evaluationCtx);
    } else if (mapFederatedUsersToLocal) {
        // If the user is federated and the MapFederatedToLocal config is enabled, then populate user attributes
        // from userstore.
        values = super.getAttributeValues(attributeType, attributeId, category, issuer, evaluationCtx);
    }
    return values;
}
 
Example 10
Source Project: balana   Source File: XACML3HigherOrderFunction.java    License: 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 11
Source Project: balana   Source File: HigherOrderFunction.java    License: Apache License 2.0 5 votes vote down vote up
/**
 * Private helper for any & all functions
 */
private EvaluationResult anyAndAllHelper(AttributeValue value, BagAttribute bag,
		Function function, EvaluationCtx context, boolean allFunction,
		boolean argumentsAreSwapped) {
	BooleanAttribute attr = BooleanAttribute.getInstance(allFunction);
	Iterator it = bag.iterator();

	while (it.hasNext()) {
		List<Evaluatable> params = new ArrayList<Evaluatable>();

		if (!argumentsAreSwapped) {
			params.add(value);
			params.add((AttributeValue) (it.next()));
		} else {
			params.add((AttributeValue) (it.next()));
			params.add(value);
		}

		EvaluationResult result = function.evaluate(params, context);

		if (result.indeterminate())
			return result;

		BooleanAttribute bool = (BooleanAttribute) (result.getAttributeValue());
		if (bool.getValue() != allFunction) {
			attr = bool;
			break;
		}
	}

	return new EvaluationResult(attr);
}
 
Example 12
Source Project: balana   Source File: AttributeSelector.java    License: Apache License 2.0 5 votes vote down vote up
/**
 * Invokes the <code>AttributeFinder</code> used by the given <code>EvaluationCtx</code> to try
 * to resolve an attribute value. If the selector is defined with MustBePresent as true, then
 * failure to find a matching value will result in Indeterminate, otherwise it will result in an
 * empty bag. To support the basic selector functionality defined in the XACML specification,
 * use a finder that has only the <code>SelectorModule</code> as a module that supports selector
 * finding.
 *
 * @param context representation of the request to search
 *
 * @return a result containing a bag either empty because no values were found or containing at
 *         least one value, or status associated with an Indeterminate result
 */

public EvaluationResult evaluate(EvaluationCtx context) {
    // query the context
    EvaluationResult result = context.getAttribute(path, type, category,
                                                            contextSelectorId, xpathVersion);

    // see if we got anything
    if (!result.indeterminate()) {
        BagAttribute bag = (BagAttribute) (result.getAttributeValue());

        // see if it's an empty bag
        if (bag.isEmpty()) {
            // see if this is an error or not
            if (mustBePresent) {
                // this is an error
                if (logger.isDebugEnabled()) {
                    logger.debug("AttributeSelector failed to resolve a "
                            + "value for a required attribute: " + path);
                }

                ArrayList<String> code = new ArrayList<String>();
                code.add(Status.STATUS_MISSING_ATTRIBUTE);

                String message = "couldn't resolve XPath expression " + path
                        + " for type " + type.toString();
                return new EvaluationResult(new Status(code, message));
            } else {
                // return the empty bag
                return result;
            }
        } else {
            // return the values
            return result;
        }
    } else {
        // return the error
        return result;
    }
}
 
Example 13
Source Project: balana   Source File: CurrentEnvModule.java    License: Apache License 2.0 5 votes vote down vote up
/**
 * Handles requests for the current Time.
 */
private EvaluationResult handleTime(URI type, String issuer, EvaluationCtx context) {
    // make sure they're asking for a time attribute
    if (!type.toString().equals(TimeAttribute.identifier))
        return new EvaluationResult(BagAttribute.createEmptyBag(type));

    // get the value from the context
    return makeBag(context.getCurrentTime());
}
 
Example 14
Source Project: balana   Source File: CurrentEnvModule.java    License: Apache License 2.0 5 votes vote down vote up
/**
 * Handles requests for the current Date.
 */
private EvaluationResult handleDate(URI type, String issuer, EvaluationCtx context) {
    // make sure they're asking for a date attribute
    if (!type.toString().equals(DateAttribute.identifier))
        return new EvaluationResult(BagAttribute.createEmptyBag(type));

    // get the value from the context
    return makeBag(context.getCurrentDate());
}
 
Example 15
Source Project: balana   Source File: CurrentEnvModule.java    License: Apache License 2.0 5 votes vote down vote up
/**
 * Handles requests for the current DateTime.
 */
private EvaluationResult handleDateTime(URI type, String issuer, EvaluationCtx context) {
    // make sure they're asking for a dateTime attribute
    if (!type.toString().equals(DateTimeAttribute.identifier))
        return new EvaluationResult(BagAttribute.createEmptyBag(type));

    // get the value from the context
    return makeBag(context.getCurrentDateTime());
}
 
Example 16
Source Project: balana   Source File: CurrentEnvModule.java    License: Apache License 2.0 5 votes vote down vote up
/**
 * Private helper that makes a bag containing only the given attribute.
 */
private EvaluationResult makeBag(AttributeValue attribute) {
    List<AttributeValue> set = new ArrayList<AttributeValue>();
    set.add(attribute);

    BagAttribute bag = new BagAttribute(attribute.getType(), set);

    return new EvaluationResult(bag);
}
 
Example 17
Source Project: balana   Source File: BasicEvaluationCtx.java    License: Apache License 2.0 5 votes vote down vote up
/**
 * Returns the attribute value(s) retrieved using the given XPath expression.
 *
 * @param path the XPath expression to search
 * @param type the type of the attribute value(s) to find
 * @param category the category the attribute value(s) must be in
 * @param contextSelector the selector to find the context to apply XPath expression
 *                       if this is null, applied for default content
 * @param xpathVersion the version of XPath to use
 *
 * @return a result containing a bag either empty because no values were found or containing at
 *         least one value, or status associated with an Indeterminate result
 */

public EvaluationResult getAttribute(String path, URI type, URI category,
                                     URI contextSelector, String xpathVersion){

    if (pdpConfig.getAttributeFinder() != null) {
        return pdpConfig.getAttributeFinder().findAttribute(path, type, this,
                                    xpathVersion);
    } else {
        logger.warn("Context tried to invoke AttributeFinder but was " +
                       "not configured with one");

        return new EvaluationResult(BagAttribute.createEmptyBag(type));
    }
}
 
Example 18
Source Project: balana   Source File: BasicEvaluationCtx.java    License: Apache License 2.0 5 votes vote down vote up
/**
 * Private helper that calls the finder if it's non-null, or else returns an empty bag
 *
 * @param type the type of the attribute value(s) to find
 * @param id the id of the attribute value(s) to find
 * @param issuer the issuer of the attribute value(s) to find or null
 * @param category the category the attribute value(s) must be in
 *
 * @return a result containing a bag either empty because no values were found or containing at
 *         least one value, or status associated with an Indeterminate result
 */
protected EvaluationResult callHelper(URI type, URI id, String issuer, URI category) {
    if (pdpConfig.getAttributeFinder() != null) {
        return pdpConfig.getAttributeFinder().findAttribute(type, id, issuer, category, this);
    } else {
        if (logger.isWarnEnabled()) {
            logger.warn("Context tried to invoke AttributeFinder but was "
                    + "not configured with one");
        }

        return new EvaluationResult(BagAttribute.createEmptyBag(type));
    }
}
 
Example 19
@Override
public Set<String> findDescendantResources(String parentResourceId, EvaluationCtx context)
        throws Exception {

    EvaluationResult environment;
    String environmentId = null;
    Set<String> resourceNames = null;

    NodeList children = context.getRequestRoot().getChildNodes();
    for (int i = 0; i < children.getLength(); i++) {
        Node child = children.item(i);
        if (child != null) {
            if (PDPConstants.ENVIRONMENT_ELEMENT.equals(child.getLocalName())) {
                if (child.getChildNodes() != null && child.getChildNodes().getLength() > 0) {
                    environment = context.getAttribute(new URI(StringAttribute.identifier),
                            new URI(PDPConstants.ENVIRONMENT_ID_DEFAULT), null,
                            new URI(XACMLConstants.ENT_CATEGORY));
                    if (environment != null && environment.getAttributeValue() != null &&
                            environment.getAttributeValue().isBag()) {
                        BagAttribute attr = (BagAttribute) environment.getAttributeValue();
                        environmentId = ((AttributeValue) attr.iterator().next()).encode();
                    }
                }
            }
        }
    }

    if (isAbstractResourceCacheEnabled) {
        IdentityCacheKey cacheKey;
        String key = PDPConstants.RESOURCE_DESCENDANTS + parentResourceId +
                (environmentId != null ? environmentId : "");
        tenantId = CarbonContext.getThreadLocalCarbonContext().getTenantId();
        cacheKey = new IdentityCacheKey(tenantId, key);
        IdentityCacheEntry cacheEntry = (IdentityCacheEntry) abstractResourceCache.getValueFromCache(cacheKey);
        if (cacheEntry != null) {
            String[] values = cacheEntry.getCacheEntryArray();
            resourceNames = new HashSet<String>(Arrays.asList(values));
            if (log.isDebugEnabled()) {
                log.debug("Carbon Resource Cache Hit");
            }
        }

        if (resourceNames != null) {
            resourceNames = findDescendantResources(parentResourceId, environmentId);
            if (log.isDebugEnabled()) {
                log.debug("Carbon Resource Cache Miss");
            }
            if (resourceNames != null && !resourceNames.isEmpty()) {
                cacheEntry = new IdentityCacheEntry(resourceNames.toArray(new String[resourceNames.size()]));
                abstractResourceCache.addToCache(cacheKey, cacheEntry);
            }
        }
    } else {
        resourceNames = findDescendantResources(parentResourceId, environmentId);
    }

    return resourceNames;
}
 
Example 20
Source Project: carbon-identity   Source File: AbstractPIPResourceFinder.java    License: Apache License 2.0 4 votes vote down vote up
@Override
public Set<String> findDescendantResources(String parentResourceId, EvaluationCtx context)
        throws Exception {

    EvaluationResult environment;
    String environmentId = null;
    Set<String> resourceNames = null;

    NodeList children = context.getRequestRoot().getChildNodes();
    for (int i = 0; i < children.getLength(); i++) {
        Node child = children.item(i);
        if (child != null) {
            if (PDPConstants.ENVIRONMENT_ELEMENT.equals(child.getLocalName())) {
                if (child.getChildNodes() != null && child.getChildNodes().getLength() > 0) {
                    environment = context.getAttribute(new URI(StringAttribute.identifier),
                            new URI(PDPConstants.ENVIRONMENT_ID_DEFAULT), null,
                            new URI(XACMLConstants.ENT_CATEGORY));
                    if (environment != null && environment.getAttributeValue() != null &&
                            environment.getAttributeValue().isBag()) {
                        BagAttribute attr = (BagAttribute) environment.getAttributeValue();
                        environmentId = ((AttributeValue) attr.iterator().next()).encode();
                    }
                }
            }
        }
    }

    if (isAbstractResourceCacheEnabled) {
        IdentityCacheKey cacheKey;
        String key = PDPConstants.RESOURCE_DESCENDANTS + parentResourceId +
                (environmentId != null ? environmentId : "");
        tenantId = CarbonContext.getThreadLocalCarbonContext().getTenantId();
        cacheKey = new IdentityCacheKey(tenantId, key);
        IdentityCacheEntry cacheEntry = (IdentityCacheEntry) abstractResourceCache.getValueFromCache(cacheKey);
        if (cacheEntry != null) {
            String[] values = cacheEntry.getCacheEntryArray();
            resourceNames = new HashSet<String>(Arrays.asList(values));
            if (log.isDebugEnabled()) {
                log.debug("Carbon Resource Cache Hit");
            }
        }

        if (resourceNames != null) {
            resourceNames = findDescendantResources(parentResourceId, environmentId);
            if (log.isDebugEnabled()) {
                log.debug("Carbon Resource Cache Miss");
            }
            if (resourceNames != null && !resourceNames.isEmpty()) {
                cacheEntry = new IdentityCacheEntry(resourceNames.toArray(new String[resourceNames.size()]));
                abstractResourceCache.addToCache(cacheKey, cacheEntry);
            }
        }
    } else {
        resourceNames = findDescendantResources(parentResourceId, environmentId);
    }

    return resourceNames;
}
 
Example 21
Source Project: balana   Source File: XACML3HigherOrderFunction.java    License: Apache License 2.0 4 votes vote down vote up
@Override
public EvaluationResult evaluate(List inputs, EvaluationCtx context) {

    Iterator iterator = inputs.iterator();

    // Get the first arg, which is the function.
    Expression xpr = (Expression) (iterator.next());
    Function function = null;

    if (xpr instanceof Function) {
        function = (Function) xpr;
    }

    // Separate the remaining inputs into primitive data types or bags of primitive types.
    List<AttributeValue> args = new ArrayList<>();
    List<BagAttribute> bagArgs = new ArrayList<>();

    while (iterator.hasNext()) {
        Evaluatable eval = (Evaluatable) (iterator.next());
        EvaluationResult result = eval.evaluate(context);
        if (result.indeterminate()) {
            return result;
        }
        if (result.getAttributeValue().returnsBag()) {
            bagArgs.add((BagAttribute) (result.getAttributeValue()));
        } else {
            args.add(result.getAttributeValue());
        }
    }

    switch (functionId) {
        case ID_ANY_OF:
            return anyAndAllHelper(context, function, args, bagArgs.get(0), false);

        case ID_ALL_OF:
            return anyAndAllHelper(context, function, args, bagArgs.get(0), true);

        case ID_ANY_OF_ANY:
            return anyOfAny(context, function, args, bagArgs);
    }
    return null;
}
 
Example 22
Source Project: balana   Source File: XACML3HigherOrderFunction.java    License: Apache License 2.0 4 votes vote down vote up
private EvaluationResult anyOfAny(EvaluationCtx context, Function function, List<AttributeValue> args,
                                  List<BagAttribute> bagArgs) {

    // The expression SHALL be evaluated as if the function named in the <Function> argument was applied
    // between every tuple of the cross product on all bags and the primitive values, and the results were
    // combined using “urn:oasis:names:tc:xacml:1.0:function:or”

    EvaluationResult result = new EvaluationResult(BooleanAttribute.getInstance(false));
    if (!args.isEmpty()) {
        for (int i = 0; i < args.size() - 1; i++) {
            AttributeValue value = args.get(i);
            List<AttributeValue> bagValue = new ArrayList<>();
            bagValue.add(value);
            BagAttribute bagArg = new BagAttribute(value.getType(), bagValue);
            result = anyAndAllHelper(context, function, args.subList(i + 1, args.size()), bagArg, false);
            if (result.indeterminate() || ((BooleanAttribute) (result.getAttributeValue())).getValue()) {
                return result;
            }
        }
        return new EvaluationResult(BooleanAttribute.getInstance(false));
    }
    if (!bagArgs.isEmpty()) {
        for (int i = 0; i < bagArgs.size(); i++) {
            for (int j = i + 1; j < bagArgs.size(); j++) {
                Iterator iIterator = bagArgs.get(i).iterator();
                while (iIterator.hasNext()) {
                    AttributeValue iValue = (AttributeValue) (iIterator.next());
                    Iterator jIterator = bagArgs.get(j).iterator();
                    while (jIterator.hasNext()) {
                        AttributeValue jValue = (AttributeValue) (jIterator.next());
                        result = getEvaluationResult(context, function, jValue, iValue, false);
                        if (result != null && (result.indeterminate() ||
                                ((BooleanAttribute) (result.getAttributeValue())).getValue())) {
                            return result;
                        }
                    }
                }
            }
        }
        return new EvaluationResult(BooleanAttribute.getInstance(false));
    }
    return null;
}
 
Example 23
Source Project: balana   Source File: HigherOrderFunction.java    License: Apache License 2.0 4 votes vote down vote up
/**
 * Private helper function that performs the any function, but lets you swap the argument order
 * (so it can be used by any-of-all)
 */
private EvaluationResult any(AttributeValue value, BagAttribute bag, Function function,
		EvaluationCtx context, boolean argumentsAreSwapped) {
	return anyAndAllHelper(value, bag, function, context, false, argumentsAreSwapped);
}
 
Example 24
Source Project: balana   Source File: HigherOrderFunction.java    License: Apache License 2.0 4 votes vote down vote up
/**
 * Private helper function that performs the all function
 */
private EvaluationResult all(AttributeValue value, BagAttribute bag, Function function,
		EvaluationCtx context) {
	return anyAndAllHelper(value, bag, function, context, true, false);
}
 
Example 25
Source Project: balana   Source File: HigherOrderFunction.java    License: Apache License 2.0 4 votes vote down vote up
/**
 * any-of-all
 */
private EvaluationResult anyOfAll(BagAttribute anyBag, BagAttribute allBag, Function function,
		EvaluationCtx context) {
	return allAnyHelper(anyBag, allBag, function, context, true);
}
 
Example 26
Source Project: balana   Source File: HigherOrderFunction.java    License: Apache License 2.0 4 votes vote down vote up
/**
 * all-of-any
 */
private EvaluationResult allOfAny(BagAttribute anyBag, BagAttribute allBag, Function function,
		EvaluationCtx context) {
	return allAnyHelper(anyBag, allBag, function, context, false);
}
 
Example 27
Source Project: balana   Source File: ConditionSetFunction.java    License: Apache License 2.0 4 votes vote down vote up
/**
 * Evaluates 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 evalResult = evalArgs(inputs, context, argValues);
	if (evalResult != null)
		return evalResult;

	// setup the two bags we'll be using
	BagAttribute[] bags = new BagAttribute[2];
	bags[0] = (BagAttribute) (argValues[0]);
	bags[1] = (BagAttribute) (argValues[1]);

	AttributeValue result = null;

	switch (getFunctionId()) {
	// *-at-least-one-member-of takes two bags of the same type and
	// returns a boolean
	case ID_BASE_AT_LEAST_ONE_MEMBER_OF:
		// true if at least one element in the first argument is in the
		// second argument (using the *-is-in semantics)

		result = BooleanAttribute.getFalseInstance();
		Iterator it = bags[0].iterator();

		while (it.hasNext()) {
			if (bags[1].contains((AttributeValue) (it.next()))) {
				result = BooleanAttribute.getTrueInstance();
				break;
			}
		}

		break;

	// *-set-equals takes two bags of the same type and returns
	// a boolean
	case ID_BASE_SUBSET:
		// returns true if the first argument is a subset of the second
		// argument (ie, all the elements in the first bag appear in
		// the second bag) ... ignore all duplicate values in both
		// input bags

		boolean subset = bags[1].containsAll(bags[0]);
		result = BooleanAttribute.getInstance(subset);

		break;

	// *-set-equals takes two bags of the same type and returns
	// a boolean
	case ID_BASE_SET_EQUALS:

		// returns true if the two inputs contain the same elements
		// discounting any duplicates in either input ... this is the same
		// as applying the and function on the subset function with
		// the two inputs, and then the two inputs reversed (ie, are the
		// two inputs subsets of each other)

		boolean equals = (bags[1].containsAll(bags[0]) && bags[0].containsAll(bags[1]));
		result = BooleanAttribute.getInstance(equals);

		break;
	}

	return new EvaluationResult(result);
}
 
Example 28
Source Project: balana   Source File: MapFunction.java    License: Apache License 2.0 4 votes vote down vote up
/**
 * Evaluates the function given the input data. Map expects a <code>Function</code> followed by
 * a <code>BagAttribute</code>.
 * 
 * @param inputs the input agrument list
 * @param context the representation of the request
 * 
 * @return the result of evaluation
 */
public EvaluationResult evaluate(List inputs, EvaluationCtx context) {

    // get the inputs, which we expect to be correct
    Iterator iterator = inputs.iterator();
    Function function = null;

    Expression xpr = (Expression) (iterator.next());
    if (xpr instanceof Function) {
        function = (Function) xpr;
    } else {
        function = (Function) (((VariableReference) xpr).getReferencedDefinition()
                .getExpression());
    }

    Evaluatable eval = (Evaluatable) (iterator.next());
    EvaluationResult result = eval.evaluate(context);

    // in a higher-order case, if anything is INDETERMINATE, then
    // we stop right away
    if (result.indeterminate())
        return result;

    BagAttribute bag = (BagAttribute) (result.getAttributeValue());

    // param: function, bag
    // return: bag
    // for each value in the bag evaluate the given function with
    // the value and put the function result in a new bag that
    // is ultimately returned

    Iterator it = bag.iterator();
    List<AttributeValue> outputs = new ArrayList<AttributeValue>();

    while (it.hasNext()) {
        List params = new ArrayList();
        params.add(it.next());
        result = function.evaluate(params, context);

        if (result.indeterminate())
            return result;

        outputs.add(result.getAttributeValue());
    }

    return new EvaluationResult(new BagAttribute(returnType, outputs));
}
 
Example 29
Source Project: balana   Source File: AttributeDesignator.java    License: Apache License 2.0 4 votes vote down vote up
/**
 * Evaluates the pre-assigned meta-data against the given context, trying to find some matching
 * values.
 *
 * @param context the representation of the request
 * @return a result containing a bag either empty because no values were found or containing at
 *         least one value, or status associated with an Indeterminate result
 */
public EvaluationResult evaluate(EvaluationCtx context) {
    EvaluationResult result = null;

    // look in  attribute values
    result = context.getAttribute(type, id, issuer, category);

    // if the lookup was indeterminate, then we return immediately
    if (result.indeterminate()){
        return result;
    }
    BagAttribute bag = (BagAttribute) (result.getAttributeValue());

    if (bag.isEmpty()) {
        // if it's empty, this may be an error
        if (mustBePresent) {
            if (logger.isDebugEnabled()) {
                logger.debug("AttributeDesignator failed to resolve a "
                        + "value for a required attribute: " + id.toString());
            }

            ArrayList<String> code = new ArrayList<String>();
            code.add(Status.STATUS_MISSING_ATTRIBUTE);

            ArrayList<MissingAttributeDetail> missingAttributes = new ArrayList<MissingAttributeDetail>();
            MissingAttributeDetail missingAttribute = new MissingAttributeDetail(id, type,
                                    category, issuer, null, XACMLConstants.XACML_VERSION_3_0);
            missingAttributes.add(missingAttribute);
            StatusDetail detail = new StatusDetail(missingAttributes);

            String message = "Couldn't find AttributeDesignator attribute";

            // Note that there is a bug in the XACML spec. You can't
            // specify an identifier without specifying acceptable
            // values. Until this is fixed, this code will only
            // return the status code, and not any hints about what
            // was missing

            /*
            * List attrs = new ArrayList(); attrs.add(new Attribute(id, ((issuer == null) ?
            * null : issuer.toString()), null, null)); StatusDetail detail = new
            * StatusDetail(attrs);
            */

            return new EvaluationResult(new Status(code, message, detail));
        }
    }

    // if we got here the bag wasn't empty, or mustBePresent was false,
    // so we just return the result
    return result;
}
 
Example 30
Source Project: balana   Source File: XACML2EvaluationCtx.java    License: Apache License 2.0 4 votes vote down vote up
/**
 * Helper function for the resource, action and environment methods to get an attribute.
 */
private EvaluationResult getGenericAttributes(URI type, URI id, URI category, String issuer,
                                                                                    Map map) {
    // try to find the id
    Set attrSet = (Set) (map.get(id.toString()));
    if (attrSet == null) {
        // the request didn't have an attribute with that id, so we should
        // try asking the attribute finder
        return callHelper(type, id, issuer, category);
    }

    // now go through each, considering each Attribute object
    List<AttributeValue> attributes = new ArrayList<AttributeValue>();
    Iterator it = attrSet.iterator();

    while (it.hasNext()) {
        Attribute attr = (Attribute) (it.next());

        // make sure the type and issuer are correct
        if ((attr.getType().equals(type))
                && ((issuer == null) || ((attr.getIssuer() != null) && (attr.getIssuer()
                .equals(issuer))))) {

            // if we got here, then we found a match, so we want to pull
            // out the values and put them in out list
            attributes.add(attr.getValue());
        }
    }

    // see if we found any acceptable attributes
    if (attributes.size() == 0) {
        // we failed to find any that matched the type/issuer, or all the
        // Attribute types were empty...so ask the finder
        if (logger.isDebugEnabled())
            logger.debug("Attribute not in request: " + id.toString()
                    + " ... querying AttributeFinder");

        return callHelper(type, id, issuer, category);
    }

    // if we got here, then we found at least one useful AttributeValue
    return new EvaluationResult(new BagAttribute(type, attributes));
}