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