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