Initial OpenECOMP policy/engine commit
[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.IOException;
26 import java.io.PrintWriter;
27 import java.net.URI;
28 import java.net.URISyntaxException;
29 import java.nio.file.Path;
30 import java.nio.file.Paths;
31 import java.util.HashMap;
32 import java.util.Map;
33 import java.util.StringTokenizer;
34
35 import javax.json.stream.JsonGenerationException;
36
37 import oasis.names.tc.xacml._3_0.core.schema.wd_17.AdviceExpressionType;
38 import oasis.names.tc.xacml._3_0.core.schema.wd_17.AdviceExpressionsType;
39 import oasis.names.tc.xacml._3_0.core.schema.wd_17.AllOfType;
40 import oasis.names.tc.xacml._3_0.core.schema.wd_17.AnyOfType;
41 import oasis.names.tc.xacml._3_0.core.schema.wd_17.AttributeAssignmentExpressionType;
42 import oasis.names.tc.xacml._3_0.core.schema.wd_17.AttributeDesignatorType;
43 import oasis.names.tc.xacml._3_0.core.schema.wd_17.AttributeValueType;
44 import oasis.names.tc.xacml._3_0.core.schema.wd_17.EffectType;
45 import oasis.names.tc.xacml._3_0.core.schema.wd_17.MatchType;
46 import oasis.names.tc.xacml._3_0.core.schema.wd_17.ObjectFactory;
47 import oasis.names.tc.xacml._3_0.core.schema.wd_17.PolicyType;
48 import oasis.names.tc.xacml._3_0.core.schema.wd_17.RuleType;
49 import oasis.names.tc.xacml._3_0.core.schema.wd_17.TargetType;
50
51 import org.apache.commons.io.FilenameUtils;
52 import org.apache.commons.logging.Log;
53 import org.apache.commons.logging.LogFactory;
54 import org.openecomp.policy.pap.xacml.rest.adapters.PolicyRestAdapter;
55
56 import org.openecomp.policy.xacml.api.XACMLErrorConstants;
57 import com.att.research.xacml.std.IdentifierImpl;
58
59 import org.openecomp.policy.common.logging.eelf.MessageCodes;
60 import org.openecomp.policy.common.logging.eelf.PolicyLogger;
61 import org.openecomp.policy.common.logging.flexlogger.FlexLogger; 
62 import org.openecomp.policy.common.logging.flexlogger.Logger; 
63
64 public class CreateClosedLoopPerformanceMetrics extends Policy {
65         
66         /**
67          * Config Fields
68          */
69         private static final Logger logger = FlexLogger.getLogger(ConfigPolicy.class);
70
71         public CreateClosedLoopPerformanceMetrics() {
72                 super();
73         }
74         
75         public CreateClosedLoopPerformanceMetrics(PolicyRestAdapter policyAdapter){
76                 this.policyAdapter = policyAdapter;
77         }
78
79         //save configuration of the policy based on the policyname
80         private void saveConfigurations(String policyName, String prevPolicyName, String jsonBody) {
81                 String domain = getParentPathSubScopeDir();
82                 String path = domain.replace('\\', '.');
83                 if(path.contains("/")){
84                         path = domain.replace('/', '.');
85                         logger.info("print the path:" +path);
86                 }
87                 try {
88                         String body = null;
89                         try {
90                                 body = jsonBody;
91                         } catch (Exception e) {
92                                 e.printStackTrace();
93                         }
94
95                         System.out.println(body);
96                         if(policyName.endsWith(".xml")){
97                                 policyName       = policyName.substring(0, policyName.lastIndexOf(".xml"));     
98                         }
99                         PrintWriter out = new PrintWriter(CONFIG_HOME + File.separator+path + "."+ policyName +".json");
100                         out.println(body);
101                         out.close();
102
103                 } catch (JsonGenerationException e) {
104                         e.printStackTrace();
105                 } catch (IOException e) {
106                         e.printStackTrace();
107                 }
108
109         }
110         
111         //getting the policy name and setting to configuration on adding .json
112         private String getConfigFile(String filename) {
113                 filename = FilenameUtils.removeExtension(filename);
114                 if (filename.endsWith(".xml")) {
115                         filename = filename.substring(0, filename.length() - 4);
116                 }
117                 filename = filename +".json";
118                 return filename;
119         }
120         
121         @Override
122         public Map<String, String> savePolicies() throws Exception {
123                 
124                 Map<String, String> successMap = new HashMap<String,String>();
125                 if(isPolicyExists()){
126                         successMap.put("EXISTS", "This Policy already exist on the PAP");
127                         return successMap;
128                 }
129                 
130                 if(!isPreparedToSave()){
131                         //Prep and configure the policy for saving
132                         prepareToSave();
133                 }
134
135                 // Until here we prepared the data and here calling the method to create xml.
136                 Path newPolicyPath = null;
137                 newPolicyPath = Paths.get(policyAdapter.getParentPath().toString(), policyName);
138                 successMap = createPolicy(newPolicyPath,getCorrectPolicyDataObject() );         
139                 if (successMap.containsKey("success")) {
140                         Path finalPolicyPath = getFinalPolicyPath();
141                         policyAdapter.setFinalPolicyPath(finalPolicyPath.toString());
142                 }
143                 return successMap;              
144         }
145         
146         //This is the method for preparing the policy for saving.  We have broken it out
147         //separately because the fully configured policy is used for multiple things
148         @Override
149         public boolean prepareToSave() throws Exception{
150
151                 if(isPreparedToSave()){
152                         //we have already done this
153                         return true;
154                 }
155                 
156                 int version = 0;
157                 String policyID = policyAdapter.getPolicyID();
158
159                 if (policyAdapter.isEditPolicy()) {
160                         version = policyAdapter.getHighestVersion() + 1;
161                 } else {
162                         version = 1;
163                 }
164                 
165                 // Create the Instance for pojo, PolicyType object is used in marshalling.
166                 if (policyAdapter.getPolicyType().equals("Config")) {
167                         PolicyType policyConfig = new PolicyType();
168
169                         policyConfig.setVersion(Integer.toString(version));
170                         policyConfig.setPolicyId(policyID);
171                         policyConfig.setTarget(new TargetType());
172                         policyAdapter.setData(policyConfig);
173                 }
174                 
175                 if (policyAdapter.getData() != null) {
176                         
177                         // Save off everything
178                         // making ready all the required elements to generate the action policy xml.
179                         // Get the uniqueness for policy name.
180                         String prevPolicyName = null;
181                         if(policyAdapter.isEditPolicy()){
182                                 prevPolicyName = "Config_PM_" + policyAdapter.getPolicyName() + "." + policyAdapter.getHighestVersion() + ".xml";
183                         }
184                         
185                         Path newFile = this.getNextLoopFilename(Paths.get(policyAdapter.getParentPath()), policyAdapter.getPolicyType(), policyAdapter.getConfigPolicyType(), policyAdapter.getPolicyName(), version);
186
187                         if (newFile == null) {
188                                 //TODO:EELF Cleanup - Remove logger
189                                 //logger.error("File already exists, cannot create the policy.");
190                                 PolicyLogger.error("File already exists, cannot create the policy.");
191                                 setPolicyExists(true);
192                                 return false;
193                         }
194                         
195                         policyName = newFile.getFileName().toString();
196                         
197                         // Save the Configurations file with the policy name with extention based on selection.
198                         String jsonBody = policyAdapter.getJsonBody();
199                         saveConfigurations(policyName, prevPolicyName, jsonBody);
200                         
201                         // Make sure the filename ends with an extension
202                         if (policyName.endsWith(".xml") == false) {
203                                 policyName = policyName + ".xml";
204                         }
205                         
206         
207                         PolicyType configPolicy = (PolicyType) policyAdapter.getData();
208                         
209                         configPolicy.setDescription(policyAdapter.getPolicyDescription());
210
211                         configPolicy.setRuleCombiningAlgId(policyAdapter.getRuleCombiningAlgId());
212                         
213                         AllOfType allOfOne = new AllOfType();
214                         final Path gitPath = Paths.get(policyAdapter.getUserGitPath().toString());
215                         String policyDir = policyAdapter.getParentPath().toString();
216                         int startIndex = policyDir.indexOf(gitPath.toString()) + gitPath.toString().length() + 1;
217                         policyDir = policyDir.substring(startIndex, policyDir.length());
218                         logger.info("print the main domain value "+policyDir);
219                         String path = policyDir.replace('\\', '.');
220                         if(path.contains("/")){
221                                 path = policyDir.replace('/', '.');
222                                 logger.info("print the path:" +path);
223                         }
224                         String fileName = FilenameUtils.removeExtension(policyName);
225                         fileName = path + "." + fileName + ".xml";
226                         String name = fileName.substring(fileName.lastIndexOf("\\") + 1, fileName.length());
227                         if ((name == null) || (name.equals(""))) {
228                                 name = fileName.substring(fileName.lastIndexOf("/") + 1, fileName.length());
229                         }
230                         allOfOne.getMatch().add(createMatch("PolicyName", name));
231                         AllOfType allOf = new AllOfType();
232                         
233                         // Adding the matches to AllOfType element Match for Ecomp
234                         allOf.getMatch().add(createMatch("ECOMPName", policyAdapter.getEcompName()));
235                         // Match for riskType
236                         allOf.getMatch().add(
237                                         createDynamicMatch("RiskType", policyAdapter.getRiskType()));
238                         // Match for riskLevel
239                         allOf.getMatch().add(
240                                         createDynamicMatch("RiskLevel", String.valueOf(policyAdapter.getRiskLevel())));
241                         // Match for riskguard
242                         allOf.getMatch().add(
243                                         createDynamicMatch("guard", policyAdapter.getGuard()));
244                         // Match for ttlDate
245                         allOf.getMatch().add(
246                                         createDynamicMatch("TTLDate", policyAdapter.getTtlDate()));
247                         // Match for ServiceType
248                         allOf.getMatch().add(createMatch("ServiceType", policyAdapter.getServiceType()));
249
250                         AnyOfType anyOf = new AnyOfType();
251                         anyOf.getAllOf().add(allOfOne);
252                         anyOf.getAllOf().add(allOf);
253
254                         TargetType target = new TargetType();
255                         ((TargetType) target).getAnyOf().add(anyOf);
256                         
257                         // Adding the target to the policy element
258                         configPolicy.setTarget((TargetType) target);
259
260                         RuleType rule = new RuleType();
261                         rule.setRuleId(policyAdapter.getRuleID());
262                         
263                         rule.setEffect(EffectType.PERMIT);
264                         
265                         // Create Target in Rule
266                         AllOfType allOfInRule = new AllOfType();
267
268                         // Creating match for ACCESS in rule target
269                         MatchType accessMatch = new MatchType();
270                         AttributeValueType accessAttributeValue = new AttributeValueType();
271                         accessAttributeValue.setDataType(STRING_DATATYPE);
272                         accessAttributeValue.getContent().add("ACCESS");
273                         accessMatch.setAttributeValue(accessAttributeValue);
274                         AttributeDesignatorType accessAttributeDesignator = new AttributeDesignatorType();
275                         URI accessURI = null;
276                         try {
277                                 accessURI = new URI(ACTION_ID);
278                         } catch (URISyntaxException e) {
279                                 //TODO:EELF Cleanup - Remove logger
280                                 //logger.error(XACMLErrorConstants.ERROR_DATA_ISSUE + e.getStackTrace());
281                                 PolicyLogger.error(MessageCodes.ERROR_DATA_ISSUE, e, "CreateClosedLoopPerformanceMetrics", "Exception creating ACCESS URI");
282                         }
283                         accessAttributeDesignator.setCategory(CATEGORY_ACTION);
284                         accessAttributeDesignator.setDataType(STRING_DATATYPE);
285                         accessAttributeDesignator.setAttributeId(new IdentifierImpl(accessURI).stringValue());
286                         accessMatch.setAttributeDesignator(accessAttributeDesignator);
287                         accessMatch.setMatchId(FUNCTION_STRING_EQUAL_IGNORE);
288
289                         // Creating Config Match in rule Target
290                         MatchType configMatch = new MatchType();
291                         AttributeValueType configAttributeValue = new AttributeValueType();
292                         configAttributeValue.setDataType(STRING_DATATYPE);
293                         configAttributeValue.getContent().add("Config");
294                         configMatch.setAttributeValue(configAttributeValue);
295                         AttributeDesignatorType configAttributeDesignator = new AttributeDesignatorType();
296                         URI configURI = null;
297                         try {
298                                 configURI = new URI(RESOURCE_ID);
299                         } catch (URISyntaxException e) {
300                                 //TODO:EELF Cleanup - Remove logger
301                                 //logger.error(XACMLErrorConstants.ERROR_DATA_ISSUE + e.getStackTrace());
302                                 PolicyLogger.error(MessageCodes.ERROR_DATA_ISSUE, e, "CreateClosedLoopPerformanceMetrics", "Exception creating Config URI");
303                         }
304                         configAttributeDesignator.setCategory(CATEGORY_RESOURCE);
305                         configAttributeDesignator.setDataType(STRING_DATATYPE);
306                         configAttributeDesignator.setAttributeId(new IdentifierImpl(configURI).stringValue());
307                         configMatch.setAttributeDesignator(configAttributeDesignator);
308                         configMatch.setMatchId(FUNCTION_STRING_EQUAL_IGNORE);
309
310                         allOfInRule.getMatch().add(accessMatch);
311                         allOfInRule.getMatch().add(configMatch);
312
313                         AnyOfType anyOfInRule = new AnyOfType();
314                         anyOfInRule.getAllOf().add(allOfInRule);
315
316                         TargetType targetInRule = new TargetType();
317                         targetInRule.getAnyOf().add(anyOfInRule);
318
319                         rule.setTarget(targetInRule);
320                         rule.setAdviceExpressions(getAdviceExpressions(version, policyName));
321
322                         configPolicy.getCombinerParametersOrRuleCombinerParametersOrVariableDefinition().add(rule);
323                         policyAdapter.setPolicyData(configPolicy);
324
325                 } else {
326                         //TODO:EELF Cleanup - Remove logger
327                         //logger.error("Unsupported data object." + policyAdapter.getData().getClass().getCanonicalName());
328                         PolicyLogger.error("Unsupported data object." + policyAdapter.getData().getClass().getCanonicalName());
329                 }
330                 setPreparedToSave(true);
331                 return true;
332         }
333         
334         // Data required for Advice part is setting here.
335         @SuppressWarnings("static-access")
336         private AdviceExpressionsType getAdviceExpressions(int version, String fileName) {
337                 AdviceExpressionsType advices = new AdviceExpressionsType();
338                 AdviceExpressionType advice = new AdviceExpressionType();
339                 advice.setAdviceId("PMID");
340                 advice.setAppliesTo(EffectType.PERMIT);
341                 // For Configuration
342                 AttributeAssignmentExpressionType assignment1 = new AttributeAssignmentExpressionType();
343                 assignment1.setAttributeId("type");
344                 assignment1.setCategory(CATEGORY_RESOURCE);
345                 assignment1.setIssuer("");
346
347                 AttributeValueType configNameAttributeValue = new AttributeValueType();
348                 configNameAttributeValue.setDataType(STRING_DATATYPE);
349                 configNameAttributeValue.getContent().add("Configuration");
350                 assignment1.setExpression(new ObjectFactory().createAttributeValue(configNameAttributeValue));
351
352                 advice.getAttributeAssignmentExpression().add(assignment1);
353                 final Path gitPath = Paths.get(policyAdapter.getUserGitPath().toString());
354                 // For Config file Url if configurations are provided.
355                 AttributeAssignmentExpressionType assignment2 = new AttributeAssignmentExpressionType();
356                 assignment2.setAttributeId("URLID");
357                 assignment2.setCategory(CATEGORY_RESOURCE);
358                 assignment2.setIssuer("");
359
360                 AttributeValueType AttributeValue = new AttributeValueType();
361                 AttributeValue.setDataType(URI_DATATYPE);
362                 String policyDir1 = policyAdapter.getParentPath().toString();
363                 int startIndex1 = policyDir1.indexOf(gitPath.toString()) + gitPath.toString().length() + 1;
364                 policyDir1 = policyDir1.substring(startIndex1, policyDir1.length());
365                 logger.info("print the main domain value"+policyDir1);
366                 String path = policyDir1.replace('\\', '.');
367                 if(path.contains("/")){
368                         path = policyDir1.replace('/', '.');
369                         logger.info("print the path:" +path);
370                 }
371                 String content = CONFIG_URL +"/Config/" + path + "." + getConfigFile(policyName);
372                 System.out.println("URL value :" + content);
373                 AttributeValue.getContent().add(content);
374                 assignment2.setExpression(new ObjectFactory().createAttributeValue(AttributeValue));
375
376                 advice.getAttributeAssignmentExpression().add(assignment2);
377                 AttributeAssignmentExpressionType assignment3 = new AttributeAssignmentExpressionType();
378                 assignment3.setAttributeId("PolicyName");
379                 assignment3.setCategory(CATEGORY_RESOURCE);
380                 assignment3.setIssuer("");
381
382                 AttributeValueType attributeValue3 = new AttributeValueType();
383                 attributeValue3.setDataType(STRING_DATATYPE);
384                 String policyDir = policyAdapter.getParentPath().toString();
385                 int startIndex = policyDir.indexOf(gitPath.toString()) + gitPath.toString().length() + 1;
386                 policyDir = policyDir.substring(startIndex, policyDir.length());
387                 StringTokenizer tokenizer = null;
388                 StringBuffer buffer = new StringBuffer();
389                 if (policyDir.contains("\\")) {
390                         tokenizer = new StringTokenizer(policyDir, "\\");
391                 } else {
392                         tokenizer = new StringTokenizer(policyDir, "/");
393                 }
394                 if (tokenizer != null) {
395                         while (tokenizer.hasMoreElements()) {
396                                 String value = tokenizer.nextToken();
397                                 buffer.append(value);
398                                 buffer.append(".");
399                         }
400                 }
401                 fileName = FilenameUtils.removeExtension(fileName);
402                 fileName = buffer.toString() + fileName + ".xml";
403                 String name = fileName.substring(fileName.lastIndexOf("\\") + 1, fileName.length());
404                 if ((name == null) || (name.equals(""))) {
405                         name = fileName.substring(fileName.lastIndexOf("/") + 1, fileName.length());
406                 }
407                 attributeValue3.getContent().add(name);
408                 assignment3.setExpression(new ObjectFactory().createAttributeValue(attributeValue3));
409                 advice.getAttributeAssignmentExpression().add(assignment3);
410
411                 AttributeAssignmentExpressionType assignment4 = new AttributeAssignmentExpressionType();
412                 assignment4.setAttributeId("VersionNumber");
413                 assignment4.setCategory(CATEGORY_RESOURCE);
414                 assignment4.setIssuer("");
415
416                 AttributeValueType configNameAttributeValue4 = new AttributeValueType();
417                 configNameAttributeValue4.setDataType(STRING_DATATYPE);
418                 configNameAttributeValue4.getContent().add(Integer.toString(version));
419                 assignment4.setExpression(new ObjectFactory().createAttributeValue(configNameAttributeValue4));
420
421                 advice.getAttributeAssignmentExpression().add(assignment4);
422
423                 AttributeAssignmentExpressionType assignment5 = new AttributeAssignmentExpressionType();
424                 assignment5.setAttributeId("matching:" + this.ECOMPID);
425                 assignment5.setCategory(CATEGORY_RESOURCE);
426                 assignment5.setIssuer("");
427
428                 AttributeValueType configNameAttributeValue5 = new AttributeValueType();
429                 configNameAttributeValue5.setDataType(STRING_DATATYPE);
430                 configNameAttributeValue5.getContent().add(policyAdapter.getEcompName());
431                 assignment5.setExpression(new ObjectFactory().createAttributeValue(configNameAttributeValue5));
432
433                 advice.getAttributeAssignmentExpression().add(assignment5);
434
435                 AttributeAssignmentExpressionType assignment6 = new AttributeAssignmentExpressionType();
436                 assignment6.setAttributeId("matching:" + this.CLOSEDLOOPID);
437                 assignment6.setCategory(CATEGORY_RESOURCE);
438                 assignment6.setIssuer("");
439
440                 AttributeValueType configNameAttributeValue6 = new AttributeValueType();
441                 configNameAttributeValue6.setDataType(STRING_DATATYPE);
442                 configNameAttributeValue6.getContent().add(policyAdapter.getServiceType());
443                 assignment6.setExpression(new ObjectFactory().createAttributeValue(configNameAttributeValue6));
444
445                 advice.getAttributeAssignmentExpression().add(assignment6);
446                 
447                 //Risk Attributes
448                 AttributeAssignmentExpressionType assignment7 = new AttributeAssignmentExpressionType();
449                 assignment7.setAttributeId("RiskType");
450                 assignment7.setCategory(CATEGORY_RESOURCE);
451                 assignment7.setIssuer("");
452
453                 AttributeValueType configNameAttributeValue7 = new AttributeValueType();
454                 configNameAttributeValue7.setDataType(STRING_DATATYPE);
455                 configNameAttributeValue7.getContent().add(policyAdapter.getRiskType());
456                 assignment7.setExpression(new ObjectFactory().createAttributeValue(configNameAttributeValue7));
457
458                 advice.getAttributeAssignmentExpression().add(assignment7);
459                 
460                 AttributeAssignmentExpressionType assignment8 = new AttributeAssignmentExpressionType();
461                 assignment8.setAttributeId("RiskLevel");
462                 assignment8.setCategory(CATEGORY_RESOURCE);
463                 assignment8.setIssuer("");
464
465                 AttributeValueType configNameAttributeValue8 = new AttributeValueType();
466                 configNameAttributeValue8.setDataType(STRING_DATATYPE);
467                 configNameAttributeValue8.getContent().add(policyAdapter.getRiskLevel());
468                 assignment8.setExpression(new ObjectFactory().createAttributeValue(configNameAttributeValue8));
469
470                 advice.getAttributeAssignmentExpression().add(assignment8);     
471
472                 AttributeAssignmentExpressionType assignment9 = new AttributeAssignmentExpressionType();
473                 assignment9.setAttributeId("guard");
474                 assignment9.setCategory(CATEGORY_RESOURCE);
475                 assignment9.setIssuer("");
476
477                 AttributeValueType configNameAttributeValue9 = new AttributeValueType();
478                 configNameAttributeValue9.setDataType(STRING_DATATYPE);
479                 configNameAttributeValue9.getContent().add(policyAdapter.getGuard());
480                 assignment9.setExpression(new ObjectFactory().createAttributeValue(configNameAttributeValue9));
481
482                 advice.getAttributeAssignmentExpression().add(assignment9);
483                 
484                 AttributeAssignmentExpressionType assignment10 = new AttributeAssignmentExpressionType();
485                 assignment10.setAttributeId("TTLDate");
486                 assignment10.setCategory(CATEGORY_RESOURCE);
487                 assignment10.setIssuer("");
488
489                 AttributeValueType configNameAttributeValue10 = new AttributeValueType();
490                 configNameAttributeValue10.setDataType(STRING_DATATYPE);
491                 configNameAttributeValue10.getContent().add(policyAdapter.getTtlDate());
492                 assignment10.setExpression(new ObjectFactory().createAttributeValue(configNameAttributeValue10));
493
494                 advice.getAttributeAssignmentExpression().add(assignment10);
495
496                 advices.getAdviceExpression().add(advice);
497                 return advices;
498         }
499
500         @Override
501         public Object getCorrectPolicyDataObject() {
502                 // TODO Auto-generated method stub
503                 return policyAdapter.getPolicyData();
504         }       
505
506 }