org.wso2.balana.xacml3.Attributes Java Examples

The following examples show how to use org.wso2.balana.xacml3.Attributes. 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: CarbonAttributeFinder.java    From carbon-identity-framework with Apache License 2.0 6 votes vote down vote up
/**
 * Converts DOM object to String. This is a helper method for creating cache key
 *
 * @param evaluationCtx EvaluationCtx
 * @return String Object
 * @throws TransformerException Exception throws if fails
 */
private String encodeContext(EvaluationCtx evaluationCtx) throws TransformerException {
    OutputStream stream = new ByteArrayOutputStream();
    evaluationCtx.getRequestCtx().encode(stream);
    String rowContext = stream.toString();
    String contextWithAttributeValues = rowContext + "][";

    StringBuilder builder = new StringBuilder();
    for (Attributes attributes : evaluationCtx.getRequestCtx().getAttributesSet()) {
        builder.append("<Attributes ").append(">");
        for (Attribute attribute : attributes.getAttributes()) {
            attribute.encode(builder);
        }
        builder.append("</Attributes>");
    }
    contextWithAttributeValues += builder.toString();

    return contextWithAttributeValues;
}
 
Example #2
Source File: RequestCtx.java    From balana with Apache License 2.0 5 votes vote down vote up
/**
 * Constructor that creates a <code>RequestCtx</code> from components.
 *
 * @param attributesSet
 * @param documentRoot the root node of the DOM tree for this request
 * @param resourceContent a text-encoded version of the content, suitable for including in the
 *            RequestType, including the root <code>RequestContent</code> node
 *
 * @throws IllegalArgumentException if the inputs are not well formed
 */
public RequestCtx(Set<Attributes> attributesSet, Node documentRoot, Set<Subject> subjects,
                  Set<Attribute> resource, Set<Attribute> action,  Set<Attribute> environment,
                  String resourceContent) throws IllegalArgumentException {

    this.attributesSet = attributesSet;
    this.documentRoot = documentRoot;
    this.subjects = subjects;
    this.resource = resource;
    this.action = action;
    this.environment = environment;
    this.resourceContent = resourceContent;
    this.xacmlVersion = XACMLConstants.XACML_VERSION_2_0;
}
 
Example #3
Source File: XACML2EvaluationCtx.java    From balana with Apache License 2.0 5 votes vote down vote up
/**
 * Changes the value of the resource-id attribute in this context. This is useful when you have
 * multiple resources (ie, a scope other than IMMEDIATE), and you need to keep changing only the
 * resource-id to evaluate the different effective requests.
 *
 * @param resourceId the new resource-id value
 */
public void setResourceId(AttributeValue resourceId, Set<Attributes> attributesSet) {
    this.resourceId = resourceId;

    // there will always be exactly one value for this attribute
    Set attrSet = (Set) (resourceMap.get(XACMLConstants.RESOURCE_ID));
    Attribute attr = (Attribute) (attrSet.iterator().next());

    // remove the old value...
    attrSet.remove(attr);

    // ...and insert the new value
    attrSet.add(new Attribute(attr.getId(), attr.getIssuer(), attr.getIssueInstant(),
            resourceId,XACMLConstants.XACML_VERSION_2_0));
}
 
Example #4
Source File: RequestCtx.java    From balana with Apache License 2.0 5 votes vote down vote up
/**
 * Encodes this  <code>AbstractRequestCtx</code>  into its XML representation and writes this encoding to the given
 * <code>OutputStream</code> with indentation.
 *
 * @param output a stream into which the XML-encoded data is written
 * @param indenter an object that creates indentation strings
 */
public void encode(OutputStream output, Indenter indenter) {

    String indent = indenter.makeString();
    PrintStream out = new PrintStream(output);

    out.println(indent + "<Request xmlns=\"" + XACMLConstants.REQUEST_CONTEXT_3_0_IDENTIFIER +
            "\" ReturnPolicyIdList=\"" + returnPolicyIdList + "\" CombinedDecision=\"" + 
            combinedDecision +   "\" >");

    indenter.in();

    for(Attributes attributes : attributesSet){
        out.println(attributes.encode());
    }

    if(defaults != null){
        defaults.encode(output, indenter);
    }

    if(multiRequests != null){
       // multiRequests 
    }

    indenter.out();

    out.println(indent + "</Request>");
}
 
