2 * ============LICENSE_START=======================================================
3 * Copyright (C) 2016-2018 Ericsson. All rights reserved.
4 * Modifications Copyright (C) 2019 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
10 * http://www.apache.org/licenses/LICENSE-2.0
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.
18 * SPDX-License-Identifier: Apache-2.0
19 * ============LICENSE_END=========================================================
22 package org.onap.policy.apex.plugins.event.carrier.restserver;
24 import java.util.EnumMap;
26 import java.util.Properties;
27 import java.util.concurrent.atomic.AtomicLong;
28 import javax.ws.rs.core.Response;
29 import org.onap.policy.apex.core.infrastructure.threading.ApplicationThreadFactory;
30 import org.onap.policy.apex.core.infrastructure.threading.ThreadUtilities;
31 import org.onap.policy.apex.service.engine.event.ApexEventConsumer;
32 import org.onap.policy.apex.service.engine.event.ApexEventException;
33 import org.onap.policy.apex.service.engine.event.ApexEventReceiver;
34 import org.onap.policy.apex.service.engine.event.PeeredReference;
35 import org.onap.policy.apex.service.engine.event.SynchronousEventCache;
36 import org.onap.policy.apex.service.parameters.eventhandler.EventHandlerParameters;
37 import org.onap.policy.apex.service.parameters.eventhandler.EventHandlerPeeredMode;
38 import org.onap.policy.common.endpoints.http.server.HttpServletServer;
39 import org.onap.policy.common.endpoints.http.server.HttpServletServerFactoryInstance;
40 import org.onap.policy.common.gson.GsonMessageBodyHandler;
41 import org.slf4j.Logger;
42 import org.slf4j.LoggerFactory;
45 * This class implements an Apex event consumer that receives events from a REST server.
47 * @author Liam Fallon (liam.fallon@ericsson.com)
49 public class ApexRestServerConsumer implements ApexEventConsumer, Runnable {
50 // Get a reference to the logger
51 private static final Logger LOGGER = LoggerFactory.getLogger(ApexRestServerConsumer.class);
53 // The amount of time to wait in milliseconds between checks that the consumer thread has stopped
54 private static final long REST_SERVER_CONSUMER_WAIT_SLEEP_TIME = 50;
56 // The event receiver that will receive events from this consumer
57 private ApexEventReceiver eventReceiver;
59 // The name for this consumer
60 private String name = null;
62 // The peer references for this event handler
63 private Map<EventHandlerPeeredMode, PeeredReference> peerReferenceMap = new EnumMap<>(EventHandlerPeeredMode.class);
65 // The consumer thread and stopping flag
66 private Thread consumerThread;
67 private boolean stopOrderedFlag = false;
69 // The local HTTP server to use for REST call reception if we are running a local Grizzly server
70 private HttpServletServer server;
72 // Holds the next identifier for event execution.
73 private static AtomicLong nextExecutionID = new AtomicLong(0L);
76 * Private utility to get the next candidate value for a Execution ID. This value will always be unique in a single
79 * @return the next candidate value for a Execution ID
81 private static synchronized long getNextExecutionId() {
82 return nextExecutionID.getAndIncrement();
89 public void init(final String consumerName, final EventHandlerParameters consumerParameters,
90 final ApexEventReceiver incomingEventReceiver) throws ApexEventException {
91 this.eventReceiver = incomingEventReceiver;
92 this.name = consumerName;
94 // Check and get the REST Properties
95 if (!(consumerParameters.getCarrierTechnologyParameters() instanceof RestServerCarrierTechnologyParameters)) {
96 final String errorMessage =
97 "specified consumer properties are not applicable to REST Server consumer (" + this.name + ")";
98 LOGGER.warn(errorMessage);
99 throw new ApexEventException(errorMessage);
102 // The REST parameters read from the parameter service
103 RestServerCarrierTechnologyParameters restConsumerProperties =
104 (RestServerCarrierTechnologyParameters) consumerParameters.getCarrierTechnologyParameters();
106 // Check if we are in synchronous mode
107 if (!consumerParameters.isPeeredMode(EventHandlerPeeredMode.SYNCHRONOUS)) {
108 final String errorMessage =
109 "REST Server consumer (" + this.name + ") must run in synchronous mode with a REST Server producer";
110 LOGGER.warn(errorMessage);
111 throw new ApexEventException(errorMessage);
114 // Check if we're in standalone mode
115 if (restConsumerProperties.isStandalone()) {
116 // Check if host and port are defined
117 if (restConsumerProperties.getHost() == null || restConsumerProperties.getPort() == -1) {
118 final String errorMessage =
119 "the parameters \"host\" and \"port\" must be defined for REST Server consumer (" + this.name
120 + ") in standalone mode";
121 LOGGER.warn(errorMessage);
122 throw new ApexEventException(errorMessage);
125 // Instantiate the standalone server
126 LOGGER.info("Creating the Apex Rest Server");
127 createServer(restConsumerProperties);
129 while (!server.isAlive()) {
130 ThreadUtilities.sleep(REST_SERVER_CONSUMER_WAIT_SLEEP_TIME);
134 // Register this consumer with the REST server end point
135 RestServerEndpoint.registerApexRestServerConsumer(this.name, this);
138 private void createServer(RestServerCarrierTechnologyParameters restConsumerProperties) {
140 server = HttpServletServerFactoryInstance.getServerFactory().build(
141 restConsumerProperties.getName(),
142 restConsumerProperties.isHttps(),
143 restConsumerProperties.getHost(),
144 restConsumerProperties.getPort(), null, true, false);
145 if (restConsumerProperties.isAaf()) {
146 server.addFilterClass(null, ApexRestServerAafFilter.class.getName());
148 server.addServletClass(null, RestServerEndpoint.class.getName());
149 server.addServletClass(null, AccessControlFilter.class.getName());
150 server.setSerializationProvider(GsonMessageBodyHandler.class.getName());
151 if (null != restConsumerProperties.getUserName()
152 && null != restConsumerProperties.getPassword()) {
153 server.setBasicAuthentication(restConsumerProperties.getUserName(),
154 restConsumerProperties.getPassword(), null);
162 public void start() {
163 // Configure and start the event reception thread
164 final String threadName = this.getClass().getName() + ":" + this.name;
165 consumerThread = new ApplicationThreadFactory(threadName).newThread(this);
166 consumerThread.setDaemon(true);
167 consumerThread.start();
174 public String getName() {
182 public PeeredReference getPeeredReference(final EventHandlerPeeredMode peeredMode) {
183 return peerReferenceMap.get(peeredMode);
190 public void setPeeredReference(final EventHandlerPeeredMode peeredMode, final PeeredReference peeredReference) {
191 peerReferenceMap.put(peeredMode, peeredReference);
195 * Receive an event for processing in Apex.
197 * @param event the event to receive
198 * @return the response from Apex
200 public Response receiveEvent(final String event) {
201 // Get an execution ID for the event
202 final long executionId = getNextExecutionId();
204 if (LOGGER.isDebugEnabled()) {
205 String message = name + ": sending event " + name + '_' + executionId + " to Apex, event=" + event;
206 LOGGER.debug(message);
210 // Send the event into Apex
211 eventReceiver.receiveEvent(executionId, new Properties(), event);
212 } catch (final Exception e) {
213 final String errorMessage = "error receiving events on event consumer " + name + ", " + e.getMessage();
214 LOGGER.warn(errorMessage, e);
215 return Response.status(Response.Status.INTERNAL_SERVER_ERROR.getStatusCode())
216 .entity("{'errorMessage', '" + errorMessage + "'}").build();
219 final SynchronousEventCache synchronousEventCache =
220 (SynchronousEventCache) peerReferenceMap.get(EventHandlerPeeredMode.SYNCHRONOUS);
221 // Wait until the event is in the cache of events sent to apex
223 ThreadUtilities.sleep(REST_SERVER_CONSUMER_WAIT_SLEEP_TIME);
225 while (!synchronousEventCache.existsEventToApex(executionId));
227 // Now wait for the reply or for the event to time put
229 ThreadUtilities.sleep(REST_SERVER_CONSUMER_WAIT_SLEEP_TIME);
231 // Check if we have received an answer from Apex
232 if (synchronousEventCache.existsEventFromApex(executionId)) {
233 // We have received a response event, read and remove the response event and remove the sent event from
235 final Object responseEvent = synchronousEventCache.removeCachedEventFromApexIfExists(executionId);
236 synchronousEventCache.removeCachedEventToApexIfExists(executionId);
238 // Return the event as a response to the call
239 return Response.status(Response.Status.OK.getStatusCode()).entity(responseEvent.toString()).build();
242 while (synchronousEventCache.existsEventToApex(executionId));
244 // The event timed out
245 final String errorMessage = "processing of event on event consumer " + name + " timed out, event=" + event;
246 LOGGER.warn(errorMessage);
247 return Response.status(Response.Status.INTERNAL_SERVER_ERROR.getStatusCode())
248 .entity("{'errorMessage', '" + errorMessage + "'}").build();
256 // Keep the consumer thread alive until it is shut down. We do not currently do anything in the thread but may
257 // do supervision in the future
258 while (consumerThread.isAlive() && !stopOrderedFlag) {
259 ThreadUtilities.sleep(REST_SERVER_CONSUMER_WAIT_SLEEP_TIME);
262 if (server != null) {
272 stopOrderedFlag = true;
274 while (consumerThread.isAlive()) {
275 ThreadUtilities.sleep(REST_SERVER_CONSUMER_WAIT_SLEEP_TIME);
277 if (server != null) {