Initial OpenECOMP policy/engine commit
[policy/engine.git] / ecomp-sdk-app / src / main / java / org / openecomp / policy / controller / PolicyValidationController.java
1 /*-
2  * ============LICENSE_START=======================================================
3  * ECOMP Policy Engine
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.controller;
22
23
24 import java.io.PrintWriter;
25 import java.util.Arrays;
26 import java.util.List;
27 import java.util.regex.Matcher;
28 import java.util.regex.Pattern;
29
30 import javax.servlet.http.HttpServletRequest;
31 import javax.servlet.http.HttpServletResponse;
32
33 import org.json.JSONObject;
34 import org.openecomp.policy.adapter.ClosedLoopFaultBody;
35 import org.openecomp.policy.adapter.ClosedLoopPMBody;
36 import org.openecomp.policy.adapter.PolicyAdapter;
37 import org.openecomp.policy.admin.RESTfulPAPEngine;
38 import org.openecomp.policy.rest.dao.SafePolicyWarningDao;
39 import org.openecomp.policy.rest.jpa.SafePolicyWarning;
40 import org.openecomp.portalsdk.core.controller.RestrictedBaseController;
41 import org.openecomp.portalsdk.core.web.support.JsonMessage;
42 import org.springframework.beans.factory.annotation.Autowired;
43 import org.springframework.stereotype.Controller;
44 import org.springframework.web.bind.annotation.RequestMapping;
45 import org.springframework.web.servlet.ModelAndView;
46
47 import com.fasterxml.jackson.databind.DeserializationFeature;
48 import com.fasterxml.jackson.databind.JsonNode;
49 import com.fasterxml.jackson.databind.ObjectMapper;
50 import com.google.common.base.CharMatcher;
51
52 @Controller
53 @RequestMapping("/")
54 public class PolicyValidationController extends RestrictedBaseController {
55         
56         public static final String CONFIG_POLICY = "Config";
57         public static final String ACTION_POLICY = "Action";
58         public static final String DECISION_POLICY = "Decision";
59         public static final String CLOSEDLOOP_POLICY = "ClosedLoop_Fault";
60         public static final String CLOSEDLOOP_PM = "ClosedLoop_PM";
61         public static final String ENFORCER_CONFIG_POLICY= "Enforcer Config";
62         public static final String MICROSERVICES="DCAE Micro Service";
63         private Pattern pattern;
64         private Matcher matcher;
65
66         private static final String EMAIL_PATTERN = 
67                         "^[_A-Za-z0-9-\\+]+(\\.[_A-Za-z0-9-]+)*@"
68                         + "[A-Za-z0-9-]+(\\.[A-Za-z0-9]+)*(\\.[A-Za-z]{2,})$";
69         
70         @Autowired
71         SafePolicyWarningDao safePolicyWarningDao;
72         
73         @RequestMapping(value={"/policyController/validate_policy.htm"}, method={org.springframework.web.bind.annotation.RequestMethod.POST})
74         public ModelAndView validatePolicy(HttpServletRequest request, HttpServletResponse response) throws Exception{
75                 try{
76                         boolean valid = true;
77                         String responseString = "";
78                         ObjectMapper mapper = new ObjectMapper();
79                         mapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);
80                         JsonNode root = mapper.readTree(request.getReader());
81                         PolicyAdapter policyData = (PolicyAdapter)mapper.readValue(root.get("policyData").toString(), PolicyAdapter.class);
82                         if(policyData.getPolicyName() != null){
83                                 String policyNameValidate = emptyValidator(policyData.getPolicyName());
84                                 if(!policyNameValidate.contains("success")){
85                                         responseString = responseString + "PolicyName:" +  policyNameValidate;
86                                         valid = false;
87                                 };
88                         }else{
89                                 responseString = responseString + "PolicyName: PolicyName Should not be empty" + "<br>";
90                         }
91                         if(policyData.getPolicyDescription() != null){
92                                 String descriptionValidate = descriptionValidator(policyData.getPolicyDescription());
93                                 if(!descriptionValidate.contains("success")){
94                                         responseString = responseString + "Description:" +  descriptionValidate;
95                                         valid = false;
96                                 }       
97                         }
98                         
99                         if(policyData.getPolicyType().equals(CONFIG_POLICY)){
100                                 if (policyData.getConfigPolicyType().equals("Base") || policyData.getConfigPolicyType().equals(CLOSEDLOOP_POLICY) 
101                                                 ||  policyData.getConfigPolicyType().equals(CLOSEDLOOP_PM) || policyData.getConfigPolicyType().equals(ENFORCER_CONFIG_POLICY) || policyData.getConfigPolicyType().equals(MICROSERVICES)) {
102                                         if(policyData.getEcompName() != null){
103                                                 String ecompNameValidate = emptyValidator(policyData.getEcompName());
104                                                 if(!ecompNameValidate.contains("success")){
105                                                         responseString = responseString + "EcompName:" +  ecompNameValidate;
106                                                         valid = false;
107                                                 }
108                                         }else{
109                                                 responseString = responseString + "Ecomp Name: Ecomp Name Should not be empty" + "<br>";
110                                         }
111                                 }
112                                 
113                                 if(policyData.getRiskType() != null){
114                                         String riskTypeValidate = emptyValidator(policyData.getRiskType());
115                                         if(!riskTypeValidate.contains("success")){
116                                                 responseString = responseString + "RiskType:" +  riskTypeValidate;
117                                                 valid = false;
118                                         }else {
119                                                 SafePolicyWarning safePolicyWarningData  = safePolicyWarningDao.getSafePolicyWarningDataById(policyData.getRiskType());
120                                                 if (safePolicyWarningData!=null){
121                                                         safePolicyWarningData.getMessage();
122                                                         responseString = responseString + "Messaage:" +  safePolicyWarningData.getMessage();
123                                                 }
124                                         }
125                                 }else {
126                                         responseString = responseString + "Risk Type: Risk Type Should not be Empty" + "<br>";
127                                         valid = false;
128                                 }
129                                 
130                                 if(policyData.getRiskLevel() != null){
131                                         String validateRiskLevel = emptyValidator(policyData.getRiskLevel());
132                                         if(!validateRiskLevel.contains("success")){
133                                                 responseString = responseString + "RiskLevel:" +  validateRiskLevel;
134                                                 valid = false;
135                                         }
136                                 }else {
137                                         responseString = responseString + "Risk Level: Risk Level Should not be Empty" + "<br>";
138                                         valid = false;
139                                 }
140                                 
141                                 if(policyData.getGuard() != null){
142                                         String validateGuard = emptyValidator(policyData.getGuard());
143                                         if(!validateGuard.contains("success")){
144                                                 responseString = responseString + "Guard:" +  validateGuard;
145                                                 valid = false;
146                                         }
147                                 }else {
148                                         responseString = responseString + "Guard: Guard Value Should not be Empty" + "<br>";
149                                         valid = false;
150                                 }
151                                 
152                                 if(policyData.getConfigPolicyType().equals("Base")){
153                                         if(policyData.getConfigName() != null){
154                                                 String configNameValidate = emptyValidator(policyData.getConfigName());
155                                                 if(!configNameValidate.contains("success")){
156                                                         responseString = responseString + "ConfigName:" +  configNameValidate;
157                                                         valid = false;
158                                                 }
159                                         }else{
160                                                 responseString = responseString + "Config Name: Config Name Should not be Empty" + "<br>";
161                                         }
162                                         if(policyData.getConfigType() != null){
163                                                 String configTypeValidate = emptyValidator(policyData.getConfigType());
164                                                 if(!configTypeValidate.contains("success")){
165                                                         responseString = responseString + "ConfigType:" +  configTypeValidate;
166                                                         valid = false;
167                                                 }
168                                         }else{
169                                                 responseString = responseString + "Config Type: Config Type Should not be Empty" + "<br>";
170                                         }
171                                         if(policyData.getConfigBodyData() != null){
172                                                 String policyType = policyData.getPolicyType();
173                                                 RESTfulPAPEngine engine = (RESTfulPAPEngine) PolicyController.getPapEngine();
174                                                 if(!engine.validatePolicyRequest(policyData, policyType)){
175                                                         responseString = responseString + "ConfigBody: Validation Failed";
176                                                         valid = false;
177                                                 }
178                                         }else{
179                                                 responseString = responseString + "Config Body: Config Body Should not be Empty" + "<br>";
180                                         }
181                                 }
182                                 
183                                 
184                                 if(policyData.getJsonBodyData() != null){
185                                         if(policyData.getConfigPolicyType().equals("ClosedLoop_PM")){
186                                                 ClosedLoopPMBody pmBody = (ClosedLoopPMBody)mapper.readValue(root.get("policyData").get("jsonBodyData").toString(), ClosedLoopPMBody.class);
187                                                 if(pmBody.getEmailAddress() != null){
188                                                         String validateEmail = validateEmailAddress(pmBody.getEmailAddress().toString());
189                                                         if(!validateEmail.contains("success")){
190                                                                 responseString = responseString + "Email:" +  validateEmail;
191                                                                 valid = false;
192                                                         }
193                                                 }else{
194                                                         valid = true;
195                                                 }
196                                         }else if(policyData.getConfigPolicyType().equals("ClosedLoop_Fault")){
197                                                 ClosedLoopFaultBody faultBody = (ClosedLoopFaultBody)mapper.readValue(root.get("policyData").get("jsonBodyData").toString(), ClosedLoopFaultBody.class);
198                                                 if(faultBody.getEmailAddress() != null){
199                                                         String validateEmail = validateEmailAddress(faultBody.getEmailAddress().toString());
200                                                         if(!validateEmail.contains("success")){
201                                                                 responseString = responseString + "Email:" +  validateEmail;
202                                                                 valid = false;
203                                                         }
204                                                 }else{
205                                                         valid = true;
206                                                 }
207                                         }       
208                                 }
209                         }
210                         if (policyData.getPolicyType().equals(DECISION_POLICY)){
211                                 String ecompNameValidate = emptyValidator(policyData.getEcompName());
212                                 if(!ecompNameValidate.contains("success")){
213                                         responseString = responseString + "EcompName:" +  ecompNameValidate;
214                                         valid = false;
215                                 }
216                         }
217                         
218                         if(policyData.getPolicyType().equals(ACTION_POLICY)){
219                                 String actionPerformer = emptyValidator(policyData.getActionPerformer());
220                                 String actionAttribute = emptyValidator(policyData.getActionAttributeValue());
221                                 if(!actionPerformer.contains("success")){
222                                         responseString = responseString + "ActionPerformer:" +  actionPerformer;
223                                         valid = false;
224                                 };
225                                 if(!actionAttribute.contains("success")){
226                                         responseString = responseString + "ActionAttribute:" +  actionAttribute;
227                                         valid = false;
228                                 };              
229                         }
230                         
231                         if(policyData.getPolicyType().equals(CONFIG_POLICY)){
232                                 if(valid){
233                                         responseString = "success" + "@#"+ responseString;
234                                 }
235                         }else{
236                                 if(valid){
237                                         responseString = "success";
238                                 }
239                         }
240                         
241                         PrintWriter out = response.getWriter();
242                         JsonMessage msg = new JsonMessage(mapper.writeValueAsString(responseString));
243                         JSONObject j = new JSONObject(msg);
244                         out.write(j.toString());
245
246                         return null;
247                 }
248                 catch (Exception e){
249                         response.setCharacterEncoding("UTF-8");
250                         request.setCharacterEncoding("UTF-8");
251                         PrintWriter out = response.getWriter();
252                         out.write(e.getMessage());
253                 }
254                 return null;
255         }
256
257         protected String  emptyValidator(String field){
258                 String error = "success";
259                 if (field.equals("") || field.contains(" ") || !field.matches("^[a-zA-Z0-9_]*$")) {
260                         error = "The Value in Required Field will allow only '{0-9}, {a-z}, {A-Z}, _' following set of Combinations";
261                         return error;
262                 } else {
263                         if(CharMatcher.ASCII.matchesAllOf((CharSequence) field)){
264                                  error = "success";
265                         }else{
266                                 error = "The Value Contains Non ASCII Characters";
267                                 return error;
268                         }       
269                 }
270                 return error;   
271         }
272         
273         protected String descriptionValidator(String field) {
274                 String error = "success";
275                 if (field.contains("@CreatedBy:") || field.contains("@ModifiedBy:")) {
276                          error = "The value in the description shouldn't contain @CreatedBy: or @ModifiedBy:";
277                          return error;
278                 } else {
279                         error = "success";
280                 }
281                 return error;   
282         }
283         
284         public String validateEmailAddress(String emailAddressValue) {
285                 String error = "success";
286                 List<String> emailList = Arrays.asList(emailAddressValue.toString().split(","));
287                 for(int i =0 ; i < emailList.size() ; i++){
288                         pattern = Pattern.compile(EMAIL_PATTERN);
289                         matcher = pattern.matcher(emailList.get(i).trim());
290                         if(!matcher.matches()){
291                                 error = "Please check the Following Email Address is not Valid ....   " +emailList.get(i).toString();
292                                 return error;
293                         }else{
294                                 error = "success";
295                         }
296                 }
297                 return error;           
298         }
299         
300 }