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