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