MS Model Input Validation
[policy/engine.git] / ONAP-PDP-REST / src / main / java / org / onap / policy / pdp / rest / api / services / CreateUpdatePolicyServiceImpl.java
1 /*-
2  * ============LICENSE_START=======================================================
3  * ONAP-PDP-REST
4  * ================================================================================
5  * Copyright (C) 2017-2018 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 package org.onap.policy.pdp.rest.api.services;
21
22 import java.text.SimpleDateFormat;
23 import java.util.Date;
24 import java.util.UUID;
25
26 import org.onap.policy.api.PolicyException;
27 import org.onap.policy.api.PolicyParameters;
28 import org.onap.policy.common.logging.flexlogger.FlexLogger;
29 import org.onap.policy.common.logging.flexlogger.Logger;
30 import org.onap.policy.pdp.rest.api.utils.PolicyApiUtils;
31 import org.onap.policy.rest.adapter.PolicyRestAdapter;
32 import org.onap.policy.rest.util.PolicyValidation;
33 import org.onap.policy.rest.util.PolicyValidationRequestWrapper;
34 import org.onap.policy.xacml.api.XACMLErrorConstants;
35 import org.springframework.http.HttpStatus;
36
37 import com.google.common.base.Strings;
38
39 public class CreateUpdatePolicyServiceImpl implements CreateUpdatePolicyService {
40         private static final Logger LOGGER = FlexLogger.getLogger(CreateUpdatePolicyServiceImpl.class.getName());
41     
42     private String policyResult = null;
43     private HttpStatus status = HttpStatus.BAD_REQUEST;
44     private Boolean updateFlag = false;
45     private String message = null;
46     private PolicyParameters policyParameters = new PolicyParameters();
47     private String policyName = null;
48     private String policyScope = null;
49     private String date = null;
50     
51         public CreateUpdatePolicyServiceImpl(PolicyParameters policyParameters,
52                         String requestID, boolean updateFlag) {
53                 this.updateFlag = updateFlag;
54         this.policyParameters = policyParameters;
55         if(policyParameters.getRequestID()==null){
56             UUID requestUUID = null;
57             if (requestID != null && !requestID.isEmpty()) {
58                 try {
59                     requestUUID = UUID.fromString(requestID);
60                 } catch (IllegalArgumentException e) {
61                     requestUUID = UUID.randomUUID();
62                     LOGGER.info("Generated Random UUID: " + requestUUID.toString(), e);
63                 }
64             }else{
65                 requestUUID = UUID.randomUUID();
66                 LOGGER.info("Generated Random UUID: " + requestUUID.toString());
67             }
68             this.policyParameters.setRequestID(requestUUID);
69         }
70         try{
71             run();
72             specialCheck();
73         }catch(PolicyException e){
74             policyResult = XACMLErrorConstants.ERROR_DATA_ISSUE + e;
75             status = HttpStatus.BAD_REQUEST;
76         }
77     }
78
79     public void run() throws PolicyException{
80         // Check Validation. 
81         if(!getValidation()){
82             LOGGER.error(message);
83             throw new PolicyException(message);
84         }
85         // Get Result. 
86         try{
87             status = HttpStatus.OK;
88             policyResult = processResult();
89         }catch (Exception e){
90             LOGGER.error(XACMLErrorConstants.ERROR_DATA_ISSUE + e);
91             status = HttpStatus.BAD_REQUEST;
92             throw new PolicyException(e);
93         }
94     }
95     
96     @SuppressWarnings("incomplete-switch")
97     public String processResult() throws PolicyException{
98         String response = null;
99         if(policyParameters.getPolicyConfigType()!=null){
100             // This is a Config Type Policy. 
101             switch(policyParameters.getPolicyConfigType()){
102             case BRMS_PARAM:
103                 BRMSParamPolicyService bRMSParamPolicyService = new BRMSParamPolicyService(policyName, policyScope, policyParameters, date);
104                 // Check Validation. 
105                 if(!bRMSParamPolicyService.getValidation()){
106                     LOGGER.error(bRMSParamPolicyService.getMessage());
107                     status = HttpStatus.BAD_REQUEST;
108                     return bRMSParamPolicyService.getMessage();
109                 }
110                 // Get Result. 
111                 response = bRMSParamPolicyService.getResult(updateFlag);
112                 break;
113             case BRMS_RAW:
114                 BRMSRawPolicyService bRMSRawPolicyService = new BRMSRawPolicyService(policyName, policyScope, policyParameters, date);
115                 // Check Validation. 
116                 if(!bRMSRawPolicyService.getValidation()){
117                     LOGGER.error(bRMSRawPolicyService.getMessage());
118                     status = HttpStatus.BAD_REQUEST;
119                     return bRMSRawPolicyService.getMessage();
120                 }
121                 // Get Result. 
122                 response = bRMSRawPolicyService.getResult(updateFlag);
123                 break;
124             case Base:
125                 ConfigPolicyService configPolicyService = new ConfigPolicyService(policyName, policyScope, policyParameters, date);
126                 // Check Validation. 
127                 if(!configPolicyService.getValidation()){
128                     LOGGER.error(configPolicyService.getMessage());
129                     status = HttpStatus.BAD_REQUEST;
130                     return configPolicyService.getMessage();
131                 }
132                 // Get Result. 
133                 response = configPolicyService.getResult(updateFlag);
134                 break;
135             case ClosedLoop_Fault:
136                 ClosedLoopFaultPolicyService closedLoopFaultPolicyService = new ClosedLoopFaultPolicyService(policyName, policyScope, policyParameters, date);
137                 // Check Validation. 
138                 if(!closedLoopFaultPolicyService.getValidation()){
139                     LOGGER.error(closedLoopFaultPolicyService.getMessage());
140                     status = HttpStatus.BAD_REQUEST;
141                     return closedLoopFaultPolicyService.getMessage();
142                 }
143                 // Get Result. 
144                 response = closedLoopFaultPolicyService.getResult(updateFlag);
145                 break;
146             case ClosedLoop_PM:
147                 ClosedLoopPMPolicyService closedLoopPMPolicyService = new ClosedLoopPMPolicyService(policyName, policyScope, policyParameters, date);
148                 // Check Validation. 
149                 if(!closedLoopPMPolicyService.getValidation()){
150                     LOGGER.error(closedLoopPMPolicyService.getMessage());
151                     status = HttpStatus.BAD_REQUEST;
152                     return closedLoopPMPolicyService.getMessage();
153                 }
154                 // Get Result. 
155                 response = closedLoopPMPolicyService.getResult(updateFlag);
156                 break;
157             case Firewall:
158                 FirewallPolicyService firewallPolicyService = new FirewallPolicyService(policyName, policyScope, policyParameters, date);
159                 // Check Validation. 
160                 if(!firewallPolicyService.getValidation()){
161                     LOGGER.error(firewallPolicyService.getMessage());
162                     status = HttpStatus.BAD_REQUEST;
163                     return firewallPolicyService.getMessage();
164                 }
165                 // Get Result. 
166                 response = firewallPolicyService.getResult(updateFlag);
167                 break;
168             case MicroService:
169                 MicroServicesPolicyService microServicesPolicyService = new MicroServicesPolicyService(policyName, policyScope, policyParameters, date);
170                 // Check Validation. 
171                 if(!microServicesPolicyService.getValidation()){
172                     LOGGER.error(microServicesPolicyService.getMessage());
173                     status = HttpStatus.BAD_REQUEST;
174                     return microServicesPolicyService.getMessage();
175                 }
176                 // Get Result. 
177                 response = microServicesPolicyService.getResult(updateFlag);
178                 break;
179             default:
180                 message = XACMLErrorConstants.ERROR_DATA_ISSUE+ " Invalid Config Type Present";
181                 LOGGER.error(message);
182                 status = HttpStatus.BAD_REQUEST;
183                 return message;
184             }
185         }else if (policyParameters.getPolicyClass()!=null){
186             switch (policyParameters.getPolicyClass()){
187             case Action:
188                 ActionPolicyService actionPolicyService = new ActionPolicyService(policyScope, policyName, policyParameters);
189                 // Check Validation. 
190                 if(!actionPolicyService.getValidation()){
191                     LOGGER.error(actionPolicyService.getMessage());
192                     status = HttpStatus.BAD_REQUEST;
193                     return actionPolicyService.getMessage();
194                 }
195                 // Get Result. 
196                 response = actionPolicyService.getResult(updateFlag);
197                 break;
198             case Decision:
199                 DecisionPolicyService decisionPolicyService = new DecisionPolicyService(policyScope, policyName, policyParameters);
200                 // Check Validation. 
201                 if(!decisionPolicyService.getValidation()){
202                     LOGGER.error(decisionPolicyService.getMessage());
203                     status = HttpStatus.BAD_REQUEST;
204                     return decisionPolicyService.getMessage();
205                 }
206                 // Get Result. 
207                 response = decisionPolicyService.getResult(updateFlag);
208                 break;
209             }
210         }else {
211             message = XACMLErrorConstants.ERROR_DATA_ISSUE + "No Policy Class found.";
212             LOGGER.error(message);
213             status = HttpStatus.BAD_REQUEST;
214             response = message;
215         }
216         return response;
217     }
218
219     protected boolean getValidation() {
220         
221         PolicyValidation validation = new PolicyValidation();
222         
223                 StringBuilder responseString;
224                 
225         if (policyParameters != null) {
226                 
227                 if (!Strings.isNullOrEmpty(policyParameters.getPolicyName())){
228                 if (policyParameters.getPolicyName().contains(".")) {
229                     policyName = policyParameters.getPolicyName().substring(policyParameters.getPolicyName().lastIndexOf('.') + 1,
230                             policyParameters.getPolicyName().length());
231                     policyScope = policyParameters.getPolicyName().substring(0,policyParameters.getPolicyName().lastIndexOf('.'));
232                     policyParameters.setPolicyName(policyName);
233                     LOGGER.info("Name is " + policyName + "   scope is " + policyScope);
234                 } else {
235                     message = XACMLErrorConstants.ERROR_DATA_ISSUE + "Policy Scope: No Policy Scope given";
236                         LOGGER.error("Common validation did not return success:  " + message);
237                     return false;
238                 }
239                 } else {
240                         message = XACMLErrorConstants.ERROR_DATA_ISSUE + "PolicyName: PolicyName Should not be empty";
241                         LOGGER.error("Common validation did not return success:  " + message);
242                         return false;
243                 }
244                 
245                 if(policyParameters.getPolicyClass() != null && "Config".equals(policyParameters.getPolicyClass().toString())){
246                         String policyConfigType = policyParameters.getPolicyConfigType().toString();
247                         if(!"BRMS_Param".equalsIgnoreCase(policyConfigType) && Strings.isNullOrEmpty(policyParameters.getConfigBody())){
248                                 message = XACMLErrorConstants.ERROR_DATA_ISSUE + "ConfigBody: No Config Body given";
249                         LOGGER.error("Common validation did not return success:  " + message);
250                     return false;
251                         }
252                 }
253
254                 try {
255                         PolicyValidationRequestWrapper wrapper = new PolicyValidationRequestWrapper();                          
256                         PolicyRestAdapter policyData = wrapper.populateRequestParameters(policyParameters);
257                         if(policyData!=null) {
258                                 responseString = validation.validatePolicy(policyData);
259                         } else {
260                                 message = XACMLErrorConstants.ERROR_DATA_ISSUE+ " improper JSON object : " + policyParameters.getConfigBody();
261                                 return false;
262                         }
263                         } catch (Exception e) {
264                                 LOGGER.error("Exception Occured during Policy Validation" +e);
265                                 if(e.getMessage()!=null){
266                                         if("Action".equals(policyParameters.getPolicyClass().toString()) && e.getMessage().contains("Index:")){
267                                                 message = XACMLErrorConstants.ERROR_DATA_ISSUE + "Rule Algorithms: One or more Fields in Rule Algorithms is Empty.";
268                                         } else {
269                                                 message = XACMLErrorConstants.ERROR_DATA_ISSUE + "Exception Occured During Policy Validation: " + e;
270                                         }
271                                 }
272                                 return false;
273                         }
274         } else {
275                 message = XACMLErrorConstants.ERROR_DATA_ISSUE + "No Policy parameters given. ";
276                 return false;
277         }
278
279         // Set some default Values. 
280         if (policyParameters.getTtlDate()!=null){
281             date = convertDate(policyParameters.getTtlDate());
282         }
283         
284         if (responseString!=null){
285                 String response = responseString.toString().substring(0, 7);
286                 if("success".equals(response)) {
287                         return true;
288                 } else {
289                         message = XACMLErrorConstants.ERROR_DATA_ISSUE + PolicyApiUtils.formatResponse(responseString);
290                         LOGGER.error("Common validation did not return success:  " + message);
291                         return false;
292                 }
293         } else {
294                         message = XACMLErrorConstants.ERROR_DATA_ISSUE + "Unknown Error Occured During Policy Validation";
295                         LOGGER.error(message);
296                         return false;
297         }
298
299     }
300     
301     protected String convertDate(Date date) {
302         String strDate = null;
303         if (date!=null) {
304             SimpleDateFormat dateformatJava = new SimpleDateFormat("dd-MM-yyyy");
305             strDate = dateformatJava.format(date);
306         }
307         return (strDate==null) ? "NA": strDate;
308     }
309
310     protected void specialCheck() {
311         if(policyResult== null || policyResult.contains("BAD REQUEST")||policyResult.contains("PE300")){
312             status = HttpStatus.BAD_REQUEST;
313         } else if (policyResult.contains("Policy Exist Error")) {
314             status = HttpStatus.CONFLICT;
315         } else if (policyResult.contains("PE200")||policyResult.contains("PE900")){
316             status = HttpStatus.INTERNAL_SERVER_ERROR;
317         }
318     }
319
320     public String getResult() {
321         return policyResult;
322     }
323
324     public HttpStatus getResponseCode() {
325         return status;
326     }
327
328 }