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