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