Example #5
Source File: RequestCtx.java    From balana with Apache License 2.0 5 votes vote down vote up
/**
 * Constructor that creates a <code>RequestCtx</code> from components.
 *
 * @param documentRoot       the root node of the DOM tree for this request
 * @param attributesSet      a <code>Set</code> of <code>Attributes</code>s
 * @param returnPolicyIdList a <code>boolean</code> value whether to send back policy list of not
 * @param combinedDecision   a <code>boolean</code> value whether to combine decisions or not
 * @param multiRequests      a <code>MultiRequests</code> for the  MultiRequests element in request
 * @param defaults           a <code>RequestDefaults</code>  for the  RequestDefaults element in request
 * @throws IllegalArgumentException if the inputs are not well formed
 */
public RequestCtx(Node documentRoot, Set<Attributes> attributesSet, boolean returnPolicyIdList,
                  boolean combinedDecision, MultiRequests multiRequests,
                  RequestDefaults defaults) throws IllegalArgumentException {


    this.xacmlVersion = XACMLConstants.XACML_VERSION_3_0;
    this.documentRoot = documentRoot;
    this.attributesSet = attributesSet;
    this.returnPolicyIdList = returnPolicyIdList;
    this.combinedDecision = combinedDecision;
    this.multiRequests = multiRequests;
    this.defaults = defaults;
}
 
Example #6
Source File: EntitlementUtil.java    From carbon-identity-framework with Apache License 2.0 5 votes vote down vote up
/**
 * This creates the XACML 3.0 Request context from AttributeDTO object model
 *
 * @param attributeDTOs AttributeDTO objects as List
 * @return DOM element as XACML request
 * @throws EntitlementException throws, if fails
 */
public static AbstractRequestCtx createRequestContext(List<AttributeDTO> attributeDTOs) {

    Set<Attributes> attributesSet = new HashSet<Attributes>();

    for (AttributeDTO DTO : attributeDTOs) {
        Attributes attributes = getAttributes(DTO);
        if (attributes != null) {
            attributesSet.add(attributes);
        }
    }
    return new org.wso2.balana.ctx.xacml3.RequestCtx(attributesSet, null);
}
 
Example #7
Source File: EntitlementUtil.java    From carbon-identity-framework with Apache License 2.0 5 votes vote down vote up
public static Attributes getAttributes(AttributeDTO attributeDataDTO) {

        try {
            AttributeValue value = Balana.getInstance().getAttributeFactory().
                    createValue(new URI(attributeDataDTO.getAttributeDataType()),
                            attributeDataDTO.getAttributeValue());
            Attribute attribute = new Attribute(new URI(attributeDataDTO.getAttributeId()),
                    null, null, value, XACMLConstants.XACML_VERSION_3_0);
            Set<Attribute> set = new HashSet<Attribute>();
            set.add(attribute);
            String category = attributeDataDTO.getCategory();
            // We are only creating XACML 3.0 requests Therefore covert order XACML categories to new uris
            if (PDPConstants.SUBJECT_ELEMENT.equals(category)) {
                category = PDPConstants.SUBJECT_CATEGORY_URI;
            } else if (PDPConstants.RESOURCE_ELEMENT.equals(category)) {
                category = PDPConstants.RESOURCE_CATEGORY_URI;
            } else if (PDPConstants.ACTION_ELEMENT.equals(category)) {
                category = PDPConstants.ACTION_CATEGORY_URI;
            } else if (PDPConstants.ENVIRONMENT_ELEMENT.equals(category)) {
                category = PDPConstants.ENVIRONMENT_CATEGORY_URI;
            }
            return new Attributes(new URI(category), set);
        } catch (Exception e) {
            log.debug(e);
            //ignore and return null;
        }

        return null;
    }
 
Example #8
Source File: EntitlementUtil.java    From carbon-identity with Apache License 2.0 5 votes vote down vote up
/**
 * This creates the XACML 3.0 Request context from AttributeDTO object model
 *
 * @param attributeDTOs AttributeDTO objects as List
 * @return DOM element as XACML request
 * @throws EntitlementException throws, if fails
 */
