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
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.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;
41 * This class implements an Apex event consumer that receives events from a REST server.
43 * @author Liam Fallon (liam.fallon@ericsson.com)
45 public class ApexRestServerConsumer extends ApexPluginsEventConsumer {
46 // Get a reference to the logger
47 private static final Logger LOGGER = LoggerFactory.getLogger(ApexRestServerConsumer.class);
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;
52 // The event receiver that will receive events from this consumer
53 private ApexEventReceiver eventReceiver;
55 // The local HTTP server to use for REST call reception if we are running a local Grizzly server
56 private HttpServletServer server;
58 // Holds the next identifier for event execution.
59 private static AtomicLong nextExecutionID = new AtomicLong(0L);
62 * Private utility to get the next candidate value for a Execution ID. This value will always be unique in a single
65 * @return the next candidate value for a Execution ID
67 private static synchronized long getNextExecutionId() {
68 return nextExecutionID.getAndIncrement();
75 public void init(final String consumerName, final EventHandlerParameters consumerParameters,
76 final ApexEventReceiver incomingEventReceiver) throws ApexEventException {
77 this.eventReceiver = incomingEventReceiver;
78 this.name = consumerName;
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);
88 // The REST parameters read from the parameter service
89 RestServerCarrierTechnologyParameters restConsumerProperties =
90 (RestServerCarrierTechnologyParameters) consumerParameters.getCarrierTechnologyParameters();
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);
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);
111 // Instantiate the standalone server
112 LOGGER.info("Creating the Apex Rest Server");
113 createServer(restConsumerProperties);
115 while (!server.isAlive()) {
116 ThreadUtilities.sleep(REST_SERVER_CONSUMER_WAIT_SLEEP_TIME);
120 // Register this consumer with the REST server end point
121 RestServerEndpoint.registerApexRestServerConsumer(this.name, this);
124 private void createServer(RestServerCarrierTechnologyParameters restConsumerProperties) {
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());
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);
145 * Receive an event for processing in Apex.
147 * @param event the event to receive
148 * @return the response from Apex
150 public Response receiveEvent(final String event) {
151 // Get an execution ID for the event
152 final long executionId = getNextExecutionId();
154 if (LOGGER.isDebugEnabled()) {
155 String message = name + ": sending event " + name + '_' + executionId + " to Apex, event=" + event;
156 LOGGER.debug(message);
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();
169 final SynchronousEventCache synchronousEventCache =
170 (SynchronousEventCache) peerReferenceMap.get(EventHandlerPeeredMode.SYNCHRONOUS);
171 // Wait until the event is in the cache of events sent to apex
173 ThreadUtilities.sleep(REST_SERVER_CONSUMER_WAIT_SLEEP_TIME);
175 while (!synchronousEventCache.existsEventToApex(executionId));
177 // Now wait for the reply or for the event to time put
179 ThreadUtilities.sleep(REST_SERVER_CONSUMER_WAIT_SLEEP_TIME);
181 // Check if we have received an answer from Apex
182 if (synchronousEventCache.existsEventFromApex(executionId)) {
183 // We have received a response event, read and remove the response event and remove the sent event from
185 final Object responseEvent = synchronousEventCache.removeCachedEventFromApexIfExists(executionId);
186 synchronousEventCache.removeCachedEventToApexIfExists(executionId);
188 // Return the event as a response to the call
189 return Response.status(Response.Status.OK.getStatusCode()).entity(responseEvent.toString()).build();
192 while (synchronousEventCache.existsEventToApex(executionId));
194 // The event timed out
195 final String errorMessage = "processing of event on event consumer " + name + " timed out, event=" + event;
196 LOGGER.warn(errorMessage);
197 return Response.status(Response.Status.INTERNAL_SERVER_ERROR.getStatusCode())
198 .entity("{'errorMessage', '" + errorMessage + "'}").build();
206 // Keep the consumer thread alive until it is shut down. We do not currently do anything in the thread but may
207 // do supervision in the future
208 while (consumerThread.isAlive() && !stopOrderedFlag) {
209 ThreadUtilities.sleep(REST_SERVER_CONSUMER_WAIT_SLEEP_TIME);
212 if (server != null) {
222 stopOrderedFlag = true;
224 while (consumerThread.isAlive()) {
225 ThreadUtilities.sleep(REST_SERVER_CONSUMER_WAIT_SLEEP_TIME);
227 if (server != null) {