ca2d797b951b57ea36044adc62541f595ffe5828
[policy/apex-pdp.git] /
1 /*-
2  * ============LICENSE_START=======================================================
3  *  Copyright (C) 2016-2018 Ericsson. All rights reserved.
4  * ================================================================================
5  * Licensed under the Apache License, Version 2.0 (the "License");
6  * you may not use this file except in compliance with the License.
7  * You may obtain a copy of the License at
8  *
9  *      http://www.apache.org/licenses/LICENSE-2.0
10  *
11  * Unless required by applicable law or agreed to in writing, software
12  * distributed under the License is distributed on an "AS IS" BASIS,
13  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
14  * See the License for the specific language governing permissions and
15  * limitations under the License.
16  *
17  * SPDX-License-Identifier: Apache-2.0
18  * ============LICENSE_END=========================================================
19  */
20
21 package org.onap.policy.apex.plugins.event.carrier.restserver;
22
23 import java.util.LinkedHashMap;
24 import java.util.Map;
25
26 import javax.ws.rs.Consumes;
27 import javax.ws.rs.GET;
28 import javax.ws.rs.POST;
29 import javax.ws.rs.PUT;
30 import javax.ws.rs.Path;
31 import javax.ws.rs.PathParam;
32 import javax.ws.rs.Produces;
33 import javax.ws.rs.core.MediaType;
34 import javax.ws.rs.core.Response;
35
36 import org.slf4j.Logger;
37 import org.slf4j.LoggerFactory;
38
39 /**
40  * The Class RestServerEndpoint is the end point servlet class for handling REST requests and responses to and from
41  * Apex.
42  *
43  * @author Liam Fallon (liam.fallon@ericsson.com)
44  */
45 @Path("/{eventInput}")
46 @Produces(
47     { MediaType.APPLICATION_JSON })
48 @Consumes(
49     { MediaType.APPLICATION_JSON })
50 public class RestServerEndpoint {
51     // Get a reference to the logger
52     private static final Logger LOGGER = LoggerFactory.getLogger(RestServerEndpoint.class);
53
54     // Statistics on the amount of HTTP messages handled
55     private static int getMessagesReceived = 0;
56     private static int postEventMessagesReceived = 0;
57     private static int putEventMessagesReceived = 0;
58
59     // This map is used to hold all the REST server event inputs. This is used to determine which consumer to send input
60     // events to
61     private static Map<String, ApexRestServerConsumer> consumerMap = new LinkedHashMap<>();
62
63     // The ID of this event input. This gets injected from the URL.
64     @PathParam("eventInput")
65     private String eventInputId = null;
66
67     /**
68      * Register an Apex consumer with the REST server end point.
69      *
70      * @param consumerEventInputId The event input ID that indicates this consumer shoud be used
71      * @param consumer The consumer to register
72      */
73     public static void registerApexRestServerConsumer(final String consumerEventInputId,
74                     final ApexRestServerConsumer consumer) {
75         consumerMap.put(consumerEventInputId, consumer);
76     }
77
78     /**
79      * Get statistics on apex REST event handling.
80      *
81      * @return the response
82      */
83     @Path("/Status")
84     @GET
85     public Response serviceGetStats() {
86         incrementGetMessages();
87         return Response.status(Response.Status.OK.getStatusCode())
88                         .entity("{\n" + "\"INPUTS\": \"" + consumerMap.keySet() + "\",\n" + "\"STAT\": "
89                                         + getMessagesReceived + ",\n" + "\"POST\": " + postEventMessagesReceived + ",\n"
90                                         + "\"PUT\":  " + putEventMessagesReceived + "\n}")
91                         .build();
92     }
93
94     /**
95      * Service post request, an incoming event over RETS to Apex.
96      *
97      * @param jsonString the JSON string containing the data coming in on the REST call
98      * @return the response event to the request
99      */
100     @Path("/EventIn")
101     @POST
102     public Response servicePostRequest(final String jsonString) {
103         incrementPostEventMessages();
104
105         if (LOGGER.isDebugEnabled()) {
106             String message = "event input " + eventInputId + ", received POST of event \"" + jsonString + "\"";
107             LOGGER.debug(message);
108         }
109
110         // Common handler method for POST and PUT requests
111         return handleEvent(jsonString);
112     }
113
114     /**
115      * Service put request, an incoming event over RETS to Apex.
116      *
117      * @param jsonString the JSON string containing the data coming in on the REST call
118      * @return the response event to the request
119      */
120     @Path("/EventIn")
121     @PUT
122     public Response servicePutRequest(final String jsonString) {
123         incrementPutEventMessages();
124
125         if (LOGGER.isDebugEnabled()) {
126             String message = "event input \"" + eventInputId + "\", received PUT of event \"" + jsonString + "\"";
127             LOGGER.debug(message);
128         }
129
130         // Common handler method for POST and PUT requests
131         return handleEvent(jsonString);
132     }
133
134     /**
135      * Common event handler for events received on POST and PUT messages.
136      *
137      * @param jsonString the JSON string containing the data coming in on the REST call
138      * @return the response event to the request
139      */
140     private Response handleEvent(final String jsonString) {
141         // Find the correct consumer for this REST message
142         final ApexRestServerConsumer eventConsumer = consumerMap.get(eventInputId);
143         if (eventConsumer == null) {
144             final String errorMessage = "event input " + eventInputId
145                             + " is not defined in the Apex configuration file";
146             LOGGER.warn(errorMessage);
147             return Response.status(Response.Status.BAD_REQUEST.getStatusCode())
148                             .entity("{'errorMessage', '" + errorMessage + "'}").build();
149         }
150
151         return eventConsumer.receiveEvent(jsonString);
152     }
153
154     /**
155      * Increment number of get messages received.
156      */
157     private static void incrementGetMessages() {
158         getMessagesReceived++;
159     }
160
161     /**
162      * Increment number of get messages received.
163      */
164     private static void incrementPutEventMessages() {
165         putEventMessagesReceived++;
166     }
167
168     /**
169      * Increment number of get messages received.
170      */
171     private static void incrementPostEventMessages() {
172         postEventMessagesReceived++;
173     }
174 }