public static AbstractRequestCtx createRequestContext(List<AttributeDTO> attributeDTOs) {

    Set<Attributes> attributesSet = new HashSet<Attributes>();

    for (AttributeDTO DTO : attributeDTOs) {
        Attributes attributes = getAttributes(DTO);
        if (attributes != null) {
            attributesSet.add(attributes);
        }
    }
    return new org.wso2.balana.ctx.xacml3.RequestCtx(attributesSet, null);
}
 
Example #9
Source File: EntitlementUtil.java    From carbon-identity with Apache License 2.0 5 votes vote down vote up
public static Attributes getAttributes(AttributeDTO attributeDataDTO) {

        try {
            AttributeValue value = Balana.getInstance().getAttributeFactory().
                    createValue(new URI(attributeDataDTO.getAttributeDataType()),
                            attributeDataDTO.getAttributeValue());
            Attribute attribute = new Attribute(new URI(attributeDataDTO.getAttributeId()),
                    null, null, value, XACMLConstants.XACML_VERSION_3_0);
            Set<Attribute> set = new HashSet<Attribute>();
            set.add(attribute);
            String category = attributeDataDTO.getCategory();
            // We are only creating XACML 3.0 requests Therefore covert order XACML categories to new uris
            if (PDPConstants.SUBJECT_ELEMENT.equals(category)) {
                category = PDPConstants.SUBJECT_CATEGORY_URI;
            } else if (PDPConstants.RESOURCE_ELEMENT.equals(category)) {
                category = PDPConstants.RESOURCE_CATEGORY_URI;
            } else if (PDPConstants.ACTION_ELEMENT.equals(category)) {
                category = PDPConstants.ACTION_CATEGORY_URI;
            } else if (PDPConstants.ENVIRONMENT_ELEMENT.equals(category)) {
                category = PDPConstants.ENVIRONMENT_CATEGORY_URI;
            }
            return new Attributes(new URI(category), set);
        } catch (Exception e) {
            log.debug(e);
            //ignore and return null;
        }

        return null;
    }
 
Example #10
Source File: Result.java    From balana with Apache License 2.0 5 votes vote down vote up
/**
 * Extract the attributes that must be included in the response
 *
 * @param attributesSet  a <code>Set</code> of <code>Attributes</code>
 */
public void processAttributes(Set<Attributes> attributesSet){

    if(attributesSet == null){
        return;
    }

    Set<Attributes> newSet = new HashSet<Attributes>();

    for(Attributes attributes : attributesSet){
        Set<Attribute> attributeSet = attributes.getAttributes();
        if(attributeSet == null){
            continue;
        }
        Set<Attribute> newAttributeSet = new HashSet<Attribute>();
        for(Attribute attribute : attributeSet){
            if(attribute.isIncludeInResult()){
                newAttributeSet.add(attribute);
            }
        }

        if(newAttributeSet.size() > 0){
            Attributes newAttributes = new Attributes(attributes.getCategory(),
                                attributes.getContent(), newAttributeSet, attributes.getId());
            newSet.add(newAttributes);
        }
    }

    this.attributes = newSet;
}
 
Example #11
Source File: JSONResponseWriter.java    From carbon-identity-framework with Apache License 2.0 4 votes vote down vote up
/**
 * Create json object value of an Attribute
 *
 * @param attributes an element of type Attributes
 * @return a JSONObject
 */
private static JsonObject getJsonObject(Attributes attributes) {

    JsonObject jsonObject = new JsonObject();
    JsonArray jsonArray = new JsonArray();
    for (Object att : attributes.getAttributes().toArray()) {
        Attribute attrib = (Attribute) att;
        if (attrib.isIncludeInResult()) {
            JsonObject element = new JsonObject();
            if (attrib.getId() != null) {
                if (xacmlJSONProfileShortFormEnable) {
                    element.addProperty(EntitlementEndpointConstants.ATTRIBUTE_ID, uriToShortenForm(attrib
                            .getId().toString()));
                } else {
                    element.addProperty(EntitlementEndpointConstants.ATTRIBUTE_ID, attrib.getId().toString());
                }
            }
            if (attrib.getValues() != null) {
                for (AttributeValue val : attrib.getValues()) {
                    if (((StringAttribute) val).getValue() != null) {
                        element.addProperty(EntitlementEndpointConstants.ATTRIBUTE_VALUE,
                                ((StringAttribute) val).getValue());
                    }
                }
            }
            element.addProperty(EntitlementEndpointConstants.ATTRIBUTE_INCLUDE_IN_RESULT,
                    String.valueOf(attrib.isIncludeInResult()));
            if (attrib.getType() != null) {
                if (xacmlJSONProfileShortFormEnable) {
                    element.addProperty(EntitlementEndpointConstants.ATTRIBUTE_DATA_TYPE,
                            uriToShortenForm(attrib.getType().toString()));
                } else {
                    element.addProperty(EntitlementEndpointConstants.ATTRIBUTE_DATA_TYPE,
                            attrib.getType().toString());
                }
            }
            jsonArray.add(element);
        }
    }
    jsonObject.add(EntitlementEndpointConstants.ATTRIBUTE, jsonArray);
    return jsonObject;
}
 
