[POLICY-122] Policy GUI Fixes
[policy/engine.git] / ECOMP-PAP-REST / src / main / java / org / openecomp / policy / pap / xacml / rest / components / Policy.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 import java.io.ByteArrayInputStream;
24 import java.io.IOException;
25 import java.io.InputStream;
26 import java.net.URI;
27 import java.net.URISyntaxException;
28 import java.nio.charset.StandardCharsets;
29 import java.nio.file.Files;
30 import java.nio.file.Path;
31 import java.nio.file.Paths;
32 import java.util.HashMap;
33 import java.util.Map;
34
35 import javax.json.Json;
36 import javax.json.JsonReader;
37
38 import org.apache.commons.io.FilenameUtils;
39 import org.json.JSONObject;
40 import org.openecomp.policy.common.logging.eelf.MessageCodes;
41 import org.openecomp.policy.common.logging.eelf.PolicyLogger;
42 import org.openecomp.policy.common.logging.flexlogger.FlexLogger;
43 import org.openecomp.policy.common.logging.flexlogger.Logger;
44 import org.openecomp.policy.rest.XACMLRestProperties;
45 import org.openecomp.policy.rest.adapter.PolicyRestAdapter;
46 import org.openecomp.policy.xacml.util.XACMLPolicyWriter;
47
48 import com.att.research.xacml.std.IdentifierImpl;
49 import com.att.research.xacml.util.XACMLProperties;
50 import com.att.research.xacmlatt.pdp.policy.PolicyDef;
51 import com.att.research.xacmlatt.pdp.policy.dom.DOMPolicyDef;
52
53 import oasis.names.tc.xacml._3_0.core.schema.wd_17.AttributeDesignatorType;
54 import oasis.names.tc.xacml._3_0.core.schema.wd_17.AttributeValueType;
55 import oasis.names.tc.xacml._3_0.core.schema.wd_17.MatchType;
56 import oasis.names.tc.xacml._3_0.core.schema.wd_17.PolicyType;
57
58 public abstract class Policy {
59         
60         private static final Logger LOGGER      = FlexLogger.getLogger(Policy.class);
61         
62
63         /**
64          * Common Fields
65          */
66         public static final String GET_INT_TYPE = "Integer";
67         public static final String GET_STRING_TYPE = "String";
68
69         public static final String ECOMPID = "ECOMPName";
70         public static final String CONFIGID = "ConfigName";
71         public static final String CLOSEDLOOPID = "ServiceType";
72
73         public static final String CONFIG_POLICY = "Config";
74         public static final String ACTION_POLICY = "Action";
75         public static final String DECISION_POLICY = "Decision";
76
77         protected String policyName = null;
78
79         protected boolean isValidForm = true;
80
81         private Path finalPolicyPath = null;
82
83         private boolean preparedToSave = false;
84
85         private boolean policyExists = false;
86
87         public Path getFinalPolicyPath() {
88                 return finalPolicyPath;
89         }
90
91         public void setFinalPolicyPath(Path finalPolicyPath) {
92                 this.finalPolicyPath = finalPolicyPath;
93         }
94
95         // Constants Used in XML Creation
96         public static final String CATEGORY_RECIPIENT_SUBJECT = "urn:oasis:names:tc:xacml:1.0:subject-category:recipient-subject";
97         public static final String CATEGORY_RESOURCE = "urn:oasis:names:tc:xacml:3.0:attribute-category:resource";
98         public static final String CATEGORY_ACTION = "urn:oasis:names:tc:xacml:3.0:attribute-category:action";
99         public static final String CATEGORY_ACCESS_SUBJECT = "urn:oasis:names:tc:xacml:1.0:subject-category:access-subject";
100         public static final String ACTION_ID = "urn:oasis:names:tc:xacml:1.0:action:action-id";
101         public static final String SUBJECT_ID = "urn:oasis:names:tc:xacml:1.0:subject:subject-id";
102         public static final String RESOURCE_ID = "urn:oasis:names:tc:xacml:1.0:resource:resource-id";
103         public static final String FUNTION_INTEGER_ONE_AND_ONLY = "urn:oasis:names:tc:xacml:1.0:function:integer-one-and-only";
104         public static final String FUNCTION_STRING_ONE_AND_ONLY = "urn:oasis:names:tc:xacml:1.0:function:string-one-and-only";
105         public static final String FUNCTION_BOOLEAN_ONE_AND_ONLY = "urn:oasis:names:tc:xacml:1.0:function:boolean-one-and-only";
106         public static final String FUNCTION_STRING_EQUAL = "urn:oasis:names:tc:xacml:1.0:function:string-equal";
107         public static final String FUNCTION_STRING_REGEX_MATCH = "org.openecomp.function.regex-match";
108         public static final String FUNCTION_STRING_REGEXP_MATCH = "urn:oasis:names:tc:xacml:1.0:function:string-regexp-match";
109         public static final String FUNCTION_STRING_EQUAL_IGNORE = "urn:oasis:names:tc:xacml:3.0:function:string-equal-ignore-case";
110         public static final String INTEGER_DATATYPE = "http://www.w3.org/2001/XMLSchema#integer";
111         public static final String BOOLEAN_DATATYPE = "http://www.w3.org/2001/XMLSchema#boolean";
112         public static final String STRING_DATATYPE = "http://www.w3.org/2001/XMLSchema#string";
113         public static final String URI_DATATYPE = "http://www.w3.org/2001/XMLSchema#anyURI";
114         public static final String RULE_VARIABLE = "var:";
115         public static final String EMPTY_STRING = "";
116         private static final String String = null;
117
118         public static String CONFIG_HOME = null;
119         public static String ACTION_HOME = null;
120         public static String CONFIG_URL = null;
121
122         protected Map<String, String> performer = new HashMap<>();
123
124         private static String actionHome = null;
125         private static String configHome = null;
126
127         public PolicyRestAdapter policyAdapter = null;
128         String ruleID = "";
129
130         public Policy() {
131                 CONFIG_HOME = getConfigHome();
132                 ACTION_HOME = getActionHome();
133                 CONFIG_URL = "$URL";
134                 performer.put("PDP", "PDPAction");
135                 performer.put("PEP", "PEPAction");
136         }
137
138         //Each policy type seems to either use policyData or data field policy adapter when
139         //getting the xml to save the policy. Instead of keep this hardcoded in the save method,
140         //this method makes it usable outside.
141         /**
142          * Return the data field of the PolicyAdapter that will be used when saving this policy
143          * with the savePolicies method.
144          * @return Either the PolicyAdapter.getData() or PolicyAdapter.getPolicyData()
145          */
146         public abstract Object getCorrectPolicyDataObject();
147         public abstract Map<String, String>  savePolicies() throws Exception;
148
149         //This is the method for preparing the policy for saving.  We have broken it out
150         //separately because the fully configured policy is used for multiple things
151         public abstract boolean prepareToSave() throws Exception;
152
153
154         // create match for ecomp and config name
155         protected MatchType createMatch(String key, String value) {
156                 MatchType match = new MatchType();
157
158                 AttributeValueType attributeValue = new AttributeValueType();
159                 attributeValue.setDataType(STRING_DATATYPE);
160                 attributeValue.getContent().add(value);
161                 match.setAttributeValue(attributeValue);
162                 AttributeDesignatorType attributeDesignator = new AttributeDesignatorType();
163                 URI uri = null;
164                 try {
165                         uri = new URI(key);
166                 } catch (URISyntaxException e) {
167                         LOGGER.error("Exception Occured"+e);
168                 }
169                 attributeDesignator.setCategory(CATEGORY_ACCESS_SUBJECT);
170                 attributeDesignator.setDataType(STRING_DATATYPE);
171                 attributeDesignator.setAttributeId(new IdentifierImpl(uri).stringValue());
172                 match.setAttributeDesignator(attributeDesignator);
173                 match.setMatchId(FUNCTION_STRING_REGEX_MATCH);
174                 return match;
175         }
176
177         // Creating the match for dynamically added components.
178         protected MatchType createDynamicMatch(String key, String value) {
179                 MatchType dynamicMatch = new MatchType();
180                 AttributeValueType dynamicAttributeValue = new AttributeValueType();
181                 String dataType = null;
182                 dataType = STRING_DATATYPE;
183                 dynamicAttributeValue.setDataType(dataType);
184                 dynamicAttributeValue.getContent().add(value);
185                 dynamicMatch.setAttributeValue(dynamicAttributeValue);
186
187                 AttributeDesignatorType dynamicAttributeDesignator = new AttributeDesignatorType();
188
189                 URI dynamicURI = null;
190                 try {
191                         dynamicURI = new URI(key);
192                 } catch (URISyntaxException e) {
193                         LOGGER.error("Exception Occured"+e);// log msg
194                 }
195                 dynamicAttributeDesignator.setCategory(CATEGORY_RESOURCE);
196                 dynamicAttributeDesignator.setDataType(dataType);
197                 dynamicAttributeDesignator.setAttributeId(new IdentifierImpl(dynamicURI).stringValue());
198                 dynamicMatch.setAttributeDesignator(dynamicAttributeDesignator);
199                 dynamicMatch.setMatchId(FUNCTION_STRING_REGEX_MATCH);
200
201                 return dynamicMatch;
202         }
203
204         //validation for numeric
205         protected boolean isNumeric(String str){
206                 for (char c : str.toCharArray()){
207                         if (!Character.isDigit(c)) return false;
208                 }
209                 return true;
210         }
211
212         // Validation for json.
213         protected static boolean isJSONValid(String data) {
214                 JsonReader jsonReader = null;
215                 try {
216                         new JSONObject(data);
217                         InputStream stream = new ByteArrayInputStream(data.getBytes(StandardCharsets.UTF_8));
218                         jsonReader = Json.createReader(stream);
219                         LOGGER.info("Json Value is: " + jsonReader.read().toString() );
220                 } catch (Exception e) {
221                         LOGGER.error("Exception Occured while reading json"+e);
222                         return false;
223                 }finally{
224                         if(jsonReader != null){
225                                 jsonReader.close();
226                         }
227                 }
228                 return true;
229         }
230
231         //  the Policy Name as Unique One throws error
232         @SuppressWarnings("static-access")
233         protected Path getNextFilename(Path parent, String policyType, String polcyFileName, Integer version) {
234                 policyType = FilenameUtils.removeExtension(policyType);
235                 polcyFileName = FilenameUtils.removeExtension(polcyFileName);
236                 Path newFile = null;
237                 String policyDir = EMPTY_STRING;
238                 String absolutePath = parent.toString();
239                 if (absolutePath != null && !absolutePath.equals(EMPTY_STRING)) {
240                         policyDir = absolutePath.substring(absolutePath.lastIndexOf("\\") + 1, absolutePath.length());
241                         if (policyDir == null || policyDir.equals(EMPTY_STRING)) {
242                                 policyDir = absolutePath.substring(absolutePath.lastIndexOf("/") + 1, absolutePath.length());
243                         }
244                 }
245
246                 String fileName = "default";
247                 if (policyDir != null && !policyDir.equals(EMPTY_STRING)) {
248                         fileName = policyType + "_" + String.format(polcyFileName) + "." + version + ".xml";
249                 } 
250                 if (fileName != null) {
251                         newFile = Paths.get(parent.toString(), fileName);
252                 }
253                 if (Files.notExists(newFile)) {
254                         return newFile;
255                 }
256                 return null;
257         }
258
259         protected Path getNextLoopFilename(Path parentPath, String policyType, String policyConfigType, String policyFileName, Integer version) {
260                 policyType = FilenameUtils.removeExtension(policyType);
261                 policyConfigType = FilenameUtils.removeExtension(policyConfigType);
262                 policyFileName = FilenameUtils.removeExtension(policyFileName);
263                 Path newFile = null;
264                 String policyDir = EMPTY_STRING;
265                 String absolutePath = parentPath.toString();
266                 if (absolutePath != null && !absolutePath.equals(EMPTY_STRING)) {
267                         policyDir = absolutePath.substring(absolutePath.lastIndexOf("\\") + 1, absolutePath.length());
268                         if (policyDir == null || policyDir.equals(EMPTY_STRING)) {
269                                 policyDir = absolutePath.substring(absolutePath.lastIndexOf("/") + 1, absolutePath.length());
270                         }
271                 }
272
273                 String fileName = "default";
274                 if (policyDir != null && !policyDir.equals(EMPTY_STRING)) {
275                         if(policyConfigType.equals("ClosedLoop_PM")){
276                                 fileName = policyType + "_" + "PM" + "_" +java.lang.String.format(policyFileName) + "." +version +".xml";
277                         }else if(policyConfigType.equals("ClosedLoop_Fault")){
278                                 fileName = policyType + "_" + "Fault" + "_" +java.lang.String.format(policyFileName) +  "." + version + ".xml";
279                         }else if(policyConfigType.equals("ClosedLoop_Fault")){
280                                 fileName = policyType + "_" + "Fault" + "_" +java.lang.String.format(policyFileName) +  "." + version + ".xml";
281                         }else if(policyConfigType.equals("Micro Service")){
282                                 fileName = policyType + "_" + "MS" + "_" + java.lang.String.format(policyFileName) + "." + version + ".xml";
283                         }
284                 } 
285                 if (fileName != null) {
286                         newFile = Paths.get(parentPath.toString(), fileName);
287                 }
288                 if (Files.notExists(newFile)) {
289                         return newFile;
290                 }
291                 return null;
292         }
293
294
295         //create policy once all the validations are completed
296         protected Map<String, String> createPolicy(final Path policyPath, final Object policyData) {
297                 Map<String, String> success = new HashMap<>(); 
298                 //
299                 // Is the root a PolicySet or Policy?
300                 //
301
302                 if (policyData instanceof PolicyType) {
303                         //
304                         // Write it out
305                         //
306                         //Does not need to be XACMLPolicyWriterWithPapNotify since it is already in the PAP
307                         //and this transaction is intercepted up stream.
308                         InputStream inputStream = null;
309                         try {
310                                 inputStream = XACMLPolicyWriter.getXmlAsInputStream((PolicyType) policyData);
311                                 PolicyDef policyDef = DOMPolicyDef.load(inputStream);
312                                 if (policyDef == null) {
313                                         success.put("validation", "PolicyDef Validation Failed");
314                                 }else{
315                                         success.put("success", "success");
316                                 }
317                         } catch (Exception e) {
318                                 LOGGER.error("PolicyDef Validation failed"+e);
319                                 success.put("error", "Validation Failed");
320                         }finally{
321                                 try {
322                                         if(inputStream != null)
323                                                 inputStream.close();
324                                 } catch (IOException e) {
325                                         LOGGER.error("Exception Occured while closing the input stream"+e);
326                                 }
327                         }
328                 } else {
329                         PolicyLogger.error("Unknown data type sent back.");
330                         return success;
331                 }
332                 return success;
333         }
334
335         public static String getConfigHome(){
336                 try {
337                         loadWebapps();
338                 } catch (Exception e) {
339                         return null;
340                 }
341                 return configHome;
342         }
343
344         public static String getActionHome(){
345                 try {
346                         loadWebapps();
347                 } catch (Exception e) {
348                         return null;
349                 }
350                 return actionHome;
351         }
352
353         private static void loadWebapps() throws Exception{
354                 if(actionHome == null || configHome == null){
355                         Path webappsPath = Paths.get(XACMLProperties.getProperty(XACMLRestProperties.PROP_PAP_WEBAPPS));
356                         //Sanity Check
357                         if (webappsPath == null) {
358                                 PolicyLogger.error("Invalid Webapps Path Location property : " + XACMLRestProperties.PROP_PAP_WEBAPPS);
359                                 throw new Exception("Invalid Webapps Path Location property : " + XACMLRestProperties.PROP_PAP_WEBAPPS);
360                         }
361                         Path webappsPathConfig;
362                         Path webappsPathAction;
363                         if(webappsPath.toString().contains("\\")){
364                                 webappsPathConfig = Paths.get(webappsPath.toString()+"\\Config");
365                                 webappsPathAction = Paths.get(webappsPath.toString()+"\\Action");
366                         }else{
367                                 webappsPathConfig = Paths.get(webappsPath.toString()+"/Config");
368                                 webappsPathAction = Paths.get(webappsPath.toString()+"/Action");
369                         }
370                         if(Files.notExists(webappsPathConfig)){
371                                 try {
372                                         Files.createDirectories(webappsPathConfig);
373                                 } catch (IOException e) {
374                                         PolicyLogger.error(MessageCodes.ERROR_PROCESS_FLOW, e, "Policy", "Failed to create config directory");
375                                 }
376                         }
377                         if(Files.notExists(webappsPathAction)){
378                                 try {
379                                         Files.createDirectories(webappsPathAction);
380                                 } catch (IOException e) {
381                                         PolicyLogger.error(MessageCodes.ERROR_PROCESS_FLOW, e, "Policy", "Failed to create config directory");
382                                 }
383                         }
384                         actionHome = webappsPathAction.toString();
385                         configHome = webappsPathConfig.toString();
386                 }
387         }
388         
389         public boolean validateConfigForm() {
390                 return true;
391         }
392
393         /**
394          * @return the preparedToSave
395          */
396         public boolean isPreparedToSave() {
397                 return preparedToSave;
398         }
399
400         /**
401          * @param preparedToSave the preparedToSave to set
402          */
403         protected void setPreparedToSave(boolean preparedToSave) {
404                 this.preparedToSave = preparedToSave;
405         }
406
407         public boolean isPolicyExists() {
408                 return policyExists;
409         }
410
411         public void setPolicyExists(boolean policyExists) {
412                 this.policyExists = policyExists;
413         }
414
415
416 }