lower code smells
[appc.git] / services / appc-dmaap-service / appc-event-listener-bundle / src / main / java / org / onap / appc / listener / AbstractListener.java
1 /*-
2  * ============LICENSE_START=======================================================
3  * ONAP : APPC
4  * ================================================================================
5  * Copyright (C) 2017-2018 AT&T Intellectual Property. All rights reserved.
6  * ================================================================================
7  * Copyright (C) 2017 Amdocs
8  * =============================================================================
9  * Modifications Copyright (C) 2019 IBM
10  * =============================================================================
11  * Licensed under the Apache License, Version 2.0 (the "License");
12  * you may not use this file except in compliance with the License.
13  * You may obtain a copy of the License at
14  * 
15  *      http://www.apache.org/licenses/LICENSE-2.0
16  * 
17  * Unless required by applicable law or agreed to in writing, software
18  * distributed under the License is distributed on an "AS IS" BASIS,
19  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
20  * See the License for the specific language governing permissions and
21  * limitations under the License.
22  * 
23  * ============LICENSE_END=========================================================
24  */
25
26 package org.onap.appc.listener;
27
28 import java.security.SecureRandom;
29 import java.util.concurrent.ArrayBlockingQueue;
30 import java.util.concurrent.BlockingQueue;
31 import java.util.concurrent.RejectedExecutionHandler;
32 import java.util.concurrent.ThreadPoolExecutor;
33 import java.util.concurrent.TimeUnit;
34 import java.util.concurrent.atomic.AtomicBoolean;
35
36 import org.apache.commons.lang3.concurrent.BasicThreadFactory;
37 import org.onap.appc.listener.impl.EventHandlerImpl;
38
39 import com.att.eelf.configuration.EELFLogger;
40 import com.att.eelf.configuration.EELFManager;
41
42 public abstract class AbstractListener implements Listener {
43
44     private final EELFLogger LOG = EELFManager.getInstance().getLogger(AbstractListener.class);
45
46     protected AtomicBoolean run = new AtomicBoolean(false);
47     protected int QUEUED_MIN = 1;
48     protected int QUEUED_MAX = 10;
49     protected int THREAD_MIN = 4;
50     protected int THREAD_MAX = THREAD_MIN; // Fixed thread pool
51     protected int THREAD_SCALE_DOWN_SEC = 10; // Number of seconds to wait until we remove idle threads
52     protected ThreadPoolExecutor executor;
53     protected EventHandler dmaap;
54     protected ListenerProperties props;
55
56     private String listenerId;
57
58     public AbstractListener(ListenerProperties props) {
59         updateProperties(props);
60
61         dmaap = new EventHandlerImpl(props);
62         if (dmaap.getClientId().equals("0")) {
63                 dmaap.setClientId(String.valueOf(new SecureRandom().nextInt(1000)));
64         }
65
66         BlockingQueue<Runnable> threadQueue = new ArrayBlockingQueue<Runnable>(QUEUED_MAX + QUEUED_MIN + 1);
67         executor = new ThreadPoolExecutor(THREAD_MIN, THREAD_MAX, THREAD_SCALE_DOWN_SEC, TimeUnit.SECONDS, threadQueue,
68             new JobRejectionHandler());
69
70         // Custom Named thread factory
71         BasicThreadFactory threadFactory = new BasicThreadFactory.Builder().namingPattern("DMaaP-Worker-%d").build();
72         executor.setThreadFactory(threadFactory);
73
74         run.set(true);
75     }
76
77     /**
78      * Starts a loop that will only end after stop() or stopNow() are called. The loop will read messages off the DMaaP
79      * topic and perform some action on them while writing messages back to DMaaP at critical points in the execution.
80      * Inherited from Runnable.
81      * 
82      * @see java.lang.Runnable#run()
83      */
84     @Override
85     public void run() {
86         LOG.error("Listener.run() has not been implemented");
87     }
88
89     @Override
90     public void stop() {
91         run.set(false);
92         LOG.info(String.format("Stopping with %d messages in queue", executor.getQueue().size()));
93         executor.shutdown();
94         try {
95             executor.awaitTermination(10, TimeUnit.SECONDS);
96         } catch (InterruptedException e) {
97             LOG.error("Listener graceful stop() failed", e);
98             Thread.currentThread().interrupt();
99         }
100         
101         // close DMaaP clients
102         if (dmaap != null) {
103                 dmaap.closeClients();
104         }
105         LOG.info("Listener Thread Pool Finished");
106     }
107
108     @Override
109     public void stopNow() {
110         run.set(false);
111         LOG.info(String.format("StopNow called. Orphaning %d messages in the queue", executor.getQueue().size()));
112         executor.getQueue().clear();
113         stop();
114     }
115
116     @Override
117     public String getBenchmark() {
118         return String.format("%s - No benchmarking implemented.", getListenerId());
119     }
120
121     @Override
122     public String getListenerId() {
123         return listenerId;
124     }
125
126     // Sets the id of the listener in
127     @Override
128     public void setListenerId(String id) {
129         listenerId = id;
130     }
131
132     private void updateProperties(ListenerProperties properties) {
133         this.props = properties;
134         QUEUED_MIN =
135             Integer.valueOf(props.getProperty(ListenerProperties.KEYS.THREADS_MIN_QUEUE, String.valueOf(QUEUED_MIN)));
136         QUEUED_MAX =
137             Integer.valueOf(props.getProperty(ListenerProperties.KEYS.THREADS_MAX_QUEUE, String.valueOf(QUEUED_MAX)));
138         THREAD_MIN =
139             Integer.valueOf(props.getProperty(ListenerProperties.KEYS.THREADS_MIN_POOL, String.valueOf(THREAD_MIN)));
140         THREAD_MAX =
141             Integer.valueOf(props.getProperty(ListenerProperties.KEYS.THREADS_MAX_POOL, String.valueOf(THREAD_MAX)));
142
143         listenerId = props.getPrefix();
144     }
145
146     /**
147      * This class will be used to handle what happens when we cannot add a job because of a ThreadPool issue. It does
148      * not get invoked if there is any fault with the job. NOTE: So far, this has only been seen when doing a
149      * {@link Listener#stopNow}
150      *
151      */
152     class JobRejectionHandler implements RejectedExecutionHandler {
153         @Override
154         public void rejectedExecution(Runnable r, ThreadPoolExecutor executor) {
155             LOG.error(String.format("A job was rejected. [%s]", r));
156         }
157     }
158 }