Example #12
Source File: Result.java    From balana with Apache License 2.0 4 votes vote down vote up
/**
 * Creates a new instance of a <code>Result</code> based on the given
 * DOM root node. A <code>ParsingException</code> is thrown if the DOM
 * root doesn't represent a valid ResultType.
 *
 * @param root the DOM root of a ResultType
 *
 * @return a new <code>Result</code>
 *
 * @throws ParsingException if the node is invalid
 */
public static AbstractResult getInstance(Node root) throws ParsingException {

    int decision = -1;
    Status status = null;
    List<ObligationResult> obligations = null;
    List<Advice> advices = null;
    Set<PolicyReference> policyReferences = null;
    Set<Attributes>  attributes = null;

    NodeList nodes = root.getChildNodes();
    for (int i = 0; i < nodes.getLength(); i++) {
        Node node = nodes.item(i);
        String name = DOMHelper.getLocalName(node);

        if (name.equals("Decision")) {
            String type = node.getFirstChild().getNodeValue();
            for (int j = 0; j < DECISIONS.length; j++) {
                if (DECISIONS[j].equals(type)) {
                    decision = j;
                    break;
                }
            }

            if (decision == -1){
                throw new ParsingException("Unknown Decision: " + type);
            }
        } else if (name.equals("Status")) {
            if(status == null){
                status = Status.getInstance(node);
            } else {
                throw new ParsingException("More than one StatusType defined");
            }
        } else if (name.equals("Obligations")) {
            if(obligations == null){
                obligations = parseObligations(node);
            } else {
                throw new ParsingException("More than one ObligationsType defined");
            }
        } else if (name.equals("AssociatedAdvice")) {
            if(advices == null){
                advices = parseAdvices(node);
            } else {
                throw new ParsingException("More than one AssociatedAdviceType defined"); 
            }
        } else if (name.equals("PolicyIdentifierList")){
            if(policyReferences == null){
                policyReferences = parsePolicyReferences(node);
            } else {
                throw new ParsingException("More than one PolicyIdentifierListType defined"); 
            }
        } else if(name.equals("Attributes")){
            if(attributes == null){
                attributes = new HashSet<Attributes>();
            }
            attributes.add(Attributes.getInstance(node));    
        }
    }

    return new Result(decision, status, obligations, advices, policyReferences, attributes);
}
 
