Fix sonars in xacml-pdp
[policy/xacml-pdp.git] / applications / guard / src / main / java / org / onap / policy / xacml / pdp / application / guard / CoordinationGuardTranslator.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.xacml.pdp.application.guard;
24
25 import com.att.research.xacml.api.Request;
26 import com.att.research.xacml.api.Response;
27 import com.att.research.xacml.util.XACMLPolicyScanner;
28 import java.io.ByteArrayInputStream;
29 import java.io.File;
30 import java.io.FileInputStream;
31 import java.io.IOException;
32 import java.io.InputStream;
33 import java.nio.charset.StandardCharsets;
34 import java.util.List;
35 import java.util.Map;
36 import java.util.UUID;
37 import org.apache.commons.io.IOUtils;
38 import org.onap.policy.common.utils.coder.CoderException;
39 import org.onap.policy.common.utils.coder.StandardYamlCoder;
40 import org.onap.policy.common.utils.resources.ResourceUtils;
41 import org.onap.policy.models.decisions.concepts.DecisionRequest;
42 import org.onap.policy.models.decisions.concepts.DecisionResponse;
43 import org.onap.policy.models.tosca.authorative.concepts.ToscaPolicy;
44 import org.onap.policy.pdp.xacml.application.common.ToscaPolicyConversionException;
45 import org.onap.policy.pdp.xacml.application.common.ToscaPolicyTranslator;
46 import org.slf4j.Logger;
47 import org.slf4j.LoggerFactory;
48
49 public class CoordinationGuardTranslator implements ToscaPolicyTranslator {
50
51     private static final Logger LOGGER = LoggerFactory.getLogger(CoordinationGuardTranslator.class);
52
53     public CoordinationGuardTranslator() {
54         super();
55     }
56
57     @Override
58     public Object convertPolicy(ToscaPolicy toscaPolicy) throws ToscaPolicyConversionException {
59         LOGGER.debug("Using CoordinationGuardTranslator.convertPolicy");
60         //
61         // Policy name should be at the root
62         //
63         String type = toscaPolicy.getType();
64         var coordinationFunctionPath = "coordination/function";
65         Map<String, Object> policyProps = toscaPolicy.getProperties();
66         LOGGER.debug("path = {}", coordinationFunctionPath);
67         LOGGER.debug("props = {}", policyProps);
68         @SuppressWarnings("unchecked")
69         List<String> controlLoop = (List<String>) policyProps.get("controlLoop");
70         var cd = new CoordinationDirective();
71         cd.setCoordinationFunction(type);
72         cd.setControlLoop(controlLoop);
73         LOGGER.debug("CoordinationDirective = {}", cd);
74         //
75         // Generate the xacml policy as a string
76         //
77         String xacmlStr = generateXacmlFromCoordinationDirective(cd, coordinationFunctionPath);
78         LOGGER.debug("xacmlStr\n{}", xacmlStr);
79         //
80         // Scan the string and convert to PoilcyType
81         //
82         try (InputStream is = new ByteArrayInputStream(xacmlStr.getBytes(StandardCharsets.UTF_8))) {
83             return XACMLPolicyScanner.readPolicy(is);
84         } catch (IOException e) {
85             throw new ToscaPolicyConversionException("Failed to read policy", e);
86         }
87     }
88
89     /**
90      * This function is not used for CLC instead
91      * the one in LegacyGuardTranslator is used.
92      */
93     @Override
94     public Request convertRequest(DecisionRequest request) throws ToscaPolicyConversionException {
95         throw new ToscaPolicyConversionException("this convertRequest shouldn't be used");
96     }
97
98     /**
99      * This function is not used for CLC instead
100      * the one in LegacyGuardTranslator is used.
101      */
102     @Override
103     public DecisionResponse convertResponse(Response xacmlResponse) {
104         LOGGER.info("this convertResponse shouldn't be used");
105         return null;
106     }
107
108     /**
109      * Load YAML coordination directive.
110      *
111      * @param directiveFilename yaml directive file to load
112      * @return the CoordinationDirective
113      */
114     public static CoordinationDirective loadCoordinationDirectiveFromFile(
115         String directiveFilename) {
116         if (directiveFilename == null) {
117             return null;
118         }
119         try (InputStream is = new FileInputStream(new File(directiveFilename))) {
120             var contents = IOUtils.toString(is, StandardCharsets.UTF_8);
121             //
122             // Read the yaml into our Java Object
123             //
124             CoordinationDirective obj =
125                 new StandardYamlCoder().decode(contents, CoordinationDirective.class);
126             LOGGER.debug(contents);
127             return obj;
128         } catch (IOException | CoderException e) {
129             LOGGER.error("Error while loading YAML coordination directive", e);
130         }
131         return null;
132     }
133
134     /**
135      * Generate Xacml rule implementing specified CoordinationDirective.
136      *
137      * @param cd the CoordinationDirective
138      * @param protoDir the directory containing Xacml implementation prototypes
139      * @return the generated Xacml policy
140      */
141     public static String generateXacmlFromCoordinationDirective(CoordinationDirective cd,
142         String protoDir) throws ToscaPolicyConversionException {
143         /*
144          * Determine file names
145          */
146         String xacmlProtoFilename =
147             protoDir + File.separator + cd.getCoordinationFunction() + ".xml";
148         LOGGER.info("xacmlProtoFilename={}", xacmlProtoFilename);
149         /*
150          * Values to be substituted for placeholder's
151          */
152         final var uniqueId = UUID.randomUUID().toString();
153         final String cLOne = cd.getControlLoop(0);
154         final String cLTwo = cd.getControlLoop(1);
155         /*
156          * Replace function placeholder's with appropriate values
157          */
158         var policyXml = ResourceUtils.getResourceAsString(xacmlProtoFilename);
159         if (policyXml == null) {
160             throw new ToscaPolicyConversionException("Unable to find prototype " + xacmlProtoFilename);
161         }
162         policyXml = policyXml.replace("UNIQUE_ID", uniqueId);
163         policyXml = policyXml.replace("CONTROL_LOOP_ONE", cLOne);
164         policyXml = policyXml.replace("CONTROL_LOOP_TWO", cLTwo);
165
166         return policyXml;
167
168     }
169
170 }