summaryrefslogtreecommitdiffstats
path: root/src/main/java/com/att/dmf/mr/resources/CambriaOutboundEventStream.java
blob: aae15fb41b96db7b6ed687a37cadc07cc8c8376e (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
/*******************************************************************************
 *  ============LICENSE_START=======================================================
 *  org.onap.dmaap
 *  ================================================================================
 *  Copyright © 2017 AT&T Intellectual Property. All rights reserved.
 *  ================================================================================
 *  Licensed under the Apache License, Version 2.0 (the "License");
 *  you may not use this file except in compliance with the License.
 *  You may obtain a copy of the License at
 *        http://www.apache.org/licenses/LICENSE-2.0
*  
 *  Unless required by applicable law or agreed to in writing, software
 *  distributed under the License is distributed on an "AS IS" BASIS,
 *  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 *  See the License for the specific language governing permissions and
 *  limitations under the License.
 *  ============LICENSE_END=========================================================
 *  
 *  ECOMP is a trademark and service mark of AT&T Intellectual Property.
 *  
 *******************************************************************************/
package com.att.dmf.mr.resources;

import java.io.IOException;
import java.io.OutputStream;
import java.util.ArrayList;
import java.util.Date;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.kafka.clients.consumer.ConsumerRecord;
import org.apache.kafka.clients.consumer.ConsumerRecords;
import org.json.JSONException;
import org.json.JSONObject;
import org.json.JSONTokener;

import com.att.ajsc.filemonitor.AJSCPropertiesMap;
import com.att.dmf.mr.CambriaApiException;
import com.att.dmf.mr.backends.Consumer;
import com.att.dmf.mr.beans.DMaaPContext;
import com.att.dmf.mr.constants.CambriaConstants;
import com.att.dmf.mr.metabroker.Topic;
import com.att.dmf.mr.utils.DMaaPResponseBuilder.StreamWriter;
import com.att.dmf.mr.utils.Utils;
import com.att.eelf.configuration.EELFLogger;
import com.att.eelf.configuration.EELFManager;

/*import com.att.sa.highlandPark.config.HpConfigContext;
import com.att.sa.highlandPark.config.HpReaderException;
import com.att.sa.highlandPark.events.HpJsonEvent;
import com.att.sa.highlandPark.events.HpJsonEventFactory;
import com.att.sa.highlandPark.processor.HpAlarmFilter;
import com.att.sa.highlandPark.processor.HpEvent;
import com.att.sa.highlandPark.processor.HpProcessingEngine;
import com.att.sa.highlandPark.processor.HpProcessingEngine.EventFactory;
*/
/**
 * class used to write the consumed messages
 * 
 * @author anowarul.islam
 *
 */
public class CambriaOutboundEventStream implements StreamWriter {
	private static final int kTopLimit = 1024 * 4;

	/**
	 * 
	 * static innerclass it takes all the input parameter for kafka consumer
	 * like limit, timeout, meta, pretty
	 * 
	 * @author anowarul.islam
	 *
	 */
	public static class Builder {

		// Required
		private final Consumer fConsumer;
		// private final rrNvReadable fSettings; // used during write to tweak
		// format, decide to explicitly
		// close stream or not

		// Optional
		private int fLimit;
		private int fTimeoutMs;
		private String fTopicFilter;
		private boolean fPretty;
		private boolean fWithMeta;
		ArrayList<Consumer> fKafkaConsumerList;

		
		/**
		 * constructor it initializes all the consumer parameters
		 * 
		 * @param c
		 * @param settings
		 */
		public Builder(Consumer c) {
			this.fConsumer = c;
			

			fLimit = CambriaConstants.kNoTimeout;
			fTimeoutMs = CambriaConstants.kNoLimit;
			fTopicFilter = CambriaConstants.kNoFilter;
			fPretty = false;
			fWithMeta = false;
			
	
		}

		/**
		 * 
		 * constructor initializes with limit
		 * 
		 * @param l
		 *            only l no of messages will be consumed
		 * @return
		 */
		public Builder limit(int l) {
			this.fLimit = l;
			return this;
		}

		/**
		 * constructor initializes with timeout
		 * 
		 * @param t
		 *            if there is no message to consume, them DMaaP will wait
		 *            for t time
		 * @return
		 */
		public Builder timeout(int t) {
			this.fTimeoutMs = t;
			return this;
		}

		/**
		 * constructor initializes with filter
		 * 
		 * @param f
		 *            filter
		 * @return
		 */
		public Builder filter(String f) {
			this.fTopicFilter = f;
			return this;
		}

		/**
		 * constructor initializes with boolean value pretty
		 * 
		 * @param p
		 *            messages print in new line
		 * @return
		 */
		public Builder pretty(boolean p) {
			fPretty = p;
			return this;
		}

		/**
		 * constructor initializes with boolean value meta
		 * 
		 * @param withMeta,
		 *            along with messages offset will print
		 * @return
		 */
		public Builder withMeta(boolean withMeta) {
			fWithMeta = withMeta;
			return this;
		}

		// public Builder atOffset ( int pos )
		
	
		// return this;
		// }
		/**
		 * method returs object of CambriaOutboundEventStream
		 * 
		 * @return
		 * @throws CambriaApiException
		 */
		public CambriaOutboundEventStream build() throws CambriaApiException {
			return new CambriaOutboundEventStream(this);
		}
	}

	@SuppressWarnings("unchecked")
	/**
	 * 
	 * @param builder
	 * @throws CambriaApiException
	 * 
	 */
	private CambriaOutboundEventStream(Builder builder) throws CambriaApiException {
		fConsumer = builder.fConsumer;
		fLimit = builder.fLimit;
		fTimeoutMs = builder.fTimeoutMs;
		
		fSent = 0;
		fPretty = builder.fPretty;
		fWithMeta = builder.fWithMeta;
		fKafkaConsumerList = builder.fKafkaConsumerList;
	/*	if (CambriaConstants.kNoFilter.equals(builder.fTopicFilter)) {
			fHpAlarmFilter = null;
			fHppe = null;
		} else {
			try {
				final JSONObject filter = new JSONObject(new JSONTokener(builder.fTopicFilter));
				HpConfigContext<HpEvent> cc = new HpConfigContext<HpEvent>();
				fHpAlarmFilter = cc.create(HpAlarmFilter.class, filter);
				final EventFactory<HpJsonEvent> ef = new HpJsonEventFactory();
				fHppe = new HpProcessingEngine<HpJsonEvent>(ef);
			} catch (HpReaderException e) {
				// JSON was okay, but the filter engine says it's bogus
				throw new CambriaApiException(HttpServletResponse.SC_BAD_REQUEST,
						"Couldn't create filter: " + e.getMessage());
			} catch (JSONException e) {
				// user sent a bogus JSON object
				throw new CambriaApiException(HttpServletResponse.SC_BAD_REQUEST,
						"Couldn't parse JSON: " + e.getMessage());
			}
		}*/
	}

	/**
	 * 
	 * interface provides onWait and onMessage methods
	 *
	 */
	public interface operation {
		/**
		 * Call thread.sleep
		 * 
		 * @throws IOException
		 */
		void onWait() throws IOException;

		/**
		 * provides the output based in the consumer paramter
		 * 
		 * @param count
		 * @param msg
		 * @throws IOException
		 */
		
		void onMessage(int count, String msg, String transId, long offSet) throws IOException, JSONException;
	}

	/**
	 * 
	 * @return
	 */
	public int getSentCount() {
		return fSent;
	}

	@Override
	/**
	 * 
	 * @param os
	 *            throws IOException
	 */
	public void write(final OutputStream os) throws IOException {
		
	
		// final boolean transactionEnabled = istransEnable;
		// synchronized(this){
		os.write('[');
		fSent = forEachMessage(new operation() {
			@Override
			public void onMessage(int count, String msg, String transId, long offSet)
					throws IOException, JSONException {

				if (count > 0) {
					os.write(',');
				}
				if (fWithMeta) {
					final JSONObject entry = new JSONObject();
					entry.put("offset", offSet);
					entry.put("message", msg);
					os.write(entry.toString().getBytes());
				} else {
					
						String jsonString = JSONObject.valueToString(msg);
					os.write(jsonString.getBytes());
				}

				if (fPretty) {
					os.write('\n');
				}

				String metricTopicname = com.att.ajsc.filemonitor.AJSCPropertiesMap
						.getProperty(CambriaConstants.msgRtr_prop, "metrics.send.cambria.topic");
				if (null == metricTopicname)
					metricTopicname = "msgrtr.apinode.metrics.dmaap";
				if (!metricTopicname.equalsIgnoreCase(topic.getName())) {
					try {
						if (istransEnable && istransType) {
							// final String transactionId =
							
							
							StringBuilder consumerInfo = new StringBuilder();
							if (null != dmaapContext && null != dmaapContext.getRequest()) {
								final HttpServletRequest request = dmaapContext.getRequest();
								consumerInfo.append("consumerIp= \"" + request.getRemoteHost() + "\",");
								consumerInfo.append("consServerIp= \"" + request.getLocalAddr() + "\",");
								consumerInfo.append("consumerId= \"" + Utils.getUserApiKey(request) + "\",");
								consumerInfo.append("consumerGroup= \""
										+ getConsumerGroupFromRequest(request.getRequestURI()) + "\",");
								consumerInfo.append("consumeTime= \"" + Utils.getFormattedDate(new Date()) + "\",");
							}
							log.info("Consumer [" + consumerInfo.toString() + "transactionId= \"" + transId
									+ "\",messageLength= \"" + msg.length() + "\",topic= \"" + topic.getName() + "\"]");
						}
					} catch (Exception e) {
					}
				}

			}

			@Override
			/**
			 * 
			 * It makes thread to wait
			 * 
			 * @throws IOException
			 */
			public void onWait() throws IOException {
				os.flush(); // likely totally unnecessary for a network socket
				try {
					// FIXME: would be good to wait/signal
					Thread.sleep(100);
				} catch (InterruptedException e) {
					// ignore
				}
			}
		});

		
		if (null != dmaapContext && istransEnable && istransType) {

			dmaapContext.getResponse().setHeader("transactionId",
					Utils.getResponseTransactionId(responseTransactionId));
		}

		os.write(']');
		os.flush();

		boolean close_out_stream = true;
		String strclose_out_stream = AJSCPropertiesMap.getProperty(CambriaConstants.msgRtr_prop, "close.output.stream");
		if (null != strclose_out_stream)
			close_out_stream = Boolean.parseBoolean(strclose_out_stream);

		
		if (close_out_stream) {
			os.close();
			
		}
	}

	/**
	 * 
	 * @param requestURI
	 * @return
	 */
	private String getConsumerGroupFromRequest(String requestURI) {
		if (null != requestURI && !requestURI.isEmpty()) {

			String consumerDetails = requestURI.substring(requestURI.indexOf("events/") + 7);

			int startIndex = consumerDetails.indexOf("/") + 1;
			int endIndex = consumerDetails.lastIndexOf("/");
			return consumerDetails.substring(startIndex, endIndex);
		}
		return null;
	}

	/**
	 * 
	 * @param op
	 * @return
	 * @throws IOException
	 * @throws JSONException
	 */
	public int forEachMessage(operation op) throws IOException, JSONException {
		final int effectiveLimit = (fLimit == 0 ? kTopLimit : fLimit);

		int count = 0;
		boolean firstPing = true;
		// boolean isTransType=false;
		final long startMs = System.currentTimeMillis();
		final long timeoutMs = fTimeoutMs + startMs -500; //500 ms used in poll 

		while (firstPing || (count == 0 && System.currentTimeMillis() < timeoutMs)) {
			if (!firstPing) {
				op.onWait();
			}
			firstPing = false;

		
				 Consumer.Message msgRecord = null;
				 while (count < effectiveLimit && (msgRecord =
				 fConsumer.nextMessage()) != null) {

				String message = "";
				String transactionid = "";
				try {
                   // String msgRecord = msg;
					JSONObject jsonMessage = new JSONObject(msgRecord);
					String[] keys = JSONObject.getNames(jsonMessage);
					boolean wrapheader1 = false;
					boolean wrapheader2 = false;
					boolean found_attr3 = false;
					String wrapElement1 = "message";
					String wrapElement2 = "msgWrapMR";
					String transIdElement = "transactionId";
					if (null != keys) {
						for (String key : keys) {
							if (key.equals(wrapElement1)) {
								wrapheader1 = true;
							} else if (key.equals(wrapElement2)) {
								wrapheader2 = true;
							} else if (key.equals(transIdElement)) {
								found_attr3 = true;
								transactionid = jsonMessage.getString(key);
							}
						}
					}

					// returns contents of attribute 1 if both attributes
					// present, otherwise
					// the whole msg
					if (wrapheader2 && found_attr3) {
						message = jsonMessage.getString(wrapElement2);
					} else if (wrapheader1 && found_attr3) {
						message = jsonMessage.getString(wrapElement1);
					} else {
						message = msgRecord.getMessage();
					}
					// jsonMessage = extractMessage(jsonMessage ,
					// "message","msgWrapMR","transactionId");
					istransType = true;
				} catch (JSONException e) { // This check is required for the
											// message sent by MR AAF flow but
											// consumed by UEB ACL flow which
											// wont expect transaction id in
											// cambria client api
					// Ignore
					log.info("JSON Exception logged when the message is non JSON Format");
				} catch (Exception exp) {
					log.info("****Some Exception occured for writing messages in topic" + topic.getName()
							+ "  Exception" + exp);
				}
				if (message == null || message.equals("")) {
					istransType = false;
					message = msgRecord.getMessage();
				}

				// If filters are enabled/set, message should be in JSON format
				// for filters to work for
				// otherwise filter will automatically ignore message in
				// non-json format.
				if (filterMatches(message)) {
					op.onMessage(count, message, transactionid, msgRecord.getOffset());
					count++;

				}

			}
		}
		return count;
	}

	

	/**
	 * 
	 * Checks whether filter is initialized
	 */
	
		
	

	/**
	 * 
	 * @param msg
	 * @return
	 */
	private boolean filterMatches(String msg) {
		boolean result = true;
		
		
				
				
			
			
			
				
			
				
		
	

		return result;
	}

	public DMaaPContext getDmaapContext() {
		return dmaapContext;
	}

	public void setDmaapContext(DMaaPContext dmaapContext) {
		this.dmaapContext = dmaapContext;
	}

	public Topic getTopic() {
		return topic;
	}

	public void setTopic(Topic topic) {
		this.topic = topic;
	}

	public void setTopicStyle(boolean aaftopic) {
		this.isAAFTopic = aaftopic;
	}

	public void setTransEnabled(boolean transEnable) {
		this.istransEnable = transEnable;
	}

	
	private final Consumer fConsumer;
	private final int fLimit;
	private final int fTimeoutMs;
	
	private final boolean fPretty;
	private final boolean fWithMeta;
	private int fSent;

	//private final HpProcessingEngine<HpJsonEvent> fHppe;
	private DMaaPContext dmaapContext;
	private String responseTransactionId;
	private Topic topic;
	private boolean isAAFTopic = false;
	private boolean istransEnable = false;
	private ArrayList<Consumer> fKafkaConsumerList;
	private boolean istransType = true;
	// private static final Logger log =
	

	private static final EELFLogger log = EELFManager.getInstance().getLogger(CambriaOutboundEventStream.class);
}