0f0996fb80c888a6e05c81e7bd0cf239b4ad8ac1
[policy/apex-pdp.git] /
1 /*-
2  * ============LICENSE_START=======================================================
3  *  Copyright (C) 2016-2018 Ericsson. All rights reserved.
4  * ================================================================================
5  * Licensed under the Apache License, Version 2.0 (the "License");
6  * you may not use this file except in compliance with the License.
7  * You may obtain a copy of the License at
8  * 
9  *      http://www.apache.org/licenses/LICENSE-2.0
10  * 
11  * Unless required by applicable law or agreed to in writing, software
12  * distributed under the License is distributed on an "AS IS" BASIS,
13  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
14  * See the License for the specific language governing permissions and
15  * limitations under the License.
16  * 
17  * SPDX-License-Identifier: Apache-2.0
18  * ============LICENSE_END=========================================================
19  */
20
21 package org.onap.policy.apex.service.engine.event.impl.filecarrierplugin.consumer;
22
23 import java.io.FileInputStream;
24 import java.io.IOException;
25 import java.io.InputStream;
26 import java.util.EnumMap;
27 import java.util.Map;
28 import java.util.concurrent.atomic.AtomicLong;
29
30 import org.onap.policy.apex.core.infrastructure.threading.ApplicationThreadFactory;
31 import org.onap.policy.apex.core.infrastructure.threading.ThreadUtilities;
32 import org.onap.policy.apex.service.engine.event.ApexEventConsumer;
33 import org.onap.policy.apex.service.engine.event.ApexEventException;
34 import org.onap.policy.apex.service.engine.event.ApexEventReceiver;
35 import org.onap.policy.apex.service.engine.event.PeeredReference;
36 import org.onap.policy.apex.service.engine.event.impl.filecarrierplugin.FileCarrierTechnologyParameters;
37 import org.onap.policy.apex.service.parameters.eventhandler.EventHandlerParameters;
38 import org.onap.policy.apex.service.parameters.eventhandler.EventHandlerPeeredMode;
39 import org.slf4j.Logger;
40 import org.slf4j.LoggerFactory;
41
42 /**
43  * Concrete implementation an Apex event consumer that reads events from a file. This consumer also implements
44  * ApexEventProducer and therefore can be used as a synchronous consumer.
45  *
46  * @author Liam Fallon (liam.fallon@ericsson.com)
47  */
48 public class ApexFileEventConsumer implements ApexEventConsumer, Runnable {
49     // Get a reference to the logger
50     private static final Logger LOGGER = LoggerFactory.getLogger(ApexFileEventConsumer.class);
51
52     // Recurring string constants
53     private static final String APEX_FILE_CONSUMER_PREAMBLE = "ApexFileConsumer \"";
54
55     // The input stream to read events from
56     private InputStream eventInputStream;
57
58     // The text block reader that will read text blocks from the contents of the file
59     private TextBlockReader textBlockReader;
60
61     // The event receiver that will receive asynchronous events from this consumer
62     private ApexEventReceiver eventReceiver = null;
63
64     // The consumer thread and stopping flag
65     private Thread consumerThread;
66
67     // The name for this consumer
68     private String consumerName = null;
69
70     // The specific carrier technology parameters for this consumer
71     private FileCarrierTechnologyParameters fileCarrierTechnologyParameters;
72
73     // The peer references for this event handler
74     private final Map<EventHandlerPeeredMode, PeeredReference> peerReferenceMap = new EnumMap<>(
75                     EventHandlerPeeredMode.class);
76
77     // Holds the next identifier for event execution.
78     private static AtomicLong nextExecutionID = new AtomicLong(0L);
79
80     /**
81      * Private utility to get the next candidate value for a Execution ID. This value will always be unique in a single
82      * JVM
83      * 
84      * @return the next candidate value for a Execution ID
85      */
86     private static synchronized long getNextExecutionId() {
87         return nextExecutionID.getAndIncrement();
88     }
89
90     /*
91      * (non-Javadoc)
92      *
93      * @see org.onap.policy.apex.apps.uservice.consumer.ApexEventConsumer#init(org.onap.policy.apex.apps.
94      * uservice.consumer.ApexEventReceiver)
95      */
96     @Override
97     public void init(final String name, final EventHandlerParameters consumerParameters,
98                     final ApexEventReceiver incomingEventReceiver) throws ApexEventException {
99         this.eventReceiver = incomingEventReceiver;
100         this.consumerName = name;
101
102         // Get and check the Apex parameters from the parameter service
103         if (consumerParameters == null) {
104             final String errorMessage = "Consumer parameters for ApexFileConsumer \"" + consumerName + "\" is null";
105             LOGGER.warn(errorMessage);
106             throw new ApexEventException(errorMessage);
107         }
108
109         // Check and get the file Properties
110         if (!(consumerParameters.getCarrierTechnologyParameters() instanceof FileCarrierTechnologyParameters)) {
111             final String errorMessage = "specified consumer properties for ApexFileConsumer \"" + consumerName
112                             + "\" are not applicable to a File consumer";
113             LOGGER.warn(errorMessage);
114             throw new ApexEventException(errorMessage);
115         }
116         fileCarrierTechnologyParameters = (FileCarrierTechnologyParameters) consumerParameters
117                         .getCarrierTechnologyParameters();
118
119         // Open the file producing events
120         try {
121             if (fileCarrierTechnologyParameters.isStandardIo()) {
122                 eventInputStream = System.in;
123             } else {
124                 eventInputStream = new FileInputStream(fileCarrierTechnologyParameters.getFileName());
125             }
126
127             // Get an event composer for our event source
128             textBlockReader = new TextBlockReaderFactory().getTaggedReader(eventInputStream,
129                             consumerParameters.getEventProtocolParameters());
130         } catch (final IOException e) {
131             final String errorMessage = APEX_FILE_CONSUMER_PREAMBLE + consumerName
132                             + "\" failed to open file for reading: \"" + fileCarrierTechnologyParameters.getFileName()
133                             + "\"";
134             LOGGER.warn(errorMessage, e);
135             throw new ApexEventException(errorMessage, e);
136         }
137
138         if (fileCarrierTechnologyParameters.getStartDelay() > 0) {
139             ThreadUtilities.sleep(fileCarrierTechnologyParameters.getStartDelay());
140         }
141     }
142
143     /*
144      * (non-Javadoc)
145      * 
146      * @see org.onap.policy.apex.service.engine.event.ApexEventConsumer#getName()
147      */
148     @Override
149     public String getName() {
150         return consumerName;
151     }
152
153     /*
154      * (non-Javadoc)
155      * 
156      * @see org.onap.policy.apex.service.engine.event.ApexEventConsumer#getPeeredReference(org.onap.
157      * policy.apex.service.parameters.eventhandler.EventHandlerPeeredMode)
158      */
159     @Override
160     public PeeredReference getPeeredReference(final EventHandlerPeeredMode peeredMode) {
161         return peerReferenceMap.get(peeredMode);
162     }
163
164     /*
165      * (non-Javadoc)
166      * 
167      * @see org.onap.policy.apex.service.engine.event.ApexEventConsumer#setPeeredReference(org.onap.
168      * policy.apex.service.parameters.eventhandler.EventHandlerPeeredMode,
169      * org.onap.policy.apex.service.engine.event.PeeredReference)
170      */
171     @Override
172     public void setPeeredReference(final EventHandlerPeeredMode peeredMode, final PeeredReference peeredReference) {
173         peerReferenceMap.put(peeredMode, peeredReference);
174     }
175
176     /*
177      * (non-Javadoc)
178      * 
179      * @see org.onap.policy.apex.service.engine.event.ApexEventConsumer#start()
180      */
181     @Override
182     public void start() {
183         // Configure and start the event reception thread
184         final String threadName = this.getClass().getName() + " : " + consumerName;
185         consumerThread = new ApplicationThreadFactory(threadName).newThread(this);
186         consumerThread.setDaemon(true);
187         consumerThread.start();
188     }
189
190     /*
191      * (non-Javadoc)
192      *
193      * @see java.lang.Runnable#run()
194      */
195     @Override
196     public void run() {
197         // Check that we have been initialized in async or sync mode
198         if (eventReceiver == null) {
199             LOGGER.warn("\"{}\" has not been initilaized for either asynchronous or synchronous event handling",
200                             consumerName);
201             return;
202         }
203
204         // Read the events from the file while there are still events in the file
205         try {
206             // Read all the text blocks
207             TextBlock textBlock;
208             do {
209                 // Read the text block
210                 textBlock = textBlockReader.readTextBlock();
211
212                 // Process the event from the text block if there is one there
213                 if (textBlock.getText() != null) {
214                     eventReceiver.receiveEvent(getNextExecutionId(), textBlock.getText());
215                 }
216             }
217             while (!textBlock.isEndOfText());
218         } catch (final Exception e) {
219             LOGGER.warn("\"" + consumerName + "\" failed to read event from file: \""
220                             + fileCarrierTechnologyParameters.getFileName() + "\"", e);
221         } finally {
222             try {
223                 eventInputStream.close();
224             } catch (final IOException e) {
225                 LOGGER.warn(APEX_FILE_CONSUMER_PREAMBLE + consumerName + "\" failed to close file: \""
226                                 + fileCarrierTechnologyParameters.getFileName() + "\"", e);
227             }
228         }
229
230     }
231
232     /*
233      * (non-Javadoc)
234      *
235      * @see org.onap.policy.apex.apps.uservice.producer.ApexEventProducer#stop()
236      */
237     @Override
238     public void stop() {
239         try {
240             eventInputStream.close();
241         } catch (final IOException e) {
242             LOGGER.warn(APEX_FILE_CONSUMER_PREAMBLE + consumerName + "\" failed to close file for reading: \""
243                             + fileCarrierTechnologyParameters.getFileName() + "\"", e);
244         }
245
246         if (consumerThread.isAlive() && !consumerThread.isInterrupted()) {
247             consumerThread.interrupt();
248         }
249     }
250 }