Example #13
Source File: TestJSONRequestParser.java    From carbon-identity-framework with Apache License 2.0 4 votes vote down vote up
@Test
public void testParse() {
    AttributeValue attributeValue = new StringAttribute("http://127.0.0.1");
    List<AttributeValue> attributeValues = new ArrayList<>();
    attributeValues.add(attributeValue);

    Attribute attribute = new Attribute(URI.create("urn:oasis:names:tc:xacml:1.0:resource:resource-id"),
            null, null, null, attributeValues, false, XACMLConstants.XACML_VERSION_3_0);
    Set<Attribute> attributeSet = new HashSet<>();
    attributeSet.add(attribute);

    Attributes category = new Attributes(URI.create(EntitlementEndpointConstants.CATEGORY_RESOURCE_URI),
            attributeSet);
    Set<Attributes> categories = new HashSet<>();
    categories.add(category);

    RequestCtx requestCtx = new RequestCtx(categories, null);


    String jsonRequest = "{\n" +
            "  \"Request\":{\n" +
            "    \"Action\":{\n" +
            "      \"Attribute\":[{\n" +
            "        \"AttributeId\":\"urn:oasis:names:tc:xacml:1.0:action:action-id\",\n" +
            "        \"Value\":\"read\"\n" +
            "      }]\n" +
            "    },\n" +
            "    \"Resource\":{\n" +
            "      \"Attribute\":[{\n" +
            "        \"AttributeId\":\"urn:oasis:names:tc:xacml:1.0:resource:resource-id\",\n" +
            "        \"Value\":\"http://127.0.0.1/service/very_secure/\"\n" +
            "      }]\n" +
            "    }\n" +
            "  }\n" +
            "}";

    String jsonRequest2 = "{\"Request\":\n" +
            "{\n" +
            "\"AccessSubject\":{\n" +
            "            \"Content\": \"PD94bWwgdmVyc2lvbj0iMS4wIj8+DQo8Y2F0YWxvZz48Ym9vayBpZD0iYmsxMDEiPjxhdXRob3I+R2FtYmFyZGVsbGEsIE1hdHRoZXc8L2F1dGhvcj48dGl0bGU+WE1MIERldmVsb3BlcidzIEd1aWRlPC90aXRsZT48Z2VucmU+Q29tcHV0ZXI8L2dlbnJlPjxwcmljZT40NC45NTwvcHJpY2U+PHB1Ymxpc2hfZGF0ZT4yMDAwLTEwLTAxPC9wdWJsaXNoX2RhdGU+PGRlc2NyaXB0aW9uPkFuIGluLWRlcHRoIGxvb2sgYXQgY3JlYXRpbmcgYXBwbGljYXRpb25zIHdpdGggWE1MLjwvZGVzY3JpcHRpb24+PC9ib29rPjwvY2F0YWxvZz4=\"\n" +
            "}\n" +
            "}}";

    try {
        RequestCtx requestCtx1 = JSONRequestParser.parse(jsonRequest);
    } catch (Exception e) {
        log.error("Exception in JSON Parser Test");
    }


}
 
Example #14
Source File: JSONRequestParser.java    From carbon-identity-framework with Apache License 2.0 4 votes vote down vote up
/**
 * This is to seperate JSON to attributes
 * @param jsonAttribute - the map of category string and the JSON Element
 * @param jsonCategory - the  main object category
 * @param categories - the set of categories
 * @throws RequestParseException
 * @throws UnknownIdentifierException
 */
private static void jsonAttributeSeperator(Map.Entry<String, JsonElement> jsonAttribute, JsonObject jsonCategory,
                                           Set<Attributes> categories) throws
        RequestParseException, UnknownIdentifierException {

    Node content = null;
    URI category = null;
    Set<Attribute> attributes = null;
    String id = null;

    if (EntitlementEndpointConstants.CATEGORY_DEFAULT.equals(jsonAttribute.getKey())) {
        if (jsonCategory.has(EntitlementEndpointConstants.CATEGORY_ID)) {
            category = stringCateogryToURI(jsonCategory
                    .get(EntitlementEndpointConstants.CATEGORY_ID)
                    .getAsString());
        }
    } else {
        if (category == null) {
            category = stringCateogryToURI(jsonAttribute.getKey());
        }
        if (jsonCategory.has(EntitlementEndpointConstants.ID)) {
            id = jsonCategory.get(EntitlementEndpointConstants.ID).getAsString();
        }
        if (jsonCategory.has(EntitlementEndpointConstants.CONTENT)) {
            DocumentBuilderFactory dbf;
            Document doc = null;

            String xmlContent = stringContentToXMLContent(jsonCategory
                    .get(EntitlementEndpointConstants.CONTENT)
                    .getAsString());
            dbf = IdentityUtil.getSecuredDocumentBuilderFactory();
            dbf.setNamespaceAware(true);

            try (ByteArrayInputStream inputStream = new ByteArrayInputStream(xmlContent.getBytes())) {
                doc = dbf.newDocumentBuilder().parse(inputStream);
            } catch (Exception e) {
                throw new JsonParseException("DOM of request element can not be created from String.", e);
            }
            if (doc != null) {
                content = doc.getDocumentElement();
            }
        }

        // Add all category attributes
        if (jsonCategory.has(EntitlementEndpointConstants.ATTRIBUTE)) {
            if (jsonCategory.get(EntitlementEndpointConstants.ATTRIBUTE).isJsonArray()) {
                attributes = new HashSet<>();
                for (JsonElement jsonElement : jsonCategory.get(EntitlementEndpointConstants.ATTRIBUTE)
                        .getAsJsonArray()) {
                    attributes.add(jsonObjectToAttribute(jsonElement.getAsJsonObject()));
                }
            }
        }

    }
    //Build the Attributes object using above values
    Attributes attributesObj = new Attributes(category, content, attributes, id);
    categories.add(attributesObj);
}
 
