Fix sonar issues in messagerouter/dmaapclient
[dmaap/messagerouter/dmaapclient.git] / src / main / java / org / onap / dmaap / mr / client / impl / MRSimplerBatchPublisher.java
1 /*******************************************************************************
2  *  ============LICENSE_START=======================================================
3  *  org.onap.dmaap
4  *  ================================================================================
5  *  Copyright © 2017 AT&T Intellectual Property. All rights reserved.
6  *  ================================================================================
7  *  Licensed under the Apache License, Version 2.0 (the "License");
8  *  you may not use this file except in compliance with the License.
9  *  You may obtain a copy of the License at
10  *        http://www.apache.org/licenses/LICENSE-2.0
11  *  
12  *  Unless required by applicable law or agreed to in writing, software
13  *  distributed under the License is distributed on an "AS IS" BASIS,
14  *  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
15  *  See the License for the specific language governing permissions and
16  *  limitations under the License.
17  *  ============LICENSE_END=========================================================
18  *
19  *  ECOMP is a trademark and service mark of AT&T Intellectual Property.
20  *  
21  *******************************************************************************/
22 package org.onap.dmaap.mr.client.impl;
23
24 import java.io.ByteArrayOutputStream;
25 import java.io.IOException;
26 import java.io.OutputStream;
27 import java.net.MalformedURLException;
28 import java.net.URI;
29 import java.net.URISyntaxException;
30 import java.util.Collection;
31 import java.util.HashMap;
32 import java.util.LinkedList;
33 import java.util.List;
34 import java.util.Map;
35 import java.util.Properties;
36 import java.util.concurrent.LinkedBlockingQueue;
37 import java.util.concurrent.ScheduledThreadPoolExecutor;
38 import java.util.concurrent.TimeUnit;
39 import java.util.zip.GZIPOutputStream;
40
41 import javax.ws.rs.core.MultivaluedMap;
42
43 import org.slf4j.Logger;
44 import org.slf4j.LoggerFactory;
45
46 import org.apache.http.HttpException;
47 import org.apache.http.HttpStatus;
48 import org.json.JSONArray;
49 import org.json.JSONObject;
50 import org.json.JSONTokener;
51
52 import com.att.aft.dme2.api.DME2Client;
53 import com.att.aft.dme2.api.DME2Exception;
54 import org.onap.dmaap.mr.client.HostSelector;
55 import org.onap.dmaap.mr.client.MRBatchingPublisher;
56 import org.onap.dmaap.mr.client.response.MRPublisherResponse;
57 import org.onap.dmaap.mr.test.clients.ProtocolTypeConstants;
58
59 public class MRSimplerBatchPublisher extends MRBaseClient implements MRBatchingPublisher {
60         private static final Logger logger = LoggerFactory.getLogger(MRSimplerBatchPublisher.class);
61
62         public static class Builder {
63                 public Builder() {
64                 }
65
66                 public Builder againstUrls(Collection<String> baseUrls) {
67                         fUrls = baseUrls;
68                         return this;
69                 }
70                 
71                 public Builder againstUrlsOrServiceName ( Collection<String> baseUrls, Collection<String> serviceName, String transportype )            
72                 {               
73                         fUrls = baseUrls;               
74                         fServiceName = serviceName;             
75                         fTransportype = transportype;           
76                         return this;            
77                 }
78
79                 public Builder onTopic(String topic) {
80                         fTopic = topic;
81                         return this;
82                 }
83
84                 public Builder batchTo(int maxBatchSize, long maxBatchAgeMs) {
85                         fMaxBatchSize = maxBatchSize;
86                         fMaxBatchAgeMs = maxBatchAgeMs;
87                         return this;
88                 }
89
90                 public Builder compress(boolean compress) {
91                         fCompress = compress;
92                         return this;
93                 }
94
95                 public Builder httpThreadTime(int threadOccuranceTime) {
96                         this.threadOccuranceTime = threadOccuranceTime;
97                         return this;
98                 }
99
100                 public Builder allowSelfSignedCertificates(boolean allowSelfSignedCerts) {
101                         fAllowSelfSignedCerts = allowSelfSignedCerts;
102                         return this;
103                 }
104
105                 public Builder withResponse(boolean withResponse) {
106                         fWithResponse = withResponse;
107                         return this;
108                 }
109
110                 public MRSimplerBatchPublisher build() {
111                         if (!fWithResponse) {
112                                 try {
113                                         return new MRSimplerBatchPublisher(fUrls, fTopic, fMaxBatchSize, fMaxBatchAgeMs, fCompress,
114                                                         fAllowSelfSignedCerts, threadOccuranceTime);
115                                 } catch (MalformedURLException e) {
116                                         throw new IllegalArgumentException(e);
117                                 }
118                         } else {
119                                 try {
120                                         return new MRSimplerBatchPublisher(fUrls, fTopic, fMaxBatchSize, fMaxBatchAgeMs, fCompress,
121                                                         fAllowSelfSignedCerts, fMaxBatchSize);
122                                 } catch (MalformedURLException e) {
123                                         throw new IllegalArgumentException(e);
124                                 }
125                         }
126
127                 }
128
129                 private Collection<String> fUrls;
130                 private Collection<String> fServiceName;                
131                 private String fTransportype;   
132                 private String fTopic;
133                 private int fMaxBatchSize = 100;
134                 private long fMaxBatchAgeMs = 1000;
135                 private boolean fCompress = false;
136                 private int threadOccuranceTime = 50;
137                 private boolean fAllowSelfSignedCerts = false;
138                 private boolean fWithResponse = false;
139
140         };
141
142         @Override
143         public int send(String partition, String msg) {
144                 return send(new message(partition, msg));
145         }
146
147         @Override
148         public int send(String msg) {
149                 return send(new message(null, msg));
150         }
151
152         @Override
153         public int send(message msg) {
154                 final LinkedList<message> list = new LinkedList<>();
155                 list.add(msg);
156                 return send(list);
157         }
158
159         @Override
160         public synchronized int send(Collection<message> msgs) {
161                 if (fClosed) {
162                         throw new IllegalStateException("The publisher was closed.");
163                 }
164
165                 for (message userMsg : msgs) {
166                         fPending.add(new TimestampedMessage(userMsg));
167                 }
168                 return getPendingMessageCount();
169         }
170
171         @Override
172         public synchronized int getPendingMessageCount() {
173                 return fPending.size();
174         }
175
176         @Override
177         public void close() {
178                 try {
179                         final List<message> remains = close(Long.MAX_VALUE, TimeUnit.MILLISECONDS);
180                         if (remains.isEmpty()) {
181                                 getLog().warn("Closing publisher with " + remains.size() + " messages unsent. "
182                                                 + "Consider using MRBatchingPublisher.close( long timeout, TimeUnit timeoutUnits ) to recapture unsent messages on close.");
183                         }
184                 } catch (InterruptedException e) {
185                         getLog().warn("Possible message loss. " + e.getMessage(), e);
186                         Thread.currentThread().interrupt();
187                 } catch (IOException e) {
188                         getLog().warn("Possible message loss. " + e.getMessage(), e);
189                 }
190         }
191
192         @Override
193         public List<message> close(long time, TimeUnit unit) throws IOException, InterruptedException {
194                 synchronized (this) {
195                         fClosed = true;
196
197                         // stop the background sender
198                         fExec.setContinueExistingPeriodicTasksAfterShutdownPolicy(false);
199                         fExec.setExecuteExistingDelayedTasksAfterShutdownPolicy(false);
200                         fExec.shutdown();
201                 }
202
203                 final long now = Clock.now();
204                 final long waitInMs = TimeUnit.MILLISECONDS.convert(time, unit);
205                 final long timeoutAtMs = now + waitInMs;
206
207                 while (Clock.now() < timeoutAtMs && getPendingMessageCount() > 0) {
208                         send(true);
209                         Thread.sleep(250);
210                 }
211
212                 synchronized (this) {
213                         final LinkedList<message> result = new LinkedList<>();
214                         fPending.drainTo(result);
215                         return result;
216                 }
217         }
218
219         /**
220          * Possibly send a batch to the MR server. This is called by the background
221          * thread and the close() method
222          * 
223          * @param force
224          */
225         private synchronized void send(boolean force) {
226                 if ((force || shouldSendNow()) && !sendBatch()) {
227                                 getLog().warn("Send failed, " + fPending.size() + " message to send.");
228
229                                 // note the time for back-off
230                                 fDontSendUntilMs = sfWaitAfterError + Clock.now();
231                 }
232         }
233
234         private synchronized boolean shouldSendNow() {
235                 boolean shouldSend = false;
236                 if (fPending.isEmpty()) {
237                         final long nowMs = Clock.now();
238
239                         shouldSend = (fPending.size() >= fMaxBatchSize);
240                         if (!shouldSend) {
241                                 final long sendAtMs = fPending.peek().timestamp + fMaxBatchAgeMs;
242                                 shouldSend = sendAtMs <= nowMs;
243                         }
244
245                         // however, wait after an error
246                         shouldSend = shouldSend && nowMs >= fDontSendUntilMs;
247                 }
248                 return shouldSend;
249         }
250
251         /**
252          * Method to parse published JSON Objects and Arrays
253          * 
254          * @return JSONArray
255          */
256         private JSONArray parseJSON() {
257                 JSONArray jsonArray = new JSONArray();
258                 for (TimestampedMessage m : fPending) {
259                         JSONTokener jsonTokener = new JSONTokener(m.fMsg);
260                         JSONObject jsonObject = null;
261                         JSONArray tempjsonArray = null;
262                         final char firstChar = jsonTokener.next();
263                         jsonTokener.back();
264                         if ('[' == firstChar) {
265                                 tempjsonArray = new JSONArray(jsonTokener);
266                                 if (null != tempjsonArray) {
267                                         for (int i = 0; i < tempjsonArray.length(); i++) {
268                                                 jsonArray.put(tempjsonArray.getJSONObject(i));
269                                         }
270                                 }
271                         } else {
272                                 jsonObject = new JSONObject(jsonTokener);
273                                 jsonArray.put(jsonObject);
274                         }
275
276                 }
277                 return jsonArray;
278         }
279
280         private synchronized boolean sendBatch() {
281                 // it's possible for this call to be made with an empty list. in this
282                 // case, just return.
283                 if (fPending.isEmpty()) {
284                         return true;
285                 }
286
287                 final long nowMs = Clock.now();
288
289                 if (this.fHostSelector != null) {
290                         host = this.fHostSelector.selectBaseHost();
291                 }
292
293                 final String httpurl = MRConstants.makeUrl(host, fTopic, props.getProperty("Protocol"),
294                                 props.getProperty("partition"));
295
296                 try {
297                         
298                         final ByteArrayOutputStream baseStream = new ByteArrayOutputStream();
299                         OutputStream os = baseStream;
300                         final String contentType = props.getProperty("contenttype");
301                         if (contentType.equalsIgnoreCase("application/json")) {
302                                 JSONArray jsonArray = parseJSON();
303                                 os.write(jsonArray.toString().getBytes());
304                                 os.close();
305
306                         } else if (contentType.equalsIgnoreCase("text/plain")) {
307                                 for (TimestampedMessage m : fPending) {
308                                         os.write(m.fMsg.getBytes());
309                                         os.write('\n');
310                                 }
311                                 os.close();
312                         } else if (contentType.equalsIgnoreCase("application/cambria")
313                                         || (contentType.equalsIgnoreCase("application/cambria-zip"))) {
314                                 if (contentType.equalsIgnoreCase("application/cambria-zip")) {
315                                         os = new GZIPOutputStream(baseStream);
316                                 }
317                                 for (TimestampedMessage m : fPending) {
318
319                                         os.write(("" + m.fPartition.length()).getBytes());
320                                         os.write('.');
321                                         os.write(("" + m.fMsg.length()).getBytes());
322                                         os.write('.');
323                                         os.write(m.fPartition.getBytes());
324                                         os.write(m.fMsg.getBytes());
325                                         os.write('\n');
326                                 }
327                                 os.close();
328                         } else {
329                                 for (TimestampedMessage m : fPending) {
330                                         os.write(m.fMsg.getBytes());
331
332                                 }
333                                 os.close();
334                         }
335
336                         final long startMs = Clock.now();
337                         if (ProtocolTypeConstants.DME2.getValue().equalsIgnoreCase(protocolFlag)) {
338
339                                 DME2Configue();
340
341                                 Thread.sleep(5);
342                                 getLog().info("sending " + fPending.size() + " msgs to " + url + subContextPath + ". Oldest: "
343                                                 + (nowMs - fPending.peek().timestamp) + " ms");
344                                 sender.setPayload(os.toString());
345                                 String dmeResponse = sender.sendAndWait(5000L);
346
347                                 final String logLine = "MR reply ok (" + (Clock.now() - startMs) + " ms):" + dmeResponse;
348                                 getLog().info(logLine);
349                                 fPending.clear();
350                                 return true;
351                         }
352
353             if (ProtocolTypeConstants.AUTH_KEY.getValue().equalsIgnoreCase(protocolFlag)) {
354                 getLog().info("sending " + fPending.size() + " msgs to " + httpurl + ". Oldest: "
355                         + (nowMs - fPending.peek().timestamp) + " ms");
356                 final JSONObject result =
357                         postAuth(new PostAuthDataObject().setPath(httpurl).setData(baseStream.toByteArray())
358                                 .setContentType(contentType).setAuthKey(authKey).setAuthDate(authDate)
359                                 .setUsername(username).setPassword(password).setProtocolFlag(protocolFlag));
360                 // Here we are checking for error response. If HTTP status
361                 // code is not within the http success response code
362                 // then we consider this as error and return false
363                 if (result.getInt("status") < 200 || result.getInt("status") > 299) {
364                     return false;
365                 }
366                 final String logLine = "MR reply ok (" + (Clock.now() - startMs) + " ms):" + result.toString();
367                 getLog().info(logLine);
368                 fPending.clear();
369                 return true;
370             }
371
372                         if (ProtocolTypeConstants.AAF_AUTH.getValue().equalsIgnoreCase(protocolFlag)) {
373                                 getLog().info("sending " + fPending.size() + " msgs to " + httpurl + ". Oldest: "
374                                                 + (nowMs - fPending.peek().timestamp) + " ms");
375                                 final JSONObject result = post(httpurl, baseStream.toByteArray(), contentType, username, password,
376                                                 protocolFlag);
377
378                                 // Here we are checking for error response. If HTTP status
379                                 // code is not within the http success response code
380                                 // then we consider this as error and return false
381                                 if (result.getInt("status") < 200 || result.getInt("status") > 299) {
382                                         return false;
383                                 }
384                                 final String logLine = "MR reply ok (" + (Clock.now() - startMs) + " ms):" + result.toString();
385                                 getLog().info(logLine);
386                                 fPending.clear();
387                                 return true;
388                         }
389                         
390                         if (ProtocolTypeConstants.HTTPNOAUTH.getValue().equalsIgnoreCase(protocolFlag)) {
391                                 getLog().info("sending " + fPending.size() + " msgs to " + httpurl + ". Oldest: "
392                                                 + (nowMs - fPending.peek().timestamp) + " ms");
393                                 final JSONObject result = postNoAuth(httpurl, baseStream.toByteArray(), contentType);
394
395                                 // Here we are checking for error response. If HTTP status
396                                 // code is not within the http success response code
397                                 // then we consider this as error and return false
398                                 if (result.getInt("status") < 200 || result.getInt("status") > 299) {
399                                         return false;
400                                 }
401                                 final String logLine = "MR reply ok (" + (Clock.now() - startMs) + " ms):" + result.toString();
402                                 getLog().info(logLine);
403                                 fPending.clear();
404                                 return true;
405                         }
406                 } catch (Exception x) {
407                         getLog().warn(x.getMessage(), x);
408                 }
409                 return false;
410         }
411
412         public synchronized MRPublisherResponse sendBatchWithResponse() {
413                 // it's possible for this call to be made with an empty list. in this
414                 // case, just return.
415                 if (fPending.isEmpty()) {
416                         pubResponse.setResponseCode(String.valueOf(HttpStatus.SC_BAD_REQUEST));
417                         pubResponse.setResponseMessage("No Messages to send");
418                         return pubResponse;
419                 }
420
421                 final long nowMs = Clock.now();
422
423                 host = this.fHostSelector.selectBaseHost();
424
425                 final String httpurl = MRConstants.makeUrl(host, fTopic, props.getProperty("Protocol"),
426                                 props.getProperty("partition"));
427                 OutputStream os = null;
428                 try {
429
430                         final ByteArrayOutputStream baseStream = new ByteArrayOutputStream();
431                         os = baseStream;
432                         final String contentType = props.getProperty("contenttype");
433                         if (contentType.equalsIgnoreCase("application/json")) {
434                                 JSONArray jsonArray = parseJSON();
435                                 os.write(jsonArray.toString().getBytes());
436                         } else if (contentType.equalsIgnoreCase("text/plain")) {
437                                 for (TimestampedMessage m : fPending) {
438                                         os.write(m.fMsg.getBytes());
439                                         os.write('\n');
440                                 }
441                         } else if (contentType.equalsIgnoreCase("application/cambria")
442                                         || (contentType.equalsIgnoreCase("application/cambria-zip"))) {
443                                 if (contentType.equalsIgnoreCase("application/cambria-zip")) {
444                                         os = new GZIPOutputStream(baseStream);
445                                 }
446                                 for (TimestampedMessage m : fPending) {
447
448                                         os.write(("" + m.fPartition.length()).getBytes());
449                                         os.write('.');
450                                         os.write(("" + m.fMsg.length()).getBytes());
451                                         os.write('.');
452                                         os.write(m.fPartition.getBytes());
453                                         os.write(m.fMsg.getBytes());
454                                         os.write('\n');
455                                 }
456                                 os.close();
457                         } else {
458                                 for (TimestampedMessage m : fPending) {
459                                         os.write(m.fMsg.getBytes());
460
461                                 }
462                         }
463
464                         final long startMs = Clock.now();
465                         if (ProtocolTypeConstants.DME2.getValue().equalsIgnoreCase(protocolFlag)) {
466
467                                 try {
468                                         DME2Configue();
469
470                                         Thread.sleep(5);
471                                         getLog().info("sending " + fPending.size() + " msgs to " + url + subContextPath + ". Oldest: "
472                                                         + (nowMs - fPending.peek().timestamp) + " ms");
473                                         sender.setPayload(os.toString());
474
475                                         String dmeResponse = sender.sendAndWait(5000L);
476
477                                         pubResponse = createMRPublisherResponse(dmeResponse, pubResponse);
478
479                                         if (Integer.valueOf(pubResponse.getResponseCode()) < 200
480                                                         || Integer.valueOf(pubResponse.getResponseCode()) > 299) {
481
482                                                 return pubResponse;
483                                         }
484                                         final String logLine = String.valueOf((Clock.now() - startMs)) + dmeResponse.toString();
485                                         getLog().info(logLine);
486                                         fPending.clear();
487
488                                 } catch (DME2Exception x) {
489                                         getLog().warn(x.getMessage(), x);
490                                         pubResponse.setResponseCode(x.getErrorCode());
491                                         pubResponse.setResponseMessage(x.getErrorMessage());
492                                 } catch (URISyntaxException x) {
493
494                                         getLog().warn(x.getMessage(), x);
495                                         pubResponse.setResponseCode(String.valueOf(HttpStatus.SC_BAD_REQUEST));
496                                         pubResponse.setResponseMessage(x.getMessage());
497                                 } catch (Exception x) {
498
499                                         pubResponse.setResponseCode(String.valueOf(HttpStatus.SC_INTERNAL_SERVER_ERROR));
500                                         pubResponse.setResponseMessage(x.getMessage());
501                                         logger.error("exception: ", x);
502
503                                 }
504
505                                 return pubResponse;
506                         }
507
508                         if (ProtocolTypeConstants.AUTH_KEY.getValue().equalsIgnoreCase(protocolFlag)) {
509                                 getLog().info("sending " + fPending.size() + " msgs to " + httpurl + ". Oldest: "
510                                                 + (nowMs - fPending.peek().timestamp) + " ms");
511                                 final String result = postAuthwithResponse(httpurl, baseStream.toByteArray(), contentType, authKey,
512                                                 authDate, username, password, protocolFlag);
513                                 // Here we are checking for error response. If HTTP status
514                                 // code is not within the http success response code
515                                 // then we consider this as error and return false
516
517                                 pubResponse = createMRPublisherResponse(result, pubResponse);
518
519                                 if (Integer.valueOf(pubResponse.getResponseCode()) < 200
520                                                 || Integer.valueOf(pubResponse.getResponseCode()) > 299) {
521
522                                         return pubResponse;
523                                 }
524
525                                 final String logLine = "MR reply ok (" + (Clock.now() - startMs) + " ms):" + result.toString();
526                                 getLog().info(logLine);
527                                 fPending.clear();
528                                 return pubResponse;
529                         }
530
531                         if (ProtocolTypeConstants.AAF_AUTH.getValue().equalsIgnoreCase(protocolFlag)) {
532                                 getLog().info("sending " + fPending.size() + " msgs to " + httpurl + ". Oldest: "
533                                                 + (nowMs - fPending.peek().timestamp) + " ms");
534                                 final String result = postWithResponse(httpurl, baseStream.toByteArray(), contentType, username,
535                                                 password, protocolFlag);
536
537                                 // Here we are checking for error response. If HTTP status
538                                 // code is not within the http success response code
539                                 // then we consider this as error and return false
540                                 pubResponse = createMRPublisherResponse(result, pubResponse);
541
542                                 if (Integer.valueOf(pubResponse.getResponseCode()) < 200
543                                                 || Integer.valueOf(pubResponse.getResponseCode()) > 299) {
544
545                                         return pubResponse;
546                                 }
547
548                                 final String logLine = String.valueOf((Clock.now() - startMs));
549                                 getLog().info(logLine);
550                                 fPending.clear();
551                                 return pubResponse;
552                         }
553                         
554                         if (ProtocolTypeConstants.HTTPNOAUTH.getValue().equalsIgnoreCase(protocolFlag)) {
555                                 getLog().info("sending " + fPending.size() + " msgs to " + httpurl + ". Oldest: "
556                                                 + (nowMs - fPending.peek().timestamp) + " ms");
557                                 final String result = postNoAuthWithResponse(httpurl, baseStream.toByteArray(), contentType);
558
559                                 // Here we are checking for error response. If HTTP status
560                                 // code is not within the http success response code
561                                 // then we consider this as error and return false
562                                 pubResponse = createMRPublisherResponse(result, pubResponse);
563
564                                 if (Integer.valueOf(pubResponse.getResponseCode()) < 200
565                                                 || Integer.valueOf(pubResponse.getResponseCode()) > 299) {
566
567                                         return pubResponse;
568                                 }
569
570                                 final String logLine = String.valueOf((Clock.now() - startMs));
571                                 getLog().info(logLine);
572                                 fPending.clear();
573                                 return pubResponse;
574                         }
575                 } catch (IllegalArgumentException x) {
576                         getLog().warn(x.getMessage(), x);
577                         pubResponse.setResponseCode(String.valueOf(HttpStatus.SC_BAD_REQUEST));
578                         pubResponse.setResponseMessage(x.getMessage());
579
580                 } catch (IOException x) {
581                         getLog().warn(x.getMessage(), x);
582                         pubResponse.setResponseCode(String.valueOf(HttpStatus.SC_INTERNAL_SERVER_ERROR));
583                         pubResponse.setResponseMessage(x.getMessage());
584
585                 } catch (HttpException x) {
586                         getLog().warn(x.getMessage(), x);
587                         pubResponse.setResponseCode(String.valueOf(HttpStatus.SC_BAD_REQUEST));
588                         pubResponse.setResponseMessage(x.getMessage());
589
590                 } catch (Exception x) {
591                         getLog().warn(x.getMessage(), x);
592
593                         pubResponse.setResponseCode(String.valueOf(HttpStatus.SC_INTERNAL_SERVER_ERROR));
594                         pubResponse.setResponseMessage(x.getMessage());
595
596                 }
597
598                 finally {
599                         if (!fPending.isEmpty()) {
600                                 getLog().warn("Send failed, " + fPending.size() + " message to send.");
601                                 pubResponse.setPendingMsgs(fPending.size());
602                         }
603                         if (os != null) {
604                                 try {
605                                         os.close();
606                                 } catch (Exception x) {
607                                         getLog().warn(x.getMessage(), x);
608                                         pubResponse.setResponseCode(String.valueOf(HttpStatus.SC_INTERNAL_SERVER_ERROR));
609                                         pubResponse.setResponseMessage("Error in closing Output Stream");
610                                 }
611                         }
612                 }
613
614                 return pubResponse;
615         }
616
617         public MRPublisherResponse createMRPublisherResponse(String reply, MRPublisherResponse mrPubResponse) {
618
619                 if (reply.isEmpty()) {
620
621                         mrPubResponse.setResponseCode(String.valueOf(HttpStatus.SC_BAD_REQUEST));
622                         mrPubResponse.setResponseMessage("Please verify the Producer properties");
623                 } else if (reply.startsWith("{")) {
624                         JSONObject jObject = new JSONObject(reply);
625                         if (jObject.has("message") && jObject.has("status")) {
626                                 String message = jObject.getString("message");
627                                 if (null != message) {
628                                         mrPubResponse.setResponseMessage(message);
629                                 }
630                                 mrPubResponse.setResponseCode(Integer.toString(jObject.getInt("status")));
631                         } else {
632                                 mrPubResponse.setResponseCode(String.valueOf(HttpStatus.SC_OK));
633                                 mrPubResponse.setResponseMessage(reply);
634                         }
635                 } else if (reply.startsWith("<")) {
636                         String responseCode = getHTTPErrorResponseCode(reply);
637                         if (responseCode.contains("403")) {
638                                 responseCode = "403";
639                         }
640                         mrPubResponse.setResponseCode(responseCode);
641                         mrPubResponse.setResponseMessage(getHTTPErrorResponseMessage(reply));
642                 }
643
644                 return mrPubResponse;
645         }
646
647         private final String fTopic;
648         private final int fMaxBatchSize;
649         private final long fMaxBatchAgeMs;
650         private final boolean fCompress;
651         private int threadOccuranceTime;
652         private boolean fClosed;
653         private String username;
654         private String password;
655         private String host;
656
657         // host selector
658         private HostSelector fHostSelector = null;
659
660         private final LinkedBlockingQueue<TimestampedMessage> fPending;
661         private long fDontSendUntilMs;
662         private final ScheduledThreadPoolExecutor fExec;
663
664         private String latitude;
665         private String longitude;
666         private String version;
667         private String serviceName;
668         private String env;
669         private String partner;
670         private String routeOffer;
671         private String subContextPath;
672         private String protocol;
673         private String methodType;
674         private String url;
675         private String dmeuser;
676         private String dmepassword;
677         private String contentType;
678         private static final long sfWaitAfterError = 10000;
679         private HashMap<String, String> DMETimeOuts;
680         private DME2Client sender;
681         public String protocolFlag = ProtocolTypeConstants.DME2.getValue();
682         private String authKey;
683         private String authDate;
684         private String handlers;
685         private Properties props;
686         public static String routerFilePath;
687         protected static final Map<String, String> headers = new HashMap<String, String>();
688         public static MultivaluedMap<String, Object> headersMap;
689
690         private MRPublisherResponse pubResponse;
691
692         public MRPublisherResponse getPubResponse() {
693                 return pubResponse;
694         }
695
696         public void setPubResponse(MRPublisherResponse pubResponse) {
697                 this.pubResponse = pubResponse;
698         }
699
700         public static String getRouterFilePath() {
701                 return routerFilePath;
702         }
703
704         public static void setRouterFilePath(String routerFilePath) {
705                 MRSimplerBatchPublisher.routerFilePath = routerFilePath;
706         }
707
708         public Properties getProps() {
709                 return props;
710         }
711
712         public void setProps(Properties props) {
713                 this.props = props;
714         }
715
716         public String getProtocolFlag() {
717                 return protocolFlag;
718         }
719
720         public void setProtocolFlag(String protocolFlag) {
721                 this.protocolFlag = protocolFlag;
722         }
723
724         private void DME2Configue() throws Exception {
725                 try {
726
727                         latitude = props.getProperty("Latitude");
728                         longitude = props.getProperty("Longitude");
729                         version = props.getProperty("Version");
730                         serviceName = props.getProperty("ServiceName");
731                         env = props.getProperty("Environment");
732                         partner = props.getProperty("Partner");
733                         routeOffer = props.getProperty("routeOffer");
734                         subContextPath = props.getProperty("SubContextPath") + fTopic;
735                         
736                         protocol = props.getProperty("Protocol");
737                         methodType = props.getProperty("MethodType");
738                         dmeuser = props.getProperty("username");
739                         dmepassword = props.getProperty("password");
740                         contentType = props.getProperty("contenttype");
741                         handlers = props.getProperty("sessionstickinessrequired");
742                         routerFilePath = props.getProperty("DME2preferredRouterFilePath");
743
744                         /**
745                          * Changes to DME2Client url to use Partner for auto failover
746                          * between data centers When Partner value is not provided use the
747                          * routeOffer value for auto failover within a cluster
748                          */
749
750                         String partitionKey = props.getProperty("partition");
751
752                         if (partner != null && !partner.isEmpty()) {
753                                 url = protocol + "://" + serviceName + "?version=" + version + "&envContext=" + env + "&partner="
754                                                 + partner;
755                                 if (partitionKey != null && !partitionKey.equalsIgnoreCase("")) {
756                                         url = url + "&partitionKey=" + partitionKey;
757                                 }
758                         } else if (routeOffer != null && !routeOffer.isEmpty()) {
759                                 url = protocol + "://" + serviceName + "?version=" + version + "&envContext=" + env + "&routeoffer="
760                                                 + routeOffer;
761                                 if (partitionKey != null && !partitionKey.equalsIgnoreCase("")) {
762                                         url = url + "&partitionKey=" + partitionKey;
763                                 }
764                         }
765
766                         DMETimeOuts = new HashMap<String, String>();
767                         DMETimeOuts.put("AFT_DME2_EP_READ_TIMEOUT_MS", props.getProperty("AFT_DME2_EP_READ_TIMEOUT_MS"));
768                         DMETimeOuts.put("AFT_DME2_ROUNDTRIP_TIMEOUT_MS", props.getProperty("AFT_DME2_ROUNDTRIP_TIMEOUT_MS"));
769                         DMETimeOuts.put("AFT_DME2_EP_CONN_TIMEOUT", props.getProperty("AFT_DME2_EP_CONN_TIMEOUT"));
770                         DMETimeOuts.put("Content-Type", contentType);
771                         System.setProperty("AFT_LATITUDE", latitude);
772                         System.setProperty("AFT_LONGITUDE", longitude);
773                         System.setProperty("AFT_ENVIRONMENT", props.getProperty("AFT_ENVIRONMENT"));
774                         // System.setProperty("DME2.DEBUG", "true");
775
776                         // SSL changes
777                         // System.setProperty("AFT_DME2_CLIENT_SSL_INCLUDE_PROTOCOLS",
778                         
779                         System.setProperty("AFT_DME2_CLIENT_SSL_INCLUDE_PROTOCOLS", "TLSv1.1,TLSv1.2");
780                         System.setProperty("AFT_DME2_CLIENT_IGNORE_SSL_CONFIG", "false");
781                         System.setProperty("AFT_DME2_CLIENT_KEYSTORE_PASSWORD", "changeit");
782
783                         // SSL changes
784
785                         sender = new DME2Client(new URI(url), 5000L);
786
787                         sender.setAllowAllHttpReturnCodes(true);
788                         sender.setMethod(methodType);
789                         sender.setSubContext(subContextPath);
790                         sender.setCredentials(dmeuser, dmepassword);
791                         sender.setHeaders(DMETimeOuts);
792                         if (handlers != null &&handlers.equalsIgnoreCase("yes")) {
793                                 sender.addHeader("AFT_DME2_EXCHANGE_REQUEST_HANDLERS",
794                                                 props.getProperty("AFT_DME2_EXCHANGE_REQUEST_HANDLERS"));
795                                 sender.addHeader("AFT_DME2_EXCHANGE_REPLY_HANDLERS",
796                                                 props.getProperty("AFT_DME2_EXCHANGE_REPLY_HANDLERS"));
797                                 sender.addHeader("AFT_DME2_REQ_TRACE_ON", props.getProperty("AFT_DME2_REQ_TRACE_ON"));
798                         } else {
799                                 sender.addHeader("AFT_DME2_EXCHANGE_REPLY_HANDLERS", "com.att.nsa.mr.dme.client.HeaderReplyHandler");
800                         }
801                 } catch (DME2Exception x) {
802                         getLog().warn(x.getMessage(), x);
803                         throw new DME2Exception(x.getErrorCode(), x.getErrorMessage());
804                 } catch (URISyntaxException x) {
805
806                         getLog().warn(x.getMessage(), x);
807                         throw new URISyntaxException(url, x.getMessage());
808                 } catch (Exception x) {
809
810                         getLog().warn(x.getMessage(), x);
811                         throw new IllegalArgumentException(x.getMessage());
812                 }
813         }
814
815         private MRSimplerBatchPublisher(Collection<String> hosts, String topic, int maxBatchSize, long maxBatchAgeMs,
816                         boolean compress) throws MalformedURLException {
817                 super(hosts);
818
819                 if (topic == null || topic.length() < 1) {
820                         throw new IllegalArgumentException("A topic must be provided.");
821                 }
822
823                 fHostSelector = new HostSelector(hosts, null);
824                 fClosed = false;
825                 fTopic = topic;
826                 fMaxBatchSize = maxBatchSize;
827                 fMaxBatchAgeMs = maxBatchAgeMs;
828                 fCompress = compress;
829
830                 fPending = new LinkedBlockingQueue<>();
831                 fDontSendUntilMs = 0;
832                 fExec = new ScheduledThreadPoolExecutor(1);
833                 pubResponse = new MRPublisherResponse();
834
835         }
836
837         private MRSimplerBatchPublisher(Collection<String> hosts, String topic, int maxBatchSize, long maxBatchAgeMs,
838                         boolean compress, boolean allowSelfSignedCerts, int httpThreadOccurnace) throws MalformedURLException {
839                 super(hosts);
840
841                 if (topic == null || topic.length() < 1) {
842                         throw new IllegalArgumentException("A topic must be provided.");
843                 }
844
845                 fHostSelector = new HostSelector(hosts, null);
846                 fClosed = false;
847                 fTopic = topic;
848                 fMaxBatchSize = maxBatchSize;
849                 fMaxBatchAgeMs = maxBatchAgeMs;
850                 fCompress = compress;
851                 threadOccuranceTime = httpThreadOccurnace;
852                 fPending = new LinkedBlockingQueue<>();
853                 fDontSendUntilMs = 0;
854                 fExec = new ScheduledThreadPoolExecutor(1);
855                 fExec.scheduleAtFixedRate(new Runnable() {
856                         @Override
857                         public void run() {
858                                 send(false);
859                         }
860                 }, 100, threadOccuranceTime, TimeUnit.MILLISECONDS);
861                 pubResponse = new MRPublisherResponse();
862         }
863
864         private static class TimestampedMessage extends message {
865                 public TimestampedMessage(message m) {
866                         super(m);
867                         timestamp = Clock.now();
868                 }
869
870                 public final long timestamp;
871         }
872
873         public String getUsername() {
874                 return username;
875         }
876
877         public void setUsername(String username) {
878                 this.username = username;
879         }
880
881         public String getPassword() {
882                 return password;
883         }
884
885         public void setPassword(String password) {
886                 this.password = password;
887         }
888
889         public String getHost() {
890                 return host;
891         }
892
893         public void setHost(String host) {
894                 this.host = host;
895         }
896
897         public String getContentType() {
898                 return contentType;
899         }
900
901         public void setContentType(String contentType) {
902                 this.contentType = contentType;
903         }
904
905         public String getAuthKey() {
906                 return authKey;
907         }
908
909         public void setAuthKey(String authKey) {
910                 this.authKey = authKey;
911         }
912
913         public String getAuthDate() {
914                 return authDate;
915         }
916
917         public void setAuthDate(String authDate) {
918                 this.authDate = authDate;
919         }
920
921 }