one more case added in DmaapClientUtilTest.java
[dmaap/messagerouter/dmaapclient.git] / src / main / java / com / att / nsa / 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 com.att.nsa.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 com.att.nsa.mr.client.HostSelector;
55 import com.att.nsa.mr.client.MRBatchingPublisher;
56 import com.att.nsa.mr.client.response.MRPublisherResponse;
57 import com.att.nsa.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<message>();
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<message>();
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()) {
227                         if (!sendBatch()) {
228                                 getLog().warn("Send failed, " + fPending.size() + " message to send.");
229
230                                 // note the time for back-off
231                                 fDontSendUntilMs = sfWaitAfterError + Clock.now();
232                         }
233                 }
234         }
235
236         private synchronized boolean shouldSendNow() {
237                 boolean shouldSend = false;
238                 if (fPending.isEmpty()) {
239                         final long nowMs = Clock.now();
240
241                         shouldSend = (fPending.size() >= fMaxBatchSize);
242                         if (!shouldSend) {
243                                 final long sendAtMs = fPending.peek().timestamp + fMaxBatchAgeMs;
244                                 shouldSend = sendAtMs <= nowMs;
245                         }
246
247                         // however, wait after an error
248                         shouldSend = shouldSend && nowMs >= fDontSendUntilMs;
249                 }
250                 return shouldSend;
251         }
252
253         /**
254          * Method to parse published JSON Objects and Arrays
255          * 
256          * @return JSONArray
257          */
258         private JSONArray parseJSON() {
259                 JSONArray jsonArray = new JSONArray();
260                 for (TimestampedMessage m : fPending) {
261                         JSONTokener jsonTokener = new JSONTokener(m.fMsg);
262                         JSONObject jsonObject = null;
263                         JSONArray tempjsonArray = null;
264                         final char firstChar = jsonTokener.next();
265                         jsonTokener.back();
266                         if ('[' == firstChar) {
267                                 tempjsonArray = new JSONArray(jsonTokener);
268                                 if (null != tempjsonArray) {
269                                         for (int i = 0; i < tempjsonArray.length(); i++) {
270                                                 jsonArray.put(tempjsonArray.getJSONObject(i));
271                                         }
272                                 }
273                         } else {
274                                 jsonObject = new JSONObject(jsonTokener);
275                                 jsonArray.put(jsonObject);
276                         }
277
278                 }
279                 return jsonArray;
280         }
281
282         private synchronized boolean sendBatch() {
283                 // it's possible for this call to be made with an empty list. in this
284                 // case, just return.
285                 if (fPending.size() < 1) {
286                         return true;
287                 }
288
289                 final long nowMs = Clock.now();
290
291                 if (this.fHostSelector != null) {
292                         host = this.fHostSelector.selectBaseHost();
293                 }
294
295                 final String httpurl = MRConstants.makeUrl(host, fTopic, props.getProperty("Protocol"),
296                                 props.getProperty("partition"));
297
298                 try {
299                         
300                         final ByteArrayOutputStream baseStream = new ByteArrayOutputStream();
301                         OutputStream os = baseStream;
302                         final String contentType = props.getProperty("contenttype");
303                         if (contentType.equalsIgnoreCase("application/json")) {
304                                 JSONArray jsonArray = parseJSON();
305                                 os.write(jsonArray.toString().getBytes());
306                                 os.close();
307
308                         } else if (contentType.equalsIgnoreCase("text/plain")) {
309                                 for (TimestampedMessage m : fPending) {
310                                         os.write(m.fMsg.getBytes());
311                                         os.write('\n');
312                                 }
313                                 os.close();
314                         } else if (contentType.equalsIgnoreCase("application/cambria")
315                                         || (contentType.equalsIgnoreCase("application/cambria-zip"))) {
316                                 if (contentType.equalsIgnoreCase("application/cambria-zip")) {
317                                         os = new GZIPOutputStream(baseStream);
318                                 }
319                                 for (TimestampedMessage m : fPending) {
320
321                                         os.write(("" + m.fPartition.length()).getBytes());
322                                         os.write('.');
323                                         os.write(("" + m.fMsg.length()).getBytes());
324                                         os.write('.');
325                                         os.write(m.fPartition.getBytes());
326                                         os.write(m.fMsg.getBytes());
327                                         os.write('\n');
328                                 }
329                                 os.close();
330                         } else {
331                                 for (TimestampedMessage m : fPending) {
332                                         os.write(m.fMsg.getBytes());
333
334                                 }
335                                 os.close();
336                         }
337
338                         final long startMs = Clock.now();
339                         if (ProtocolTypeConstants.DME2.getValue().equalsIgnoreCase(protocolFlag)) {
340
341                                 DME2Configue();
342
343                                 Thread.sleep(5);
344                                 getLog().info("sending " + fPending.size() + " msgs to " + url + subContextPath + ". Oldest: "
345                                                 + (nowMs - fPending.peek().timestamp) + " ms");
346                                 sender.setPayload(os.toString());
347                                 String dmeResponse = sender.sendAndWait(5000L);
348
349                                 final String logLine = "MR reply ok (" + (Clock.now() - startMs) + " ms):" + dmeResponse.toString();
350                                 getLog().info(logLine);
351                                 fPending.clear();
352                                 return true;
353                         }
354
355                         if (ProtocolTypeConstants.AUTH_KEY.getValue().equalsIgnoreCase(protocolFlag)) {
356                                 getLog().info("sending " + fPending.size() + " msgs to " + httpurl + ". Oldest: "
357                                                 + (nowMs - fPending.peek().timestamp) + " ms");
358                                 final JSONObject result = postAuth(httpurl, baseStream.toByteArray(), contentType, authKey, authDate,
359                                                 username, password, 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 (IllegalArgumentException x) {
407                         getLog().warn(x.getMessage(), x);
408                 } catch (IOException x) {
409                         getLog().warn(x.getMessage(), x);
410                 } catch (HttpException x) {
411                         getLog().warn(x.getMessage(), x);
412                 } catch (Exception x) {
413                         getLog().warn(x.getMessage(), x);
414                 }
415                 return false;
416         }
417
418         public synchronized MRPublisherResponse sendBatchWithResponse() {
419                 // it's possible for this call to be made with an empty list. in this
420                 // case, just return.
421                 if (fPending.isEmpty()) {
422                         pubResponse.setResponseCode(String.valueOf(HttpStatus.SC_BAD_REQUEST));
423                         pubResponse.setResponseMessage("No Messages to send");
424                         return pubResponse;
425                 }
426
427                 final long nowMs = Clock.now();
428
429                 host = this.fHostSelector.selectBaseHost();
430
431                 final String httpurl = MRConstants.makeUrl(host, fTopic, props.getProperty("Protocol"),
432                                 props.getProperty("partition"));
433                 OutputStream os = null;
434                 try {
435
436                         final ByteArrayOutputStream baseStream = new ByteArrayOutputStream();
437                         os = baseStream;
438                         final String contentType = props.getProperty("contenttype");
439                         if (contentType.equalsIgnoreCase("application/json")) {
440                                 JSONArray jsonArray = parseJSON();
441                                 os.write(jsonArray.toString().getBytes());
442                         } else if (contentType.equalsIgnoreCase("text/plain")) {
443                                 for (TimestampedMessage m : fPending) {
444                                         os.write(m.fMsg.getBytes());
445                                         os.write('\n');
446                                 }
447                         } else if (contentType.equalsIgnoreCase("application/cambria")
448                                         || (contentType.equalsIgnoreCase("application/cambria-zip"))) {
449                                 if (contentType.equalsIgnoreCase("application/cambria-zip")) {
450                                         os = new GZIPOutputStream(baseStream);
451                                 }
452                                 for (TimestampedMessage m : fPending) {
453
454                                         os.write(("" + m.fPartition.length()).getBytes());
455                                         os.write('.');
456                                         os.write(("" + m.fMsg.length()).getBytes());
457                                         os.write('.');
458                                         os.write(m.fPartition.getBytes());
459                                         os.write(m.fMsg.getBytes());
460                                         os.write('\n');
461                                 }
462                                 os.close();
463                         } else {
464                                 for (TimestampedMessage m : fPending) {
465                                         os.write(m.fMsg.getBytes());
466
467                                 }
468                         }
469
470                         final long startMs = Clock.now();
471                         if (ProtocolTypeConstants.DME2.getValue().equalsIgnoreCase(protocolFlag)) {
472
473                                 try {
474                                         DME2Configue();
475
476                                         Thread.sleep(5);
477                                         getLog().info("sending " + fPending.size() + " msgs to " + url + subContextPath + ". Oldest: "
478                                                         + (nowMs - fPending.peek().timestamp) + " ms");
479                                         sender.setPayload(os.toString());
480
481                                         String dmeResponse = sender.sendAndWait(5000L);
482
483                                         pubResponse = createMRPublisherResponse(dmeResponse, pubResponse);
484
485                                         if (Integer.valueOf(pubResponse.getResponseCode()) < 200
486                                                         || Integer.valueOf(pubResponse.getResponseCode()) > 299) {
487
488                                                 return pubResponse;
489                                         }
490                                         final String logLine = String.valueOf((Clock.now() - startMs)) + dmeResponse.toString();
491                                         getLog().info(logLine);
492                                         fPending.clear();
493
494                                 } catch (DME2Exception x) {
495                                         getLog().warn(x.getMessage(), x);
496                                         pubResponse.setResponseCode(x.getErrorCode());
497                                         pubResponse.setResponseMessage(x.getErrorMessage());
498                                 } catch (URISyntaxException x) {
499
500                                         getLog().warn(x.getMessage(), x);
501                                         pubResponse.setResponseCode(String.valueOf(HttpStatus.SC_BAD_REQUEST));
502                                         pubResponse.setResponseMessage(x.getMessage());
503                                 } catch (Exception x) {
504
505                                         pubResponse.setResponseCode(String.valueOf(HttpStatus.SC_INTERNAL_SERVER_ERROR));
506                                         pubResponse.setResponseMessage(x.getMessage());
507                                         logger.error("exception: ", x);
508
509                                 }
510
511                                 return pubResponse;
512                         }
513
514                         if (ProtocolTypeConstants.AUTH_KEY.getValue().equalsIgnoreCase(protocolFlag)) {
515                                 getLog().info("sending " + fPending.size() + " msgs to " + httpurl + ". Oldest: "
516                                                 + (nowMs - fPending.peek().timestamp) + " ms");
517                                 final String result = postAuthwithResponse(httpurl, baseStream.toByteArray(), contentType, authKey,
518                                                 authDate, username, password, protocolFlag);
519                                 // Here we are checking for error response. If HTTP status
520                                 // code is not within the http success response code
521                                 // then we consider this as error and return false
522
523                                 pubResponse = createMRPublisherResponse(result, pubResponse);
524
525                                 if (Integer.valueOf(pubResponse.getResponseCode()) < 200
526                                                 || Integer.valueOf(pubResponse.getResponseCode()) > 299) {
527
528                                         return pubResponse;
529                                 }
530
531                                 final String logLine = "MR reply ok (" + (Clock.now() - startMs) + " ms):" + result.toString();
532                                 getLog().info(logLine);
533                                 fPending.clear();
534                                 return pubResponse;
535                         }
536
537                         if (ProtocolTypeConstants.AAF_AUTH.getValue().equalsIgnoreCase(protocolFlag)) {
538                                 getLog().info("sending " + fPending.size() + " msgs to " + httpurl + ". Oldest: "
539                                                 + (nowMs - fPending.peek().timestamp) + " ms");
540                                 final String result = postWithResponse(httpurl, baseStream.toByteArray(), contentType, username,
541                                                 password, protocolFlag);
542
543                                 // Here we are checking for error response. If HTTP status
544                                 // code is not within the http success response code
545                                 // then we consider this as error and return false
546                                 pubResponse = createMRPublisherResponse(result, pubResponse);
547
548                                 if (Integer.valueOf(pubResponse.getResponseCode()) < 200
549                                                 || Integer.valueOf(pubResponse.getResponseCode()) > 299) {
550
551                                         return pubResponse;
552                                 }
553
554                                 final String logLine = String.valueOf((Clock.now() - startMs));
555                                 getLog().info(logLine);
556                                 fPending.clear();
557                                 return pubResponse;
558                         }
559                         
560                         if (ProtocolTypeConstants.HTTPNOAUTH.getValue().equalsIgnoreCase(protocolFlag)) {
561                                 getLog().info("sending " + fPending.size() + " msgs to " + httpurl + ". Oldest: "
562                                                 + (nowMs - fPending.peek().timestamp) + " ms");
563                                 final String result = postNoAuthWithResponse(httpurl, baseStream.toByteArray(), contentType);
564
565                                 // Here we are checking for error response. If HTTP status
566                                 // code is not within the http success response code
567                                 // then we consider this as error and return false
568                                 pubResponse = createMRPublisherResponse(result, pubResponse);
569
570                                 if (Integer.valueOf(pubResponse.getResponseCode()) < 200
571                                                 || Integer.valueOf(pubResponse.getResponseCode()) > 299) {
572
573                                         return pubResponse;
574                                 }
575
576                                 final String logLine = String.valueOf((Clock.now() - startMs));
577                                 getLog().info(logLine);
578                                 fPending.clear();
579                                 return pubResponse;
580                         }
581                 } catch (IllegalArgumentException x) {
582                         getLog().warn(x.getMessage(), x);
583                         pubResponse.setResponseCode(String.valueOf(HttpStatus.SC_BAD_REQUEST));
584                         pubResponse.setResponseMessage(x.getMessage());
585
586                 } catch (IOException x) {
587                         getLog().warn(x.getMessage(), x);
588                         pubResponse.setResponseCode(String.valueOf(HttpStatus.SC_INTERNAL_SERVER_ERROR));
589                         pubResponse.setResponseMessage(x.getMessage());
590
591                 } catch (HttpException x) {
592                         getLog().warn(x.getMessage(), x);
593                         pubResponse.setResponseCode(String.valueOf(HttpStatus.SC_BAD_REQUEST));
594                         pubResponse.setResponseMessage(x.getMessage());
595
596                 } catch (Exception x) {
597                         getLog().warn(x.getMessage(), x);
598
599                         pubResponse.setResponseCode(String.valueOf(HttpStatus.SC_INTERNAL_SERVER_ERROR));
600                         pubResponse.setResponseMessage(x.getMessage());
601
602                 }
603
604                 finally {
605                         if (fPending.size() > 0) {
606                                 getLog().warn("Send failed, " + fPending.size() + " message to send.");
607                                 pubResponse.setPendingMsgs(fPending.size());
608                         }
609                         if (os != null) {
610                                 try {
611                                         os.close();
612                                 } catch (Exception x) {
613                                         getLog().warn(x.getMessage(), x);
614                                         pubResponse.setResponseCode(String.valueOf(HttpStatus.SC_INTERNAL_SERVER_ERROR));
615                                         pubResponse.setResponseMessage("Error in closing Output Stream");
616                                 }
617                         }
618                 }
619
620                 return pubResponse;
621         }
622
623         public MRPublisherResponse createMRPublisherResponse(String reply, MRPublisherResponse mrPubResponse) {
624
625                 if (reply.isEmpty()) {
626
627                         mrPubResponse.setResponseCode(String.valueOf(HttpStatus.SC_BAD_REQUEST));
628                         mrPubResponse.setResponseMessage("Please verify the Producer properties");
629                 } else if (reply.startsWith("{")) {
630                         JSONObject jObject = new JSONObject(reply);
631                         if (jObject.has("message") && jObject.has("status")) {
632                                 String message = jObject.getString("message");
633                                 if (null != message) {
634                                         mrPubResponse.setResponseMessage(message);
635                                 }
636                                 mrPubResponse.setResponseCode(Integer.toString(jObject.getInt("status")));
637                         } else {
638                                 mrPubResponse.setResponseCode(String.valueOf(HttpStatus.SC_OK));
639                                 mrPubResponse.setResponseMessage(reply);
640                         }
641                 } else if (reply.startsWith("<")) {
642                         String responseCode = getHTTPErrorResponseCode(reply);
643                         if (responseCode.contains("403")) {
644                                 responseCode = "403";
645                         }
646                         mrPubResponse.setResponseCode(responseCode);
647                         mrPubResponse.setResponseMessage(getHTTPErrorResponseMessage(reply));
648                 }
649
650                 return mrPubResponse;
651         }
652
653         private final String fTopic;
654         private final int fMaxBatchSize;
655         private final long fMaxBatchAgeMs;
656         private final boolean fCompress;
657         private int threadOccuranceTime;
658         private boolean fClosed;
659         private String username;
660         private String password;
661         private String host;
662
663         // host selector
664         private HostSelector fHostSelector = null;
665
666         private final LinkedBlockingQueue<TimestampedMessage> fPending;
667         private long fDontSendUntilMs;
668         private final ScheduledThreadPoolExecutor fExec;
669
670         private String latitude;
671         private String longitude;
672         private String version;
673         private String serviceName;
674         private String env;
675         private String partner;
676         private String routeOffer;
677         private String subContextPath;
678         private String protocol;
679         private String methodType;
680         private String url;
681         private String dmeuser;
682         private String dmepassword;
683         private String contentType;
684         private static final long sfWaitAfterError = 10000;
685         private HashMap<String, String> DMETimeOuts;
686         private DME2Client sender;
687         public String protocolFlag = ProtocolTypeConstants.DME2.getValue();
688         private String authKey;
689         private String authDate;
690         private String handlers;
691         private Properties props;
692         public static String routerFilePath;
693         protected static final Map<String, String> headers = new HashMap<String, String>();
694         public static MultivaluedMap<String, Object> headersMap;
695
696         private MRPublisherResponse pubResponse;
697
698         public MRPublisherResponse getPubResponse() {
699                 return pubResponse;
700         }
701
702         public void setPubResponse(MRPublisherResponse pubResponse) {
703                 this.pubResponse = pubResponse;
704         }
705
706         public static String getRouterFilePath() {
707                 return routerFilePath;
708         }
709
710         public static void setRouterFilePath(String routerFilePath) {
711                 MRSimplerBatchPublisher.routerFilePath = routerFilePath;
712         }
713
714         public Properties getProps() {
715                 return props;
716         }
717
718         public void setProps(Properties props) {
719                 this.props = props;
720         }
721
722         public String getProtocolFlag() {
723                 return protocolFlag;
724         }
725
726         public void setProtocolFlag(String protocolFlag) {
727                 this.protocolFlag = protocolFlag;
728         }
729
730         private void DME2Configue() throws Exception {
731                 try {
732
733                         latitude = props.getProperty("Latitude");
734                         longitude = props.getProperty("Longitude");
735                         version = props.getProperty("Version");
736                         serviceName = props.getProperty("ServiceName");
737                         env = props.getProperty("Environment");
738                         partner = props.getProperty("Partner");
739                         routeOffer = props.getProperty("routeOffer");
740                         subContextPath = props.getProperty("SubContextPath") + fTopic;
741                         
742                         protocol = props.getProperty("Protocol");
743                         methodType = props.getProperty("MethodType");
744                         dmeuser = props.getProperty("username");
745                         dmepassword = props.getProperty("password");
746                         contentType = props.getProperty("contenttype");
747                         handlers = props.getProperty("sessionstickinessrequired");
748                         routerFilePath = props.getProperty("DME2preferredRouterFilePath");
749
750                         /**
751                          * Changes to DME2Client url to use Partner for auto failover
752                          * between data centers When Partner value is not provided use the
753                          * routeOffer value for auto failover within a cluster
754                          */
755
756                         String partitionKey = props.getProperty("partition");
757
758                         if (partner != null && !partner.isEmpty()) {
759                                 url = protocol + "://" + serviceName + "?version=" + version + "&envContext=" + env + "&partner="
760                                                 + partner;
761                                 if (partitionKey != null && !partitionKey.equalsIgnoreCase("")) {
762                                         url = url + "&partitionKey=" + partitionKey;
763                                 }
764                         } else if (routeOffer != null && !routeOffer.isEmpty()) {
765                                 url = protocol + "://" + serviceName + "?version=" + version + "&envContext=" + env + "&routeoffer="
766                                                 + routeOffer;
767                                 if (partitionKey != null && !partitionKey.equalsIgnoreCase("")) {
768                                         url = url + "&partitionKey=" + partitionKey;
769                                 }
770                         }
771
772                         DMETimeOuts = new HashMap<String, String>();
773                         DMETimeOuts.put("AFT_DME2_EP_READ_TIMEOUT_MS", props.getProperty("AFT_DME2_EP_READ_TIMEOUT_MS"));
774                         DMETimeOuts.put("AFT_DME2_ROUNDTRIP_TIMEOUT_MS", props.getProperty("AFT_DME2_ROUNDTRIP_TIMEOUT_MS"));
775                         DMETimeOuts.put("AFT_DME2_EP_CONN_TIMEOUT", props.getProperty("AFT_DME2_EP_CONN_TIMEOUT"));
776                         DMETimeOuts.put("Content-Type", contentType);
777                         System.setProperty("AFT_LATITUDE", latitude);
778                         System.setProperty("AFT_LONGITUDE", longitude);
779                         System.setProperty("AFT_ENVIRONMENT", props.getProperty("AFT_ENVIRONMENT"));
780                         // System.setProperty("DME2.DEBUG", "true");
781
782                         // SSL changes
783                         // System.setProperty("AFT_DME2_CLIENT_SSL_INCLUDE_PROTOCOLS",
784                         
785                         System.setProperty("AFT_DME2_CLIENT_SSL_INCLUDE_PROTOCOLS", "TLSv1.1,TLSv1.2");
786                         System.setProperty("AFT_DME2_CLIENT_IGNORE_SSL_CONFIG", "false");
787                         System.setProperty("AFT_DME2_CLIENT_KEYSTORE_PASSWORD", "changeit");
788
789                         // SSL changes
790
791                         sender = new DME2Client(new URI(url), 5000L);
792
793                         sender.setAllowAllHttpReturnCodes(true);
794                         sender.setMethod(methodType);
795                         sender.setSubContext(subContextPath);
796                         sender.setCredentials(dmeuser, dmepassword);
797                         sender.setHeaders(DMETimeOuts);
798                         if (handlers != null &&handlers.equalsIgnoreCase("yes")) {
799                                 sender.addHeader("AFT_DME2_EXCHANGE_REQUEST_HANDLERS",
800                                                 props.getProperty("AFT_DME2_EXCHANGE_REQUEST_HANDLERS"));
801                                 sender.addHeader("AFT_DME2_EXCHANGE_REPLY_HANDLERS",
802                                                 props.getProperty("AFT_DME2_EXCHANGE_REPLY_HANDLERS"));
803                                 sender.addHeader("AFT_DME2_REQ_TRACE_ON", props.getProperty("AFT_DME2_REQ_TRACE_ON"));
804                         } else {
805                                 sender.addHeader("AFT_DME2_EXCHANGE_REPLY_HANDLERS", "com.att.nsa.mr.dme.client.HeaderReplyHandler");
806                         }
807                 } catch (DME2Exception x) {
808                         getLog().warn(x.getMessage(), x);
809                         throw new DME2Exception(x.getErrorCode(), x.getErrorMessage());
810                 } catch (URISyntaxException x) {
811
812                         getLog().warn(x.getMessage(), x);
813                         throw new URISyntaxException(url, x.getMessage());
814                 } catch (Exception x) {
815
816                         getLog().warn(x.getMessage(), x);
817                         throw new IllegalArgumentException(x.getMessage());
818                 }
819         }
820
821         private MRSimplerBatchPublisher(Collection<String> hosts, String topic, int maxBatchSize, long maxBatchAgeMs,
822                         boolean compress) throws MalformedURLException {
823                 super(hosts);
824
825                 if (topic == null || topic.length() < 1) {
826                         throw new IllegalArgumentException("A topic must be provided.");
827                 }
828
829                 fHostSelector = new HostSelector(hosts, null);
830                 fClosed = false;
831                 fTopic = topic;
832                 fMaxBatchSize = maxBatchSize;
833                 fMaxBatchAgeMs = maxBatchAgeMs;
834                 fCompress = compress;
835
836                 fPending = new LinkedBlockingQueue<TimestampedMessage>();
837                 fDontSendUntilMs = 0;
838                 fExec = new ScheduledThreadPoolExecutor(1);
839                 pubResponse = new MRPublisherResponse();
840
841         }
842
843         private MRSimplerBatchPublisher(Collection<String> hosts, String topic, int maxBatchSize, long maxBatchAgeMs,
844                         boolean compress, boolean allowSelfSignedCerts, int httpThreadOccurnace) throws MalformedURLException {
845                 super(hosts);
846
847                 if (topic == null || topic.length() < 1) {
848                         throw new IllegalArgumentException("A topic must be provided.");
849                 }
850
851                 fHostSelector = new HostSelector(hosts, null);
852                 fClosed = false;
853                 fTopic = topic;
854                 fMaxBatchSize = maxBatchSize;
855                 fMaxBatchAgeMs = maxBatchAgeMs;
856                 fCompress = compress;
857                 threadOccuranceTime = httpThreadOccurnace;
858                 fPending = new LinkedBlockingQueue<TimestampedMessage>();
859                 fDontSendUntilMs = 0;
860                 fExec = new ScheduledThreadPoolExecutor(1);
861                 fExec.scheduleAtFixedRate(new Runnable() {
862                         @Override
863                         public void run() {
864                                 send(false);
865                         }
866                 }, 100, threadOccuranceTime, TimeUnit.MILLISECONDS);
867                 pubResponse = new MRPublisherResponse();
868         }
869
870         private static class TimestampedMessage extends message {
871                 public TimestampedMessage(message m) {
872                         super(m);
873                         timestamp = Clock.now();
874                 }
875
876                 public final long timestamp;
877         }
878
879         public String getUsername() {
880                 return username;
881         }
882
883         public void setUsername(String username) {
884                 this.username = username;
885         }
886
887         public String getPassword() {
888                 return password;
889         }
890
891         public void setPassword(String password) {
892                 this.password = password;
893         }
894
895         public String getHost() {
896                 return host;
897         }
898
899         public void setHost(String host) {
900                 this.host = host;
901         }
902
903         public String getContentType() {
904                 return contentType;
905         }
906
907         public void setContentType(String contentType) {
908                 this.contentType = contentType;
909         }
910
911         public String getAuthKey() {
912                 return authKey;
913         }
914
915         public void setAuthKey(String authKey) {
916                 this.authKey = authKey;
917         }
918
919         public String getAuthDate() {
920                 return authDate;
921         }
922
923         public void setAuthDate(String authDate) {
924                 this.authDate = authDate;
925         }
926
927 }