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