Update css file name in conf.py
[policy/engine.git] / ONAP-PAP-REST / src / main / java / org / onap / policy / pap / xacml / rest / components / CreateClosedLoopPerformanceMetrics.java
1 /*-
2  * ============LICENSE_START=======================================================
3  * ONAP-PAP-REST
4  * ================================================================================
5  * Copyright (C) 2017, 2019 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  * ============LICENSE_END=========================================================
19  */
20
21 package org.onap.policy.pap.xacml.rest.components;
22
23 import com.att.research.xacml.api.pap.PAPException;
24 import com.att.research.xacml.std.IdentifierImpl;
25
26 import java.io.File;
27 import java.io.PrintWriter;
28 import java.net.URI;
29 import java.net.URISyntaxException;
30 import java.nio.file.Path;
31 import java.nio.file.Paths;
32 import java.util.HashMap;
33 import java.util.Map;
34
35 import oasis.names.tc.xacml._3_0.core.schema.wd_17.AdviceExpressionType;
36 import oasis.names.tc.xacml._3_0.core.schema.wd_17.AdviceExpressionsType;
37 import oasis.names.tc.xacml._3_0.core.schema.wd_17.AllOfType;
38 import oasis.names.tc.xacml._3_0.core.schema.wd_17.AnyOfType;
39 import oasis.names.tc.xacml._3_0.core.schema.wd_17.AttributeAssignmentExpressionType;
40 import oasis.names.tc.xacml._3_0.core.schema.wd_17.AttributeDesignatorType;
41 import oasis.names.tc.xacml._3_0.core.schema.wd_17.AttributeValueType;
42 import oasis.names.tc.xacml._3_0.core.schema.wd_17.EffectType;
43 import oasis.names.tc.xacml._3_0.core.schema.wd_17.MatchType;
44 import oasis.names.tc.xacml._3_0.core.schema.wd_17.ObjectFactory;
45 import oasis.names.tc.xacml._3_0.core.schema.wd_17.PolicyType;
46 import oasis.names.tc.xacml._3_0.core.schema.wd_17.RuleType;
47 import oasis.names.tc.xacml._3_0.core.schema.wd_17.TargetType;
48
49 import org.apache.commons.io.FilenameUtils;
50 import org.onap.policy.common.logging.eelf.MessageCodes;
51 import org.onap.policy.common.logging.eelf.PolicyLogger;
52 import org.onap.policy.common.logging.flexlogger.FlexLogger;
53 import org.onap.policy.common.logging.flexlogger.Logger;
54 import org.onap.policy.rest.adapter.PolicyRestAdapter;
55
56 public class CreateClosedLoopPerformanceMetrics extends Policy {
57
58     private static final Logger LOGGER = FlexLogger.getLogger(CreateClosedLoopPerformanceMetrics.class);
59
60     public CreateClosedLoopPerformanceMetrics() {
61         super();
62     }
63
64     public CreateClosedLoopPerformanceMetrics(PolicyRestAdapter policyAdapter) {
65         this.policyAdapter = policyAdapter;
66     }
67
68     // save configuration of the policy based on the policyname
69     private void saveConfigurations(String policyName, final String jsonBody) {
70
71         if (policyName.endsWith(".xml")) {
72             policyName = policyName.substring(0, policyName.lastIndexOf(".xml"));
73         }
74         try (PrintWriter out = new PrintWriter(CONFIG_HOME + File.separator + "." + policyName + ".json")) {
75             out.println(jsonBody);
76             policyAdapter.setJsonBody(jsonBody);
77             policyAdapter.setConfigBodyData(jsonBody);
78         } catch (Exception e) {
79             LOGGER.error("Exception Occured" + e);
80         }
81     }
82
83     // getting the policy name and setting to configuration on adding .json
84     private String getConfigFile(String filename) {
85         filename = FilenameUtils.removeExtension(filename);
86         if (filename.endsWith(".xml")) {
87             filename = filename.substring(0, filename.length() - 4);
88         }
89         filename = filename + ".json";
90         return filename;
91     }
92
93     @Override
94     public Map<String, String> savePolicies() throws PAPException {
95
96         Map<String, String> successMap = new HashMap<>();
97         if (isPolicyExists()) {
98             successMap.put("EXISTS", "This Policy already exist on the PAP");
99             return successMap;
100         }
101
102         if (!isPreparedToSave()) {
103             // Prep and configure the policy for saving
104             prepareToSave();
105         }
106
107         // Until here we prepared the data and here calling the method to create xml.
108         Path newPolicyPath = null;
109         newPolicyPath = Paths.get(policyAdapter.getNewFileName());
110
111         successMap = createPolicy(newPolicyPath, getCorrectPolicyDataObject());
112
113         return successMap;
114     }
115
116     // This is the method for preparing the policy for saving. We have broken it out
117     // separately because the fully configured policy is used for multiple things
118     @Override
119     public boolean prepareToSave() throws PAPException {
120
121         if (isPreparedToSave()) {
122             // we have already done this
123             return true;
124         }
125
126         int version = 0;
127         String policyID = policyAdapter.getPolicyID();
128         version = policyAdapter.getHighestVersion();
129
130         // Create the Instance for pojo, PolicyType object is used in marshalling.
131         if (policyAdapter.getPolicyType().equals("Config")) {
132             PolicyType policyConfig = new PolicyType();
133
134             policyConfig.setVersion(Integer.toString(version));
135             policyConfig.setPolicyId(policyID);
136             policyConfig.setTarget(new TargetType());
137             policyAdapter.setData(policyConfig);
138         }
139         policyName = policyAdapter.getNewFileName();
140         if (policyAdapter.getData() != null) {
141             // Save the Configurations file with the policy name with extention based on selection.
142             String jsonBody = policyAdapter.getJsonBody();
143             saveConfigurations(policyName, jsonBody);
144
145             // Make sure the filename ends with an extension
146             if (policyName.endsWith(".xml") == false) {
147                 policyName = policyName + ".xml";
148             }
149
150             PolicyType configPolicy = (PolicyType) policyAdapter.getData();
151
152             configPolicy.setDescription(policyAdapter.getPolicyDescription());
153
154             configPolicy.setRuleCombiningAlgId(policyAdapter.getRuleCombiningAlgId());
155
156             AllOfType allOfOne = new AllOfType();
157             String fileName = policyAdapter.getNewFileName();
158             String name = fileName.substring(fileName.lastIndexOf("\\") + 1, fileName.length());
159             if ((name == null) || (name.equals(""))) {
160                 name = fileName.substring(fileName.lastIndexOf("/") + 1, fileName.length());
161             }
162             allOfOne.getMatch().add(createMatch("PolicyName", name));
163             AllOfType allOf = new AllOfType();
164
165             // Adding the matches to AllOfType element Match for Onap
166             allOf.getMatch().add(createMatch("ONAPName", policyAdapter.getOnapName()));
167             // Match for riskType
168             allOf.getMatch().add(createDynamicMatch("RiskType", policyAdapter.getRiskType()));
169             // Match for riskLevel
170             allOf.getMatch().add(createDynamicMatch("RiskLevel", String.valueOf(policyAdapter.getRiskLevel())));
171             // Match for riskguard
172             allOf.getMatch().add(createDynamicMatch("guard", policyAdapter.getGuard()));
173             // Match for ttlDate
174             allOf.getMatch().add(createDynamicMatch("TTLDate", policyAdapter.getTtlDate()));
175             // Match for ServiceType
176             allOf.getMatch().add(createMatch("ServiceType", policyAdapter.getServiceType()));
177
178             AnyOfType anyOf = new AnyOfType();
179             anyOf.getAllOf().add(allOfOne);
180             anyOf.getAllOf().add(allOf);
181
182             TargetType target = new TargetType();
183             ((TargetType) target).getAnyOf().add(anyOf);
184
185             // Adding the target to the policy element
186             configPolicy.setTarget((TargetType) target);
187
188             RuleType rule = new RuleType();
189             rule.setRuleId(policyAdapter.getRuleID());
190
191             rule.setEffect(EffectType.PERMIT);
192
193             // Create Target in Rule
194             AllOfType allOfInRule = new AllOfType();
195
196             // Creating match for ACCESS in rule target
197             MatchType accessMatch = new MatchType();
198             AttributeValueType accessAttributeValue = new AttributeValueType();
199             accessAttributeValue.setDataType(STRING_DATATYPE);
200             accessAttributeValue.getContent().add("ACCESS");
201             accessMatch.setAttributeValue(accessAttributeValue);
202             AttributeDesignatorType accessAttributeDesignator = new AttributeDesignatorType();
203             URI accessURI = null;
204             try {
205                 accessURI = new URI(ACTION_ID);
206             } catch (URISyntaxException e) {
207                 PolicyLogger.error(MessageCodes.ERROR_DATA_ISSUE, e, "CreateClosedLoopPerformanceMetrics",
208                         "Exception creating ACCESS URI");
209             }
210             accessAttributeDesignator.setCategory(CATEGORY_ACTION);
211             accessAttributeDesignator.setDataType(STRING_DATATYPE);
212             accessAttributeDesignator.setAttributeId(new IdentifierImpl(accessURI).stringValue());
213             accessMatch.setAttributeDesignator(accessAttributeDesignator);
214             accessMatch.setMatchId(FUNCTION_STRING_EQUAL_IGNORE);
215
216             // Creating Config Match in rule Target
217             MatchType configMatch = new MatchType();
218             AttributeValueType configAttributeValue = new AttributeValueType();
219             configAttributeValue.setDataType(STRING_DATATYPE);
220             configAttributeValue.getContent().add("Config");
221             configMatch.setAttributeValue(configAttributeValue);
222             AttributeDesignatorType configAttributeDesignator = new AttributeDesignatorType();
223             URI configURI = null;
224             try {
225                 configURI = new URI(RESOURCE_ID);
226             } catch (URISyntaxException e) {
227                 PolicyLogger.error(MessageCodes.ERROR_DATA_ISSUE, e, "CreateClosedLoopPerformanceMetrics",
228                         "Exception creating Config URI");
229             }
230             configAttributeDesignator.setCategory(CATEGORY_RESOURCE);
231             configAttributeDesignator.setDataType(STRING_DATATYPE);
232             configAttributeDesignator.setAttributeId(new IdentifierImpl(configURI).stringValue());
233             configMatch.setAttributeDesignator(configAttributeDesignator);
234             configMatch.setMatchId(FUNCTION_STRING_EQUAL_IGNORE);
235
236             allOfInRule.getMatch().add(accessMatch);
237             allOfInRule.getMatch().add(configMatch);
238
239             AnyOfType anyOfInRule = new AnyOfType();
240             anyOfInRule.getAllOf().add(allOfInRule);
241
242             TargetType targetInRule = new TargetType();
243             targetInRule.getAnyOf().add(anyOfInRule);
244
245             rule.setTarget(targetInRule);
246             rule.setAdviceExpressions(getAdviceExpressions(version, policyName));
247
248             configPolicy.getCombinerParametersOrRuleCombinerParametersOrVariableDefinition().add(rule);
249             policyAdapter.setPolicyData(configPolicy);
250
251         } else {
252             PolicyLogger.error("Unsupported data object." + policyAdapter.getData().getClass().getCanonicalName());
253         }
254         setPreparedToSave(true);
255         return true;
256     }
257
258     // Data required for Advice part is setting here.
259     @SuppressWarnings("static-access")
260     private AdviceExpressionsType getAdviceExpressions(int version, String fileName) {
261         AdviceExpressionsType advices = new AdviceExpressionsType();
262         AdviceExpressionType advice = new AdviceExpressionType();
263         advice.setAdviceId("PMID");
264         advice.setAppliesTo(EffectType.PERMIT);
265         // For Configuration
266         AttributeAssignmentExpressionType assignment1 = new AttributeAssignmentExpressionType();
267         assignment1.setAttributeId("type");
268         assignment1.setCategory(CATEGORY_RESOURCE);
269         assignment1.setIssuer("");
270
271         AttributeValueType configNameAttributeValue = new AttributeValueType();
272         configNameAttributeValue.setDataType(STRING_DATATYPE);
273         configNameAttributeValue.getContent().add("Configuration");
274         assignment1.setExpression(new ObjectFactory().createAttributeValue(configNameAttributeValue));
275
276         advice.getAttributeAssignmentExpression().add(assignment1);
277         // For Config file Url if configurations are provided.
278         AttributeAssignmentExpressionType assignment2 = new AttributeAssignmentExpressionType();
279         assignment2.setAttributeId("URLID");
280         assignment2.setCategory(CATEGORY_RESOURCE);
281         assignment2.setIssuer("");
282
283         AttributeValueType AttributeValue = new AttributeValueType();
284         AttributeValue.setDataType(URI_DATATYPE);
285         String content = CONFIG_URL + "/Config/" + getConfigFile(policyName);
286         AttributeValue.getContent().add(content);
287         assignment2.setExpression(new ObjectFactory().createAttributeValue(AttributeValue));
288
289         advice.getAttributeAssignmentExpression().add(assignment2);
290         AttributeAssignmentExpressionType assignment3 = new AttributeAssignmentExpressionType();
291         assignment3.setAttributeId("PolicyName");
292         assignment3.setCategory(CATEGORY_RESOURCE);
293         assignment3.setIssuer("");
294
295         AttributeValueType attributeValue3 = new AttributeValueType();
296         attributeValue3.setDataType(STRING_DATATYPE);
297         fileName = FilenameUtils.removeExtension(fileName);
298         fileName = fileName + ".xml";
299         String name = fileName.substring(fileName.lastIndexOf("\\") + 1, fileName.length());
300         if ((name == null) || (name.equals(""))) {
301             name = fileName.substring(fileName.lastIndexOf("/") + 1, fileName.length());
302         }
303         attributeValue3.getContent().add(name);
304         assignment3.setExpression(new ObjectFactory().createAttributeValue(attributeValue3));
305         advice.getAttributeAssignmentExpression().add(assignment3);
306
307         AttributeAssignmentExpressionType assignment4 = new AttributeAssignmentExpressionType();
308         assignment4.setAttributeId("VersionNumber");
309         assignment4.setCategory(CATEGORY_RESOURCE);
310         assignment4.setIssuer("");
311
312         AttributeValueType configNameAttributeValue4 = new AttributeValueType();
313         configNameAttributeValue4.setDataType(STRING_DATATYPE);
314         configNameAttributeValue4.getContent().add(Integer.toString(version));
315         assignment4.setExpression(new ObjectFactory().createAttributeValue(configNameAttributeValue4));
316
317         advice.getAttributeAssignmentExpression().add(assignment4);
318
319         AttributeAssignmentExpressionType assignment5 = new AttributeAssignmentExpressionType();
320         assignment5.setAttributeId("matching:" + this.ONAPID);
321         assignment5.setCategory(CATEGORY_RESOURCE);
322         assignment5.setIssuer("");
323
324         AttributeValueType configNameAttributeValue5 = new AttributeValueType();
325         configNameAttributeValue5.setDataType(STRING_DATATYPE);
326         configNameAttributeValue5.getContent().add(policyAdapter.getOnapName());
327         assignment5.setExpression(new ObjectFactory().createAttributeValue(configNameAttributeValue5));
328
329         advice.getAttributeAssignmentExpression().add(assignment5);
330
331         AttributeAssignmentExpressionType assignment6 = new AttributeAssignmentExpressionType();
332         assignment6.setAttributeId("matching:" + this.CLOSEDLOOPID);
333         assignment6.setCategory(CATEGORY_RESOURCE);
334         assignment6.setIssuer("");
335
336         AttributeValueType configNameAttributeValue6 = new AttributeValueType();
337         configNameAttributeValue6.setDataType(STRING_DATATYPE);
338         configNameAttributeValue6.getContent().add(policyAdapter.getServiceType());
339         assignment6.setExpression(new ObjectFactory().createAttributeValue(configNameAttributeValue6));
340
341         advice.getAttributeAssignmentExpression().add(assignment6);
342
343         // Risk Attributes
344         AttributeAssignmentExpressionType assignment7 = new AttributeAssignmentExpressionType();
345         assignment7.setAttributeId("RiskType");
346         assignment7.setCategory(CATEGORY_RESOURCE);
347         assignment7.setIssuer("");
348
349         AttributeValueType configNameAttributeValue7 = new AttributeValueType();
350         configNameAttributeValue7.setDataType(STRING_DATATYPE);
351         configNameAttributeValue7.getContent().add(policyAdapter.getRiskType());
352         assignment7.setExpression(new ObjectFactory().createAttributeValue(configNameAttributeValue7));
353
354         advice.getAttributeAssignmentExpression().add(assignment7);
355
356         AttributeAssignmentExpressionType assignment8 = new AttributeAssignmentExpressionType();
357         assignment8.setAttributeId("RiskLevel");
358         assignment8.setCategory(CATEGORY_RESOURCE);
359         assignment8.setIssuer("");
360
361         AttributeValueType configNameAttributeValue8 = new AttributeValueType();
362         configNameAttributeValue8.setDataType(STRING_DATATYPE);
363         configNameAttributeValue8.getContent().add(policyAdapter.getRiskLevel());
364         assignment8.setExpression(new ObjectFactory().createAttributeValue(configNameAttributeValue8));
365
366         advice.getAttributeAssignmentExpression().add(assignment8);
367
368         AttributeAssignmentExpressionType assignment9 = new AttributeAssignmentExpressionType();
369         assignment9.setAttributeId("guard");
370         assignment9.setCategory(CATEGORY_RESOURCE);
371         assignment9.setIssuer("");
372
373         AttributeValueType configNameAttributeValue9 = new AttributeValueType();
374         configNameAttributeValue9.setDataType(STRING_DATATYPE);
375         configNameAttributeValue9.getContent().add(policyAdapter.getGuard());
376         assignment9.setExpression(new ObjectFactory().createAttributeValue(configNameAttributeValue9));
377
378         advice.getAttributeAssignmentExpression().add(assignment9);
379
380         AttributeAssignmentExpressionType assignment10 = new AttributeAssignmentExpressionType();
381         assignment10.setAttributeId("TTLDate");
382         assignment10.setCategory(CATEGORY_RESOURCE);
383         assignment10.setIssuer("");
384
385         AttributeValueType configNameAttributeValue10 = new AttributeValueType();
386         configNameAttributeValue10.setDataType(STRING_DATATYPE);
387         configNameAttributeValue10.getContent().add(policyAdapter.getTtlDate());
388         assignment10.setExpression(new ObjectFactory().createAttributeValue(configNameAttributeValue10));
389
390         advice.getAttributeAssignmentExpression().add(assignment10);
391
392         advices.getAdviceExpression().add(advice);
393         return advices;
394     }
395
396     @Override
397     public Object getCorrectPolicyDataObject() {
398         return policyAdapter.getPolicyData();
399     }
400
401 }