Update license date and text
[aai/router-core.git] / src / main / java / org / onap / aai / event / EventBusConsumer.java
1 /**
2  * ============LICENSE_START=======================================================
3  * org.onap.aai
4  * ================================================================================
5  * Copyright © 2017-2018 AT&T Intellectual Property. All rights reserved.
6  * Copyright © 2017-2018 Amdocs
7  * ================================================================================
8  * Licensed under the Apache License, Version 2.0 (the "License");
9  * you may not use this file except in compliance with the License.
10  * You may obtain a copy of the License at
11  *
12  *       http://www.apache.org/licenses/LICENSE-2.0
13  *
14  * Unless required by applicable law or agreed to in writing, software
15  * distributed under the License is distributed on an "AS IS" BASIS,
16  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
17  * See the License for the specific language governing permissions and
18  * limitations under the License.
19  * ============LICENSE_END=========================================================
20  */
21 package org.onap.aai.event;
22
23 import com.att.nsa.cambria.client.CambriaClientBuilders;
24 import com.att.nsa.cambria.client.CambriaClientBuilders.ConsumerBuilder;
25 import com.att.nsa.cambria.client.CambriaConsumer;
26
27 import org.apache.camel.Exchange;
28 import org.apache.camel.Message;
29 import org.apache.camel.Processor;
30 import org.apache.camel.impl.ScheduledPollConsumer;
31 import org.onap.aai.logging.RouterCoreMsgs;
32 import org.onap.aai.cl.api.Logger;
33 import org.onap.aai.cl.eelf.LoggerFactory;
34 import org.onap.aai.cl.mdc.MdcContext;
35
36 import java.net.MalformedURLException;
37 import java.security.GeneralSecurityException;
38 import java.util.Arrays;
39 import java.util.List;
40 import java.util.UUID;
41 import java.util.concurrent.ScheduledThreadPoolExecutor;
42
43 /**
44  * The consumer component which is used to pull messages off of the event bus and send them to the
45  * next processor in the route chain. This type of consumer is based off of a scheduled poller so
46  * that events are pulled on a regular basis.
47  */
48 public class EventBusConsumer extends ScheduledPollConsumer {
49
50   private Logger logger = LoggerFactory.getInstance().getLogger(EventBusConsumer.class);
51   private Logger auditLogger = LoggerFactory.getInstance().getAuditLogger(EventBusConsumer.class);
52   private final EventBusEndpoint endpoint;
53
54   private CambriaConsumer consumer;
55
56   /**
57    * EventBusConsumer Constructor.
58    */
59   public EventBusConsumer(EventBusEndpoint endpoint, Processor processor) {
60     super(endpoint, processor);
61     super.setDelay(endpoint.getPollingDelay());
62     this.endpoint = endpoint;
63
64     setScheduledExecutorService(new ScheduledThreadPoolExecutor(endpoint.getPoolSize()));
65
66     String[] urls = endpoint.getUrl().split(",");
67
68     List<String> urlList = null;
69
70     if (urls != null) {
71       urlList = Arrays.asList(urls);
72     }
73
74     try {
75
76       ConsumerBuilder consumerBuilder = new CambriaClientBuilders.ConsumerBuilder()
77           .usingHosts(urlList).onTopic(endpoint.getEventTopic())
78           .knownAs(endpoint.getGroupName(), endpoint.getGroupId());
79
80       String apiKey = endpoint.getApiKey();
81       String apiSecret = endpoint.getApiSecret();
82
83       if (apiKey != null && apiSecret != null) {
84         consumerBuilder.authenticatedBy(endpoint.getApiKey(), endpoint.getApiSecret());
85       }
86
87       consumer = consumerBuilder.build();
88
89     } catch (MalformedURLException | GeneralSecurityException e) {
90       logger.error(RouterCoreMsgs.EVENT_CONSUMER_CREATION_EXCEPTION, e, e.getLocalizedMessage());
91     }
92   }
93
94   /**
95    * Method which is called by the Camel process on a scheduled basis. This specific implementation
96    * reads messages off of the configured topic and schedules tasks to process them .
97    * 
98    * @return the number of messages that were processed off the event queue
99    */
100   @Override
101   protected int poll() throws Exception {
102
103     logger.debug("Checking for event on topic: " + endpoint.getEventTopic());
104
105     int processCount = 0;
106
107     Iterable<String> messages = consumer.fetch();
108
109     String topic = endpoint.getEventTopic();
110
111     for (String message : messages) {
112       Exchange exchange = endpoint.createExchange();
113       exchange.getIn().setBody(message);
114       getScheduledExecutorService().submit(new EventProcessor(exchange, topic));
115       ++processCount;
116     }
117     return processCount;
118   }
119   @Override
120   protected void doStop() throws Exception {
121     super.doStop();
122     if (consumer != null) {
123       consumer.close();
124     }
125   }
126   @Override
127   protected void doShutdown() throws Exception {
128     super.doShutdown();
129     if (consumer != null) {
130       consumer.close();
131     }
132   }
133
134   /**
135    * Class responsible for processing messages pulled off of the event bus.
136    */
137   private class EventProcessor implements Runnable {
138
139     private Exchange message;
140
141     private String topic;
142
143     EventProcessor(Exchange message, String topic) {
144       this.message = message;
145       this.topic = topic;
146     }
147         @Override
148     public void run() {
149       try {
150
151         MdcContext.initialize(UUID.randomUUID().toString(), "DataRouter", "", "Event-Bus", "");
152
153         // Sends the message to the next processor in the defined Camel route
154         getProcessor().process(message);
155
156         Message response = message.getOut();
157         if (response != null) {
158           logger.debug("Routing response: " + response.getBody());
159         }
160
161       } catch (Exception e) {
162         logger.error(RouterCoreMsgs.EVENT_PROCESSING_EXCEPTION,e,e.getLocalizedMessage());
163       } finally {
164         // log exception if an exception occurred and was not handled
165         if (message.getException() != null) {
166           logger.info(RouterCoreMsgs.PROCESS_EVENT, topic, "FAILURE");
167           auditLogger.info(RouterCoreMsgs.PROCESS_EVENT, topic, "FAILURE");
168         } else {
169           logger.info(RouterCoreMsgs.PROCESS_EVENT, topic, "SUCCESS");
170           auditLogger.info(RouterCoreMsgs.PROCESS_EVENT, topic, "SUCCESS");
171         }
172       }
173     }
174   }
175 }