Fix sonars in xacml-pdp
[policy/xacml-pdp.git] / applications / common / src / main / java / org / onap / policy / pdp / xacml / application / common / std / StdCombinedPolicyResultsTranslator.java
1 /*-
2  * ============LICENSE_START=======================================================
3  * ONAP
4  * ================================================================================
5  * Copyright (C) 2019-2021 AT&T Intellectual Property. All rights reserved.
6  * ================================================================================
7  * Licensed under the Apache License, Version 2.0 (the "License");
8  * you may not use this file except in compliance with the License.
9  * You may obtain a copy of the License at
10  *
11  *      http://www.apache.org/licenses/LICENSE-2.0
12  *
13  * Unless required by applicable law or agreed to in writing, software
14  * distributed under the License is distributed on an "AS IS" BASIS,
15  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
16  * See the License for the specific language governing permissions and
17  * limitations under the License.
18  *
19  * SPDX-License-Identifier: Apache-2.0
20  * ============LICENSE_END=========================================================
21  */
22
23 package org.onap.policy.pdp.xacml.application.common.std;
24
25 import com.att.research.xacml.api.Advice;
26 import com.att.research.xacml.api.DataTypeException;
27 import com.att.research.xacml.api.Identifier;
28 import com.att.research.xacml.api.Obligation;
29 import com.att.research.xacml.api.Request;
30 import com.att.research.xacml.api.XACML3;
31 import com.att.research.xacml.std.annotations.RequestParser;
32 import com.google.common.base.Strings;
33 import java.util.Collection;
34 import java.util.Map;
35 import oasis.names.tc.xacml._3_0.core.schema.wd_17.AnyOfType;
36 import oasis.names.tc.xacml._3_0.core.schema.wd_17.EffectType;
37 import oasis.names.tc.xacml._3_0.core.schema.wd_17.PolicyType;
38 import oasis.names.tc.xacml._3_0.core.schema.wd_17.RuleType;
39 import oasis.names.tc.xacml._3_0.core.schema.wd_17.TargetType;
40 import org.onap.policy.common.utils.coder.CoderException;
41 import org.onap.policy.common.utils.coder.StandardCoder;
42 import org.onap.policy.models.decisions.concepts.DecisionRequest;
43 import org.onap.policy.models.decisions.concepts.DecisionResponse;
44 import org.onap.policy.models.tosca.authorative.concepts.ToscaPolicy;
45 import org.onap.policy.pdp.xacml.application.common.OnapObligation;
46 import org.onap.policy.pdp.xacml.application.common.ToscaDictionary;
47 import org.onap.policy.pdp.xacml.application.common.ToscaPolicyConversionException;
48 import org.onap.policy.pdp.xacml.application.common.ToscaPolicyTranslatorUtils;
49 import org.slf4j.Logger;
50 import org.slf4j.LoggerFactory;
51
52 public class StdCombinedPolicyResultsTranslator extends StdBaseTranslator {
53
54     private static final Logger LOGGER = LoggerFactory.getLogger(StdCombinedPolicyResultsTranslator.class);
55
56     public StdCombinedPolicyResultsTranslator() {
57         super();
58     }
59
60     @Override
61     public Object convertPolicy(ToscaPolicy toscaPolicy) throws ToscaPolicyConversionException {
62         //
63         // Sanity checks
64         //
65         if (toscaPolicy == null) {
66             throw new ToscaPolicyConversionException("Cannot convert a NULL policy");
67         }
68         if (toscaPolicy.getMetadata() == null) {
69             throw new ToscaPolicyConversionException("Cannot convert a policy with missing metadata section");
70         }
71         //
72         // Get the policy Id
73         //
74         String policyId = toscaPolicy.getMetadata().get(POLICY_ID);
75         //
76         // Set it as the policy ID
77         //
78         var newPolicyType = new PolicyType();
79         newPolicyType.setPolicyId(policyId);
80         //
81         // Optional description
82         //
83         newPolicyType.setDescription(toscaPolicy.getDescription());
84         //
85         // There should be a metadata section
86         //
87         this.fillMetadataSection(newPolicyType, toscaPolicy.getMetadata());
88         //
89         // Set the combining rule
90         //
91         newPolicyType.setRuleCombiningAlgId(XACML3.ID_RULE_FIRST_APPLICABLE.stringValue());
92         //
93         // Generate the TargetType
94         //
95         var target = this.generateTargetType(policyId, toscaPolicy.getType(), toscaPolicy.getVersion());
96         newPolicyType.setTarget(target);
97         //
98         // Now create the Permit Rule
99         // No target since the policy has a target
100         // With obligations.
101         //
102         var rule = new RuleType();
103         rule.setDescription("Default is to PERMIT if the policy matches.");
104         rule.setRuleId(policyId + ":rule");
105         rule.setEffect(EffectType.PERMIT);
106         rule.setTarget(new TargetType());
107         //
108         // Now represent the policy as Json
109         //
110         var coder = new StandardCoder();
111         String jsonPolicy;
112         try {
113             jsonPolicy = coder.encode(toscaPolicy);
114         } catch (CoderException e) {
115             throw new ToscaPolicyConversionException(e);
116         }
117         addObligation(rule, policyId, jsonPolicy, null, toscaPolicy.getType());
118         //
119         // Add the rule to the policy
120         //
121         newPolicyType.getCombinerParametersOrRuleCombinerParametersOrVariableDefinition().add(rule);
122         //
123         // Return our new policy
124         //
125         return newPolicyType;
126     }
127
128     @Override
129     public Request convertRequest(DecisionRequest request) throws ToscaPolicyConversionException {
130         LOGGER.info("Converting Request {}", request);
131         try {
132             return RequestParser.parseRequest(StdCombinedPolicyRequest.createInstance(request));
133         } catch (IllegalArgumentException | IllegalAccessException | DataTypeException e) {
134             throw new ToscaPolicyConversionException("Failed to parse request", e);
135         }
136     }
137
138     /**
139      * scanObligations - scans the list of obligations and make appropriate method calls to process
140      * obligations.
141      *
142      * @param obligations Collection of obligation objects
143      * @param decisionResponse DecisionResponse object used to store any results from obligations.
144      */
145     @Override
146     protected void scanObligations(Collection<Obligation> obligations, DecisionResponse decisionResponse) {
147         for (Obligation obligation : obligations) {
148             Identifier obligationId = obligation.getId();
149             LOGGER.info("Obligation: {}", obligationId);
150             if (ToscaDictionary.ID_OBLIGATION_REST_BODY.equals(obligationId)) {
151                 scanContentObligation(obligation, decisionResponse);
152             }
153         }
154     }
155
156     /**
157      * scanAdvice - not implemented in this class.
158      *
159      * @param advice Collection of advice objects
160      * @param DecisionResponse DecisionResponse object
161      */
162     @Override
163     protected void scanAdvice(Collection<Advice> advice, DecisionResponse decisionResponse) {
164         //
165         // By default there are no advice supported in this object. Please override and provide
166         // any needed functionality.
167         //
168         LOGGER.warn("Advice found - not supported in this class {}", this.getClass());
169     }
170
171     /**
172      * scanContentObligation - scans the specific obligation for policy-id and policy-content.
173      *
174      * @param obligation Obligation incoming obligation object
175      * @param decisionResponse DecisionResponse object
176      */
177     protected void scanContentObligation(Obligation obligation, DecisionResponse decisionResponse) {
178         //
179         // Create our OnapObligation which will scan for attributes
180         //
181         var onapObligation = new OnapObligation(obligation);
182         //
183         // Get the attributes we care about
184         //
185         String policyId = onapObligation.getPolicyId();
186         Map<String, Object> policyContent = onapObligation.getPolicyContentAsMap();
187         //
188         // Sanity check that we got the attributes we care about. NOTE: This translator
189         // ensures that these are set when convertPolicy is called.
190         //
191         if (! Strings.isNullOrEmpty(policyId) && policyContent != null) {
192             decisionResponse.getPolicies().put(policyId, policyContent);
193         } else {
194             LOGGER.error("Missing obligation policyId {} or policyContent {}", policyId,
195                     policyContent == null ? "null" : policyContent.size());
196         }
197     }
198
199     /**
200      * generateTargetType - Generates a TargetType object for the policy-id and policy-type.
201      *
202      * @param policyId String policy-id
203      * @param policyType String policy type
204      * @param policyTypeVersion String policy type version
205      * @return TargetType object
206      */
207     protected TargetType generateTargetType(String policyId, String policyType, String policyTypeVersion) {
208         //
209         // Create all the match's that are possible
210         //
211         // This is for the Policy Id
212         //
213         var matchPolicyId = ToscaPolicyTranslatorUtils.buildMatchTypeDesignator(
214                 XACML3.ID_FUNCTION_STRING_EQUAL,
215                 policyId,
216                 XACML3.ID_DATATYPE_STRING,
217                 ToscaDictionary.ID_RESOURCE_POLICY_ID,
218                 XACML3.ID_ATTRIBUTE_CATEGORY_RESOURCE);
219         //
220         // This is for the Policy Type
221         //
222         var matchPolicyType = ToscaPolicyTranslatorUtils.buildMatchTypeDesignator(
223                 XACML3.ID_FUNCTION_STRING_EQUAL,
224                 policyType,
225                 XACML3.ID_DATATYPE_STRING,
226                 ToscaDictionary.ID_RESOURCE_POLICY_TYPE,
227                 XACML3.ID_ATTRIBUTE_CATEGORY_RESOURCE);
228         //
229         // This is for the Policy Type version
230         //
231         var matchPolicyTypeVersion = ToscaPolicyTranslatorUtils.buildMatchTypeDesignator(
232                 XACML3.ID_FUNCTION_STRING_EQUAL,
233                 policyTypeVersion,
234                 XACML3.ID_DATATYPE_STRING,
235                 ToscaDictionary.ID_RESOURCE_POLICY_TYPE_VERSION,
236                 XACML3.ID_ATTRIBUTE_CATEGORY_RESOURCE);
237         //
238         // This is our outer AnyOf - which is an OR
239         //
240         var anyOf = new AnyOfType();
241         //
242         // Create AllOf (AND) of just Policy Id
243         //
244         anyOf.getAllOf().add(ToscaPolicyTranslatorUtils.buildAllOf(matchPolicyId));
245         //
246         // Create AllOf (AND) of just Policy Type
247         //
248         anyOf.getAllOf().add(ToscaPolicyTranslatorUtils.buildAllOf(matchPolicyType));
249         //
250         // Create AllOf (AND) of Policy Type and Policy Type Version
251         //
252         anyOf.getAllOf().add(ToscaPolicyTranslatorUtils.buildAllOf(matchPolicyType, matchPolicyTypeVersion));
253         //
254         // Now we can create the TargetType, add the top-level anyOf (OR),
255         // and return the value.
256         //
257         var target = new TargetType();
258         target.getAnyOf().add(anyOf);
259         return target;
260     }
261
262 }