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