Example #15
Source File: JSONRequestParser.java    From carbon-identity-framework with Apache License 2.0 4 votes vote down vote up
/**
 * Static method that will convert a XACML JSON Request to a <code>{@link RequestCtx}</code> instance
 *
 * @param jsonRequest <code>String</code> with JSON request
 * @return <code>{@link RequestCtx}</code> instance that can be used to evaluate on Balana
 * @throws JsonParseException         <code>{@link JsonParseException}</code>
 * @throws RequestParseException      <code>{@link RequestParseException}</code>
 * @throws UnknownIdentifierException <code>{@link UnknownIdentifierException}</code>
 */
public static RequestCtx parse(String jsonRequest) throws JsonParseException, RequestParseException,
        UnknownIdentifierException {
    JsonObject requestObject = null;
    Set<Attributes> categories = new HashSet<>();
    boolean returnPolicyIdList = false;
    boolean combinedDecision = false;
    MultiRequests multiRequests = null;
    RequestDefaults requestDefaults = null;

    try {
        requestObject = gson.fromJson(jsonRequest, JsonObject.class);
        requestObject = requestObject.get("Request").getAsJsonObject();
    } catch (Exception e) {
        throw new JsonParseException("Error in JSON Request String");
    }

    Set<Map.Entry<String, JsonElement>> jsonAttributes = requestObject.entrySet();

    for (Map.Entry<String, JsonElement> jsonAttribute : jsonAttributes) {
        if (jsonAttribute.getValue().isJsonPrimitive()) {
            switch (jsonAttribute.getKey()) {
                case XACMLConstants.RETURN_POLICY_LIST:
                    if (jsonAttribute.getValue().getAsBoolean() == true) {
                        returnPolicyIdList = true;
                    }
                    break;

                case XACMLConstants.COMBINE_DECISION:
                    if (jsonAttribute.getValue().getAsBoolean() == true) {
                        combinedDecision = true;
                    }
                    break;

                case EntitlementEndpointConstants.XPATH_VERSION:
                    String xPathVersion = jsonAttribute.getValue().getAsString();
                    requestDefaults = new RequestDefaults(xPathVersion);
                    break;
            }
        } else if (!jsonAttribute.getValue().isJsonNull()) {
            JsonObject jsonCategory = null;
            if (jsonAttribute.getValue().isJsonObject()) {
                jsonCategory = jsonAttribute.getValue().getAsJsonObject();
                jsonAttributeSeperator(jsonAttribute, jsonCategory, categories);

            } else if (jsonAttribute.getValue().isJsonArray()) {
                for (JsonElement jsonElement : jsonAttribute.getValue().getAsJsonArray()) {
                    jsonCategory = jsonElement.getAsJsonObject();
                    jsonAttributeSeperator(jsonAttribute, jsonCategory, categories);
                }
            } else if (EntitlementEndpointConstants.MULTI_REQUESTS.equals(jsonAttribute.getKey())) {
                Set<Map.Entry<String, JsonElement>> jsonRequestReferences = jsonCategory.entrySet();
                Set<RequestReference> requestReferences = new HashSet<>();

                if (jsonRequestReferences.isEmpty()) {
                    throw new RequestParseException("MultiRequest should contain at least one Reference Request");
                }
                for (Map.Entry<String, JsonElement> jsonRequstReference : jsonRequestReferences) {
                    requestReferences.add(jsonObjectToRequestReference(jsonRequstReference.getValue()
                            .getAsJsonObject()));
                }
                multiRequests = new MultiRequests(requestReferences);
            }
        }

    }

    return new RequestCtx(null,
            categories, returnPolicyIdList, combinedDecision, multiRequests, requestDefaults);

}
 
