Changes for checkstyle 8.32
[policy/apex-pdp.git] / plugins / plugins-event / plugins-event-carrier / plugins-event-carrier-restserver / src / main / java / org / onap / policy / apex / plugins / event / carrier / restserver / ApexRestServerConsumer.java
1 /*-
2  * ============LICENSE_START=======================================================
3  *  Copyright (C) 2016-2018 Ericsson. All rights reserved.
4  *  Modifications Copyright (C) 2019-2020 Nordix Foundation.
5  * ================================================================================
6  * Licensed under the Apache License, Version 2.0 (the "License");
7  * you may not use this file except in compliance with the License.
8  * You may obtain a copy of the License at
9  *
10  *      http://www.apache.org/licenses/LICENSE-2.0
11  *
12  * Unless required by applicable law or agreed to in writing, software
13  * distributed under the License is distributed on an "AS IS" BASIS,
14  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
15  * See the License for the specific language governing permissions and
16  * limitations under the License.
17  *
18  * SPDX-License-Identifier: Apache-2.0
19  * ============LICENSE_END=========================================================
20  */
21
22 package org.onap.policy.apex.plugins.event.carrier.restserver;
23
24 import java.util.Properties;
25 import java.util.concurrent.atomic.AtomicLong;
26 import javax.ws.rs.core.Response;
27 import org.onap.policy.apex.core.infrastructure.threading.ThreadUtilities;
28 import org.onap.policy.apex.service.engine.event.ApexEventException;
29 import org.onap.policy.apex.service.engine.event.ApexEventReceiver;
30 import org.onap.policy.apex.service.engine.event.ApexPluginsEventConsumer;
31 import org.onap.policy.apex.service.engine.event.SynchronousEventCache;
32 import org.onap.policy.apex.service.parameters.eventhandler.EventHandlerParameters;
33 import org.onap.policy.apex.service.parameters.eventhandler.EventHandlerPeeredMode;
34 import org.onap.policy.common.endpoints.http.server.HttpServletServer;
35 import org.onap.policy.common.endpoints.http.server.HttpServletServerFactoryInstance;
36 import org.onap.policy.common.gson.GsonMessageBodyHandler;
37 import org.slf4j.Logger;
38 import org.slf4j.LoggerFactory;
39
40 /**
41  * This class implements an Apex event consumer that receives events from a REST server.
42  *
43  * @author Liam Fallon (liam.fallon@ericsson.com)
44  */
45 public class ApexRestServerConsumer extends ApexPluginsEventConsumer {
46     // Get a reference to the logger
47     private static final Logger LOGGER = LoggerFactory.getLogger(ApexRestServerConsumer.class);
48
49     // The amount of time to wait in milliseconds between checks that the consumer thread has stopped
50     private static final long REST_SERVER_CONSUMER_WAIT_SLEEP_TIME = 50;
51
52     // The event receiver that will receive events from this consumer
53     private ApexEventReceiver eventReceiver;
54
55     // The local HTTP server to use for REST call reception if we are running a local Grizzly server
56     private HttpServletServer server;
57
58     // Holds the next identifier for event execution.
59     private static AtomicLong nextExecutionID = new AtomicLong(0L);
60
61     /**
62      * Private utility to get the next candidate value for a Execution ID. This value will always be unique in a single
63      * JVM
64      *
65      * @return the next candidate value for a Execution ID
66      */
67     private static synchronized long getNextExecutionId() {
68         return nextExecutionID.getAndIncrement();
69     }
70
71     /**
72      * {@inheritDoc}.
73      */
74     @Override
75     public void init(final String consumerName, final EventHandlerParameters consumerParameters,
76             final ApexEventReceiver incomingEventReceiver) throws ApexEventException {
77         this.eventReceiver = incomingEventReceiver;
78         this.name = consumerName;
79
80         // Check and get the REST Properties
81         if (!(consumerParameters.getCarrierTechnologyParameters() instanceof RestServerCarrierTechnologyParameters)) {
82             final String errorMessage =
83                     "specified consumer properties are not applicable to REST Server consumer (" + this.name + ")";
84             LOGGER.warn(errorMessage);
85             throw new ApexEventException(errorMessage);
86         }
87
88         // The REST parameters read from the parameter service
89         RestServerCarrierTechnologyParameters restConsumerProperties =
90                 (RestServerCarrierTechnologyParameters) consumerParameters.getCarrierTechnologyParameters();
91
92         // Check if we are in synchronous mode
93         if (!consumerParameters.isPeeredMode(EventHandlerPeeredMode.SYNCHRONOUS)) {
94             final String errorMessage =
95                     "REST Server consumer (" + this.name + ") must run in synchronous mode with a REST Server producer";
96             LOGGER.warn(errorMessage);
97             throw new ApexEventException(errorMessage);
98         }
99
100         // Check if we're in standalone mode
101         if (restConsumerProperties.isStandalone()) {
102             // Check if host and port are defined
103             if (restConsumerProperties.getHost() == null || restConsumerProperties.getPort() == -1) {
104                 final String errorMessage =
105                         "the parameters \"host\" and \"port\" must be defined for REST Server consumer (" + this.name
106                                 + ") in standalone mode";
107                 LOGGER.warn(errorMessage);
108                 throw new ApexEventException(errorMessage);
109             }
110
111             // Instantiate the standalone server
112             LOGGER.info("Creating the Apex Rest Server");
113             createServer(restConsumerProperties);
114             server.start();
115             while (!server.isAlive()) {
116                 ThreadUtilities.sleep(REST_SERVER_CONSUMER_WAIT_SLEEP_TIME);
117             }
118         }
119
120         // Register this consumer with the REST server end point
121         RestServerEndpoint.registerApexRestServerConsumer(this.name, this);
122     }
123
124     private void createServer(RestServerCarrierTechnologyParameters restConsumerProperties) {
125
126         server = HttpServletServerFactoryInstance.getServerFactory().build(
127             restConsumerProperties.getName(),
128             restConsumerProperties.isHttps(),
129             restConsumerProperties.getHost(),
130             restConsumerProperties.getPort(), null, true, false);
131         if (restConsumerProperties.isAaf()) {
132             server.addFilterClass(null, ApexRestServerAafFilter.class.getName());
133         }
134         server.addServletClass(null, RestServerEndpoint.class.getName());
135         server.addServletClass(null, AccessControlFilter.class.getName());
136         server.setSerializationProvider(GsonMessageBodyHandler.class.getName());
137         if (null != restConsumerProperties.getUserName()
138             && null != restConsumerProperties.getPassword()) {
139             server.setBasicAuthentication(restConsumerProperties.getUserName(),
140                 restConsumerProperties.getPassword(), null);
141         }
142     }
143
144     /**
145      * Receive an event for processing in Apex.
146      *
147      * @param event the event to receive
148      * @return the response from Apex
149      */
150     public Response receiveEvent(final String event) {
151         // Get an execution ID for the event
152         final long executionId = getNextExecutionId();
153
154         if (LOGGER.isDebugEnabled()) {
155             String message = name + ": sending event " + name + '_' + executionId + " to Apex, event=" + event;
156             LOGGER.debug(message);
157         }
158
159         try {
160             // Send the event into Apex
161             eventReceiver.receiveEvent(executionId, new Properties(), event);
162         } catch (final Exception e) {
163             final String errorMessage = "error receiving events on event consumer " + name + ", " + e.getMessage();
164             LOGGER.warn(errorMessage, e);
165             return Response.status(Response.Status.INTERNAL_SERVER_ERROR.getStatusCode())
166                     .entity("{'errorMessage', '" + errorMessage + "'}").build();
167         }
168
169         final SynchronousEventCache synchronousEventCache =
170                 (SynchronousEventCache) peerReferenceMap.get(EventHandlerPeeredMode.SYNCHRONOUS);
171         // Wait until the event is in the cache of events sent to apex
172         do {
173             ThreadUtilities.sleep(REST_SERVER_CONSUMER_WAIT_SLEEP_TIME);
174         } while (!synchronousEventCache.existsEventToApex(executionId));
175
176         // Now wait for the reply or for the event to time put
177         do {
178             ThreadUtilities.sleep(REST_SERVER_CONSUMER_WAIT_SLEEP_TIME);
179
180             // Check if we have received an answer from Apex
181             if (synchronousEventCache.existsEventFromApex(executionId)) {
182                 // We have received a response event, read and remove the response event and remove the sent event from
183                 // the cache
184                 final Object responseEvent = synchronousEventCache.removeCachedEventFromApexIfExists(executionId);
185                 synchronousEventCache.removeCachedEventToApexIfExists(executionId);
186
187                 // Return the event as a response to the call
188                 return Response.status(Response.Status.OK.getStatusCode()).entity(responseEvent.toString()).build();
189             }
190         } while (synchronousEventCache.existsEventToApex(executionId));
191
192         // The event timed out
193         final String errorMessage = "processing of event on event consumer " + name + " timed out, event=" + event;
194         LOGGER.warn(errorMessage);
195         return Response.status(Response.Status.INTERNAL_SERVER_ERROR.getStatusCode())
196                 .entity("{'errorMessage', '" + errorMessage + "'}").build();
197     }
198
199     /**
200      * {@inheritDoc}.
201      */
202     @Override
203     public void run() {
204         // Keep the consumer thread alive until it is shut down. We do not currently do anything in the thread but may
205         // do supervision in the future
206         while (consumerThread.isAlive() && !stopOrderedFlag) {
207             ThreadUtilities.sleep(REST_SERVER_CONSUMER_WAIT_SLEEP_TIME);
208         }
209
210         if (server != null) {
211             server.shutdown();
212         }
213     }
214
215     /**
216      * {@inheritDoc}.
217      */
218     @Override
219     public void stop() {
220         stopOrderedFlag = true;
221
222         while (consumerThread.isAlive()) {
223             ThreadUtilities.sleep(REST_SERVER_CONSUMER_WAIT_SLEEP_TIME);
224         }
225         if (server != null) {
226             server.stop();
227         }
228     }
229 }