[POLICY-122] Policy GUI Fixes
[policy/engine.git] / ECOMP-PDP-REST / src / main / java / org / openecomp / policy / pdp / rest / api / services / SendEventService.java
1 /*-
2  * ============LICENSE_START=======================================================
3  * ECOMP-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.openecomp.policy.pdp.rest.api.services;
21
22 import java.util.ArrayList;
23 import java.util.Collection;
24 import java.util.HashSet;
25 import java.util.Map;
26 import java.util.Map.Entry;
27 import java.util.UUID;
28
29 import javax.json.Json;
30 import javax.json.JsonArrayBuilder;
31 import javax.json.JsonObject;
32 import javax.json.JsonObjectBuilder;
33
34 import org.openecomp.policy.api.EventRequestParameters;
35 import org.openecomp.policy.api.PolicyEventException;
36 import org.openecomp.policy.api.PolicyResponse;
37 import org.openecomp.policy.api.PolicyResponseStatus;
38 import org.openecomp.policy.common.logging.flexlogger.FlexLogger;
39 import org.openecomp.policy.common.logging.flexlogger.Logger;
40 import org.openecomp.policy.pdp.rest.api.models.PDPResponse;
41 import org.openecomp.policy.std.StdPolicyResponse;
42 import org.openecomp.policy.xacml.api.XACMLErrorConstants;
43 import org.springframework.http.HttpStatus;
44
45 public class SendEventService {
46     private static final Logger LOGGER = FlexLogger.getLogger(SendEventService.class.getName());
47     
48     private Collection<PolicyResponse> policyResponses = null;
49     private HttpStatus status = HttpStatus.BAD_REQUEST;
50     private EventRequestParameters eventRequestParameters = null;
51     private String message = null;
52
53     public SendEventService(EventRequestParameters eventRequestParameters,
54             String requestID) {
55         this.eventRequestParameters=eventRequestParameters;
56         if(eventRequestParameters.getRequestID()==null){
57             UUID requestUUID = null;
58             if (requestID != null && !requestID.isEmpty()) {
59                 try {
60                     requestUUID = UUID.fromString(requestID);
61                 } catch (IllegalArgumentException e) {
62                     requestUUID = UUID.randomUUID();
63                     LOGGER.info("Generated Random UUID: " + requestUUID.toString(), e);
64                 }
65             }else{
66                 requestUUID = UUID.randomUUID();
67                 LOGGER.info("Generated Random UUID: " + requestUUID.toString());
68             }
69             this.eventRequestParameters.setRequestID(requestUUID);
70         }
71         policyResponses = new ArrayList<>();
72         try{
73             run();
74         }catch(PolicyEventException e){
75             StdPolicyResponse policyResponse = new StdPolicyResponse();
76             policyResponse.setPolicyResponseMessage(XACMLErrorConstants.ERROR_DATA_ISSUE+e);
77             policyResponse.setPolicyResponseStatus(PolicyResponseStatus.NO_ACTION_REQUIRED);
78             policyResponses.add(policyResponse);
79             status = HttpStatus.BAD_REQUEST;
80         }
81     }
82
83     private void run() throws PolicyEventException{
84         // getValidation. 
85         if(!getValidation()){
86             LOGGER.error(message);
87             throw new PolicyEventException(message);
88         }
89         // Generate Request. 
90         String modelString = getModel().toString();
91         LOGGER.debug("Generated JSON Request is: " + modelString);
92         // Process Result. 
93         try {
94             PDPServices pdpServices = new PDPServices(); 
95             status = HttpStatus.OK;
96             policyResponses = eventResult(pdpServices.generateRequest(modelString, eventRequestParameters.getRequestID(),false, false));
97         } catch (Exception e) {
98             LOGGER.error(XACMLErrorConstants.ERROR_DATA_ISSUE + e);
99             status = HttpStatus.BAD_REQUEST;
100             throw new PolicyEventException(XACMLErrorConstants.ERROR_DATA_ISSUE +e);
101         }
102     }
103
104     private Collection<PolicyResponse> eventResult(
105             Collection<PDPResponse> generateRequest) {
106         Collection<PolicyResponse> result = new HashSet<>();
107         if (generateRequest == null) {
108             return result;
109         }
110         if (!generateRequest.isEmpty()) {
111             for (PDPResponse stdStatus : generateRequest) {
112                 StdPolicyResponse policyResponse = new StdPolicyResponse();
113                 policyResponse.setActionAdvised(stdStatus.getActionAdvised());
114                 policyResponse.setActionTaken(stdStatus.getActionTaken());
115                 policyResponse.setPolicyResponseMessage(stdStatus.getPolicyResponseMessage());
116                 policyResponse.setPolicyResponseStatus(stdStatus.getPolicyResponseStatus());
117                 policyResponse.setRequestAttributes(eventRequestParameters.getEventAttributes());
118                 result.add(policyResponse);
119             }
120         }
121         return result;
122     }
123
124     private JsonObject getModel() throws PolicyEventException{
125         JsonArrayBuilder resourceArray = Json.createArrayBuilder();
126         Map<String,String> eventAttributes = eventRequestParameters.getEventAttributes();
127         for (Entry<String,String> key : eventAttributes.entrySet()) {
128             if (key.getKey().isEmpty()) {
129                 String message = XACMLErrorConstants.ERROR_DATA_ISSUE + "Cannot have an Empty Key";
130                 LOGGER.error(message);
131                 throw new PolicyEventException(message);
132             }
133             JsonObjectBuilder resourceBuilder = Json.createObjectBuilder();
134             if (key.getValue().matches("[0-9]+")) {
135                 int val = Integer.parseInt(key.getValue());
136                 resourceBuilder.add("Value", val);
137             } else {
138                 resourceBuilder.add("Value", key.getValue());
139             }
140             resourceBuilder.add("AttributeId", key.getKey());
141             resourceArray.add(resourceBuilder);
142         }
143         return Json.createObjectBuilder()
144                 .add("Request", Json.createObjectBuilder()
145                                 .add("Resource",Json.createObjectBuilder()
146                                                 .add("Attribute",resourceArray)))
147                 .build();
148     }
149
150     private boolean getValidation() {
151         if (eventRequestParameters == null) {
152             message = XACMLErrorConstants.ERROR_DATA_ISSUE + "No event Parameters Given. ";
153             return false;
154         }
155         if (eventRequestParameters.getEventAttributes() == null || eventRequestParameters.getEventAttributes().isEmpty()){
156             message = XACMLErrorConstants.ERROR_DATA_ISSUE + "No event Attributes Given. ";
157             return false;
158         }
159         return true;
160     }
161
162     public Collection<PolicyResponse> getResult() {
163         return policyResponses;
164     }
165
166     public HttpStatus getResponseCode() {
167         return status;
168     }
169
170 }