Example #16
Source File: JSONResponseWriter.java    From carbon-identity-framework with Apache License 2.0 4 votes vote down vote up
/**
 * Private method to convert a given Balana <code>{@link AbstractResult}</code> to a <code>{@link JsonObject}</code>
 *
 * @param result <code>{@link AbstractResult}</code>
 * @return <code>{@link JsonObject}</code>
 * @throws ResponseWriteException <code>{@link ResponseWriteException}</code>
 */
private static JsonObject abstractResultToJSONObject(AbstractResult result) throws ResponseWriteException {

    JsonObject jsonResult = new JsonObject();

    //Decision property is mandatory, if not set throw error
    if (result.getDecision() == -1) {
        throw new ResponseWriteException(40031, "XACML Result should contain the Decision");
    }
    jsonResult.addProperty(EntitlementEndpointConstants.DECISION,
            AbstractResult.DECISIONS[result.getDecision()]);

    //If Status object is present, convert it
    if (result.getStatus() != null) {
        jsonResult.add(EntitlementEndpointConstants.STATUS, statusToJSONObject(result.getStatus()));
    }

    //If Obligations are present
    if (result.getObligations() != null && !result.getObligations().isEmpty()) {
        //can only get ObligationResult objects from balana
        JsonArray obligations = new JsonArray();
        for (ObligationResult obligation : result.getObligations()) {
            if (obligation instanceof Obligation) {
                obligations.add(obligationToJsonObject((Obligation) obligation));
            } else {
                obligations.add(new JsonPrimitive(obligation.encode()));
            }
        }

        jsonResult.add(EntitlementEndpointConstants.OBLIGATIONS, obligations);
    }

    // Do the same with attributes
    if (result.getAdvices() != null && !result.getAdvices().isEmpty()) {
        //can only get ObligationResult objects from balana
        JsonArray advices = new JsonArray();
        for (Advice advice : result.getAdvices()) {
            advices.add(adviceToJsonObject(advice));
        }

        jsonResult.add(EntitlementEndpointConstants.ASSOCIATED_ADVICE, advices);
    }

    // If includeInResponse=true, other attributes will be populated from here with the decision.
    if (((Result) result).getAttributes() != null && !((Result) result).getAttributes().isEmpty()) {
        Set<Attributes> attributes = ((Result) result).getAttributes();

        for (Attributes attribute : attributes) {

            switch (attribute.getCategory().toString()) {
                case EntitlementEndpointConstants.CATEGORY_ACTION_URI:
                    jsonResult.add(EntitlementEndpointConstants.CATEGORY_ACTION, getJsonObject(attribute));
                    break;

                case EntitlementEndpointConstants.CATEGORY_RESOURCE_URI:
                    jsonResult.add(EntitlementEndpointConstants.CATEGORY_RESOURCE, getJsonObject(attribute));
                    break;

                case EntitlementEndpointConstants.CATEGORY_ACCESS_SUBJECT_URI:
                    jsonResult.add(EntitlementEndpointConstants.CATEGORY_ACCESS_SUBJECT, getJsonObject(attribute));
                    break;

                case EntitlementEndpointConstants.CATEGORY_ENVIRONMENT_URI:
                    jsonResult.add(EntitlementEndpointConstants.CATEGORY_ENVIRONMENT, getJsonObject(attribute));
                    break;

                case EntitlementEndpointConstants.CATEGORY_RECIPIENT_SUBJECT_URI:
                    jsonResult.add(EntitlementEndpointConstants.CATEGORY_RECIPIENT_SUBJECT,
                            getJsonObject(attribute));
                    break;

                case EntitlementEndpointConstants.CATEGORY_INTERMEDIARY_SUBJECT_URI:
                    jsonResult.add(EntitlementEndpointConstants.CATEGORY_INTERMEDIARY_SUBJECT,
                            getJsonObject(attribute));
                    break;

                case EntitlementEndpointConstants.CATEGORY_CODEBASE_URI:
                    jsonResult.add(EntitlementEndpointConstants.CATEGORY_CODEBASE, getJsonObject(attribute));
                    break;

                case EntitlementEndpointConstants.CATEGORY_REQUESTING_MACHINE_URI:
                    jsonResult.add(EntitlementEndpointConstants.CATEGORY_REQUESTING_MACHINE,
                            getJsonObject(attribute));
                    break;

                default:
                    jsonResult.add(attribute.getCategory().toString(), getJsonObject(attribute));
                    break;
            }
        }
    }

    return jsonResult;
}
 
Example #17
Source File: Result.java    From balana with Apache License 2.0 3 votes vote down vote up
/**
 *
 * @param decision
 * @param status
 * @param obligationResults
 * @param advices
 * @param policyReferences
 * @param attributes
 * @throws IllegalArgumentException
 */
public Result(int decision, Status status, List<ObligationResult> obligationResults,
              List<Advice> advices, Set<PolicyReference> policyReferences, Set<Attributes> attributes)
                                                            throws IllegalArgumentException {
    super(decision, status, obligationResults, advices, XACMLConstants.XACML_VERSION_3_0);
    this.policyReferences = policyReferences;
    processAttributes(attributes);
}
 
Example #18
Source File: RequestCtx.java    From balana with Apache License 2.0 3 votes vote down vote up
/**
 * Constructor that creates a <code>RequestCtx</code> from components.
 *
 * @param attributesSet
 * @param documentRoot the root node of the DOM tree for this request
 * @param resourceContent a text-encoded version of the content, suitable for including in the
 *            RequestType, including the root <code>RequestContent</code> node
 * 
 * @throws IllegalArgumentException if the inputs are not well formed
 */
public RequestCtx(Set<Attributes> attributesSet, Node documentRoot, String resourceContent)
                                                                throws IllegalArgumentException {

    this.attributesSet = attributesSet;
    this.documentRoot = documentRoot;
    this.resourceContent = resourceContent;
    this.xacmlVersion = XACMLConstants.XACML_VERSION_2_0;
}
 
Example #19
Source File: Result.java    From balana with Apache License 2.0 2 votes vote down vote up
/**
 * Return set of attributes that is sent to PEP
 *
 * @return set of attributes
 */
public Set<Attributes> getAttributes() {
    return attributes;
}
 
Example #20
Source File: RequestCtx.java    From balana with Apache License 2.0 2 votes vote down vote up
/**
 * Constructor that creates a <code>RequestCtx</code> from components.
 *
 * @param attributesSet a <code>Set</code> of <code>Attributes</code>s
 * @param documentRoot  the root node of the DOM tree for this request 
 * @throws IllegalArgumentException if the inputs are not well formed
 */
public RequestCtx(Set<Attributes> attributesSet, Node documentRoot) {
    this(documentRoot, attributesSet, false, false, null, null);
}
 
Example #21
Source File: AbstractRequestCtx.java    From balana with Apache License 2.0 2 votes vote down vote up
/**
 *  Returns a <code>Set</code> containing <code>Attribute</code> objects.
 *
 * @return  the request' s all attributes as <code>Set</code>
 */
public Set<Attributes> getAttributesSet() {
    return attributesSet;
}
 
Example #22
Source File: RequestCtx.java    From balana with Apache License 2.0 2 votes vote down vote up
/**
 * Constructor that creates a <code>RequestCtx</code> from components.
 *
 */
public RequestCtx(Set<Attributes> attributesSet, Node documentRoot) {
    this(attributesSet, documentRoot, null);
}
 
Example #23
Source File: RequestCtx.java    From balana with Apache License 2.0 2 votes vote down vote up
/**
 * Constructor that creates a <code>RequestCtx</code> from components.
 *
 * @param documentRoot the root node of the DOM tree for this request
 * @param version xacml version of the request
 */
public RequestCtx(Set<Attributes> attributesSet, Node documentRoot, int version) {
    this(attributesSet, documentRoot,  null);
}
 
Example #24
Source File: RequestCtx.java    From balana with Apache License 2.0 2 votes vote down vote up
/**
 * Constructor that creates a <code>RequestCtx</code> from components.
 *
 * @param resourceContent a text-encoded version of the content, suitable for including in the
 *            RequestType, including the root <code>RequestContent</code> node
 */
public RequestCtx(Set<Attributes> attributesSet,  String resourceContent) {
    this( attributesSet, null, resourceContent);
}