From 72a9ab9e886cdeabc4b43418a7054a5796a0ff55 Mon Sep 17 00:00:00 2001 From: sliard Date: Mon, 12 Apr 2021 15:58:22 +0200 Subject: [DMAAP-CLIENT] First sonar issues review part2 update Copyright informations fix checkstyle warning and fix code review comments remove Prop Issue-ID: DMAAP-1585 Change-Id: I445ca5d0888a555acbac70af7ed571be26d74f79 Signed-off-by: sliard --- pom.xml | 22 +- .../org/onap/dmaap/mr/client/HostSelector.java | 262 ++- .../onap/dmaap/mr/client/MRBatchingPublisher.java | 47 +- .../java/org/onap/dmaap/mr/client/MRClient.java | 81 +- .../org/onap/dmaap/mr/client/MRClientBuilders.java | 363 ++-- .../org/onap/dmaap/mr/client/MRClientFactory.java | 499 +++--- .../java/org/onap/dmaap/mr/client/MRConsumer.java | 55 +- .../onap/dmaap/mr/client/MRIdentityManager.java | 136 +- .../java/org/onap/dmaap/mr/client/MRPublisher.java | 122 +- .../org/onap/dmaap/mr/client/MRTopicManager.java | 322 ++-- .../org/onap/dmaap/mr/client/ProtocolType.java | 47 + .../java/org/onap/dmaap/mr/client/impl/Clock.java | 70 +- .../onap/dmaap/mr/client/impl/DmaapClientUtil.java | 138 +- .../onap/dmaap/mr/client/impl/MRBaseClient.java | 722 ++++---- .../dmaap/mr/client/impl/MRBatchPublisher.java | 807 ++++----- .../dmaap/mr/client/impl/MRClientVersionInfo.java | 50 +- .../org/onap/dmaap/mr/client/impl/MRConstants.java | 295 ++-- .../onap/dmaap/mr/client/impl/MRConsumerImpl.java | 168 +- .../org/onap/dmaap/mr/client/impl/MRFormat.java | 61 +- .../onap/dmaap/mr/client/impl/MRMetaClient.java | 436 +++-- .../mr/client/impl/MRSimplerBatchPublisher.java | 1757 ++++++++++---------- .../mr/client/response/MRConsumerResponse.java | 53 +- .../mr/client/response/MRPublisherResponse.java | 63 +- .../client/DefaultLoggingFailoverFaultHandler.java | 52 - .../dmaap/mr/dme/client/HeaderReplyHandler.java | 59 +- .../mr/dme/client/PreferredRouteReplyHandler.java | 86 +- .../dme/client/PreferredRouteRequestHandler.java | 50 +- .../dmaap/mr/dme/client/SimpleExampleConsumer.java | 88 - .../mr/dme/client/SimpleExamplePublisher.java | 128 -- .../dmaap/mr/test/clients/ConsolePublisher.java | 95 -- .../mr/test/clients/ProtocolTypeConstants.java | 44 - .../onap/dmaap/mr/test/clients/SampleConsumer.java | 87 - .../dmaap/mr/test/clients/SamplePublisher.java | 85 - .../mr/test/clients/SimpleExampleConsumer.java | 84 - .../SimpleExampleConsumerWithReturnResponse.java | 98 -- .../mr/test/clients/SimpleExamplePublisher.java | 97 -- .../SimpleExamplePublisherWithResponse.java | 82 - .../mr/test/support/MRBatchingPublisherMock.java | 184 -- .../onap/dmaap/mr/test/support/MRConsumerMock.java | 169 -- .../org/onap/dmaap/mr/tools/ApiKeyCommand.java | 191 +-- .../java/org/onap/dmaap/mr/tools/AuthCommand.java | 76 +- .../org/onap/dmaap/mr/tools/ClusterCommand.java | 88 +- .../org/onap/dmaap/mr/tools/MRCommandContext.java | 151 +- src/main/java/org/onap/dmaap/mr/tools/MRTool.java | 49 - .../org/onap/dmaap/mr/tools/MessageCommand.java | 170 +- .../java/org/onap/dmaap/mr/tools/ToolsUtil.java | 22 +- .../java/org/onap/dmaap/mr/tools/TopicCommand.java | 321 ++-- .../java/org/onap/dmaap/mr/tools/TraceCommand.java | 159 +- .../org/onap/dmaap/mr/tools/ValidatorUtil.java | 338 ++-- src/main/resources/dme2/consumer.properties | 4 +- src/main/resources/dme2/producer.properties | 6 +- .../org/onap/dmaap/mr/client/HostSelectorTest.java | 53 +- .../org/onap/dmaap/mr/client/JUnitTestSuite.java | 24 +- .../onap/dmaap/mr/client/MRClientBuildersTest.java | 14 +- .../onap/dmaap/mr/client/MRClientFactoryTest.java | 96 +- .../java/org/onap/dmaap/mr/client/TestRunner.java | 26 +- .../dmaap/mr/client/impl/DMaapClientUtilTest.java | 80 +- .../dmaap/mr/client/impl/MRBaseClientTest.java | 709 ++++---- .../dmaap/mr/client/impl/MRBatchPublisherTest.java | 53 +- .../onap/dmaap/mr/client/impl/MRConstantsTest.java | 217 ++- .../dmaap/mr/client/impl/MRConsumerImplTest.java | 273 +-- .../dmaap/mr/client/impl/MRMetaClientTest.java | 178 +- .../mr/client/impl/MRSimplerBatchConsumerTest.java | 80 +- .../client/impl/MRSimplerBatchPublisherTest.java | 448 +++-- .../dmaap/mr/client/response/JUnitTestSuite.java | 23 +- .../mr/client/response/MRConsumerResponseTest.java | 85 +- .../client/response/MRPublisherResponseTest.java | 103 +- .../onap/dmaap/mr/client/response/TestRunner.java | 26 +- .../DefaultLoggingFailoverFaultHandlerTest.java | 59 - .../mr/dme/client/HeaderReplyHandlerTest.java | 80 +- .../onap/dmaap/mr/dme/client/JUnitTestSuite.java | 26 +- .../dme/client/PreferredRouteReplyHandlerTest.java | 94 +- .../client/PreferredRouteRequestHandlerTest.java | 56 +- .../dmaap/mr/dme/client/SimpleExampleConsumer.java | 87 + .../mr/dme/client/SimpleExamplePublisher.java | 123 ++ .../mr/dme/client/SimpleExamplePublisherTest.java | 47 +- .../org/onap/dmaap/mr/dme/client/TestRunner.java | 26 +- .../dmaap/mr/test/clients/ConsolePublisher.java | 90 + .../mr/test/clients/ConsolePublisherTest.java | 42 +- .../onap/dmaap/mr/test/clients/JUnitTestSuite.java | 27 +- .../mr/test/clients/ProtocolTypeConstantsTest.java | 49 +- .../onap/dmaap/mr/test/clients/SampleConsumer.java | 81 + .../dmaap/mr/test/clients/SampleConsumerTest.java | 40 +- .../dmaap/mr/test/clients/SamplePublisher.java | 82 + .../dmaap/mr/test/clients/SamplePublisherTest.java | 42 +- .../mr/test/clients/SimpleExampleConsumer.java | 89 + .../mr/test/clients/SimpleExampleConsumerTest.java | 42 +- .../SimpleExampleConsumerWithReturnResponse.java | 91 + ...impleExampleConsumerWithReturnResponseTest.java | 40 +- .../mr/test/clients/SimpleExamplePublisher.java | 94 ++ .../test/clients/SimpleExamplePublisherTest.java | 108 +- .../SimpleExamplePublisherWithResponse.java | 85 + .../SimpleExamplePublisherWithResponseTest.java | 65 +- .../org/onap/dmaap/mr/test/clients/TestRunner.java | 26 +- .../onap/dmaap/mr/test/support/JUnitTestSuite.java | 23 +- .../mr/test/support/MRBatchingPublisherMock.java | 167 ++ .../test/support/MRBatchingPublisherMockTest.java | 237 +-- .../onap/dmaap/mr/test/support/MRConsumerMock.java | 148 ++ .../dmaap/mr/test/support/MRConsumerMockTest.java | 286 ++-- .../org/onap/dmaap/mr/test/support/TestRunner.java | 26 +- .../org/onap/dmaap/mr/tools/ApiKeyCommandTest.java | 361 ++-- .../org/onap/dmaap/mr/tools/AuthCommandTest.java | 121 +- .../onap/dmaap/mr/tools/ClusterCommandTest.java | 111 +- .../org/onap/dmaap/mr/tools/JUnitTestSuite.java | 25 +- .../onap/dmaap/mr/tools/MRCommandContextTest.java | 165 +- src/test/java/org/onap/dmaap/mr/tools/MRTool.java | 49 + .../onap/dmaap/mr/tools/MessageCommandTest.java | 357 ++-- .../java/org/onap/dmaap/mr/tools/TestRunner.java | 26 +- .../org/onap/dmaap/mr/tools/ToolsUtilTest.java | 9 +- .../org/onap/dmaap/mr/tools/TopicCommandTest.java | 377 ++--- .../org/onap/dmaap/mr/tools/TraceCommandTest.java | 105 +- .../org/onap/dmaap/mr/tools/ValidatorUtilTest.java | 395 +++-- src/test/resources/dme2/consumer.properties | 2 +- src/test/resources/dme2/producer.properties | 6 +- 114 files changed, 8260 insertions(+), 8554 deletions(-) create mode 100644 src/main/java/org/onap/dmaap/mr/client/ProtocolType.java delete mode 100644 src/main/java/org/onap/dmaap/mr/dme/client/DefaultLoggingFailoverFaultHandler.java delete mode 100644 src/main/java/org/onap/dmaap/mr/dme/client/SimpleExampleConsumer.java delete mode 100644 src/main/java/org/onap/dmaap/mr/dme/client/SimpleExamplePublisher.java delete mode 100644 src/main/java/org/onap/dmaap/mr/test/clients/ConsolePublisher.java delete mode 100644 src/main/java/org/onap/dmaap/mr/test/clients/ProtocolTypeConstants.java delete mode 100644 src/main/java/org/onap/dmaap/mr/test/clients/SampleConsumer.java delete mode 100644 src/main/java/org/onap/dmaap/mr/test/clients/SamplePublisher.java delete mode 100644 src/main/java/org/onap/dmaap/mr/test/clients/SimpleExampleConsumer.java delete mode 100644 src/main/java/org/onap/dmaap/mr/test/clients/SimpleExampleConsumerWithReturnResponse.java delete mode 100644 src/main/java/org/onap/dmaap/mr/test/clients/SimpleExamplePublisher.java delete mode 100644 src/main/java/org/onap/dmaap/mr/test/clients/SimpleExamplePublisherWithResponse.java delete mode 100644 src/main/java/org/onap/dmaap/mr/test/support/MRBatchingPublisherMock.java delete mode 100644 src/main/java/org/onap/dmaap/mr/test/support/MRConsumerMock.java delete mode 100644 src/main/java/org/onap/dmaap/mr/tools/MRTool.java delete mode 100644 src/test/java/org/onap/dmaap/mr/dme/client/DefaultLoggingFailoverFaultHandlerTest.java create mode 100644 src/test/java/org/onap/dmaap/mr/dme/client/SimpleExampleConsumer.java create mode 100644 src/test/java/org/onap/dmaap/mr/dme/client/SimpleExamplePublisher.java create mode 100644 src/test/java/org/onap/dmaap/mr/test/clients/ConsolePublisher.java create mode 100644 src/test/java/org/onap/dmaap/mr/test/clients/SampleConsumer.java create mode 100644 src/test/java/org/onap/dmaap/mr/test/clients/SamplePublisher.java create mode 100644 src/test/java/org/onap/dmaap/mr/test/clients/SimpleExampleConsumer.java create mode 100644 src/test/java/org/onap/dmaap/mr/test/clients/SimpleExampleConsumerWithReturnResponse.java create mode 100644 src/test/java/org/onap/dmaap/mr/test/clients/SimpleExamplePublisher.java create mode 100644 src/test/java/org/onap/dmaap/mr/test/clients/SimpleExamplePublisherWithResponse.java create mode 100644 src/test/java/org/onap/dmaap/mr/test/support/MRBatchingPublisherMock.java create mode 100644 src/test/java/org/onap/dmaap/mr/test/support/MRConsumerMock.java create mode 100644 src/test/java/org/onap/dmaap/mr/tools/MRTool.java diff --git a/pom.xml b/pom.xml index 3555fd4..2be51ac 100644 --- a/pom.xml +++ b/pom.xml @@ -142,20 +142,6 @@ - - - - jakarta.xml.bind jakarta.xml.bind-api @@ -300,6 +286,7 @@ maven-javadoc-plugin 2.10.4 + false false -Xdoclint:none @@ -325,13 +312,6 @@ - org.jacoco jacoco-maven-plugin diff --git a/src/main/java/org/onap/dmaap/mr/client/HostSelector.java b/src/main/java/org/onap/dmaap/mr/client/HostSelector.java index 9bd73f9..f872745 100644 --- a/src/main/java/org/onap/dmaap/mr/client/HostSelector.java +++ b/src/main/java/org/onap/dmaap/mr/client/HostSelector.java @@ -4,11 +4,13 @@ * ================================================================================ * Copyright © 2017 AT&T Intellectual Property. All rights reserved. * ================================================================================ + * Modifications Copyright © 2021 Orange. + * ================================================================================ * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * http://www.apache.org/licenses/LICENSE-2.0 - * + * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. @@ -17,182 +19,158 @@ * ============LICENSE_END========================================================= * * ECOMP is a trademark and service mark of AT&T Intellectual Property. - * + * *******************************************************************************/ + package org.onap.dmaap.mr.client; +import java.security.SecureRandom; +import java.util.ArrayList; import java.util.Collection; import java.util.Iterator; import java.util.LinkedList; -import java.util.Random; import java.util.Set; import java.util.TreeSet; -import java.util.Vector; import java.util.concurrent.DelayQueue; import java.util.concurrent.Delayed; import java.util.concurrent.TimeUnit; import org.slf4j.Logger; import org.slf4j.LoggerFactory; -public class HostSelector -{ - private final TreeSet fBaseHosts; - private final DelayQueue fBlacklist; - private String fIdealHost; - private String fCurrentHost; - private static final Logger log = LoggerFactory.getLogger(HostSelector.class); - - public HostSelector(String hostPart) - { - this(makeSet(hostPart), null); - } - - public HostSelector(Collection baseHosts) - { - this(baseHosts, null); - } - - public HostSelector(Collection baseHosts, String signature) - { - if (baseHosts.isEmpty()) - { - throw new IllegalArgumentException("At least one host must be provided."); - } +public class HostSelector { + private final TreeSet baseHosts; + private final DelayQueue blacklist; + private String idealHost; + private String currentHost; + private static final Logger logger = LoggerFactory.getLogger(HostSelector.class); - this.fBaseHosts = new TreeSet(baseHosts); - this.fBlacklist = new DelayQueue(); - this.fIdealHost = null; - - if (signature == null) { - return; - } - int index = 0 ; - int value = signature.hashCode(); - if(value!=0) { - index = Math.abs(value) % baseHosts.size(); - } - Iterator it = this.fBaseHosts.iterator(); - while (index-- > 0) - { - it.next(); - } - this.fIdealHost = ((String)it.next()); - } - - public String selectBaseHost() - { - if (this.fCurrentHost == null) - { - makeSelection(); + public HostSelector(String hostPart) { + this(makeSet(hostPart), null); } - return this.fCurrentHost; - } - - public void reportReachabilityProblem(long blacklistUnit, TimeUnit blacklistTimeUnit) - { - if (this.fCurrentHost == null) - { - log.warn("Reporting reachability problem, but no host is currently selected."); + + public HostSelector(Collection baseHosts) { + this(baseHosts, null); } - if (blacklistUnit > 0L) - { - for (BlacklistEntry be : this.fBlacklist) - { - if (be.getHost().equals(this.fCurrentHost)) - { - be.expireNow(); + public HostSelector(Collection baseHosts, String signature) { + if (baseHosts.isEmpty()) { + throw new IllegalArgumentException("At least one host must be provided."); } - } - LinkedList devNull = new LinkedList(); - this.fBlacklist.drainTo(devNull); + this.baseHosts = new TreeSet<>(baseHosts); + this.blacklist = new DelayQueue<>(); + this.idealHost = null; - if (this.fCurrentHost != null) - { - this.fBlacklist.add(new BlacklistEntry(this.fCurrentHost, TimeUnit.MILLISECONDS.convert(blacklistUnit, blacklistTimeUnit))); - } - } - this.fCurrentHost = null; - } - - private String makeSelection() - { - TreeSet workingSet = new TreeSet(this.fBaseHosts); - - LinkedList devNull = new LinkedList(); - this.fBlacklist.drainTo(devNull); - for (BlacklistEntry be : this.fBlacklist) - { - workingSet.remove(be.getHost()); + if (signature == null) { + return; + } + int index = 0; + int value = signature.hashCode(); + if (value != 0) { + index = Math.abs(value) % baseHosts.size(); + } + Iterator it = this.baseHosts.iterator(); + while (index-- > 0) { + it.next(); + } + this.idealHost = (it.next()); } - if (workingSet.isEmpty()) - { - log.warn("All hosts were blacklisted; reverting to full set of hosts."); - workingSet.addAll(this.fBaseHosts); - this.fCurrentHost = null; + public String selectBaseHost() { + if (this.currentHost == null) { + makeSelection(); + } + return this.currentHost; } - String selection = null; - if ((this.fCurrentHost != null) && (workingSet.contains(this.fCurrentHost))) - { - selection = this.fCurrentHost; - } - else if ((this.fIdealHost != null) && (workingSet.contains(this.fIdealHost))) - { - selection = this.fIdealHost; - } - else - { - int index = 0; - int value = new Random().nextInt(); - Vector v = new Vector(workingSet); - if(value!=0) { - index = Math.abs(value) % workingSet.size(); - } - selection = (String)v.elementAt(index); + public void reportReachabilityProblem(long blacklistUnit, TimeUnit blacklistTimeUnit) { + if (this.currentHost == null) { + logger.warn("Reporting reachability problem, but no host is currently selected."); + } + + if (blacklistUnit > 0L) { + for (BlacklistEntry be : this.blacklist) { + if (be.getHost().equals(this.currentHost)) { + be.expireNow(); + } + } + + LinkedList devNull = new LinkedList<>(); + this.blacklist.drainTo(devNull); + + if (this.currentHost != null) { + this.blacklist.add(new BlacklistEntry(this.currentHost, + TimeUnit.MILLISECONDS.convert(blacklistUnit, blacklistTimeUnit))); + } + } + this.currentHost = null; } - this.fCurrentHost = selection; - return this.fCurrentHost; - } + private String makeSelection() { + TreeSet workingSet = new TreeSet<>(this.baseHosts); - private static Set makeSet(String s) - { - TreeSet set = new TreeSet(); - set.add(s); - return set; } + LinkedList devNull = new LinkedList<>(); + this.blacklist.drainTo(devNull); + for (BlacklistEntry be : this.blacklist) { + workingSet.remove(be.getHost()); + } - private static class BlacklistEntry implements Delayed { - private final String fHost; - private long fExpireAtMs; + if (workingSet.isEmpty()) { + logger.warn("All hosts were blacklisted; reverting to full set of hosts."); + workingSet.addAll(this.baseHosts); + this.currentHost = null; + } - public BlacklistEntry(String host, long delayMs) { - this.fHost = host; - this.fExpireAtMs = (System.currentTimeMillis() + delayMs); - } + String selection = null; + if ((this.currentHost != null) && (workingSet.contains(this.currentHost))) { + selection = this.currentHost; + } else if ((this.idealHost != null) && (workingSet.contains(this.idealHost))) { + selection = this.idealHost; + } else { + int index = 0; + int value = new SecureRandom().nextInt(); + ArrayList workingArray = new ArrayList<>(workingSet); + if (value != 0) { + index = Math.abs(value) % workingSet.size(); + } + selection = workingArray.get(index); + } - public void expireNow() - { - this.fExpireAtMs = 0L; + this.currentHost = selection; + return this.currentHost; } - public String getHost() - { - return this.fHost; + private static Set makeSet(String firstTreeElem) { + TreeSet set = new TreeSet<>(); + set.add(firstTreeElem); + return set; } - public int compareTo(Delayed o) - { - Long thisDelay = Long.valueOf(getDelay(TimeUnit.MILLISECONDS)); - return thisDelay.compareTo(Long.valueOf(o.getDelay(TimeUnit.MILLISECONDS))); - } + private static class BlacklistEntry implements Delayed { + private final String host; + private long expireAtMs; - public long getDelay(TimeUnit unit) - { - long remainingMs = this.fExpireAtMs - System.currentTimeMillis(); - return unit.convert(remainingMs, TimeUnit.MILLISECONDS); + public BlacklistEntry(String host, long delayMs) { + this.host = host; + this.expireAtMs = (System.currentTimeMillis() + delayMs); + } + + public void expireNow() { + this.expireAtMs = 0L; + } + + public String getHost() { + return this.host; + } + + public int compareTo(Delayed object) { + Long thisDelay = getDelay(TimeUnit.MILLISECONDS); + return thisDelay.compareTo(object.getDelay(TimeUnit.MILLISECONDS)); + } + + public long getDelay(TimeUnit unit) { + long remainingMs = this.expireAtMs - System.currentTimeMillis(); + return unit.convert(remainingMs, TimeUnit.MILLISECONDS); + } } - } } diff --git a/src/main/java/org/onap/dmaap/mr/client/MRBatchingPublisher.java b/src/main/java/org/onap/dmaap/mr/client/MRBatchingPublisher.java index df440bb..0ee5a0b 100644 --- a/src/main/java/org/onap/dmaap/mr/client/MRBatchingPublisher.java +++ b/src/main/java/org/onap/dmaap/mr/client/MRBatchingPublisher.java @@ -4,11 +4,13 @@ * ================================================================================ * Copyright © 2017 AT&T Intellectual Property. All rights reserved. * ================================================================================ + * Modifications Copyright © 2021 Orange. + * ================================================================================ * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * http://www.apache.org/licenses/LICENSE-2.0 - * + * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. @@ -17,8 +19,9 @@ * ============LICENSE_END========================================================= * * ECOMP is a trademark and service mark of AT&T Intellectual Property. - * + * *******************************************************************************/ + package org.onap.dmaap.mr.client; import java.io.IOException; @@ -29,27 +32,27 @@ import org.onap.dmaap.mr.client.response.MRPublisherResponse; /** * A MR batching publisher is a publisher with additional functionality * for managing delayed sends. - * - * @author author * + * @author author */ -public interface MRBatchingPublisher extends MRPublisher -{ - /** - * Get the number of messages that have not yet been sent. - * @return the number of pending messages - */ - int getPendingMessageCount (); +public interface MRBatchingPublisher extends MRPublisher { + /** + * Get the number of messages that have not yet been sent. + * + * @return the number of pending messages + */ + int getPendingMessageCount(); + + /** + * Close this publisher, sending any remaining messages. + * + * @param timeout an amount of time to wait for unsent messages to be sent + * @param timeoutUnits the time unit for the timeout arg + * @return a list of any unsent messages after the timeout + * @throws IOException exception + * @throws InterruptedException exception + */ + List close(long timeout, TimeUnit timeoutUnits) throws IOException, InterruptedException; - /** - * Close this publisher, sending any remaining messages. - * @param timeout an amount of time to wait for unsent messages to be sent - * @param timeoutUnits the time unit for the timeout arg - * @return a list of any unsent messages after the timeout - * @throws IOException exception - * @throws InterruptedException exception - */ - List close ( long timeout, TimeUnit timeoutUnits ) throws IOException, InterruptedException; - - MRPublisherResponse sendBatchWithResponse (); + MRPublisherResponse sendBatchWithResponse(); } diff --git a/src/main/java/org/onap/dmaap/mr/client/MRClient.java b/src/main/java/org/onap/dmaap/mr/client/MRClient.java index 8cbf9e0..f1a642b 100644 --- a/src/main/java/org/onap/dmaap/mr/client/MRClient.java +++ b/src/main/java/org/onap/dmaap/mr/client/MRClient.java @@ -4,11 +4,13 @@ * ================================================================================ * Copyright © 2017 AT&T Intellectual Property. All rights reserved. * ================================================================================ + * Modifications Copyright © 2021 Orange. + * ================================================================================ * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * http://www.apache.org/licenses/LICENSE-2.0 - * + * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. @@ -17,50 +19,55 @@ * ============LICENSE_END========================================================= * * ECOMP is a trademark and service mark of AT&T Intellectual Property. - * + * *******************************************************************************/ + package org.onap.dmaap.mr.client; import org.slf4j.Logger; -public interface MRClient -{ - /** - * An exception at the MR layer. This is used when the HTTP transport - * layer returns a success code but the transaction is not completed as expected. - */ - public class MRApiException extends Exception - { - private static final long serialVersionUID = 1L; - public MRApiException ( String msg ) { super ( msg ); } - public MRApiException ( String msg, Throwable t ) { super ( msg, t ); } - } +public interface MRClient { + /** + * An exception at the MR layer. This is used when the HTTP transport + * layer returns a success code but the transaction is not completed as expected. + */ + class MRApiException extends Exception { + private static final long serialVersionUID = 1L; + + public MRApiException(String msg) { + super(msg); + } + + public MRApiException(String msg, Throwable t) { + super(msg, t); + } + } - /** - * Optionally set the Logger to use - * @param log log - */ - void logTo ( Logger log ); + /** + * Optionally set the Logger to use. + * + * @param log log + */ + void logTo(Logger log); - /** - * Set the API credentials for this client connection. Subsequent calls will - * include authentication headers.who i - */ - /** - * @param apiKey apikey - * @param apiSecret apisec - */ - void setApiCredentials ( String apiKey, String apiSecret ); + /** + * Set the API credentials for this client connection. Subsequent calls will + * include authentication headers.who i + * + * @param apiKey apikey + * @param apiSecret apisec + */ + void setApiCredentials(String apiKey, String apiSecret); - /** - * Remove API credentials, if any, on this connection. Subsequent calls will not include - * authentication headers. - */ - void clearApiCredentials (); + /** + * Remove API credentials, if any, on this connection. Subsequent calls will not include + * authentication headers. + */ + void clearApiCredentials(); - /** - * Close this connection. Some client interfaces have additional close capability. - */ - void close (); + /** + * Close this connection. Some client interfaces have additional close capability. + */ + void close(); } diff --git a/src/main/java/org/onap/dmaap/mr/client/MRClientBuilders.java b/src/main/java/org/onap/dmaap/mr/client/MRClientBuilders.java index 91e10e0..e8e7003 100644 --- a/src/main/java/org/onap/dmaap/mr/client/MRClientBuilders.java +++ b/src/main/java/org/onap/dmaap/mr/client/MRClientBuilders.java @@ -5,12 +5,13 @@ * Copyright © 2017 AT&T Intellectual Property. All rights reserved. * ================================================================================ * Modifications Copyright © 2018 IBM. + * Modifications Copyright © 2021 Orange. * ================================================================================ * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * http://www.apache.org/licenses/LICENSE-2.0 - * + * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. @@ -19,30 +20,31 @@ * ============LICENSE_END========================================================= * * ECOMP is a trademark and service mark of AT&T Intellectual Property. - * + * *******************************************************************************/ + package org.onap.dmaap.mr.client; import java.net.MalformedURLException; import java.util.Collection; +import java.util.Collections; import java.util.TreeSet; import java.util.UUID; - -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; - import org.onap.dmaap.mr.client.impl.MRConsumerImpl; import org.onap.dmaap.mr.client.impl.MRMetaClient; import org.onap.dmaap.mr.client.impl.MRSimplerBatchPublisher; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; /** - * A collection of builders for various types of MR API clients - * + * A collection of builders for various types of MR API clients. + * * @author author */ -public class MRClientBuilders -{ - private final static String ILLEGAL_ARGUMENT_MESSAGE = "You must provide at least one host and a topic name."; +public class MRClientBuilders { + private static final Logger logger = LoggerFactory.getLogger(MRClientBuilders.class); + + private static final String ILLEGAL_ARGUMENT_MESSAGE = "You must provide at least one host and a topic name."; /** * Instantiates MRClientBuilders. @@ -50,115 +52,124 @@ public class MRClientBuilders private MRClientBuilders() { // prevent instantiation } - + /** - * A builder for a topic Consumer + * A builder for a topic Consumer. + * * @author author */ - public static class ConsumerBuilder - { + public static class ConsumerBuilder { /** - * Set the host list + * Set the host list. + * * @param hostList a comma-separated list of hosts to use to connect to MR * @return this builder */ - public ConsumerBuilder usingHosts ( String hostList ) { - return usingHosts ( MRConsumerImpl.stringToList(hostList) ); + public ConsumerBuilder usingHosts(String hostList) { + return usingHosts(MRConsumerImpl.stringToList(hostList)); } /** - * Set the host list + * Set the host list. + * * @param hostSet a set of hosts to use to connect to MR * @return this builder */ - public ConsumerBuilder usingHosts ( Collection hostSet ) { - fHosts = hostSet; return this; + public ConsumerBuilder usingHosts(Collection hostSet) { + fHosts = hostSet; + return this; } /** - * Set the topic + * Set the topic. + * * @param topic the name of the topic to consume * @return this builder */ - public ConsumerBuilder onTopic ( String topic ) { - fTopic=topic; - return this; + public ConsumerBuilder onTopic(String topic) { + fTopic = topic; + return this; } /** - * Set the consumer's group and ID + * Set the consumer's group and ID. + * * @param consumerGroup The name of the consumer group this consumer is part of - * @param consumerId The unique id of this consumer in its group + * @param consumerId The unique id of this consumer in its group * @return this builder */ - public ConsumerBuilder knownAs ( String consumerGroup, String consumerId ) { - fGroup = consumerGroup; - fId = consumerId; - return this; + public ConsumerBuilder knownAs(String consumerGroup, String consumerId) { + fGroup = consumerGroup; + fId = consumerId; + return this; } /** * Set the API key and secret for this client. + * * @param apiKey * @param apiSecret * @return this builder */ - public ConsumerBuilder authenticatedBy ( String apiKey, String apiSecret ) { - fApiKey = apiKey; - fApiSecret = apiSecret; - return this; + public ConsumerBuilder authenticatedBy(String apiKey, String apiSecret) { + fApiKey = apiKey; + fApiSecret = apiSecret; + return this; } /** - * Set the server side timeout - * @param timeoutMs The amount of time in milliseconds that the server should keep the connection open while waiting for message traffic. + * Set the server side timeout. + * + * @param timeoutMs The amount of time in milliseconds that the server should keep the connection open while waiting for message traffic. * @return this builder */ - public ConsumerBuilder waitAtServer ( int timeoutMs ) { - fTimeoutMs = timeoutMs; - return this; - }; + public ConsumerBuilder waitAtServer(int timeoutMs) { + fTimeoutMs = timeoutMs; + return this; + } /** - * Set the maximum number of messages to receive per transaction + * Set the maximum number of messages to receive per transaction. + * * @param limit The maximum number of messages to receive from the server in one transaction. * @return this builder */ - public ConsumerBuilder receivingAtMost ( int limit ) { - fLimit = limit; - return this; - }; + public ConsumerBuilder receivingAtMost(int limit) { + fLimit = limit; + return this; + } /** - * Set a filter to use on the server + * Set a filter to use on the server. + * * @param filter a Highland Park standard library filter encoded in JSON * @return this builder */ - public ConsumerBuilder withServerSideFilter ( String filter ) { - fFilter = filter; - return this; + public ConsumerBuilder withServerSideFilter(String filter) { + fFilter = filter; + return this; } /** - * Build the consumer + * Build the consumer. + * * @return a consumer */ - public MRConsumer build () - { - if ( fHosts == null || fHosts.isEmpty() || fTopic == null ) - { - throw new IllegalArgumentException ( ILLEGAL_ARGUMENT_MESSAGE ); + public MRConsumer build() { + if (fHosts == null || fHosts.isEmpty() || fTopic == null) { + throw new IllegalArgumentException(ILLEGAL_ARGUMENT_MESSAGE); } - if ( fGroup == null ) - { - fGroup = UUID.randomUUID ().toString (); + if (fGroup == null) { + fGroup = UUID.randomUUID().toString(); fId = "0"; - log.info ( "Creating non-restartable client with group " + fGroup + " and ID " + fId + "." ); + logger.info("Creating non-restartable client with group {} and ID {}.", fGroup, fId); } - if ( sfConsumerMock != null ) return sfConsumerMock; + if (sfConsumerMock != null) { + return sfConsumerMock; + } try { return new MRConsumerImpl.MRConsumerImplBuilder().setHostPart(fHosts) .setTopic(fTopic).setConsumerGroup(fGroup).setConsumerId(fId) @@ -181,137 +192,142 @@ public class MRClientBuilders private String fFilter = null; } - /*************************************************************************/ - /*************************************************************************/ - /*************************************************************************/ + //*************************************************************************/ + //*************************************************************************/ + //*************************************************************************/ /** - * A publisher builder + * A publisher builder. + * * @author author */ - public static class PublisherBuilder - { + public static class PublisherBuilder { /** - * Set the MR/UEB host(s) to use + * Set the MR/UEB host(s) to use. + * * @param hostlist The host(s) used in the URL to MR. Can be "host:port", can be multiple comma-separated entries. * @return this builder */ - public PublisherBuilder usingHosts ( String hostlist ) { - return usingHosts ( MRConsumerImpl.stringToList(hostlist) ); + public PublisherBuilder usingHosts(String hostlist) { + return usingHosts(MRConsumerImpl.stringToList(hostlist)); } /** - * Set the MR/UEB host(s) to use + * Set the MR/UEB host(s) to use. + * * @param hostSet The host(s) used in the URL to MR. Can be "host:port" * @return this builder */ - public PublisherBuilder usingHosts ( String[] hostSet ) - { - final TreeSet hosts = new TreeSet<> (); - for ( String hp : hostSet ) - { - hosts.add ( hp ); - } - return usingHosts ( hosts ); + public PublisherBuilder usingHosts(String[] hostSet) { + final TreeSet hosts = new TreeSet<>(); + Collections.addAll(hosts, hostSet); + return usingHosts(hosts); } /** - * Set the MR/UEB host(s) to use + * Set the MR/UEB host(s) to use. + * * @param hostlist The host(s) used in the URL to MR. Can be "host:port". * @return this builder */ - public PublisherBuilder usingHosts ( Collection hostlist ) { - fHosts=hostlist; - return this; + public PublisherBuilder usingHosts(Collection hostlist) { + fHosts = hostlist; + return this; } /** - * Set the topic to publish on + * Set the topic to publish on. + * * @param topic The topic on which to publish messages. * @return this builder */ - public PublisherBuilder onTopic ( String topic ) { - fTopic = topic; - return this; + public PublisherBuilder onTopic(String topic) { + fTopic = topic; + return this; } /** * Batch message sends with the given limits. + * * @param messageCount The largest set of messages to batch. - * @param ageInMs The maximum age of a message waiting in a batch. + * @param ageInMs The maximum age of a message waiting in a batch. * @return this builder */ - public PublisherBuilder limitBatch ( int messageCount, int ageInMs ) { - fMaxBatchSize = messageCount; - fMaxBatchAgeMs = ageInMs; - return this; + public PublisherBuilder limitBatch(int messageCount, int ageInMs) { + fMaxBatchSize = messageCount; + fMaxBatchAgeMs = ageInMs; + return this; } /** - * Compress transactions + * Compress transactions. + * * @return this builder */ - public PublisherBuilder withCompresion () { - return enableCompresion(true); + public PublisherBuilder withCompresion() { + return enableCompresion(true); } /** - * Do not compress transactions + * Do not compress transactions. + * * @return this builder */ - public PublisherBuilder withoutCompresion () { - return enableCompresion(false); + public PublisherBuilder withoutCompresion() { + return enableCompresion(false); } /** - * Set the compression option + * Set the compression option. + * * @param compress true to gzip compress transactions * @return this builder */ - public PublisherBuilder enableCompresion ( boolean compress ) { - fCompress = compress; - return this; + public PublisherBuilder enableCompresion(boolean compress) { + fCompress = compress; + return this; } /** * Set the API key and secret for this client. + * * @param apiKey * @param apiSecret * @return this builder */ - public PublisherBuilder authenticatedBy ( String apiKey, String apiSecret ) { - fApiKey = apiKey; - fApiSecret = apiSecret; - return this; + public PublisherBuilder authenticatedBy(String apiKey, String apiSecret) { + fApiKey = apiKey; + fApiSecret = apiSecret; + return this; } /** - * Build the publisher + * Build the publisher. + * * @return a batching publisher */ - public MRBatchingPublisher build () - { - if ( fHosts == null || fHosts.isEmpty() || fTopic == null ) - { - throw new IllegalArgumentException ( ILLEGAL_ARGUMENT_MESSAGE ); + public MRBatchingPublisher build() { + if (fHosts == null || fHosts.isEmpty() || fTopic == null) { + throw new IllegalArgumentException(ILLEGAL_ARGUMENT_MESSAGE); } - if ( sfPublisherMock != null ) return sfPublisherMock; - - final MRSimplerBatchPublisher pub = new MRSimplerBatchPublisher.Builder (). - againstUrls ( fHosts ). - onTopic ( fTopic ). - batchTo ( fMaxBatchSize, fMaxBatchAgeMs ). - compress ( fCompress ). - build (); - if ( fApiKey != null ) - { - pub.setApiCredentials ( fApiKey, fApiSecret ); + if (sfPublisherMock != null) { + return sfPublisherMock; + } + + final MRSimplerBatchPublisher pub = new MRSimplerBatchPublisher.Builder() + .againstUrls(fHosts) + .onTopic(fTopic) + .batchTo(fMaxBatchSize, fMaxBatchAgeMs) + .compress(fCompress) + .build(); + if (fApiKey != null) { + pub.setApiCredentials(fApiKey, fApiSecret); } return pub; } - + private Collection fHosts = null; private String fTopic = null; private int fMaxBatchSize = 1; @@ -322,50 +338,54 @@ public class MRClientBuilders } /** - * A builder for an identity manager + * A builder for an identity manager. + * * @author author */ - public static class IdentityManagerBuilder extends AbstractAuthenticatedManagerBuilder - { + public static class IdentityManagerBuilder extends AbstractAuthenticatedManagerBuilder { @Override - protected MRIdentityManager constructClient ( Collection hosts ) { try { - return new MRMetaClient ( hosts ); - } catch (MalformedURLException e) { - throw new IllegalArgumentException(e); - } } + protected MRIdentityManager constructClient(Collection hosts) { + try { + return new MRMetaClient(hosts); + } catch (MalformedURLException e) { + throw new IllegalArgumentException(e); + } + } } /** - * A builder for a topic manager + * A builder for a topic manager. + * * @author author */ - public static class TopicManagerBuilder extends AbstractAuthenticatedManagerBuilder - { + public static class TopicManagerBuilder extends AbstractAuthenticatedManagerBuilder { @Override - protected MRTopicManager constructClient ( Collection hosts ) { try { - return new MRMetaClient ( hosts ); - } catch (MalformedURLException e) { - throw new IllegalArgumentException(e); - } } + protected MRTopicManager constructClient(Collection hosts) { + try { + return new MRMetaClient(hosts); + } catch (MalformedURLException e) { + throw new IllegalArgumentException(e); + } + } } /** * Inject a consumer. Used to support unit tests. + * * @param cc */ - public static void $testInject ( MRConsumer cc ) - { + public static void $testInject(MRConsumer cc) { sfConsumerMock = cc; } /** * Inject a publisher. Used to support unit tests. + * * @param pub */ - public static void $testInject ( MRBatchingPublisher pub ) - { + public static void $testInject(MRBatchingPublisher pub) { sfPublisherMock = pub; } @@ -373,69 +393,66 @@ public class MRClientBuilders static MRBatchingPublisher sfPublisherMock = null; /** - * A builder for an identity manager + * A builder for an identity manager. + * * @author author */ - public static abstract class AbstractAuthenticatedManagerBuilder - { - /** - * Construct an identity manager builder. - */ - public AbstractAuthenticatedManagerBuilder () {} + public abstract static class AbstractAuthenticatedManagerBuilder { /** - * Set the host list + * Set the host list. + * * @param hostList a comma-separated list of hosts to use to connect to MR * @return this builder */ - public AbstractAuthenticatedManagerBuilder usingHosts ( String hostList ) { - return usingHosts ( MRConsumerImpl.stringToList(hostList) ); + public AbstractAuthenticatedManagerBuilder usingHosts(String hostList) { + return usingHosts(MRConsumerImpl.stringToList(hostList)); } /** - * Set the host list + * Set the host list. + * * @param hostSet a set of hosts to use to connect to MR * @return this builder */ - public AbstractAuthenticatedManagerBuilder usingHosts ( Collection hostSet ) { - fHosts = hostSet; - return this; + public AbstractAuthenticatedManagerBuilder usingHosts(Collection hostSet) { + fHosts = hostSet; + return this; } /** * Set the API key and secret for this client. + * * @param apiKey * @param apiSecret * @return this builder */ - public AbstractAuthenticatedManagerBuilder authenticatedBy ( String apiKey, String apiSecret ) { - fApiKey = apiKey; - fApiSecret = apiSecret; - return this; + public AbstractAuthenticatedManagerBuilder authenticatedBy(String apiKey, String apiSecret) { + fApiKey = apiKey; + fApiSecret = apiSecret; + return this; } /** - * Build the consumer + * Build the consumer. + * * @return a consumer */ - public T build () - { - if ( fHosts.isEmpty() ) - { - throw new IllegalArgumentException ( ILLEGAL_ARGUMENT_MESSAGE ); + public T build() { + if (fHosts.isEmpty()) { + throw new IllegalArgumentException(ILLEGAL_ARGUMENT_MESSAGE); } - final T mgr = constructClient ( fHosts ); - mgr.setApiCredentials ( fApiKey, fApiSecret ); + final T mgr = constructClient(fHosts); + mgr.setApiCredentials(fApiKey, fApiSecret); return mgr; } - protected abstract T constructClient ( Collection hosts ); + protected abstract T constructClient(Collection hosts); private Collection fHosts = null; private String fApiKey = null; private String fApiSecret = null; } - - private static final Logger log = LoggerFactory.getLogger ( MRClientBuilders.class ); + } diff --git a/src/main/java/org/onap/dmaap/mr/client/MRClientFactory.java b/src/main/java/org/onap/dmaap/mr/client/MRClientFactory.java index 1780703..88d3dab 100644 --- a/src/main/java/org/onap/dmaap/mr/client/MRClientFactory.java +++ b/src/main/java/org/onap/dmaap/mr/client/MRClientFactory.java @@ -5,12 +5,13 @@ * Copyright © 2017 AT&T Intellectual Property. All rights reserved. * ================================================================================ * Modifications Copyright © 2018 IBM. - * ================================================================================ + * Modifications Copyright © 2021 Orange. + * ================================================================================ * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * http://www.apache.org/licenses/LICENSE-2.0 - * + * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. @@ -19,22 +20,30 @@ * ============LICENSE_END========================================================= * * ECOMP is a trademark and service mark of AT&T Intellectual Property. - * + * *******************************************************************************/ + package org.onap.dmaap.mr.client; -import java.io.*; +import java.io.File; +import java.io.FileInputStream; +import java.io.FileNotFoundException; +import java.io.FileReader; +import java.io.FileWriter; +import java.io.IOException; +import java.io.InputStream; import java.net.MalformedURLException; import java.util.Collection; +import java.util.Collections; import java.util.Map; import java.util.Properties; import java.util.TreeSet; import java.util.UUID; import javax.ws.rs.core.MultivaluedMap; + import org.onap.dmaap.mr.client.impl.MRConsumerImpl; import org.onap.dmaap.mr.client.impl.MRMetaClient; import org.onap.dmaap.mr.client.impl.MRSimplerBatchPublisher; -import org.onap.dmaap.mr.test.clients.ProtocolTypeConstants; import org.onap.dmaap.mr.tools.ValidatorUtil; /** @@ -50,10 +59,12 @@ import org.onap.dmaap.mr.tools.ValidatorUtil; * instance.)
*
* Publishers - * + * * @author author */ public class MRClientFactory { + + private static final String ID = "id"; private static final String AUTH_KEY = "authKey"; private static final String AUTH_DATE = "authDate"; private static final String PASSWORD = "password"; @@ -63,6 +74,36 @@ public class MRClientFactory { private static final String DME2PREFERRED_ROUTER_FILE_PATH = "DME2preferredRouterFilePath"; private static final String TOPIC = "topic"; private static final String TRANSPORT_TYPE = "TransportType"; + private static final String MAX_BATCH_SIZE = "maxBatchSize"; + private static final String MAX_AGE_MS = "maxAgeMs"; + private static final String MESSAGE_SENT_THREAD_OCCURRENCE_OLD = "MessageSentThreadOccurance"; + private static final String MESSAGE_SENT_THREAD_OCCURRENCE = "MessageSentThreadOccurrence"; + private static final String GROUP = "group"; + private static final String SERVICE_NAME = "ServiceName"; + private static final String PARTNER = "Partner"; + private static final String ROUTE_OFFER = "routeOffer"; + private static final String PROTOCOL = "Protocol"; + private static final String METHOD_TYPE = "MethodType"; + private static final String CONTENT_TYPE = "contenttype"; + private static final String LATITUDE = "Latitude"; + private static final String LONGITUDE = "Longitude"; + private static final String AFT_ENVIRONMENT = "AFT_ENVIRONMENT"; + private static final String VERSION = "Version"; + private static final String ENVIRONMENT = "Environment"; + private static final String SUB_CONTEXT_PATH = "SubContextPath"; + private static final String SESSION_STICKINESS_REQUIRED = "sessionstickinessrequired"; + private static final String PARTITION = "partition"; + private static final String COMPRESS = "compress"; + private static final String TIMEOUT = "timeout"; + private static final String LIMIT = "limit"; + private static final String AFT_DME2_EP_READ_TIMEOUT_MS = "AFT_DME2_EP_READ_TIMEOUT_MS"; + private static final String AFT_DME2_ROUNDTRIP_TIMEOUT_MS = "AFT_DME2_ROUNDTRIP_TIMEOUT_MS"; + private static final String AFT_DME2_EP_CONN_TIMEOUT = "AFT_DME2_EP_CONN_TIMEOUT"; + private static final String AFT_DME2_EXCHANGE_REQUEST_HANDLERS = "AFT_DME2_EXCHANGE_REQUEST_HANDLERS"; + private static final String AFT_DME2_EXCHANGE_REPLY_HANDLERS = "AFT_DME2_EXCHANGE_REPLY_HANDLERS"; + private static final String AFT_DME2_REQ_TRACE_ON = "AFT_DME2_REQ_TRACE_ON"; + private static final String DME2_PER_HANDLER_TIMEOUT_MS = "DME2_PER_HANDLER_TIMEOUT_MS"; + private static final String DME2_REPLY_HANDLER_TIMEOUT_MS = "DME2_REPLY_HANDLER_TIMEOUT_MS"; private static MultivaluedMap httpHeadersMap; public static Map DME2HeadersMap; @@ -82,6 +123,7 @@ public class MRClientFactory { /** * Add getter to avoid direct access to static header map. + * * @return */ public static MultivaluedMap getHTTPHeadersMap() { @@ -90,6 +132,7 @@ public class MRClientFactory { /** * Add setter to avoid direct access to static header map. + * * @param headers */ public static void setHTTPHeadersMap(MultivaluedMap headers) { @@ -100,15 +143,11 @@ public class MRClientFactory { * Create a consumer instance with the default timeout and no limit on * messages returned. This consumer operates as an independent consumer * (i.e., not in a group) and is NOT re-startable across sessions. - * - * @param hostList - * A comma separated list of hosts to use to connect to MR. You - * can include port numbers (3904 is the default). For example, - * "hostname:8080," - * - * @param topic - * The topic to consume - * + * + * @param hostList A comma separated list of hosts to use to connect to MR. You + * can include port numbers (3904 is the default). For example, + * "hostname:8080," + * @param topic The topic to consume * @return a consumer */ public static MRConsumer createConsumer(String hostList, String topic) { @@ -119,12 +158,9 @@ public class MRClientFactory { * Create a consumer instance with the default timeout and no limit on * messages returned. This consumer operates as an independent consumer * (i.e., not in a group) and is NOT re-startable across sessions. - * - * @param hostSet - * The host used in the URL to MR. Entries can be "host:port". - * @param topic - * The topic to consume - * + * + * @param hostSet The host used in the URL to MR. Entries can be "host:port". + * @param topic The topic to consume * @return a consumer */ public static MRConsumer createConsumer(Collection hostSet, String topic) { @@ -136,14 +172,10 @@ public class MRClientFactory { * timeout, and no limit on messages returned. This consumer operates as an * independent consumer (i.e., not in a group) and is NOT re-startable * across sessions. - * - * @param hostSet - * The host used in the URL to MR. Entries can be "host:port". - * @param topic - * The topic to consume - * @param filter - * a filter to use on the server side - * + * + * @param hostSet The host used in the URL to MR. Entries can be "host:port". + * @param topic The topic to consume + * @param filter a filter to use on the server side * @return a consumer */ public static MRConsumer createConsumer(Collection hostSet, String topic, String filter) { @@ -155,20 +187,15 @@ public class MRClientFactory { * messages returned. This consumer can operate in a logical group and is * re-startable across sessions when you use the same group and ID on * restart. - * - * @param hostSet - * The host used in the URL to MR. Entries can be "host:port". - * @param topic - * The topic to consume - * @param consumerGroup - * The name of the consumer group this consumer is part of - * @param consumerId - * The unique id of this consume in its group - * + * + * @param hostSet The host used in the URL to MR. Entries can be "host:port". + * @param topic The topic to consume + * @param consumerGroup The name of the consumer group this consumer is part of + * @param consumerId The unique id of this consume in its group * @return a consumer */ public static MRConsumer createConsumer(Collection hostSet, final String topic, final String consumerGroup, - final String consumerId) { + final String consumerId) { return createConsumer(hostSet, topic, consumerGroup, consumerId, -1, -1); } @@ -177,27 +204,20 @@ public class MRClientFactory { * messages returned. This consumer can operate in a logical group and is * re-startable across sessions when you use the same group and ID on * restart. - * - * @param hostSet - * The host used in the URL to MR. Entries can be "host:port". - * @param topic - * The topic to consume - * @param consumerGroup - * The name of the consumer group this consumer is part of - * @param consumerId - * The unique id of this consume in its group - * @param timeoutMs - * The amount of time in milliseconds that the server should keep - * the connection open while waiting for message traffic. Use -1 - * for default timeout. - * @param limit - * A limit on the number of messages returned in a single call. - * Use -1 for no limit. - * + * + * @param hostSet The host used in the URL to MR. Entries can be "host:port". + * @param topic The topic to consume + * @param consumerGroup The name of the consumer group this consumer is part of + * @param consumerId The unique id of this consume in its group + * @param timeoutMs The amount of time in milliseconds that the server should keep + * the connection open while waiting for message traffic. Use -1 + * for default timeout. + * @param limit A limit on the number of messages returned in a single call. + * Use -1 for no limit. * @return a consumer */ public static MRConsumer createConsumer(Collection hostSet, final String topic, final String consumerGroup, - final String consumerId, int timeoutMs, int limit) { + final String consumerId, int timeoutMs, int limit) { return createConsumer(hostSet, topic, consumerGroup, consumerId, timeoutMs, limit, null, null, null); } @@ -206,31 +226,23 @@ public class MRClientFactory { * messages returned. This consumer can operate in a logical group and is * re-startable across sessions when you use the same group and ID on * restart. This consumer also uses server-side filtering. - * - * @param hostList - * A comma separated list of hosts to use to connect to MR. You - * can include port numbers (3904 is the default)" - * @param topic - * The topic to consume - * @param consumerGroup - * The name of the consumer group this consumer is part of - * @param consumerId - * The unique id of this consume in its group - * @param timeoutMs - * The amount of time in milliseconds that the server should keep - * the connection open while waiting for message traffic. Use -1 - * for default timeout. - * @param limit - * A limit on the number of messages returned in a single call. - * Use -1 for no limit. - * @param filter - * A Highland Park filter expression using only built-in filter - * components. Use null for "no filter". - * + * + * @param hostList A comma separated list of hosts to use to connect to MR. You + * can include port numbers (3904 is the default)" + * @param topic The topic to consume + * @param consumerGroup The name of the consumer group this consumer is part of + * @param consumerId The unique id of this consume in its group + * @param timeoutMs The amount of time in milliseconds that the server should keep + * the connection open while waiting for message traffic. Use -1 + * for default timeout. + * @param limit A limit on the number of messages returned in a single call. + * Use -1 for no limit. + * @param filter A Highland Park filter expression using only built-in filter + * components. Use null for "no filter". * @return a consumer */ public static MRConsumer createConsumer(String hostList, final String topic, final String consumerGroup, - final String consumerId, int timeoutMs, int limit, String filter, String apiKey, String apiSecret) { + final String consumerId, int timeoutMs, int limit, String filter, String apiKey, String apiSecret) { return createConsumer(MRConsumerImpl.stringToList(hostList), topic, consumerGroup, consumerId, timeoutMs, limit, filter, apiKey, apiSecret); } @@ -240,32 +252,25 @@ public class MRClientFactory { * messages returned. This consumer can operate in a logical group and is * re-startable across sessions when you use the same group and ID on * restart. This consumer also uses server-side filtering. - * - * @param hostSet - * The host used in the URL to MR. Entries can be "host:port". - * @param topic - * The topic to consume - * @param consumerGroup - * The name of the consumer group this consumer is part of - * @param consumerId - * The unique id of this consume in its group - * @param timeoutMs - * The amount of time in milliseconds that the server should keep - * the connection open while waiting for message traffic. Use -1 - * for default timeout. - * @param limit - * A limit on the number of messages returned in a single call. - * Use -1 for no limit. - * @param filter - * A Highland Park filter expression using only built-in filter - * components. Use null for "no filter". - * + * + * @param hostSet The host used in the URL to MR. Entries can be "host:port". + * @param topic The topic to consume + * @param consumerGroup The name of the consumer group this consumer is part of + * @param consumerId The unique id of this consume in its group + * @param timeoutMs The amount of time in milliseconds that the server should keep + * the connection open while waiting for message traffic. Use -1 + * for default timeout. + * @param limit A limit on the number of messages returned in a single call. + * Use -1 for no limit. + * @param filter A Highland Park filter expression using only built-in filter + * components. Use null for "no filter". * @return a consumer */ public static MRConsumer createConsumer(Collection hostSet, final String topic, final String consumerGroup, - final String consumerId, int timeoutMs, int limit, String filter, String apiKey, String apiSecret) { - if (MRClientBuilders.sfConsumerMock != null) + final String consumerId, int timeoutMs, int limit, String filter, String apiKey, String apiSecret) { + if (MRClientBuilders.sfConsumerMock != null) { return MRClientBuilders.sfConsumerMock; + } try { return new MRConsumerImpl.MRConsumerImplBuilder().setHostPart(hostSet).setTopic(topic) .setConsumerGroup(consumerGroup).setConsumerId(consumerId) @@ -277,21 +282,19 @@ public class MRClientFactory { } } - /*************************************************************************/ - /*************************************************************************/ - /*************************************************************************/ + //************************************************************************* + //************************************************************************* + //************************************************************************* /** * Create a publisher that sends each message (or group of messages) * immediately. Most applications should favor higher latency for much * higher message throughput and the "simple publisher" is not a good * choice. - * - * @param hostlist - * The host used in the URL to MR. Can be "host:port", can be - * multiple comma-separated entries. - * @param topic - * The topic on which to publish messages. + * + * @param hostlist The host used in the URL to MR. Can be "host:port", can be + * multiple comma-separated entries. + * @param topic The topic on which to publish messages. * @return a publisher */ public static MRBatchingPublisher createSimplePublisher(String hostlist, String topic) { @@ -302,94 +305,69 @@ public class MRClientFactory { * Create a publisher that batches messages. Be sure to close the publisher * to send the last batch and ensure a clean shutdown. Message payloads are * not compressed. - * - * @param hostlist - * The host used in the URL to MR. Can be "host:port", can be - * multiple comma-separated entries. - * @param topic - * The topic on which to publish messages. - * @param maxBatchSize - * The largest set of messages to batch - * @param maxAgeMs - * The maximum age of a message waiting in a batch - * + * + * @param hostlist The host used in the URL to MR. Can be "host:port", can be + * multiple comma-separated entries. + * @param topic The topic on which to publish messages. + * @param maxBatchSize The largest set of messages to batch + * @param maxAgeMs The maximum age of a message waiting in a batch * @return a publisher */ public static MRBatchingPublisher createBatchingPublisher(String hostlist, String topic, int maxBatchSize, - long maxAgeMs) { + long maxAgeMs) { return createBatchingPublisher(hostlist, topic, maxBatchSize, maxAgeMs, false); } /** * Create a publisher that batches messages. Be sure to close the publisher * to send the last batch and ensure a clean shutdown. - * - * @param hostlist - * The host used in the URL to MR. Can be "host:port", can be - * multiple comma-separated entries. - * @param topic - * The topic on which to publish messages. - * @param maxBatchSize - * The largest set of messages to batch - * @param maxAgeMs - * The maximum age of a message waiting in a batch - * @param compress - * use gzip compression - * + * + * @param hostlist The host used in the URL to MR. Can be "host:port", can be + * multiple comma-separated entries. + * @param topic The topic on which to publish messages. + * @param maxBatchSize The largest set of messages to batch + * @param maxAgeMs The maximum age of a message waiting in a batch + * @param compress use gzip compression * @return a publisher */ public static MRBatchingPublisher createBatchingPublisher(String hostlist, String topic, int maxBatchSize, - long maxAgeMs, boolean compress) { + long maxAgeMs, boolean compress) { return createBatchingPublisher(MRConsumerImpl.stringToList(hostlist), topic, maxBatchSize, maxAgeMs, compress); } /** * Create a publisher that batches messages. Be sure to close the publisher * to send the last batch and ensure a clean shutdown. - * - * @param hostSet - * A set of hosts to be used in the URL to MR. Can be - * "host:port". Use multiple entries to enable failover. - * @param topic - * The topic on which to publish messages. - * @param maxBatchSize - * The largest set of messages to batch - * @param maxAgeMs - * The maximum age of a message waiting in a batch - * @param compress - * use gzip compression - * + * + * @param hostSet A set of hosts to be used in the URL to MR. Can be + * "host:port". Use multiple entries to enable failover. + * @param topic The topic on which to publish messages. + * @param maxBatchSize The largest set of messages to batch + * @param maxAgeMs The maximum age of a message waiting in a batch + * @param compress use gzip compression * @return a publisher */ public static MRBatchingPublisher createBatchingPublisher(String[] hostSet, String topic, int maxBatchSize, - long maxAgeMs, boolean compress) { + long maxAgeMs, boolean compress) { final TreeSet hosts = new TreeSet<>(); - for (String hp : hostSet) { - hosts.add(hp); - } + Collections.addAll(hosts, hostSet); return createBatchingPublisher(hosts, topic, maxBatchSize, maxAgeMs, compress); } /** * Create a publisher that batches messages. Be sure to close the publisher * to send the last batch and ensure a clean shutdown. - * - * @param hostSet - * A set of hosts to be used in the URL to MR. Can be - * "host:port". Use multiple entries to enable failover. - * @param topic - * The topic on which to publish messages. - * @param maxBatchSize - * The largest set of messages to batch - * @param maxAgeMs - * The maximum age of a message waiting in a batch - * @param compress - * use gzip compression - * + * + * @param hostSet A set of hosts to be used in the URL to MR. Can be + * "host:port". Use multiple entries to enable failover. + * @param topic The topic on which to publish messages. + * @param maxBatchSize The largest set of messages to batch + * @param maxAgeMs The maximum age of a message waiting in a batch + * @param compress use gzip compression * @return a publisher */ public static MRBatchingPublisher createBatchingPublisher(Collection hostSet, String topic, - int maxBatchSize, long maxAgeMs, boolean compress) { + int maxBatchSize, long maxAgeMs, boolean compress) { return new MRSimplerBatchPublisher.Builder().againstUrls(hostSet).onTopic(topic).batchTo(maxBatchSize, maxAgeMs) .compress(compress).build(); } @@ -397,28 +375,20 @@ public class MRClientFactory { /** * Create a publisher that batches messages. Be sure to close the publisher * to send the last batch and ensure a clean shutdown. - * - * @param host - * A host to be used in the URL to MR. Can be "host:port". Use - * multiple entries to enable failover. - * @param topic - * The topic on which to publish messages. - * @param username - * username - * @param password - * password - * @param maxBatchSize - * The largest set of messages to batch - * @param maxAgeMs - * The maximum age of a message waiting in a batch - * @param compress - * use gzip compression - * @param protocolFlag - * http auth or ueb auth or dme2 method + * + * @param host A host to be used in the URL to MR. Can be "host:port". Use + * multiple entries to enable failover. + * @param topic The topic on which to publish messages. + * @param username username + * @param password password + * @param maxBatchSize The largest set of messages to batch + * @param maxAgeMs The maximum age of a message waiting in a batch + * @param compress use gzip compression + * @param protocolFlag http auth or ueb auth or dme2 method * @return MRBatchingPublisher obj */ public static MRBatchingPublisher createBatchingPublisher(String host, String topic, final String username, - final String password, int maxBatchSize, long maxAgeMs, boolean compress, String protocolFlag) { + final String password, int maxBatchSize, long maxAgeMs, boolean compress, String protocolFlag) { MRSimplerBatchPublisher pub = new MRSimplerBatchPublisher.Builder() .againstUrls(MRConsumerImpl.stringToList(host)).onTopic(topic).batchTo(maxBatchSize, maxAgeMs) .compress(compress).build(); @@ -433,14 +403,11 @@ public class MRClientFactory { /** * Create a publisher that batches messages. Be sure to close the publisher * to send the last batch and ensure a clean shutdown - * - * @param props - * props set all properties for publishing message + * + * @param props props set all properties for publishing message * @return MRBatchingPublisher obj - * @throws FileNotFoundException - * exc - * @throws IOException - * ioex + * @throws FileNotFoundException exc + * @throws IOException ioex */ public static MRBatchingPublisher createBatchingPublisher(Properties props, boolean withResponse) throws FileNotFoundException, IOException { @@ -450,14 +417,11 @@ public class MRClientFactory { /** * Create a publisher that batches messages. Be sure to close the publisher * to send the last batch and ensure a clean shutdown - * - * @param props - * props set all properties for publishing message + * + * @param props props set all properties for publishing message * @return MRBatchingPublisher obj - * @throws FileNotFoundException - * exc - * @throws IOException - * ioex + * @throws FileNotFoundException exc + * @throws IOException ioex */ public static MRBatchingPublisher createBatchingPublisher(Properties props) throws FileNotFoundException, IOException { @@ -467,19 +431,16 @@ public class MRClientFactory { /** * Create a publisher that batches messages. Be sure to close the publisher * to send the last batch and ensure a clean shutdown - * - * @param producerFilePath - * set all properties for publishing message + * + * @param producerFilePath set all properties for publishing message * @return MRBatchingPublisher obj - * @throws FileNotFoundException - * exc - * @throws IOException - * ioex + * @throws FileNotFoundException exc + * @throws IOException ioex */ public static MRBatchingPublisher createBatchingPublisher(final String producerFilePath) throws FileNotFoundException, IOException { Properties props = new Properties(); - try(InputStream input = new FileInputStream(producerFilePath)) { + try (InputStream input = new FileInputStream(producerFilePath)) { props.load(input); } return createBatchingPublisher(props); @@ -488,19 +449,16 @@ public class MRClientFactory { /** * Create a publisher that will contain send methods that return response * object to user. - * - * @param producerFilePath - * set all properties for publishing message + * + * @param producerFilePath set all properties for publishing message * @return MRBatchingPublisher obj - * @throws FileNotFoundException - * exc - * @throws IOException - * ioex + * @throws FileNotFoundException exc + * @throws IOException ioex */ public static MRBatchingPublisher createBatchingPublisher(final String producerFilePath, boolean withResponse) throws FileNotFoundException, IOException { Properties props = new Properties(); - try(InputStream input = new FileInputStream(producerFilePath)) { + try (InputStream input = new FileInputStream(producerFilePath)) { props.load(input); } return createBatchingPublisher(props, withResponse); @@ -510,26 +468,32 @@ public class MRClientFactory { throws FileNotFoundException, IOException { assert props != null; MRSimplerBatchPublisher pub; + + String messageSentThreadOccurrence = props.getProperty(MESSAGE_SENT_THREAD_OCCURRENCE); + if (messageSentThreadOccurrence == null || messageSentThreadOccurrence.isEmpty()) { + messageSentThreadOccurrence = props.getProperty(MESSAGE_SENT_THREAD_OCCURRENCE_OLD); + } + if (withResponse) { pub = new MRSimplerBatchPublisher.Builder() - .againstUrlsOrServiceName(MRConsumerImpl.stringToList(props.getProperty(HOST)),MRConsumerImpl.stringToList(props.getProperty("ServiceName")), props.getProperty(TRANSPORT_TYPE)) + .againstUrlsOrServiceName(MRConsumerImpl.stringToList(props.getProperty(HOST)), MRConsumerImpl.stringToList(props.getProperty(SERVICE_NAME)), props.getProperty(TRANSPORT_TYPE)) .onTopic(props.getProperty(TOPIC)) - .batchTo(Integer.parseInt(props.getProperty("maxBatchSize")), - Integer.parseInt(props.getProperty("maxAgeMs").toString())) - .compress(Boolean.parseBoolean(props.getProperty("compress"))) - .httpThreadTime(Integer.parseInt(props.getProperty("MessageSentThreadOccurance"))) + .batchTo(Integer.parseInt(props.getProperty(MAX_BATCH_SIZE)), + Integer.parseInt(props.getProperty(MAX_AGE_MS).toString())) + .compress(Boolean.parseBoolean(props.getProperty(COMPRESS))) + .httpThreadTime(Integer.parseInt(messageSentThreadOccurrence)) .withResponse(withResponse).build(); } else { pub = new MRSimplerBatchPublisher.Builder() - .againstUrlsOrServiceName(MRConsumerImpl.stringToList(props.getProperty(HOST)), MRConsumerImpl.stringToList(props.getProperty("ServiceName")), props.getProperty(TRANSPORT_TYPE)) + .againstUrlsOrServiceName(MRConsumerImpl.stringToList(props.getProperty(HOST)), MRConsumerImpl.stringToList(props.getProperty(SERVICE_NAME)), props.getProperty(TRANSPORT_TYPE)) .onTopic(props.getProperty(TOPIC)) - .batchTo(Integer.parseInt(props.getProperty("maxBatchSize")), - Integer.parseInt(props.getProperty("maxAgeMs").toString())) - .compress(Boolean.parseBoolean(props.getProperty("compress"))) - .httpThreadTime(Integer.parseInt(props.getProperty("MessageSentThreadOccurance"))).build(); + .batchTo(Integer.parseInt(props.getProperty(MAX_BATCH_SIZE)), + Integer.parseInt(props.getProperty(MAX_AGE_MS).toString())) + .compress(Boolean.parseBoolean(props.getProperty(COMPRESS))) + .httpThreadTime(Integer.parseInt(messageSentThreadOccurrence)).build(); } pub.setHost(props.getProperty(HOST)); - if (props.getProperty(TRANSPORT_TYPE).equalsIgnoreCase(ProtocolTypeConstants.AUTH_KEY.getValue())) { + if (props.getProperty(TRANSPORT_TYPE).equalsIgnoreCase(ProtocolType.AUTH_KEY.getValue())) { pub.setAuthKey(props.getProperty(AUTH_KEY)); pub.setAuthDate(props.getProperty(AUTH_DATE)); @@ -542,7 +506,7 @@ public class MRClientFactory { pub.setProtocolFlag(props.getProperty(TRANSPORT_TYPE)); pub.setProps(props); prop = new Properties(); - if (props.getProperty(TRANSPORT_TYPE).equalsIgnoreCase(ProtocolTypeConstants.DME2.getValue())) { + if (props.getProperty(TRANSPORT_TYPE).equalsIgnoreCase(ProtocolType.DME2.getValue())) { routeFilePath = props.getProperty(DME2PREFERRED_ROUTER_FILE_PATH); routeReader = new FileReader(new File(routeFilePath)); File fo = new File(routeFilePath); @@ -555,14 +519,11 @@ public class MRClientFactory { /** * Create an identity manager client to work with API keys. - * - * @param hostSet - * A set of hosts to be used in the URL to MR. Can be - * "host:port". Use multiple entries to enable failover. - * @param apiKey - * Your API key - * @param apiSecret - * Your API secret + * + * @param hostSet A set of hosts to be used in the URL to MR. Can be + * "host:port". Use multiple entries to enable failover. + * @param apiKey Your API key + * @param apiSecret Your API secret * @return an identity manager */ public static MRIdentityManager createIdentityManager(Collection hostSet, String apiKey, String apiSecret) { @@ -578,14 +539,11 @@ public class MRClientFactory { /** * Create a topic manager for working with topics. - * - * @param hostSet - * A set of hosts to be used in the URL to MR. Can be - * "host:port". Use multiple entries to enable failover. - * @param apiKey - * Your API key - * @param apiSecret - * Your API secret + * + * @param hostSet A set of hosts to be used in the URL to MR. Can be + * "host:port". Use multiple entries to enable failover. + * @param apiKey Your API key + * @param apiSecret Your API secret * @return a topic manager */ public static MRTopicManager createTopicManager(Collection hostSet, String apiKey, String apiSecret) { @@ -601,7 +559,7 @@ public class MRClientFactory { /** * Inject a consumer. Used to support unit tests. - * + * * @param cc */ public static void $testInject(MRConsumer cc) { @@ -609,13 +567,13 @@ public class MRClientFactory { } public static MRConsumer createConsumer(String host, String topic, String username, String password, String group, - String id, int i, int j, String protocalFlag, String consumerFilePath) { + String id, int timeout, int limit, String protocalFlag, String consumerFilePath) { MRConsumerImpl sub; try { sub = new MRConsumerImpl.MRConsumerImplBuilder() .setHostPart(MRConsumerImpl.stringToList(host)).setTopic(topic) - .setConsumerGroup(group).setConsumerId(id).setTimeoutMs(i).setLimit(j) + .setConsumerGroup(group).setConsumerId(id).setTimeoutMs(timeout).setLimit(limit) .setFilter(null).setApiKey_username(null).setApiSecret_password(null) .createMRConsumerImpl(); } catch (MalformedURLException e) { @@ -631,13 +589,13 @@ public class MRClientFactory { } public static MRConsumer createConsumer(String host, String topic, String username, String password, String group, - String id, String protocalFlag, String consumerFilePath, int i, int j) { + String id, String protocalFlag, String consumerFilePath, int timeout, int limit) { MRConsumerImpl sub; try { sub = new MRConsumerImpl.MRConsumerImplBuilder() .setHostPart(MRConsumerImpl.stringToList(host)).setTopic(topic) - .setConsumerGroup(group).setConsumerId(id).setTimeoutMs(i).setLimit(j) + .setConsumerGroup(group).setConsumerId(id).setTimeoutMs(timeout).setLimit(limit) .setFilter(null).setApiKey_username(null).setApiSecret_password(null) .createMRConsumerImpl(); } catch (MalformedURLException e) { @@ -654,7 +612,7 @@ public class MRClientFactory { public static MRConsumer createConsumer(String consumerFilePath) throws FileNotFoundException, IOException { Properties props = new Properties(); - try(InputStream input = new FileInputStream(consumerFilePath)) { + try (InputStream input = new FileInputStream(consumerFilePath)) { props.load(input); } return createConsumer(props); @@ -663,26 +621,29 @@ public class MRClientFactory { public static MRConsumer createConsumer(Properties props) throws FileNotFoundException, IOException { int timeout; ValidatorUtil.validateSubscriber(props); - if (props.getProperty("timeout") != null) - timeout = Integer.parseInt(props.getProperty("timeout")); - else + if (props.getProperty(TIMEOUT) != null) { + timeout = Integer.parseInt(props.getProperty(TIMEOUT)); + } else { timeout = -1; + } int limit; - if (props.getProperty("limit") != null) - limit = Integer.parseInt(props.getProperty("limit")); - else + if (props.getProperty(LIMIT) != null) { + limit = Integer.parseInt(props.getProperty(LIMIT)); + } else { limit = -1; + } String group; - if (props.getProperty("group") == null) + if (props.getProperty(GROUP) == null) { group = UUID.randomUUID().toString(); - else - group = props.getProperty("group"); + } else { + group = props.getProperty(GROUP); + } MRConsumerImpl sub = null; - if (props.getProperty(TRANSPORT_TYPE).equalsIgnoreCase(ProtocolTypeConstants.AUTH_KEY.getValue())) { + if (props.getProperty(TRANSPORT_TYPE).equalsIgnoreCase(ProtocolType.AUTH_KEY.getValue())) { sub = new MRConsumerImpl.MRConsumerImplBuilder() .setHostPart(MRConsumerImpl.stringToList(props.getProperty(HOST))) .setTopic(props.getProperty(TOPIC)).setConsumerGroup(group) - .setConsumerId(props.getProperty("id")).setTimeoutMs(timeout).setLimit(limit) + .setConsumerId(props.getProperty(ID)).setTimeoutMs(timeout).setLimit(limit) .setFilter(props.getProperty(FILTER)) .setApiKey_username(props.getProperty(AUTH_KEY)) .setApiSecret_password(props.getProperty(AUTH_DATE)).createMRConsumerImpl(); @@ -694,29 +655,29 @@ public class MRClientFactory { sub = new MRConsumerImpl.MRConsumerImplBuilder() .setHostPart(MRConsumerImpl.stringToList(props.getProperty(HOST))) .setTopic(props.getProperty(TOPIC)).setConsumerGroup(group) - .setConsumerId(props.getProperty("id")).setTimeoutMs(timeout).setLimit(limit) + .setConsumerId(props.getProperty(ID)).setTimeoutMs(timeout).setLimit(limit) .setFilter(props.getProperty(FILTER)) .setApiKey_username(props.getProperty(USERNAME)) .setApiSecret_password(props.getProperty(PASSWORD)).createMRConsumerImpl(); sub.setUsername(props.getProperty(USERNAME)); sub.setPassword(props.getProperty(PASSWORD)); } - + sub.setProps(props); sub.setHost(props.getProperty(HOST)); sub.setProtocolFlag(props.getProperty(TRANSPORT_TYPE)); sub.setfFilter(props.getProperty(FILTER)); - if (props.getProperty(TRANSPORT_TYPE).equalsIgnoreCase(ProtocolTypeConstants.DME2.getValue())) { + if (props.getProperty(TRANSPORT_TYPE).equalsIgnoreCase(ProtocolType.DME2.getValue())) { MRConsumerImpl.setRouterFilePath(props.getProperty(DME2PREFERRED_ROUTER_FILE_PATH)); routeFilePath = props.getProperty(DME2PREFERRED_ROUTER_FILE_PATH); routeReader = new FileReader(new File(routeFilePath)); prop = new Properties(); File fo = new File(routeFilePath); - if (!fo.exists()) { - routeWriter = new FileWriter(new File(routeFilePath)); - } + if (!fo.exists()) { + routeWriter = new FileWriter(new File(routeFilePath)); + } } - + return sub; } } diff --git a/src/main/java/org/onap/dmaap/mr/client/MRConsumer.java b/src/main/java/org/onap/dmaap/mr/client/MRConsumer.java index b2f7563..8196a0a 100644 --- a/src/main/java/org/onap/dmaap/mr/client/MRConsumer.java +++ b/src/main/java/org/onap/dmaap/mr/client/MRConsumer.java @@ -4,11 +4,13 @@ * ================================================================================ * Copyright © 2017 AT&T Intellectual Property. All rights reserved. * ================================================================================ + * Modifications Copyright © 2021 Orange. + * ================================================================================ * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * http://www.apache.org/licenses/LICENSE-2.0 - * + * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. @@ -17,38 +19,37 @@ * ============LICENSE_END========================================================= * * ECOMP is a trademark and service mark of AT&T Intellectual Property. - * + * *******************************************************************************/ + package org.onap.dmaap.mr.client; import java.io.IOException; - import org.onap.dmaap.mr.client.response.MRConsumerResponse; -public interface MRConsumer extends MRClient -{ - /** - * Fetch a set of messages. The consumer's timeout and message limit are used if set in the constructor call. +public interface MRConsumer extends MRClient { + /** + * Fetch a set of messages. The consumer's timeout and message limit are used if set in the constructor call. + * + * @return a set of messages + * @throws IOException + */ + Iterable fetch() throws IOException, Exception; + + /** + * Fetch a set of messages with an explicit timeout and limit for this call. These values + * override any set in the constructor call. + * + * @param timeoutMs The amount of time in milliseconds that the server should keep the connection + * open while waiting for message traffic. Use -1 for default timeout (controlled on the server-side). + * @param limit A limit on the number of messages returned in a single call. Use -1 for no limit. + * @return a set messages + * @throws IOException if there's a problem connecting to the server + */ + Iterable fetch(int timeoutMs, int limit) throws IOException, Exception; + + MRConsumerResponse fetchWithReturnConsumerResponse(); - * @return a set of messages - * @throws IOException - */ - Iterable fetch () throws IOException, Exception; - /** - * Fetch a set of messages with an explicit timeout and limit for this call. These values - * override any set in the constructor call. - * - * @param timeoutMs The amount of time in milliseconds that the server should keep the connection - * open while waiting for message traffic. Use -1 for default timeout (controlled on the server-side). - * @param limit A limit on the number of messages returned in a single call. Use -1 for no limit. - * @return a set messages - * @throws IOException if there's a problem connecting to the server - */ - Iterable fetch ( int timeoutMs, int limit ) throws IOException, Exception; - - MRConsumerResponse fetchWithReturnConsumerResponse (); - - - MRConsumerResponse fetchWithReturnConsumerResponse ( int timeoutMs, int limit ); + MRConsumerResponse fetchWithReturnConsumerResponse(int timeoutMs, int limit); } diff --git a/src/main/java/org/onap/dmaap/mr/client/MRIdentityManager.java b/src/main/java/org/onap/dmaap/mr/client/MRIdentityManager.java index 1905f82..16236a7 100644 --- a/src/main/java/org/onap/dmaap/mr/client/MRIdentityManager.java +++ b/src/main/java/org/onap/dmaap/mr/client/MRIdentityManager.java @@ -4,11 +4,13 @@ * ================================================================================ * Copyright © 2017 AT&T Intellectual Property. All rights reserved. * ================================================================================ + * Modifications Copyright © 2021 Orange. + * ================================================================================ * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * http://www.apache.org/licenses/LICENSE-2.0 - * + * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. @@ -17,84 +19,86 @@ * ============LICENSE_END========================================================= * * ECOMP is a trademark and service mark of AT&T Intellectual Property. - * + * *******************************************************************************/ -package org.onap.dmaap.mr.client; -import java.io.IOException; +package org.onap.dmaap.mr.client; import com.att.nsa.apiClient.credentials.ApiCredential; import com.att.nsa.apiClient.http.HttpException; import com.att.nsa.apiClient.http.HttpObjectNotFoundException; +import java.io.IOException; + /** * A client for manipulating API keys. - * @author author * + * @author author */ -public interface MRIdentityManager extends MRClient -{ - /** - * An API Key record - */ - public interface ApiKey - { - /** - * Get the email address associated with the API key - * @return the email address on the API key or null - */ - String getEmail (); +public interface MRIdentityManager extends MRClient { + /** + * An API Key record. + */ + interface ApiKey { + /** + * Get the email address associated with the API key. + * + * @return the email address on the API key or null + */ + String getEmail(); + + /** + * Get the description associated with the API key. + * + * @return the description on the API key or null + */ + String getDescription(); + } - /** - * Get the description associated with the API key - * @return the description on the API key or null - */ - String getDescription (); - } + /** + * Create a new API key on the UEB cluster. The returned credential instance + * contains the new API key and API secret. This is the only time the secret + * is available to the client -- there's no API for retrieving it later -- so + * your application must store it securely. + * + * @param email + * @param description + * @return a new credential + * @throws HttpException + * @throws MRApiException + * @throws IOException + */ + ApiCredential createApiKey(String email, String description) throws HttpException, MRApiException, IOException; - /** - * Create a new API key on the UEB cluster. The returned credential instance - * contains the new API key and API secret. This is the only time the secret - * is available to the client -- there's no API for retrieving it later -- so - * your application must store it securely. - * - * @param email - * @param description - * @return a new credential - * @throws HttpException - * @throws MRApiException - * @throws IOException - */ - ApiCredential createApiKey ( String email, String description ) throws HttpException, MRApiException, IOException; - - /** - * Get basic info about a known API key - * @param apiKey - * @return the API key's info or null if it doesn't exist - * @throws HttpObjectNotFoundException, HttpException, MRApiException - * @throws IOException - */ - ApiKey getApiKey ( String apiKey ) throws HttpObjectNotFoundException, HttpException, MRApiException, IOException; + /** + * Get basic info about a known API key. + * + * @param apiKey + * @return the API key's info or null if it doesn't exist + * @throws HttpObjectNotFoundException, HttpException, MRApiException + * @throws IOException + */ + ApiKey getApiKey(String apiKey) throws HttpObjectNotFoundException, HttpException, MRApiException, IOException; - /** - * Update the record for the API key used to authenticate this request. The UEB - * API requires that you authenticate with the same key you're updating, so the - * API key being changed is the one used for setApiCredentials. - * - * @param email use null to keep the current value - * @param description use null to keep the current value - * @throws IOException - * @throws HttpException - * @throws HttpObjectNotFoundException - */ - void updateCurrentApiKey ( String email, String description ) throws HttpObjectNotFoundException, HttpException, IOException; + /** + * Update the record for the API key used to authenticate this request. The UEB + * API requires that you authenticate with the same key you're updating, so the + * API key being changed is the one used for setApiCredentials. + * + * @param email use null to keep the current value + * @param description use null to keep the current value + * @throws IOException + * @throws HttpException + * @throws HttpObjectNotFoundException + */ + void updateCurrentApiKey(String email, String description) throws HttpObjectNotFoundException, HttpException, IOException; - /** - * Delete the *current* API key. After this call returns, the API key - * used to authenticate will no longer be valid. - * - * @throws IOException - * @throws HttpException - */ - void deleteCurrentApiKey () throws HttpException, IOException; + /** + * Delete the *current* API key. After this call returns, the API key + * used to authenticate will no longer be valid. + * + * @throws IOException + * @throws HttpException + */ + void deleteCurrentApiKey() throws HttpException, IOException; } diff --git a/src/main/java/org/onap/dmaap/mr/client/MRPublisher.java b/src/main/java/org/onap/dmaap/mr/client/MRPublisher.java index e900229..1e703e6 100644 --- a/src/main/java/org/onap/dmaap/mr/client/MRPublisher.java +++ b/src/main/java/org/onap/dmaap/mr/client/MRPublisher.java @@ -4,11 +4,13 @@ * ================================================================================ * Copyright © 2017 AT&T Intellectual Property. All rights reserved. * ================================================================================ + * Modifications Copyright © 2021 Orange. + * ================================================================================ * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * http://www.apache.org/licenses/LICENSE-2.0 - * + * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. @@ -17,8 +19,9 @@ * ============LICENSE_END========================================================= * * ECOMP is a trademark and service mark of AT&T Intellectual Property. - * + * *******************************************************************************/ + package org.onap.dmaap.mr.client; import java.io.IOException; @@ -26,68 +29,67 @@ import java.util.Collection; /** * A MR publishing interface. - * */ -public interface MRPublisher extends MRClient -{ - /** - * A simple message container - */ - public static class message - { - public message ( String partition, String msg ) - { - fPartition = partition == null ? "" : partition; - fMsg = msg; - if ( fMsg == null ) - { - throw new IllegalArgumentException ( "Can't send a null message." ); - } - } +public interface MRPublisher extends MRClient { + /** + * A simple message container. + */ + class Message { + public Message(String partition, String msg) { + fPartition = partition == null ? "" : partition; + fMsg = msg; + if (fMsg == null) { + throw new IllegalArgumentException("Can't send a null message."); + } + } + + public Message(Message msg) { + this(msg.fPartition, msg.fMsg); + } + + public final String fPartition; + public final String fMsg; + } - public message ( message msg ) - { - this ( msg.fPartition, msg.fMsg ); - } + /** + * Send the given message without partition. partition will be placed at HTTP request level. + * + * @param msg message to sent + * @return the number of pending messages + * @throws IOException exception + */ + int send(String msg) throws IOException; - public final String fPartition; - public final String fMsg; - } - - /** - * Send the given message without partition. partition will be placed at HTTP request level. - * @param msg message to sent - * @return the number of pending messages - * @throws IOException exception - */ - int send ( String msg ) throws IOException; - /** - * Send the given message using the given partition. - * @param partition partition - * @param msg message - * @return the number of pending messages - * @throws IOException exception - */ - int send ( String partition, String msg ) throws IOException; + /** + * Send the given message using the given partition. + * + * @param partition partition + * @param msg message + * @return the number of pending messages + * @throws IOException exception + */ + int send(String partition, String msg) throws IOException; - /** - * Send the given message using its partition. - * @param msg mesg - * @return the number of pending messages - * @throws IOException exp - */ - int send ( message msg ) throws IOException; + /** + * Send the given message using its partition. + * + * @param msg mesg + * @return the number of pending messages + * @throws IOException exp + */ + int send(Message msg) throws IOException; - /** - * Send the given messages using their partitions. - * @param msgs msg - * @return the number of pending messages - * @throws IOException exp - */ - int send ( Collection msgs ) throws IOException; + /** + * Send the given messages using their partitions. + * + * @param msgs msg + * @return the number of pending messages + * @throws IOException exp + */ + int send(Collection msgs) throws IOException; - /** - * Close this publisher. It's an error to call send() after close() - */ - void close (); + /** + * Close this publisher. It's an error to call send() after close() + */ + void close(); } diff --git a/src/main/java/org/onap/dmaap/mr/client/MRTopicManager.java b/src/main/java/org/onap/dmaap/mr/client/MRTopicManager.java index 54ca7ec..1d8deee 100644 --- a/src/main/java/org/onap/dmaap/mr/client/MRTopicManager.java +++ b/src/main/java/org/onap/dmaap/mr/client/MRTopicManager.java @@ -4,11 +4,13 @@ * ================================================================================ * Copyright © 2017 AT&T Intellectual Property. All rights reserved. * ================================================================================ + * Modifications Copyright © 2021 Orange. + * ================================================================================ * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * http://www.apache.org/licenses/LICENSE-2.0 - * + * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. @@ -17,167 +19,183 @@ * ============LICENSE_END========================================================= * * ECOMP is a trademark and service mark of AT&T Intellectual Property. - * + * *******************************************************************************/ -package org.onap.dmaap.mr.client; -import java.io.IOException; -import java.util.Set; +package org.onap.dmaap.mr.client; import com.att.nsa.apiClient.http.HttpException; import com.att.nsa.apiClient.http.HttpObjectNotFoundException; +import java.io.IOException; +import java.util.Set; + /** * A client for working with topic metadata. + * * @author author */ -public interface MRTopicManager extends MRClient -{ - /** - * Get the topics available in the cluster - * @return a set of topic names - * @throws IOException - */ - Set getTopics () throws IOException; - - /** - * Information about a topic. - */ - public interface TopicInfo - { - /** - * Get the owner of the topic - * @return the owner, or null if no entry - */ - String getOwner (); - - /** - * Get the description for this topic - * @return the description, or null if no entry - */ - String getDescription (); - - /** - * Get the set of allowed producers (as API keys) on this topic - * @return the set of allowed producers, null of no ACL exists/enabled - */ - Set getAllowedProducers (); - - /** - * Get the set of allowed consumers (as API keys) on this topic - * @return the set of allowed consumers, null of no ACL exists/enabled - */ - Set getAllowedConsumers (); - } - - /** - * Get information about a topic. - * @param topic - * @return topic information - * @throws IOException - * @throws HttpObjectNotFoundException - */ - TopicInfo getTopicMetadata ( String topic ) throws HttpObjectNotFoundException, IOException; - - /** - * Create a new topic. - * @param topicName - * @param topicDescription - * @param partitionCount - * @param replicationCount - * @throws HttpException - * @throws IOException - */ - void createTopic ( String topicName, String topicDescription, int partitionCount, int replicationCount ) throws HttpException, IOException; - - /** - * Delete the topic. This call must be authenticated and the API key listed as owner on the topic. - * NOTE: The MR (UEB) API server does not support topic deletion at this time (mid 2015) - * @param topic - * @throws HttpException - * @throws IOException - * @deprecated If/when the Kafka system supports topic delete, or the implementation changes, this will be restored. - */ - @Deprecated - void deleteTopic ( String topic ) throws HttpException, IOException; - - /** - * Can any client produce events into this topic without authentication? - * @param topic - * @return true if the topic is open for producing - * @throws IOException - * @throws HttpObjectNotFoundException - */ - boolean isOpenForProducing ( String topic ) throws HttpObjectNotFoundException, IOException; - - /** - * Get the set of allowed producers. If the topic is open, the result is null. - * @param topic - * @return a set of allowed producers or null - * @throws IOException - * @throws HttpObjectNotFoundException - */ - Set getAllowedProducers ( String topic ) throws HttpObjectNotFoundException, IOException; - - /** - * Allow the given API key to produce messages on the given topic. The caller must - * own this topic. - * @param topic - * @param apiKey - * @throws HttpException - * @throws HttpObjectNotFoundException - * @throws IOException - */ - void allowProducer ( String topic, String apiKey ) throws HttpObjectNotFoundException, HttpException, IOException; - - /** - * Revoke the given API key's authorization to produce messages on the given topic. - * The caller must own this topic. - * @param topic - * @param apiKey - * @throws HttpException - * @throws IOException - */ - void revokeProducer ( String topic, String apiKey ) throws HttpException, IOException; - - /** - * Can any client consume events from this topic without authentication? - * @param topic - * @return true if the topic is open for consuming - * @throws IOException - * @throws HttpObjectNotFoundException - */ - boolean isOpenForConsuming ( String topic ) throws HttpObjectNotFoundException, IOException; - - /** - * Get the set of allowed consumers. If the topic is open, the result is null. - * @param topic - * @return a set of allowed consumers or null - * @throws IOException - * @throws HttpObjectNotFoundException - */ - Set getAllowedConsumers ( String topic ) throws HttpObjectNotFoundException, IOException; - - /** - * Allow the given API key to consume messages on the given topic. The caller must - * own this topic. - * @param topic - * @param apiKey - * @throws HttpException - * @throws HttpObjectNotFoundException - * @throws IOException - */ - void allowConsumer ( String topic, String apiKey ) throws HttpObjectNotFoundException, HttpException, IOException; - - /** - * Revoke the given API key's authorization to consume messages on the given topic. - * The caller must own this topic. - * @param topic - * @param apiKey - * @throws HttpException - * @throws IOException - */ - void revokeConsumer ( String topic, String apiKey ) throws HttpException, IOException; +public interface MRTopicManager extends MRClient { + /** + * Get the topics available in the cluster. + * + * @return a set of topic names + * @throws IOException + */ + Set getTopics() throws IOException; + + /** + * Information about a topic. + */ + interface TopicInfo { + /** + * Get the owner of the topic. + * + * @return the owner, or null if no entry + */ + String getOwner(); + + /** + * Get the description for this topic. + * + * @return the description, or null if no entry + */ + String getDescription(); + + /** + * Get the set of allowed producers (as API keys) on this topic. + * + * @return the set of allowed producers, null of no ACL exists/enabled + */ + Set getAllowedProducers(); + + /** + * Get the set of allowed consumers (as API keys) on this topic. + * + * @return the set of allowed consumers, null of no ACL exists/enabled + */ + Set getAllowedConsumers(); + } + + /** + * Get information about a topic. + * + * @param topic + * @return topic information + * @throws IOException + * @throws HttpObjectNotFoundException + */ + TopicInfo getTopicMetadata(String topic) throws HttpObjectNotFoundException, IOException; + + /** + * Create a new topic. + * + * @param topicName + * @param topicDescription + * @param partitionCount + * @param replicationCount + * @throws HttpException + * @throws IOException + */ + void createTopic(String topicName, String topicDescription, int partitionCount, int replicationCount) throws HttpException, IOException; + + /** + * Delete the topic. This call must be authenticated and the API key listed as owner on the topic. + * NOTE: The MR (UEB) API server does not support topic deletion at this time (mid 2015) + * + * @param topic + * @throws HttpException + * @throws IOException + * @deprecated If/when the Kafka system supports topic delete, or the implementation changes, this will be restored. + */ + @Deprecated + void deleteTopic(String topic) throws HttpException, IOException; + + /** + * Can any client produce events into this topic without authentication? + * + * @param topic + * @return true if the topic is open for producing + * @throws IOException + * @throws HttpObjectNotFoundException + */ + boolean isOpenForProducing(String topic) throws HttpObjectNotFoundException, IOException; + + /** + * Get the set of allowed producers. If the topic is open, the result is null. + * + * @param topic + * @return a set of allowed producers or null + * @throws IOException + * @throws HttpObjectNotFoundException + */ + Set getAllowedProducers(String topic) throws HttpObjectNotFoundException, IOException; + + /** + * Allow the given API key to produce messages on the given topic. The caller must + * own this topic. + * + * @param topic + * @param apiKey + * @throws HttpException + * @throws HttpObjectNotFoundException + * @throws IOException + */ + void allowProducer(String topic, String apiKey) throws HttpObjectNotFoundException, HttpException, IOException; + + /** + * Revoke the given API key's authorization to produce messages on the given topic. + * The caller must own this topic. + * + * @param topic + * @param apiKey + * @throws HttpException + * @throws IOException + */ + void revokeProducer(String topic, String apiKey) throws HttpException, IOException; + + /** + * Can any client consume events from this topic without authentication? + * + * @param topic + * @return true if the topic is open for consuming + * @throws IOException + * @throws HttpObjectNotFoundException + */ + boolean isOpenForConsuming(String topic) throws HttpObjectNotFoundException, IOException; + + /** + * Get the set of allowed consumers. If the topic is open, the result is null. + * + * @param topic + * @return a set of allowed consumers or null + * @throws IOException + * @throws HttpObjectNotFoundException + */ + Set getAllowedConsumers(String topic) throws HttpObjectNotFoundException, IOException; + + /** + * Allow the given API key to consume messages on the given topic. The caller must + * own this topic. + * + * @param topic + * @param apiKey + * @throws HttpException + * @throws HttpObjectNotFoundException + * @throws IOException + */ + void allowConsumer(String topic, String apiKey) throws HttpObjectNotFoundException, HttpException, IOException; + + /** + * Revoke the given API key's authorization to consume messages on the given topic. + * The caller must own this topic. + * + * @param topic + * @param apiKey + * @throws HttpException + * @throws IOException + */ + void revokeConsumer(String topic, String apiKey) throws HttpException, IOException; } diff --git a/src/main/java/org/onap/dmaap/mr/client/ProtocolType.java b/src/main/java/org/onap/dmaap/mr/client/ProtocolType.java new file mode 100644 index 0000000..9d04d64 --- /dev/null +++ b/src/main/java/org/onap/dmaap/mr/client/ProtocolType.java @@ -0,0 +1,47 @@ +/******************************************************************************* + * ============LICENSE_START======================================================= + * org.onap.dmaap + * ================================================================================ + * Copyright © 2021 Orange Intellectual Property. All rights reserved. + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============LICENSE_END========================================================= + * + * ECOMP is a trademark and service mark of AT&T Intellectual Property. + * + *******************************************************************************/ + +package org.onap.dmaap.mr.client; + +/** + * Enumeration with all Protocol we can use. + * + * @author sliard + * + */ +public enum ProtocolType { + + DME2("DME2"), + AAF_AUTH("HTTPAAF"), + AUTH_KEY("HTTPAUTH"), + HTTPNOAUTH("HTTPNOAUTH"); + + private String value; + + ProtocolType(String value) { + this.value = value; + } + + public String getValue() { + return value; + } +} diff --git a/src/main/java/org/onap/dmaap/mr/client/impl/Clock.java b/src/main/java/org/onap/dmaap/mr/client/impl/Clock.java index 6670399..64a9f5e 100644 --- a/src/main/java/org/onap/dmaap/mr/client/impl/Clock.java +++ b/src/main/java/org/onap/dmaap/mr/client/impl/Clock.java @@ -4,11 +4,13 @@ * ================================================================================ * Copyright © 2017 AT&T Intellectual Property. All rights reserved. * ================================================================================ + * Modifications Copyright © 2021 Orange. + * ================================================================================ * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * http://www.apache.org/licenses/LICENSE-2.0 - * + * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. @@ -17,47 +19,43 @@ * ============LICENSE_END========================================================= * * ECOMP is a trademark and service mark of AT&T Intellectual Property. - * + * *******************************************************************************/ + package org.onap.dmaap.mr.client.impl; -public class Clock -{ - public synchronized static Clock getIt () - { - if ( sfClock == null ) - { - sfClock = new Clock (); - } - return sfClock; - } +public class Clock { + public static synchronized Clock getIt() { + if (sfClock == null) { + sfClock = new Clock(); + } + return sfClock; + } - /** - * Get the system's current time in milliseconds. - * @return the current time - */ - public static long now () - { - return getIt().nowImpl (); - } + /** + * Get the system's current time in milliseconds. + * + * @return the current time + */ + public static long now() { + return getIt().nowImpl(); + } - /** - * Get current time in milliseconds - * @return current time in ms - */ - protected long nowImpl () - { - return System.currentTimeMillis (); - } + /** + * Get current time in milliseconds. + * + * @return current time in ms + */ + protected long nowImpl() { + return System.currentTimeMillis(); + } - protected Clock () - { - } + protected Clock() { + } - private static Clock sfClock = null; + private static Clock sfClock = null; - protected synchronized static void register ( Clock testClock ) - { - sfClock = testClock; - } + protected static synchronized void register(Clock testClock) { + sfClock = testClock; + } } diff --git a/src/main/java/org/onap/dmaap/mr/client/impl/DmaapClientUtil.java b/src/main/java/org/onap/dmaap/mr/client/impl/DmaapClientUtil.java index 948ca31..5219286 100644 --- a/src/main/java/org/onap/dmaap/mr/client/impl/DmaapClientUtil.java +++ b/src/main/java/org/onap/dmaap/mr/client/impl/DmaapClientUtil.java @@ -4,6 +4,8 @@ * ================================================================================ * Copyright © 2017 AT&T Intellectual Property. All rights reserved. * ================================================================================ + * Modifications Copyright © 2021 Orange. + * ================================================================================ * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at @@ -19,6 +21,7 @@ * ECOMP is a trademark and service mark of AT&T Intellectual Property. * *******************************************************************************/ + package org.onap.dmaap.mr.client.impl; import java.util.Properties; @@ -27,6 +30,7 @@ import javax.ws.rs.client.ClientBuilder; import javax.ws.rs.client.Entity; import javax.ws.rs.client.WebTarget; import javax.ws.rs.core.Response; + import org.glassfish.jersey.apache.connector.ApacheConnectorProvider; import org.glassfish.jersey.client.ClientConfig; import org.glassfish.jersey.client.ClientProperties; @@ -34,92 +38,96 @@ import org.glassfish.jersey.client.authentication.HttpAuthenticationFeature; public class DmaapClientUtil { - private static final String MR_AUTH_CONSTANT = "X-CambriaAuth"; - private static final String MR_DATE_CONSTANT = "X-CambriaDate"; - private static final String[] httpClientProperties = { ClientProperties.CONNECT_TIMEOUT, - ClientProperties.READ_TIMEOUT, ClientProperties.PROXY_USERNAME, ClientProperties.PROXY_PASSWORD, - ClientProperties.PROXY_URI }; + private DmaapClientUtil() { + + } + + private static final String MR_AUTH_CONSTANT = "X-CambriaAuth"; + private static final String MR_DATE_CONSTANT = "X-CambriaDate"; + private static final String[] httpClientProperties = {ClientProperties.CONNECT_TIMEOUT, + ClientProperties.READ_TIMEOUT, ClientProperties.PROXY_USERNAME, ClientProperties.PROXY_PASSWORD, + ClientProperties.PROXY_URI}; - public static ClientConfig getClientConfig(Properties properties) { - ClientConfig config = new ClientConfig(); - if (properties != null && !properties.isEmpty()) { - setHttpClientProperties(config, properties); - } - return config; - } + public static ClientConfig getClientConfig(Properties properties) { + ClientConfig config = new ClientConfig(); + if (properties != null && !properties.isEmpty()) { + setHttpClientProperties(config, properties); + } + return config; + } - private static void setHttpClientProperties(ClientConfig config, Properties properties) { - for (int i = 0; i < httpClientProperties.length; i++) { - if ((properties.getProperty(httpClientProperties[i]) != null)) { - config.property(httpClientProperties[i], properties.getProperty(httpClientProperties[i])); - } - } - if ((properties.getProperty(ClientProperties.PROXY_URI) != null) && - !(properties.getProperty(ClientProperties.PROXY_URI).isEmpty())) { - config.connectorProvider(new ApacheConnectorProvider()); - } // else the default connectorProvider (HttpConnectorProvider) will be used + private static void setHttpClientProperties(ClientConfig config, Properties properties) { + for (String httpClientProperty : httpClientProperties) { + if ((properties.getProperty(httpClientProperty) != null)) { + config.property(httpClientProperty, properties.getProperty(httpClientProperty)); + } + } + if ((properties.getProperty(ClientProperties.PROXY_URI) != null) + && !(properties.getProperty(ClientProperties.PROXY_URI).isEmpty())) { + config.connectorProvider(new ApacheConnectorProvider()); + } // else the default connectorProvider (HttpConnectorProvider) will be used - } + } - public static WebTarget getTarget(ClientConfig config, final String path, final String username, - final String password) { - Client client = null; - if (config != null) { - client = ClientBuilder.newClient(config); - } else { - client = ClientBuilder.newClient(); - } - HttpAuthenticationFeature feature = HttpAuthenticationFeature.universal(username, password); - client.register(feature); + public static WebTarget getTarget(ClientConfig config, final String path, final String username, + final String password) { + Client client = null; + if (config != null) { + client = ClientBuilder.newClient(config); + } else { + client = ClientBuilder.newClient(); + } + HttpAuthenticationFeature feature = HttpAuthenticationFeature.universal(username, password); + client.register(feature); - return client.target(path); - } + return client.target(path); + } - public static WebTarget getTarget(ClientConfig config, final String path) { + public static WebTarget getTarget(ClientConfig config, final String path) { - Client client = null; - if (config != null&&config.getProperties().size()>0) { - client = ClientBuilder.newClient(config); - } else { - client = ClientBuilder.newClient(); - } - return client.target(path); - } + Client client = null; + if (config != null && config.getProperties().size() > 0) { + client = ClientBuilder.newClient(config); + } else { + client = ClientBuilder.newClient(); + } + return client.target(path); + } - public static Response getResponsewtCambriaAuth(WebTarget target, String username, String password) { - return target.request().header(MR_AUTH_CONSTANT, username).header(MR_DATE_CONSTANT, password).get(); + public static Response getResponsewtCambriaAuth(WebTarget target, String username, String password) { + return target.request().header(MR_AUTH_CONSTANT, username).header(MR_DATE_CONSTANT, password).get(); - } + } - public static Response postResponsewtCambriaAuth(WebTarget target, String username, String password, byte[] data, - String contentType) { - return target.request().header(MR_AUTH_CONSTANT, username).header(MR_DATE_CONSTANT, password) - .post(Entity.entity(data, contentType)); + public static Response postResponsewtCambriaAuth(WebTarget target, String username, String password, byte[] data, + String contentType) { + return target.request().header(MR_AUTH_CONSTANT, username).header(MR_DATE_CONSTANT, password) + .post(Entity.entity(data, contentType)); - } + } - public static Response getResponsewtBasicAuth(WebTarget target, String authHeader) { + public static Response getResponsewtBasicAuth(WebTarget target, String authHeader) { - return target.request().header("Authorization", "Basic " + authHeader).get(); + return target.request().header("Authorization", "Basic " + authHeader).get(); - } + } - public static Response postResponsewtBasicAuth(WebTarget target, String authHeader, byte[] data, - String contentType) { + public static Response postResponsewtBasicAuth(WebTarget target, String authHeader, byte[] data, + String contentType) { - return target.request().header("Authorization", "Basic " + authHeader).post(Entity.entity(data, contentType)); + return target.request().header("Authorization", "Basic " + authHeader).post(Entity.entity(data, contentType)); - } + } - public static Response getResponsewtNoAuth(WebTarget target) { + public static Response getResponsewtNoAuth(WebTarget target) { - return target.request().get(); + return target.request().get(); - } + } - public static Response postResponsewtNoAuth(WebTarget target, byte[] data, String contentType) { - return target.request().post(Entity.entity(data, contentType)); + public static Response postResponsewtNoAuth(WebTarget target, byte[] data, String contentType) { + return target.request().post(Entity.entity(data, contentType)); - } + } } diff --git a/src/main/java/org/onap/dmaap/mr/client/impl/MRBaseClient.java b/src/main/java/org/onap/dmaap/mr/client/impl/MRBaseClient.java index 07cf6a7..9522c90 100644 --- a/src/main/java/org/onap/dmaap/mr/client/impl/MRBaseClient.java +++ b/src/main/java/org/onap/dmaap/mr/client/impl/MRBaseClient.java @@ -4,11 +4,13 @@ * ================================================================================ * Copyright © 2017 AT&T Intellectual Property. All rights reserved. * ================================================================================ + * Modifications Copyright © 2021 Orange. + * ================================================================================ * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * http://www.apache.org/licenses/LICENSE-2.0 - * + * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. @@ -17,387 +19,387 @@ * ============LICENSE_END========================================================= * * ECOMP is a trademark and service mark of AT&T Intellectual Property. - * + * *******************************************************************************/ + package org.onap.dmaap.mr.client.impl; +import com.att.nsa.apiClient.http.CacheUse; +import com.att.nsa.apiClient.http.HttpClient; import java.net.MalformedURLException; import java.util.Collection; import java.util.Set; import java.util.TreeSet; import java.util.concurrent.TimeUnit; - import javax.ws.rs.client.WebTarget; import javax.ws.rs.core.Response; import org.apache.http.HttpException; +import org.apache.http.HttpStatus; import org.glassfish.jersey.client.ClientConfig; import org.glassfish.jersey.internal.util.Base64; import org.json.JSONArray; import org.json.JSONException; import org.json.JSONObject; import org.json.JSONTokener; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; - -import com.att.nsa.apiClient.http.CacheUse; -import com.att.nsa.apiClient.http.HttpClient; import org.onap.dmaap.mr.client.MRClient; import org.onap.dmaap.mr.client.MRClientFactory; -import org.onap.dmaap.mr.test.clients.ProtocolTypeConstants; +import org.onap.dmaap.mr.client.ProtocolType; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; public class MRBaseClient extends HttpClient implements MRClient { - private final static String HEADER_TRANSACTION_ID = "transactionid"; - - private final static String JSON_RESULT = "result"; - private final static String JSON_STATUS = "status"; - - private final static String AUTH_FAILED = "Authentication Failed: Username/password/AuthKey/AuthDate parameter(s) cannot be null or empty."; - private final static String LOG_TRANSACTION_ID = "TransactionId : "; - - private ClientConfig clientConfig = null; - - protected MRBaseClient(Collection hosts) throws MalformedURLException { - super(ConnectionType.HTTP, hosts, MRConstants.STD_MR_SERVICE_PORT); - - fLog = LoggerFactory.getLogger(this.getClass().getName()); - } - - protected MRBaseClient(Collection hosts, int stdSvcPort) throws MalformedURLException { - super(ConnectionType.HTTP, hosts, stdSvcPort); - - fLog = LoggerFactory.getLogger(this.getClass().getName()); - } - - protected MRBaseClient(Collection hosts, String clientSignature) throws MalformedURLException { - super(ConnectionType.HTTP, hosts, MRConstants.STD_MR_SERVICE_PORT, clientSignature, CacheUse.NONE, 1, 1L, - TimeUnit.MILLISECONDS, 32, 32, 600000); - - fLog = LoggerFactory.getLogger(this.getClass().getName()); - } - - public ClientConfig getClientConfig1() { - return clientConfig; - } - - public void setClientConfig(ClientConfig config) { - this.clientConfig = config; - } - - @Override - public void close() { - // nothing to close - } - - protected Set jsonArrayToSet(JSONArray a) { - if (a == null) - return null; - - final TreeSet set = new TreeSet<>(); - for (int i = 0; i < a.length(); i++) { - set.add(a.getString(i)); - } - return set; - } - - public void logTo(Logger log) { - fLog = log; - replaceLogger(log); - } - - protected Logger getLog() { - return fLog; - } - - private Logger fLog; - - public JSONObject post(final String path, final byte[] data, final String contentType, final String username, - final String password, final String protocalFlag) throws HttpException, JSONException { - if ((null != username && null != password)) { - WebTarget target = null; - Response response = null; - target = DmaapClientUtil.getTarget(clientConfig,path, username, password); - String encoding = Base64.encodeAsString(username + ":" + password); - - response = DmaapClientUtil.postResponsewtBasicAuth(target, encoding, data, contentType); - - return getResponseDataInJson(response); - } else { - throw new HttpException(AUTH_FAILED); - } - } - - public JSONObject postNoAuth(final String path, final byte[] data, String contentType) - throws HttpException, JSONException { - WebTarget target = null; - Response response = null; - if (contentType == null) { - contentType = "text/pain"; - } - target = DmaapClientUtil.getTarget(clientConfig,path); - - response = DmaapClientUtil.postResponsewtNoAuth(target, data, contentType); - - return getResponseDataInJson(response); - } - - public String postWithResponse(final String path, final byte[] data, final String contentType, - final String username, final String password, final String protocolFlag) - throws HttpException, JSONException { - String responseData = null; - if ((null != username && null != password)) { - WebTarget target = null; - Response response = null; - target = DmaapClientUtil.getTarget(clientConfig,path, username, password); - String encoding = Base64.encodeAsString(username + ":" + password); - - response = DmaapClientUtil.postResponsewtBasicAuth(target, encoding, data, contentType); - - responseData = (String) response.readEntity(String.class); - return responseData; - } else { - throw new HttpException(AUTH_FAILED); - } - } - - public String postNoAuthWithResponse(final String path, final byte[] data, String contentType) - throws HttpException, JSONException { - - String responseData = null; - WebTarget target = null; - Response response = null; - if (contentType == null) { - contentType = "text/pain"; - } - target = DmaapClientUtil.getTarget(clientConfig,path); - - response = DmaapClientUtil.postResponsewtNoAuth(target, data, contentType); - responseData = (String) response.readEntity(String.class); - return responseData; - } - - public JSONObject postAuth(PostAuthDataObject postAuthDO) throws HttpException, JSONException { - if ((null != postAuthDO.getUsername() && null != postAuthDO.getPassword())) { - WebTarget target = null; - Response response = null; - target = DmaapClientUtil.getTarget(clientConfig,postAuthDO.getPath(), postAuthDO.getUsername(), - postAuthDO.getPassword()); - response = DmaapClientUtil.postResponsewtCambriaAuth(target, postAuthDO.getAuthKey(), - postAuthDO.getAuthDate(), postAuthDO.getData(), postAuthDO.getContentType()); - return getResponseDataInJson(response); - } else { - throw new HttpException(AUTH_FAILED); - } - } - - public String postAuthwithResponse(final String path, final byte[] data, final String contentType, - final String authKey, final String authDate, final String username, final String password, - final String protocolFlag) throws HttpException, JSONException { - String responseData = null; - if ((null != username && null != password)) { - WebTarget target = null; - Response response = null; - target = DmaapClientUtil.getTarget(clientConfig,path, username, password); - response = DmaapClientUtil.postResponsewtCambriaAuth(target, authKey, authDate, data, contentType); - responseData = (String) response.readEntity(String.class); - return responseData; - - } else { - throw new HttpException(AUTH_FAILED); - } - } - - public JSONObject get(final String path, final String username, final String password, final String protocolFlag) - throws HttpException, JSONException { - if (null != username && null != password) { - - WebTarget target = null; - Response response = null; - - if (ProtocolTypeConstants.AUTH_KEY.getValue().equalsIgnoreCase(protocolFlag)) { - target = DmaapClientUtil.getTarget(clientConfig,path); - response = DmaapClientUtil.getResponsewtCambriaAuth(target, username, password); - } else { - target = DmaapClientUtil.getTarget(clientConfig,path, username, password); - String encoding = Base64.encodeAsString(username + ":" + password); - - response = DmaapClientUtil.getResponsewtBasicAuth(target, encoding); - - } - return getResponseDataInJson(response); - } else { - throw new HttpException(AUTH_FAILED); - } - } - - public String getResponse(final String path, final String username, final String password, - final String protocolFlag) throws HttpException, JSONException { - String responseData = null; - if (null != username && null != password) { - WebTarget target = null; - Response response = null; - if (ProtocolTypeConstants.AUTH_KEY.getValue().equalsIgnoreCase(protocolFlag)) { - target = DmaapClientUtil.getTarget(clientConfig,path); - response = DmaapClientUtil.getResponsewtCambriaAuth(target, username, password); - } else { - target = DmaapClientUtil.getTarget(clientConfig,path, username, password); - String encoding = Base64.encodeAsString(username + ":" + password); - response = DmaapClientUtil.getResponsewtBasicAuth(target, encoding); - } - MRClientFactory.setHTTPHeadersMap(response.getHeaders()); - - String transactionid = response.getHeaderString(HEADER_TRANSACTION_ID); - if (transactionid != null && !transactionid.equalsIgnoreCase("")) { - fLog.info(LOG_TRANSACTION_ID + transactionid); - } - - responseData = (String) response.readEntity(String.class); - return responseData; - } else { - throw new HttpException(AUTH_FAILED); - } - } - - public JSONObject getAuth(final String path, final String authKey, final String authDate, final String username, - final String password, final String protocolFlag) throws HttpException, JSONException { - if (null != username && null != password) { - WebTarget target = null; - Response response = null; - target = DmaapClientUtil.getTarget(clientConfig,path, username, password); - response = DmaapClientUtil.getResponsewtCambriaAuth(target, authKey, authDate); - - return getResponseDataInJson(response); - } else { - throw new HttpException(AUTH_FAILED); - } - } - - public JSONObject getNoAuth(final String path) throws HttpException, JSONException { - - WebTarget target = null; - Response response = null; - target = DmaapClientUtil.getTarget(clientConfig,path); - response = DmaapClientUtil.getResponsewtNoAuth(target); - - return getResponseDataInJson(response); - } - - public String getAuthResponse(final String path, final String authKey, final String authDate, final String username, - final String password, final String protocolFlag) throws HttpException, JSONException { - String responseData = null; - if (null != username && null != password) { - WebTarget target = null; - Response response = null; - target = DmaapClientUtil.getTarget(clientConfig,path, username, password); - response = DmaapClientUtil.getResponsewtCambriaAuth(target, authKey, authDate); - - MRClientFactory.setHTTPHeadersMap(response.getHeaders()); - - String transactionid = response.getHeaderString(HEADER_TRANSACTION_ID); - if (transactionid != null && !transactionid.equalsIgnoreCase("")) { - fLog.info(LOG_TRANSACTION_ID + transactionid); - } - - responseData = (String) response.readEntity(String.class); - return responseData; - } else { - throw new HttpException(AUTH_FAILED); - } - } - - public String getNoAuthResponse(String path, final String username, final String password, - final String protocolFlag) throws HttpException, JSONException { - String responseData = null; - WebTarget target = null; - Response response = null; - target = DmaapClientUtil.getTarget(clientConfig,path, username, password); - response = DmaapClientUtil.getResponsewtNoAuth(target); - - MRClientFactory.setHTTPHeadersMap(response.getHeaders()); - - String transactionid = response.getHeaderString(HEADER_TRANSACTION_ID); - if (transactionid != null && !transactionid.equalsIgnoreCase("")) { - fLog.info(LOG_TRANSACTION_ID + transactionid); - } - - responseData = (String) response.readEntity(String.class); - return responseData; - - } - - private JSONObject getResponseDataInJson(Response response) throws JSONException { - try { - MRClientFactory.setHTTPHeadersMap(response.getHeaders()); - - // MultivaluedMap headersMap = - // for(String key : headersMap.keySet()) { - String transactionid = response.getHeaderString(HEADER_TRANSACTION_ID); - if (transactionid != null && !transactionid.equalsIgnoreCase("")) { - fLog.info(LOG_TRANSACTION_ID + transactionid); - } - - if (response.getStatus() == 403) { - JSONObject jsonObject = null; - jsonObject = new JSONObject(); - JSONArray jsonArray = new JSONArray(); - jsonArray.put(response.getEntity()); - jsonObject.put(JSON_RESULT, jsonArray); - jsonObject.put(JSON_STATUS, response.getStatus()); - return jsonObject; - } - String responseData = (String) response.readEntity(String.class); - - JSONTokener jsonTokener = new JSONTokener(responseData); - JSONObject jsonObject = null; - final char firstChar = jsonTokener.next(); - jsonTokener.back(); - if ('[' == firstChar) { - JSONArray jsonArray = new JSONArray(jsonTokener); - jsonObject = new JSONObject(); - jsonObject.put(JSON_RESULT, jsonArray); - jsonObject.put(JSON_STATUS, response.getStatus()); - } else { - jsonObject = new JSONObject(jsonTokener); - jsonObject.put(JSON_STATUS, response.getStatus()); - } - - return jsonObject; - } catch (JSONException excp) { - fLog.error("DMAAP - Error reading response data.", excp); - return null; - } - - } - - public String getHTTPErrorResponseMessage(String responseString) { - - String response = null; - int beginIndex = 0; - int endIndex = 0; - if (responseString.contains("")) { - - beginIndex = responseString.indexOf("body>") + 5; - endIndex = responseString.indexOf("")) { - beginIndex = responseString.indexOf("title>") + 6; - endIndex = responseString.indexOf(" hosts) throws MalformedURLException { + super(ConnectionType.HTTP, hosts, MRConstants.STD_MR_SERVICE_PORT); + + logger = LoggerFactory.getLogger(this.getClass().getName()); + } + + protected MRBaseClient(Collection hosts, int stdSvcPort) throws MalformedURLException { + super(ConnectionType.HTTP, hosts, stdSvcPort); + + logger = LoggerFactory.getLogger(this.getClass().getName()); + } + + protected MRBaseClient(Collection hosts, String clientSignature) throws MalformedURLException { + super(ConnectionType.HTTP, hosts, MRConstants.STD_MR_SERVICE_PORT, clientSignature, CacheUse.NONE, 1, 1L, + TimeUnit.MILLISECONDS, 32, 32, 600000); + + logger = LoggerFactory.getLogger(this.getClass().getName()); + } + + public ClientConfig getClientConfig1() { + return clientConfig; + } + + public void setClientConfig(ClientConfig config) { + this.clientConfig = config; + } + + @Override + public void close() { + // nothing to close + } + + protected Set jsonArrayToSet(JSONArray array) { + if (array == null) { + return null; + } + final TreeSet set = new TreeSet<>(); + for (int i = 0; i < array.length(); i++) { + set.add(array.getString(i)); + } + return set; + } + + public void logTo(Logger log) { + logger = log; + replaceLogger(log); + } + + protected Logger getLog() { + return logger; + } + + private Logger logger; + + public JSONObject post(final String path, final byte[] data, final String contentType, final String username, + final String password, final String protocalFlag) throws HttpException, JSONException { + if ((null != username && null != password)) { + WebTarget target = null; + Response response = null; + target = DmaapClientUtil.getTarget(clientConfig, path, username, password); + String encoding = Base64.encodeAsString(username + ":" + password); + + response = DmaapClientUtil.postResponsewtBasicAuth(target, encoding, data, contentType); + + return getResponseDataInJson(response); + } else { + throw new HttpException(AUTH_FAILED); + } + } + + public JSONObject postNoAuth(final String path, final byte[] data, String contentType) + throws HttpException, JSONException { + WebTarget target = null; + Response response = null; + if (contentType == null) { + contentType = "text/pain"; + } + target = DmaapClientUtil.getTarget(clientConfig, path); + + response = DmaapClientUtil.postResponsewtNoAuth(target, data, contentType); + + return getResponseDataInJson(response); + } + + public String postWithResponse(final String path, final byte[] data, final String contentType, + final String username, final String password, final String protocolFlag) + throws HttpException, JSONException { + String responseData = null; + if ((null != username && null != password)) { + WebTarget target = null; + Response response = null; + target = DmaapClientUtil.getTarget(clientConfig, path, username, password); + String encoding = Base64.encodeAsString(username + ":" + password); + + response = DmaapClientUtil.postResponsewtBasicAuth(target, encoding, data, contentType); + + responseData = response.readEntity(String.class); + return responseData; + } else { + throw new HttpException(AUTH_FAILED); + } + } + + public String postNoAuthWithResponse(final String path, final byte[] data, String contentType) + throws HttpException, JSONException { + + String responseData = null; + WebTarget target = null; + Response response = null; + if (contentType == null) { + contentType = "text/pain"; + } + target = DmaapClientUtil.getTarget(clientConfig, path); + + response = DmaapClientUtil.postResponsewtNoAuth(target, data, contentType); + responseData = response.readEntity(String.class); + return responseData; + } + + public JSONObject postAuth(PostAuthDataObject postAuthDO) throws HttpException, JSONException { + if ((null != postAuthDO.getUsername() && null != postAuthDO.getPassword())) { + WebTarget target = null; + Response response = null; + target = DmaapClientUtil.getTarget(clientConfig, postAuthDO.getPath(), postAuthDO.getUsername(), + postAuthDO.getPassword()); + response = DmaapClientUtil.postResponsewtCambriaAuth(target, postAuthDO.getAuthKey(), + postAuthDO.getAuthDate(), postAuthDO.getData(), postAuthDO.getContentType()); + return getResponseDataInJson(response); + } else { + throw new HttpException(AUTH_FAILED); + } + } + + public String postAuthwithResponse(final String path, final byte[] data, final String contentType, + final String authKey, final String authDate, final String username, final String password, + final String protocolFlag) throws HttpException, JSONException { + String responseData = null; + if ((null != username && null != password)) { + WebTarget target = null; + Response response = null; + target = DmaapClientUtil.getTarget(clientConfig, path, username, password); + response = DmaapClientUtil.postResponsewtCambriaAuth(target, authKey, authDate, data, contentType); + responseData = response.readEntity(String.class); + return responseData; + + } else { + throw new HttpException(AUTH_FAILED); + } + } + + public JSONObject get(final String path, final String username, final String password, final String protocolFlag) + throws HttpException, JSONException { + if (null != username && null != password) { + + WebTarget target = null; + Response response = null; + + if (ProtocolType.AUTH_KEY.getValue().equalsIgnoreCase(protocolFlag)) { + target = DmaapClientUtil.getTarget(clientConfig, path); + response = DmaapClientUtil.getResponsewtCambriaAuth(target, username, password); + } else { + target = DmaapClientUtil.getTarget(clientConfig, path, username, password); + String encoding = Base64.encodeAsString(username + ":" + password); + + response = DmaapClientUtil.getResponsewtBasicAuth(target, encoding); + + } + return getResponseDataInJson(response); + } else { + throw new HttpException(AUTH_FAILED); + } + } + + public String getResponse(final String path, final String username, final String password, + final String protocolFlag) throws HttpException, JSONException { + String responseData = null; + if (null != username && null != password) { + WebTarget target = null; + Response response = null; + if (ProtocolType.AUTH_KEY.getValue().equalsIgnoreCase(protocolFlag)) { + target = DmaapClientUtil.getTarget(clientConfig, path); + response = DmaapClientUtil.getResponsewtCambriaAuth(target, username, password); + } else { + target = DmaapClientUtil.getTarget(clientConfig, path, username, password); + String encoding = Base64.encodeAsString(username + ":" + password); + response = DmaapClientUtil.getResponsewtBasicAuth(target, encoding); + } + MRClientFactory.setHTTPHeadersMap(response.getHeaders()); + + String transactionid = response.getHeaderString(HEADER_TRANSACTION_ID); + if (transactionid != null && !transactionid.equalsIgnoreCase("")) { + logger.info(LOG_TRANSACTION_ID, transactionid); + } + + responseData = response.readEntity(String.class); + return responseData; + } else { + throw new HttpException(AUTH_FAILED); + } + } + + public JSONObject getAuth(final String path, final String authKey, final String authDate, final String username, + final String password, final String protocolFlag) throws HttpException, JSONException { + if (null != username && null != password) { + WebTarget target = null; + Response response = null; + target = DmaapClientUtil.getTarget(clientConfig, path, username, password); + response = DmaapClientUtil.getResponsewtCambriaAuth(target, authKey, authDate); + + return getResponseDataInJson(response); + } else { + throw new HttpException(AUTH_FAILED); + } + } + + public JSONObject getNoAuth(final String path) throws HttpException, JSONException { + + WebTarget target = null; + Response response = null; + target = DmaapClientUtil.getTarget(clientConfig, path); + response = DmaapClientUtil.getResponsewtNoAuth(target); + + return getResponseDataInJson(response); + } + + public String getAuthResponse(final String path, final String authKey, final String authDate, final String username, + final String password, final String protocolFlag) throws HttpException, JSONException { + String responseData = null; + if (null != username && null != password) { + WebTarget target = null; + Response response = null; + target = DmaapClientUtil.getTarget(clientConfig, path, username, password); + response = DmaapClientUtil.getResponsewtCambriaAuth(target, authKey, authDate); + + MRClientFactory.setHTTPHeadersMap(response.getHeaders()); + + String transactionid = response.getHeaderString(HEADER_TRANSACTION_ID); + if (transactionid != null && !transactionid.equalsIgnoreCase("")) { + logger.info(LOG_TRANSACTION_ID, transactionid); + } + + responseData = response.readEntity(String.class); + return responseData; + } else { + throw new HttpException(AUTH_FAILED); + } + } + + public String getNoAuthResponse(String path, final String username, final String password, + final String protocolFlag) throws HttpException, JSONException { + String responseData = null; + WebTarget target = null; + Response response = null; + target = DmaapClientUtil.getTarget(clientConfig, path, username, password); + response = DmaapClientUtil.getResponsewtNoAuth(target); + + MRClientFactory.setHTTPHeadersMap(response.getHeaders()); + + String transactionid = response.getHeaderString(HEADER_TRANSACTION_ID); + if (transactionid != null && !transactionid.equalsIgnoreCase("")) { + logger.info(LOG_TRANSACTION_ID, transactionid); + } + + responseData = response.readEntity(String.class); + return responseData; + + } + + private JSONObject getResponseDataInJson(Response response) throws JSONException { + try { + MRClientFactory.setHTTPHeadersMap(response.getHeaders()); + + // MultivaluedMap headersMap = + // for(String key : headersMap.keySet()) { + String transactionid = response.getHeaderString(HEADER_TRANSACTION_ID); + if (transactionid != null && !transactionid.equalsIgnoreCase("")) { + logger.info(LOG_TRANSACTION_ID, transactionid); + } + + if (response.getStatus() == HttpStatus.SC_FORBIDDEN) { + JSONObject jsonObject = null; + jsonObject = new JSONObject(); + JSONArray jsonArray = new JSONArray(); + jsonArray.put(response.getEntity()); + jsonObject.put(JSON_RESULT, jsonArray); + jsonObject.put(JSON_STATUS, response.getStatus()); + return jsonObject; + } + String responseData = response.readEntity(String.class); + + JSONTokener jsonTokener = new JSONTokener(responseData); + JSONObject jsonObject = null; + final char firstChar = jsonTokener.next(); + jsonTokener.back(); + if ('[' == firstChar) { + JSONArray jsonArray = new JSONArray(jsonTokener); + jsonObject = new JSONObject(); + jsonObject.put(JSON_RESULT, jsonArray); + jsonObject.put(JSON_STATUS, response.getStatus()); + } else { + jsonObject = new JSONObject(jsonTokener); + jsonObject.put(JSON_STATUS, response.getStatus()); + } + + return jsonObject; + } catch (JSONException excp) { + logger.error("DMAAP - Error reading response data.", excp); + return null; + } + + } + + public String getHTTPErrorResponseMessage(String responseString) { + + String response = null; + int beginIndex = 0; + int endIndex = 0; + if (responseString.contains("")) { + + beginIndex = responseString.indexOf("body>") + 5; + endIndex = responseString.indexOf("")) { + beginIndex = responseString.indexOf("title>") + 6; + endIndex = responseString.indexOf(" baseUrls, String topic, int maxBatchSize, long maxAgeMs, boolean compress ) - { - if ( maxAgeMs < MIN_MAX_AGE_MS) - { - fLog.warn ( "Max age in ms is less than the minimum. Overriding to " + MIN_MAX_AGE_MS); - maxAgeMs = MIN_MAX_AGE_MS; - } - - try { - fSender = new Sender ( baseUrls, topic, maxBatchSize, maxAgeMs, compress ); - } catch (MalformedURLException e) { - throw new IllegalArgumentException (e); - } - - // FIXME: this strategy needs an overhaul -- why not just run a thread that knows how to wait for - // the oldest msg to hit max age? (locking is complicated, but should be do-able) - fExec = new ScheduledThreadPoolExecutor ( 1 ); - fExec.scheduleAtFixedRate ( fSender, 100, 50, TimeUnit.MILLISECONDS ); - } - - @Override - public void setApiCredentials ( String apiKey, String apiSecret ) - { - fSender.setApiCredentials ( apiKey, apiSecret ); - } - - @Override - public void clearApiCredentials () - { - fSender.clearApiCredentials (); - } - - /** - * Send the given message with the given partition - * @param partition - * @param msg - * @throws IOException - */ - @Override - public int send ( String partition, String msg ) throws IOException - { - return send ( new message ( partition, msg ) ); - } - @Override - public int send ( String msg ) throws IOException - { - return send ( new message ( "",msg ) ); - } - /** - * Send the given message - * @param userMsg a message - * @throws IOException - */ - @Override - public int send ( message userMsg ) throws IOException - { - final LinkedList list = new LinkedList (); - list.add ( userMsg ); - return send ( list ); - } - - /** - * Send the given set of messages - * @param msgs the set of messages, sent in order of iteration - * @return the number of messages in the pending queue (this could actually be less than the size of the given collection, depending on thread timing) - * @throws IOException - */ - @Override - public int send ( Collection msgs ) throws IOException - { - if ( msgs.isEmpty() ) - { - fSender.queue ( msgs ); - } - return fSender.size (); - } - - @Override - public int getPendingMessageCount () - { - return fSender.size (); - } - - /** - * Send any pending messages and close this publisher. - * @throws IOException - * @throws InterruptedException - */ - @Override - public void close () - { - try - { - final List remains = close ( Long.MAX_VALUE, TimeUnit.MILLISECONDS ); - if ( remains.isEmpty() ) - { - fLog.warn ( "Closing publisher with " + remains.size() + " messages unsent. " - + "(Consider using the alternate close method to capture unsent messages in this case.)" ); - } - } - catch ( InterruptedException e ) - { - fLog.warn ( "Possible message loss. " + e.getMessage(), e ); - Thread.currentThread().interrupt(); - } - catch ( IOException e ) - { - fLog.warn ( "Possible message loss. " + e.getMessage(), e ); - } - } - - public List close ( long time, TimeUnit unit ) throws InterruptedException, IOException - { - fExec.setContinueExistingPeriodicTasksAfterShutdownPolicy ( false ); - fExec.setExecuteExistingDelayedTasksAfterShutdownPolicy ( false ); - fExec.shutdown (); - - final long waitInMs = TimeUnit.MILLISECONDS.convert ( time, unit ); - final long timeoutAtMs = System.currentTimeMillis () + waitInMs; - while ( System.currentTimeMillis () < timeoutAtMs && getPendingMessageCount() > 0 ) - { - fSender.checkSend ( true ); - Thread.sleep ( 250 ); - } - - final LinkedList result = new LinkedList (); - fSender.drainTo ( result ); - return result; - } - - private final ScheduledThreadPoolExecutor fExec; - private final Sender fSender; - - private static class TimestampedMessage extends message - { - public TimestampedMessage ( message m ) - { - super ( m ); - timestamp = System.currentTimeMillis (); - } - public final long timestamp; - } - - private Logger fLog = LoggerFactory.getLogger ( MRBatchPublisher.class ); - - private class Sender extends MRBaseClient implements Runnable - { - public Sender ( Collection baseUrls, String topic, int maxBatch, long maxAgeMs, boolean compress ) throws MalformedURLException - { - super ( baseUrls ); - - fNextBatch = new LinkedList (); - fSendingBatch = null; - fTopic = topic; - fMaxBatchSize = maxBatch; - fMaxAgeMs = maxAgeMs; - fCompress = compress; - fLock = new ReentrantReadWriteLock (); - fWriteLock = fLock.writeLock (); - fReadLock = fLock.readLock (); - fDontSendUntilMs = 0; - } - - public void drainTo ( LinkedList list ) - { - fWriteLock.lock (); - try - { - if ( fSendingBatch != null ) - { - list.addAll ( fSendingBatch ); - } - list.addAll ( fNextBatch ); - - fSendingBatch = null; - fNextBatch.clear (); - } - finally - { - fWriteLock.unlock (); - } - } - - /** - * Called periodically by the background executor. - */ - @Override - public void run () - { - try - { - checkSend ( false ); - } - catch ( IOException e ) - { - fLog.warn ( "MR background send: " + e.getMessage () ); - fLog.error( "IOException " + e ); - } - } - - public int size () - { - fReadLock.lock (); - try - { - return fNextBatch.size () + ( fSendingBatch == null ? 0 : fSendingBatch.size () ); - } - finally - { - fReadLock.unlock (); - } - } - - /** - * Called to queue a message. - * @param msgs - * @throws IOException - */ - public void queue ( Collection msgs ) throws IOException - { - fWriteLock.lock (); - try - { - for ( message userMsg : msgs ) - { - if ( userMsg != null ) - { - fNextBatch.add ( new TimestampedMessage ( userMsg ) ); - } - else - { - fLog.warn ( "MRBatchPublisher::Sender::queue received a null message." ); - } - } - } - finally - { - fWriteLock.unlock(); - } - checkSend ( false ); - } - - /** - * Send a batch if the queue is long enough, or the first pending message is old enough. - * @param force - * @throws IOException - */ - public void checkSend ( boolean force ) throws IOException - { - // hold a read lock just long enough to evaluate whether a batch - // should be sent - boolean shouldSend = false; - fReadLock.lock (); - try - { - if ( fNextBatch.isEmpty() ) - { - final long nowMs = System.currentTimeMillis (); - shouldSend = ( force || fNextBatch.size() >= fMaxBatchSize ); - if ( !shouldSend ) - { - final long sendAtMs = fNextBatch.getFirst ().timestamp + fMaxAgeMs; - shouldSend = sendAtMs <= nowMs; - } - - // however, unless forced, wait after an error - shouldSend = force || ( shouldSend && nowMs >= fDontSendUntilMs ); - } - // else: even in 'force', there's nothing to send, so shouldSend=false is fine - } - finally - { - fReadLock.unlock (); - } - - // if a send is required, acquire a write lock, swap out the next batch, - // swap in a fresh batch, and release the lock for the caller to start - // filling a batch again. After releasing the lock, send the current - // batch. (There could be more messages added between read unlock and - // write lock, but that's fine.) - if ( shouldSend ) - { - fSendingBatch = null; - - fWriteLock.lock (); - try - { - fSendingBatch = fNextBatch; - fNextBatch = new LinkedList (); - } - finally - { - fWriteLock.unlock (); - } - - if ( !doSend ( fSendingBatch, this, fTopic, fCompress, fLog ) ) - { - fLog.warn ( "Send failed, rebuilding send queue." ); - - // note the time for back-off - fDontSendUntilMs = SF_WAIT_AFTER_ERROR + System.currentTimeMillis (); - - // the send failed. reconstruct the pending queue - fWriteLock.lock (); - try - { - final LinkedList nextGroup = fNextBatch; - fNextBatch = fSendingBatch; - fNextBatch.addAll ( nextGroup ); - fSendingBatch = null; - fLog.info ( "Send queue rebuilt; " + fNextBatch.size () + " messages to send." ); - } - finally - { - fWriteLock.unlock (); - } - } - else - { - fWriteLock.lock (); - try - { - fSendingBatch = null; - } - finally - { - fWriteLock.unlock (); - } - } - } - } - - private LinkedList fNextBatch; - private LinkedList fSendingBatch; - private final String fTopic; - private final int fMaxBatchSize; - private final long fMaxAgeMs; - private final boolean fCompress; - private final ReentrantReadWriteLock fLock; - private final WriteLock fWriteLock; - private final ReadLock fReadLock; - private long fDontSendUntilMs; - private static final long SF_WAIT_AFTER_ERROR = 1000; - } - - // this is static so that it's clearly not using any mutable member data outside of a lock - private static boolean doSend ( LinkedList toSend, HttpClient client, String topic, boolean compress, Logger log ) - { - // it's possible for this call to be made with an empty list. in this case, just return. - if ( toSend.isEmpty() ) - { - return true; - } - - final long nowMs = System.currentTimeMillis (); - final String url = MRConstants.makeUrl ( topic ); - - log.info ( "sending " + toSend.size() + " msgs to " + url + ". Oldest: " + ( nowMs - toSend.getFirst().timestamp ) + " ms" ); - - final ByteArrayOutputStream baseStream = new ByteArrayOutputStream (); - try - { - OutputStream os = baseStream; - if ( compress ) - { - os = new GZIPOutputStream ( baseStream ); - } - for ( TimestampedMessage m : toSend ) - { - os.write ( ( "" + m.fPartition.length () ).getBytes() ); - os.write ( '.' ); - os.write ( ( "" + m.fMsg.length () ).getBytes() ); - os.write ( '.' ); - os.write ( m.fPartition.getBytes() ); - os.write ( m.fMsg.getBytes() ); - os.write ( '\n' ); - } - os.close (); - } - catch ( IOException e ) - { - log.warn ( "Problem writing stream to post: " + e.getMessage (),e ); - return false; - } - - boolean result = false; - final long startMs = System.currentTimeMillis (); - try - { - client.post ( url, compress ? - MRFormat.CAMBRIA_ZIP.toString () : - MRFormat.CAMBRIA.toString (), - baseStream.toByteArray(), false ); - result = true; - } - catch ( HttpException e ) - { - log.warn ( "Problem posting to MR: " + e.getMessage(),e ); - } - catch ( IOException e ) - { - log.warn ( "Problem posting to MR: " + e.getMessage(),e ); - } - - log.info ( "MR response (" + (System.currentTimeMillis ()-startMs) + " ms): OK" ); - return result; - } - - @Override - public void logTo ( Logger log ) - { - fLog = log; - } - - @Override - public MRPublisherResponse sendBatchWithResponse() { - // TODO Auto-generated method stub - return null; - } - +public class MRBatchPublisher implements MRBatchingPublisher { + public static final long MIN_MAX_AGE_MS = 1; + + /** + * Create a batch publisher. + * + * @param baseUrls the base URLs, like "localhost:8080". This class adds the correct application path. + * @param topic the topic to publish to + * @param maxBatchSize the maximum size of a batch + * @param maxAgeMs the maximum age of a batch + */ + public MRBatchPublisher(Collection baseUrls, String topic, int maxBatchSize, long maxAgeMs, boolean compress) { + if (maxAgeMs < MIN_MAX_AGE_MS) { + logger.warn("Max age in ms is less than the minimum. Overriding to " + MIN_MAX_AGE_MS); + maxAgeMs = MIN_MAX_AGE_MS; + } + + try { + fSender = new Sender(baseUrls, topic, maxBatchSize, maxAgeMs, compress); + } catch (MalformedURLException e) { + throw new IllegalArgumentException(e); + } + + // FIXME: this strategy needs an overhaul -- why not just run a thread that knows how to wait for + // the oldest msg to hit max age? (locking is complicated, but should be do-able) + fExec = new ScheduledThreadPoolExecutor(1); + fExec.scheduleAtFixedRate(fSender, 100, 50, TimeUnit.MILLISECONDS); + } + + @Override + public void setApiCredentials(String apiKey, String apiSecret) { + fSender.setApiCredentials(apiKey, apiSecret); + } + + @Override + public void clearApiCredentials() { + fSender.clearApiCredentials(); + } + + /** + * Send the given message with the given partition. + * + * @param partition + * @param msg + * @throws IOException + */ + @Override + public int send(String partition, String msg) throws IOException { + return send(new Message(partition, msg)); + } + + @Override + public int send(String msg) throws IOException { + return send(new Message("", msg)); + } + + /** + * Send the given message. + * + * @param userMsg a message + * @throws IOException + */ + @Override + public int send(Message userMsg) throws IOException { + final LinkedList list = new LinkedList<>(); + list.add(userMsg); + return send(list); + } + + /** + * Send the given set of messages. + * + * @param msgs the set of messages, sent in order of iteration + * @return the number of messages in the pending queue (this could actually be less than the size of the given collection, depending on thread timing) + * @throws IOException + */ + @Override + public int send(Collection msgs) throws IOException { + if (msgs.isEmpty()) { + fSender.queue(msgs); + } + return fSender.size(); + } + + @Override + public int getPendingMessageCount() { + return fSender.size(); + } + + /** + * Send any pending messages and close this publisher. + */ + @Override + public void close() { + try { + final List remains = close(Long.MAX_VALUE, TimeUnit.MILLISECONDS); + if (remains.isEmpty()) { + logger.warn("Closing publisher with {} messages unsent. (Consider using the alternate close method to capture unsent messages in this case.)", remains.size()); + } + } catch (InterruptedException e) { + logger.warn("Possible message loss. " + e.getMessage(), e); + Thread.currentThread().interrupt(); + } catch (IOException e) { + logger.warn("Possible message loss. " + e.getMessage(), e); + } + } + + public List close(long time, TimeUnit unit) throws InterruptedException, IOException { + fExec.setContinueExistingPeriodicTasksAfterShutdownPolicy(false); + fExec.setExecuteExistingDelayedTasksAfterShutdownPolicy(false); + fExec.shutdown(); + + final long waitInMs = TimeUnit.MILLISECONDS.convert(time, unit); + final long timeoutAtMs = System.currentTimeMillis() + waitInMs; + while (System.currentTimeMillis() < timeoutAtMs && getPendingMessageCount() > 0) { + fSender.checkSend(true); + Thread.sleep(250); + } + + final LinkedList result = new LinkedList<>(); + fSender.drainTo(result); + return result; + } + + private final ScheduledThreadPoolExecutor fExec; + private final Sender fSender; + + private static class TimestampedMessage extends Message { + public TimestampedMessage(Message m) { + super(m); + timestamp = System.currentTimeMillis(); + } + + public final long timestamp; + } + + private Logger logger = LoggerFactory.getLogger(MRBatchPublisher.class); + + private class Sender extends MRBaseClient implements Runnable { + public Sender(Collection baseUrls, String topic, int maxBatch, long maxAgeMs, boolean compress) throws MalformedURLException { + super(baseUrls); + + fNextBatch = new LinkedList<>(); + fSendingBatch = null; + fTopic = topic; + fMaxBatchSize = maxBatch; + fMaxAgeMs = maxAgeMs; + fCompress = compress; + fLock = new ReentrantReadWriteLock(); + fWriteLock = fLock.writeLock(); + fReadLock = fLock.readLock(); + fDontSendUntilMs = 0; + } + + public void drainTo(List list) { + fWriteLock.lock(); + try { + if (fSendingBatch != null) { + list.addAll(fSendingBatch); + } + list.addAll(fNextBatch); + + fSendingBatch = null; + fNextBatch.clear(); + } finally { + fWriteLock.unlock(); + } + } + + /** + * Called periodically by the background executor. + */ + @Override + public void run() { + try { + checkSend(false); + } catch (Exception e) { + logger.warn("MR background send: {}", e.getMessage()); + logger.error("IOException {}", e.getMessage()); + } + } + + public int size() { + fReadLock.lock(); + try { + return fNextBatch.size() + (fSendingBatch == null ? 0 : fSendingBatch.size()); + } finally { + fReadLock.unlock(); + } + } + + /** + * Called to queue a message. + * + * @param msgs + * @throws IOException + */ + public void queue(Collection msgs) { + fWriteLock.lock(); + try { + for (Message userMsg : msgs) { + if (userMsg != null) { + fNextBatch.add(new TimestampedMessage(userMsg)); + } else { + logger.warn("MRBatchPublisher::Sender::queue received a null message."); + } + } + } finally { + fWriteLock.unlock(); + } + checkSend(false); + } + + /** + * Send a batch if the queue is long enough, or the first pending message is old enough. + * + * @param force + */ + public void checkSend(boolean force) { + // hold a read lock just long enough to evaluate whether a batch + // should be sent + boolean shouldSend = false; + fReadLock.lock(); + try { + if (fNextBatch.isEmpty()) { + final long nowMs = System.currentTimeMillis(); + shouldSend = (force || fNextBatch.size() >= fMaxBatchSize); + if (!shouldSend) { + final long sendAtMs = fNextBatch.getFirst().timestamp + fMaxAgeMs; + shouldSend = sendAtMs <= nowMs; + } + + // however, unless forced, wait after an error + shouldSend = force || (shouldSend && nowMs >= fDontSendUntilMs); + } + // else: even in 'force', there's nothing to send, so shouldSend=false is fine + } finally { + fReadLock.unlock(); + } + + // if a send is required, acquire a write lock, swap out the next batch, + // swap in a fresh batch, and release the lock for the caller to start + // filling a batch again. After releasing the lock, send the current + // batch. (There could be more messages added between read unlock and + // write lock, but that's fine.) + if (shouldSend) { + fSendingBatch = null; + + fWriteLock.lock(); + try { + fSendingBatch = fNextBatch; + fNextBatch = new LinkedList<>(); + } finally { + fWriteLock.unlock(); + } + + if (!doSend(fSendingBatch, this, fTopic, fCompress, logger)) { + logger.warn("Send failed, rebuilding send queue."); + + // note the time for back-off + fDontSendUntilMs = SF_WAIT_AFTER_ERROR + System.currentTimeMillis(); + + // the send failed. reconstruct the pending queue + fWriteLock.lock(); + try { + final LinkedList nextGroup = fNextBatch; + fNextBatch = fSendingBatch; + fNextBatch.addAll(nextGroup); + fSendingBatch = null; + logger.info("Send queue rebuilt; {} messages to send.", fNextBatch.size()); + } finally { + fWriteLock.unlock(); + } + } else { + fWriteLock.lock(); + try { + fSendingBatch = null; + } finally { + fWriteLock.unlock(); + } + } + } + } + + private LinkedList fNextBatch; + private LinkedList fSendingBatch; + private final String fTopic; + private final int fMaxBatchSize; + private final long fMaxAgeMs; + private final boolean fCompress; + private final ReentrantReadWriteLock fLock; + private final WriteLock fWriteLock; + private final ReadLock fReadLock; + private long fDontSendUntilMs; + private static final long SF_WAIT_AFTER_ERROR = 1000; + } + + // this is static so that it's clearly not using any mutable member data outside of a lock + private static boolean doSend(LinkedList toSend, HttpClient client, String topic, boolean compress, Logger log) { + // it's possible for this call to be made with an empty list. in this case, just return. + if (toSend.isEmpty()) { + return true; + } + + final long nowMs = System.currentTimeMillis(); + final String url = MRConstants.makeUrl(topic); + + log.info("sending {} msgs to {}. Oldest: {} ms", toSend.size(), url, (nowMs - toSend.getFirst().timestamp)); + + final ByteArrayOutputStream baseStream = new ByteArrayOutputStream(); + try { + OutputStream os = baseStream; + if (compress) { + os = new GZIPOutputStream(baseStream); + } + for (TimestampedMessage m : toSend) { + os.write(("" + m.fPartition.length()).getBytes()); + os.write('.'); + os.write(("" + m.fMsg.length()).getBytes()); + os.write('.'); + os.write(m.fPartition.getBytes()); + os.write(m.fMsg.getBytes()); + os.write('\n'); + } + os.close(); + } catch (IOException e) { + log.warn("Problem writing stream to post: " + e.getMessage(), e); + return false; + } + + boolean result = false; + final long startMs = System.currentTimeMillis(); + try { + client.post(url, + compress ? MRFormat.CAMBRIA_ZIP.toString() : MRFormat.CAMBRIA.toString(), + baseStream.toByteArray(), false); + result = true; + } catch (HttpException | IOException e) { + log.warn("Problem posting to MR: " + e.getMessage(), e); + } + + log.info("MR response ({} ms): OK", (System.currentTimeMillis() - startMs)); + return result; + } + + @Override + public void logTo(Logger log) { + logger = log; + } + + @Override + public MRPublisherResponse sendBatchWithResponse() { + // Auto-generated method stub + return null; + } + } diff --git a/src/main/java/org/onap/dmaap/mr/client/impl/MRClientVersionInfo.java b/src/main/java/org/onap/dmaap/mr/client/impl/MRClientVersionInfo.java index 6a13910..0507eee 100644 --- a/src/main/java/org/onap/dmaap/mr/client/impl/MRClientVersionInfo.java +++ b/src/main/java/org/onap/dmaap/mr/client/impl/MRClientVersionInfo.java @@ -4,11 +4,13 @@ * ================================================================================ * Copyright © 2017 AT&T Intellectual Property. All rights reserved. * ================================================================================ + * Modifications Copyright © 2021 Orange. + * ================================================================================ * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * http://www.apache.org/licenses/LICENSE-2.0 - * + * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. @@ -17,37 +19,37 @@ * ============LICENSE_END========================================================= * * ECOMP is a trademark and service mark of AT&T Intellectual Property. - * + * *******************************************************************************/ + package org.onap.dmaap.mr.client.impl; import java.io.IOException; import java.io.InputStream; import java.util.Properties; - import org.slf4j.Logger; import org.slf4j.LoggerFactory; -public class MRClientVersionInfo -{ - private static final Logger logger = LoggerFactory.getLogger(MRClientVersionInfo.class); - public static String getVersion () - { - return version; - } +public class MRClientVersionInfo { + private static final Logger logger = LoggerFactory.getLogger(MRClientVersionInfo.class); + + public static String getVersion() { + return VERSION; + } + + private static final Properties PROPS = new Properties(); + private static final String VERSION; - private static final Properties props = new Properties(); - private static final String version; - static { - String use = null; - try (InputStream is = MRClientVersionInfo.class.getResourceAsStream("/MRClientVersion.properties" )) { - if (is != null) { - props.load(is); - use = props.getProperty ( "MRClientVersion", null ); - } - } catch ( IOException e ) { - logger.error("exception: ", e); - } - version = use; - } + static { + String use = null; + try (InputStream is = MRClientVersionInfo.class.getResourceAsStream("/MRClientVersion.properties")) { + if (is != null) { + PROPS.load(is); + use = PROPS.getProperty("MRClientVersion", null); + } + } catch (IOException e) { + logger.error("exception: ", e); + } + VERSION = use; + } } diff --git a/src/main/java/org/onap/dmaap/mr/client/impl/MRConstants.java b/src/main/java/org/onap/dmaap/mr/client/impl/MRConstants.java index dbf6b4d..b05d839 100644 --- a/src/main/java/org/onap/dmaap/mr/client/impl/MRConstants.java +++ b/src/main/java/org/onap/dmaap/mr/client/impl/MRConstants.java @@ -4,11 +4,13 @@ * ================================================================================ * Copyright © 2017 AT&T Intellectual Property. All rights reserved. * ================================================================================ + * Modifications Copyright © 2021 Orange. + * ================================================================================ * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * http://www.apache.org/licenses/LICENSE-2.0 - * + * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. @@ -17,162 +19,155 @@ * ============LICENSE_END========================================================= * * ECOMP is a trademark and service mark of AT&T Intellectual Property. - * + * *******************************************************************************/ + package org.onap.dmaap.mr.client.impl; -import java.io.UnsupportedEncodingException; import java.net.URLEncoder; +import java.nio.charset.StandardCharsets; import java.util.ArrayList; import java.util.Collection; import java.util.List; - import org.apache.http.HttpHost; -class MRConstants -{ - private static final String PROTOCOL = "http"; - public static final String CONTEXT = "/"; - public static final String BASE_PATH = "events/"; - public static final int STD_MR_SERVICE_PORT = 8080; - - public static String escape ( String s ) - { - try - { - return URLEncoder.encode ( s, "UTF-8"); - } - catch ( UnsupportedEncodingException e ) - { - throw new IllegalArgumentException(e); - } - } - - public static String makeUrl ( String rawTopic ) - { - final String cleanTopic = escape ( rawTopic ); - - final StringBuffer url = new StringBuffer(). - append ( MRConstants.CONTEXT). - append ( MRConstants.BASE_PATH). - append ( cleanTopic ); - return url.toString (); - } - - public static String makeUrl ( final String host, final String rawTopic ) - { - final String cleanTopic = escape ( rawTopic ); - final StringBuffer url = new StringBuffer(); - - if (!host.startsWith("http") && !host.startsWith("https") ) { - url.append( PROTOCOL + "://" ); - } - url.append(host); - url.append ( MRConstants.CONTEXT); - url.append ( MRConstants.BASE_PATH); - url.append ( cleanTopic ); - return url.toString (); - } - - public static String makeUrl ( final String host, final String rawTopic, final String transferprotocol,final String parttion ) - { - final String cleanTopic = escape ( rawTopic ); - - final StringBuffer url = new StringBuffer(); - - if (transferprotocol !=null && !transferprotocol.equals("")) { - url.append( transferprotocol + "://" ); - }else{ - url.append( PROTOCOL + "://" ); - } - url.append(host); - url.append ( MRConstants.CONTEXT); - url.append ( MRConstants.BASE_PATH); - url.append ( cleanTopic ); - if(parttion!=null && !parttion.equalsIgnoreCase("")) - url.append("?partitionKey=").append(parttion); - return url.toString (); - } - public static String makeConsumerUrl ( String topic, String rawConsumerGroup, String rawConsumerId ) - { - final String cleanConsumerGroup = escape ( rawConsumerGroup ); - final String cleanConsumerId = escape ( rawConsumerId ); - return MRConstants.CONTEXT + MRConstants.BASE_PATH + topic + "/" + cleanConsumerGroup + "/" + cleanConsumerId; - } - - /** - * Create a list of HttpHosts from an input list of strings. Input strings have - * host[:port] as format. If the port section is not provided, the default port is used. - * - * @param hosts - * @return a list of hosts - */ - public static List createHostsList(Collection hosts) - { - final ArrayList convertedHosts = new ArrayList<> (); - for ( String host : hosts ) - { - if ( host.length () == 0 ) continue; - convertedHosts.add ( hostForString ( host ) ); - } - return convertedHosts; - } - - /** - * Return an HttpHost from an input string. Input string has - * host[:port] as format. If the port section is not provided, the default port is used. - * - * @param host - * @return a list of hosts - */ - public static HttpHost hostForString ( String host ) - { - if ( host.length() < 1 ) throw new IllegalArgumentException ( "An empty host entry is invalid." ); - - String hostPart = host; - int port = STD_MR_SERVICE_PORT; - - final int colon = host.indexOf ( ':' ); - if ( colon == 0 ) throw new IllegalArgumentException ( "Host entry '" + host + "' is invalid." ); - if ( colon > 0 ) - { - hostPart = host.substring ( 0, colon ).trim(); - - final String portPart = host.substring ( colon + 1 ).trim(); - if ( portPart.length () > 0 ) - { - try - { - port = Integer.parseInt ( portPart ); - } - catch ( NumberFormatException x ) - { - throw new IllegalArgumentException ( "Host entry '" + host + "' is invalid.", x ); - } - } - // else: use default port on "foo:" - } - - return new HttpHost ( hostPart, port ); - } - - public static String makeConsumerUrl(String host, String fTopic, String fGroup, String fId,final String transferprotocol) { - final String cleanConsumerGroup = escape ( fGroup ); - final String cleanConsumerId = escape ( fId ); - - StringBuffer url = new StringBuffer(); - - if (transferprotocol !=null && !transferprotocol.equals("")) { - url.append( transferprotocol + "://" ); - }else{ - url.append( PROTOCOL + "://" ); - } - - url.append(host); - url.append(CONTEXT); - url.append(BASE_PATH); - url.append(fTopic + "/" + cleanConsumerGroup + "/" + cleanConsumerId); - - return url.toString(); - } +class MRConstants { + + private MRConstants() { + + } + + private static final String PROTOCOL = "http"; + public static final String CONTEXT = "/"; + public static final String BASE_PATH = "events/"; + public static final int STD_MR_SERVICE_PORT = 8080; + + public static String escape(String url) { + return URLEncoder.encode(url, StandardCharsets.UTF_8); + } + + public static String makeUrl(String rawTopic) { + final String cleanTopic = escape(rawTopic); + + return new StringBuilder() + .append(MRConstants.CONTEXT) + .append(MRConstants.BASE_PATH) + .append(cleanTopic).toString(); + } + + public static String makeUrl(final String host, final String rawTopic) { + final String cleanTopic = escape(rawTopic); + final StringBuilder url = new StringBuilder(); + + if (!host.startsWith("http") && !host.startsWith("https")) { + url.append(PROTOCOL).append("://"); + } + url.append(host); + url.append(MRConstants.CONTEXT); + url.append(MRConstants.BASE_PATH); + url.append(cleanTopic); + return url.toString(); + } + + public static String makeUrl(final String host, final String rawTopic, final String transferProtocol, final String partition) { + final String cleanTopic = escape(rawTopic); + + final StringBuilder url = new StringBuilder(); + + if (transferProtocol != null && !transferProtocol.isEmpty()) { + url.append(transferProtocol).append("://"); + } else { + url.append(PROTOCOL).append("://"); + } + url.append(host); + url.append(MRConstants.CONTEXT); + url.append(MRConstants.BASE_PATH); + url.append(cleanTopic); + if (partition != null && !partition.isEmpty()) { + url.append("?partitionKey=").append(partition); + } + return url.toString(); + } + + public static String makeConsumerUrl(String topic, String rawConsumerGroup, String rawConsumerId) { + final String cleanConsumerGroup = escape(rawConsumerGroup); + final String cleanConsumerId = escape(rawConsumerId); + return MRConstants.CONTEXT + MRConstants.BASE_PATH + topic + "/" + cleanConsumerGroup + "/" + cleanConsumerId; + } + + /** + * Create a list of HttpHosts from an input list of strings. Input strings have + * host[:port] as format. If the port section is not provided, the default port is used. + * + * @param hosts + * @return a list of hosts + */ + public static List createHostsList(Collection hosts) { + final ArrayList convertedHosts = new ArrayList<>(); + for (String host : hosts) { + if (host.length() == 0) { + continue; + } + convertedHosts.add(hostForString(host)); + } + return convertedHosts; + } + + /** + * Return an HttpHost from an input string. Input string has + * host[:port] as format. If the port section is not provided, the default port is used. + * + * @param host + * @return a list of hosts + */ + public static HttpHost hostForString(String host) { + if (host.length() < 1) { + throw new IllegalArgumentException("An empty host entry is invalid."); + } + + String hostPart = host; + int port = STD_MR_SERVICE_PORT; + + final int colon = host.indexOf(':'); + if (colon == 0) { + throw new IllegalArgumentException("Host entry '" + host + "' is invalid."); + } + if (colon > 0) { + hostPart = host.substring(0, colon).trim(); + + final String portPart = host.substring(colon + 1).trim(); + if (portPart.length() > 0) { + try { + port = Integer.parseInt(portPart); + } catch (NumberFormatException x) { + throw new IllegalArgumentException("Host entry '" + host + "' is invalid.", x); + } + } + // else: use default port on "foo:" + } + + return new HttpHost(hostPart, port); + } + + public static String makeConsumerUrl(String host, String topic, String group, String id, final String transferprotocol) { + final String cleanConsumerGroup = escape(group); + final String cleanConsumerId = escape(id); + + StringBuilder url = new StringBuilder(); + + if (transferprotocol != null && !transferprotocol.equals("")) { + url.append(transferprotocol).append("://"); + } else { + url.append(PROTOCOL).append("://"); + } + + url.append(host) + .append(CONTEXT) + .append(BASE_PATH) + .append(topic) + .append("/").append(cleanConsumerGroup) + .append("/").append(cleanConsumerId); + + return url.toString(); + } } diff --git a/src/main/java/org/onap/dmaap/mr/client/impl/MRConsumerImpl.java b/src/main/java/org/onap/dmaap/mr/client/impl/MRConsumerImpl.java index 6c67313..57ae3ee 100644 --- a/src/main/java/org/onap/dmaap/mr/client/impl/MRConsumerImpl.java +++ b/src/main/java/org/onap/dmaap/mr/client/impl/MRConsumerImpl.java @@ -4,11 +4,13 @@ * ================================================================================ * Copyright © 2017 AT&T Intellectual Property. All rights reserved. * ================================================================================ + * Modifications Copyright © 2021 Orange. + * ================================================================================ * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * http://www.apache.org/licenses/LICENSE-2.0 - * + * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. @@ -17,24 +19,26 @@ * ============LICENSE_END========================================================= * * ECOMP is a trademark and service mark of AT&T Intellectual Property. - * + * *******************************************************************************/ + package org.onap.dmaap.mr.client.impl; import com.att.aft.dme2.api.DME2Client; import com.att.aft.dme2.api.DME2Exception; -import org.onap.dmaap.mr.client.HostSelector; -import org.onap.dmaap.mr.client.MRClientFactory; -import org.onap.dmaap.mr.client.MRConsumer; -import org.onap.dmaap.mr.client.response.MRConsumerResponse; -import org.onap.dmaap.mr.test.clients.ProtocolTypeConstants; - -import java.io.*; +import java.io.FileInputStream; +import java.io.IOException; +import java.io.InputStream; +import java.io.UnsupportedEncodingException; import java.net.MalformedURLException; import java.net.URI; import java.net.URISyntaxException; import java.net.URLEncoder; -import java.util.*; +import java.util.Collection; +import java.util.HashMap; +import java.util.LinkedList; +import java.util.List; +import java.util.Properties; import java.util.concurrent.TimeUnit; import org.apache.http.HttpException; import org.apache.http.HttpStatus; @@ -42,20 +46,24 @@ import org.json.JSONArray; import org.json.JSONException; import org.json.JSONObject; import org.json.JSONTokener; +import org.onap.dmaap.mr.client.HostSelector; +import org.onap.dmaap.mr.client.MRClientFactory; +import org.onap.dmaap.mr.client.MRConsumer; +import org.onap.dmaap.mr.client.ProtocolType; +import org.onap.dmaap.mr.client.response.MRConsumerResponse; import org.slf4j.Logger; import org.slf4j.LoggerFactory; public class MRConsumerImpl extends MRBaseClient implements MRConsumer { - private Logger log = LoggerFactory.getLogger(this.getClass().getName()); + private static final Logger logger = LoggerFactory.getLogger(MRConsumerImpl.class); public static final String ROUTER_FILE_PATH = null; - public String protocolFlag = ProtocolTypeConstants.DME2.getValue(); + public String protocolFlag = ProtocolType.DME2.getValue(); public String consumerFilePath; private static final String JSON_RESULT = "result"; - private static final String PROPS_PROTOCOL = "Protocol"; private static final String EXECPTION_MESSAGE = "exception: "; private static final String SUCCESS_MESSAGE = "Success"; @@ -70,6 +78,29 @@ public class MRConsumerImpl extends MRBaseClient implements MRConsumer { private static final String URL_PARAM_LIMIT = "limit"; private static final String URL_PARAM_TIMEOUT = "timeout"; + private static final String USERNAME = "username"; + private static final String SERVICE_NAME = "ServiceName"; + private static final String PARTNER = "Partner"; + private static final String ROUTE_OFFER = "routeOffer"; + private static final String PROTOCOL = "Protocol"; + private static final String METHOD_TYPE = "MethodType"; + private static final String CONTENT_TYPE = "contenttype"; + private static final String LATITUDE = "Latitude"; + private static final String LONGITUDE = "Longitude"; + private static final String AFT_ENVIRONMENT = "AFT_ENVIRONMENT"; + private static final String VERSION = "Version"; + private static final String ENVIRONMENT = "Environment"; + private static final String SUB_CONTEXT_PATH = "SubContextPath"; + private static final String SESSION_STICKINESS_REQUIRED = "sessionstickinessrequired"; + private static final String AFT_DME2_EP_READ_TIMEOUT_MS = "AFT_DME2_EP_READ_TIMEOUT_MS"; + private static final String AFT_DME2_ROUNDTRIP_TIMEOUT_MS = "AFT_DME2_ROUNDTRIP_TIMEOUT_MS"; + private static final String AFT_DME2_EP_CONN_TIMEOUT = "AFT_DME2_EP_CONN_TIMEOUT"; + private static final String AFT_DME2_EXCHANGE_REQUEST_HANDLERS = "AFT_DME2_EXCHANGE_REQUEST_HANDLERS"; + private static final String AFT_DME2_EXCHANGE_REPLY_HANDLERS = "AFT_DME2_EXCHANGE_REPLY_HANDLERS"; + private static final String AFT_DME2_REQ_TRACE_ON = "AFT_DME2_REQ_TRACE_ON"; + private static final String DME2_PER_HANDLER_TIMEOUT_MS = "DME2_PER_HANDLER_TIMEOUT_MS"; + private static final String DME2_REPLY_HANDLER_TIMEOUT_MS = "DME2_REPLY_HANDLER_TIMEOUT_MS"; + private final String fTopic; private final String fGroup; private final String fId; @@ -192,8 +223,8 @@ public class MRConsumerImpl extends MRBaseClient implements MRConsumer { public Iterable fetch(int timeoutMs, int limit) throws Exception { final LinkedList msgs = new LinkedList<>(); - ProtocolTypeConstants protocolFlagEnum = null; - for(ProtocolTypeConstants type : ProtocolTypeConstants.values()) { + ProtocolType protocolFlagEnum = null; + for (ProtocolType type : ProtocolType.values()) { if (type.getValue().equalsIgnoreCase(protocolFlag)) { protocolFlagEnum = type; } @@ -211,27 +242,27 @@ public class MRConsumerImpl extends MRBaseClient implements MRConsumer { break; case AAF_AUTH: String urlAuthPath = createUrlPath(MRConstants.makeConsumerUrl(fHostSelector.selectBaseHost(), fTopic, - fGroup, fId, props.getProperty(PROPS_PROTOCOL)), timeoutMs, limit); + fGroup, fId, props.getProperty(PROTOCOL)), timeoutMs, limit); final JSONObject o = get(urlAuthPath, username, password, protocolFlag); readJsonData(msgs, o); break; case AUTH_KEY: final String urlKeyPath = createUrlPath( - MRConstants.makeConsumerUrl(host, fTopic, fGroup, fId, props.getProperty(PROPS_PROTOCOL)), + MRConstants.makeConsumerUrl(host, fTopic, fGroup, fId, props.getProperty(PROTOCOL)), timeoutMs, limit); final JSONObject authObject = getAuth(urlKeyPath, authKey, authDate, username, password, protocolFlag); readJsonData(msgs, authObject); break; case HTTPNOAUTH: final String urlNoAuthPath = createUrlPath(MRConstants.makeConsumerUrl(fHostSelector.selectBaseHost(), fTopic, - fGroup, fId, props.getProperty(PROPS_PROTOCOL)), timeoutMs, limit); + fGroup, fId, props.getProperty(PROTOCOL)), timeoutMs, limit); readJsonData(msgs, getNoAuth(urlNoAuthPath)); break; } } catch (JSONException e) { // unexpected response reportProblemWithResponse(); - log.error(EXECPTION_MESSAGE, e); + logger.error(EXECPTION_MESSAGE, e); } catch (HttpException e) { throw new IOException(e); } @@ -244,10 +275,11 @@ public class MRConsumerImpl extends MRBaseClient implements MRConsumer { final JSONArray a = o.getJSONArray(JSON_RESULT); if (a != null) { for (int i = 0; i < a.length(); i++) { - if (a.get(i) instanceof String) + if (a.get(i) instanceof String) { msgs.add(a.getString(i)); - else + } else { msgs.add(a.getJSONObject(i).toString()); + } } } } @@ -264,7 +296,7 @@ public class MRConsumerImpl extends MRBaseClient implements MRConsumer { final LinkedList msgs = new LinkedList<>(); MRConsumerResponse mrConsumerResponse = new MRConsumerResponse(); try { - if (ProtocolTypeConstants.DME2.getValue().equalsIgnoreCase(protocolFlag)) { + if (ProtocolType.DME2.getValue().equalsIgnoreCase(protocolFlag)) { dmeConfigure(timeoutMs, limit); long timeout = (dme2ReplyHandlerTimeoutMs > 0 && longPollingMs == timeoutMs) ? dme2ReplyHandlerTimeoutMs @@ -277,9 +309,9 @@ public class MRConsumerImpl extends MRBaseClient implements MRConsumer { createMRConsumerResponse(reply, mrConsumerResponse); } - if (ProtocolTypeConstants.AAF_AUTH.getValue().equalsIgnoreCase(protocolFlag)) { + if (ProtocolType.AAF_AUTH.getValue().equalsIgnoreCase(protocolFlag)) { final String urlPath = createUrlPath(MRConstants.makeConsumerUrl(fHostSelector.selectBaseHost(), fTopic, - fGroup, fId, props.getProperty(PROPS_PROTOCOL)), timeoutMs, limit); + fGroup, fId, props.getProperty(PROTOCOL)), timeoutMs, limit); String response = getResponse(urlPath, username, password, protocolFlag); final JSONObject o = getResponseDataInJsonWithResponseReturned(response); @@ -287,9 +319,9 @@ public class MRConsumerImpl extends MRBaseClient implements MRConsumer { createMRConsumerResponse(response, mrConsumerResponse); } - if (ProtocolTypeConstants.AUTH_KEY.getValue().equalsIgnoreCase(protocolFlag)) { + if (ProtocolType.AUTH_KEY.getValue().equalsIgnoreCase(protocolFlag)) { final String urlPath = createUrlPath( - MRConstants.makeConsumerUrl(host, fTopic, fGroup, fId, props.getProperty(PROPS_PROTOCOL)), + MRConstants.makeConsumerUrl(host, fTopic, fGroup, fId, props.getProperty(PROTOCOL)), timeoutMs, limit); String response = getAuthResponse(urlPath, authKey, authDate, username, password, protocolFlag); @@ -298,9 +330,9 @@ public class MRConsumerImpl extends MRBaseClient implements MRConsumer { createMRConsumerResponse(response, mrConsumerResponse); } - if (ProtocolTypeConstants.HTTPNOAUTH.getValue().equalsIgnoreCase(protocolFlag)) { + if (ProtocolType.HTTPNOAUTH.getValue().equalsIgnoreCase(protocolFlag)) { final String urlPath = createUrlPath(MRConstants.makeConsumerUrl(fHostSelector.selectBaseHost(), fTopic, - fGroup, fId, props.getProperty(PROPS_PROTOCOL)), timeoutMs, limit); + fGroup, fId, props.getProperty(PROTOCOL)), timeoutMs, limit); String response = getNoAuthResponse(urlPath, username, password, protocolFlag); final JSONObject o = getResponseDataInJsonWithResponseReturned(response); @@ -311,19 +343,19 @@ public class MRConsumerImpl extends MRBaseClient implements MRConsumer { } catch (JSONException e) { mrConsumerResponse.setResponseMessage(String.valueOf(HttpStatus.SC_INTERNAL_SERVER_ERROR)); mrConsumerResponse.setResponseMessage(e.getMessage()); - log.error("json exception: ", e); + logger.error("json exception: ", e); } catch (HttpException e) { mrConsumerResponse.setResponseMessage(String.valueOf(HttpStatus.SC_INTERNAL_SERVER_ERROR)); mrConsumerResponse.setResponseMessage(e.getMessage()); - log.error("http exception: ", e); + logger.error("http exception: ", e); } catch (DME2Exception e) { mrConsumerResponse.setResponseCode(e.getErrorCode()); mrConsumerResponse.setResponseMessage(e.getErrorMessage()); - log.error("DME2 exception: ", e); + logger.error("DME2 exception: ", e); } catch (Exception e) { mrConsumerResponse.setResponseMessage(String.valueOf(HttpStatus.SC_INTERNAL_SERVER_ERROR)); mrConsumerResponse.setResponseMessage(e.getMessage()); - log.error(EXECPTION_MESSAGE, e); + logger.error(EXECPTION_MESSAGE, e); } mrConsumerResponse.setActualMessages(msgs); return mrConsumerResponse; @@ -331,16 +363,16 @@ public class MRConsumerImpl extends MRBaseClient implements MRConsumer { @Override protected void reportProblemWithResponse() { - log.warn("There was a problem with the server response. Blacklisting for 3 minutes."); + logger.warn("There was a problem with the server response. Blacklisting for 3 minutes."); super.reportProblemWithResponse(); fHostSelector.reportReachabilityProblem(3, TimeUnit.MINUTES); } private void createMRConsumerResponse(String reply, MRConsumerResponse mrConsumerResponse) { if (reply.startsWith("{")) { - JSONObject jObject = new JSONObject(reply); - String message = jObject.getString("message"); - int status = jObject.getInt("status"); + JSONObject jsonObject = new JSONObject(reply); + String message = jsonObject.getString("message"); + int status = jsonObject.getInt("status"); mrConsumerResponse.setResponseCode(Integer.toString(status)); @@ -372,7 +404,7 @@ public class MRConsumerImpl extends MRBaseClient implements MRConsumer { return jsonObject; } catch (JSONException excp) { - log.error("DMAAP - Error reading response data.", excp); + logger.error("DMAAP - Error reading response data.", excp); return null; } } @@ -403,22 +435,22 @@ public class MRConsumerImpl extends MRBaseClient implements MRConsumer { private void dmeConfigure(int timeoutMs, int limit) throws IOException, DME2Exception, URISyntaxException { this.longPollingMs = timeoutMs; - String latitude = props.getProperty("Latitude"); - String longitude = props.getProperty("Longitude"); - String version = props.getProperty("Version"); - String serviceName = props.getProperty("ServiceName"); - String env = props.getProperty("Environment"); - String partner = props.getProperty("Partner"); - String routeOffer = props.getProperty("routeOffer"); - String subContextPath = props.getProperty("SubContextPath") + fTopic + "/" + fGroup + "/" + fId; - String protocol = props.getProperty(PROPS_PROTOCOL); - String methodType = props.getProperty("MethodType"); - String dmeuser = props.getProperty("username"); - String dmepassword = props.getProperty("password"); - String contenttype = props.getProperty("contenttype"); - String handlers = props.getProperty("sessionstickinessrequired"); - - /** + String latitude = props.getProperty(LATITUDE); + String longitude = props.getProperty(LONGITUDE); + String version = props.getProperty(VERSION); + String serviceName = props.getProperty(SERVICE_NAME); + String env = props.getProperty(ENVIRONMENT); + String partner = props.getProperty(PARTNER); + String routeOffer = props.getProperty(ROUTE_OFFER); + String subContextPath = props.getProperty(SUB_CONTEXT_PATH) + fTopic + "/" + fGroup + "/" + fId; + String protocol = props.getProperty(PROTOCOL); + String methodType = props.getProperty(METHOD_TYPE); + String dmeuser = props.getProperty(USERNAME); + String dmepassword = props.getProperty(USERNAME); + String contenttype = props.getProperty(CONTENT_TYPE); + String handlers = props.getProperty(SESSION_STICKINESS_REQUIRED); + + /* * Changes to DME2Client url to use Partner for auto failover between data centers When Partner value is not * provided use the routeOffer value for auto failover within a cluster */ @@ -458,13 +490,13 @@ public class MRConsumerImpl extends MRBaseClient implements MRConsumer { url = contextUrl.toString(); DMETimeOuts = new HashMap<>(); - DMETimeOuts.put("AFT_DME2_EP_READ_TIMEOUT_MS", props.getProperty("AFT_DME2_EP_READ_TIMEOUT_MS")); - DMETimeOuts.put("AFT_DME2_ROUNDTRIP_TIMEOUT_MS", props.getProperty("AFT_DME2_ROUNDTRIP_TIMEOUT_MS")); - DMETimeOuts.put("AFT_DME2_EP_CONN_TIMEOUT", props.getProperty("AFT_DME2_EP_CONN_TIMEOUT")); + DMETimeOuts.put("AFT_DME2_EP_READ_TIMEOUT_MS", props.getProperty(AFT_DME2_EP_READ_TIMEOUT_MS)); + DMETimeOuts.put("AFT_DME2_ROUNDTRIP_TIMEOUT_MS", props.getProperty(AFT_DME2_ROUNDTRIP_TIMEOUT_MS)); + DMETimeOuts.put("AFT_DME2_EP_CONN_TIMEOUT", props.getProperty(AFT_DME2_EP_CONN_TIMEOUT)); DMETimeOuts.put("Content-Type", contenttype); System.setProperty("AFT_LATITUDE", latitude); System.setProperty("AFT_LONGITUDE", longitude); - System.setProperty("AFT_ENVIRONMENT", props.getProperty("AFT_ENVIRONMENT")); + System.setProperty("AFT_ENVIRONMENT", props.getProperty(AFT_ENVIRONMENT)); // SSL changes System.setProperty("AFT_DME2_CLIENT_SSL_INCLUDE_PROTOCOLS", "TLSv1.1,TLSv1.2"); @@ -474,7 +506,7 @@ public class MRConsumerImpl extends MRBaseClient implements MRConsumer { long dme2PerEndPointTimeoutMs; try { - dme2PerEndPointTimeoutMs = Long.parseLong(props.getProperty("DME2_PER_HANDLER_TIMEOUT_MS")); + dme2PerEndPointTimeoutMs = Long.parseLong(props.getProperty(DME2_PER_HANDLER_TIMEOUT_MS)); // backward compatibility if (dme2PerEndPointTimeoutMs <= 0) { dme2PerEndPointTimeoutMs = timeoutMs + DEFAULT_DME2_PER_ENDPOINT_TIMEOUT_MS; @@ -483,15 +515,15 @@ public class MRConsumerImpl extends MRBaseClient implements MRConsumer { // backward compatibility dme2PerEndPointTimeoutMs = timeoutMs + DEFAULT_DME2_PER_ENDPOINT_TIMEOUT_MS; getLog().debug( - "DME2_PER_HANDLER_TIMEOUT_MS not set and using default " + DEFAULT_DME2_PER_ENDPOINT_TIMEOUT_MS); + DME2_PER_HANDLER_TIMEOUT_MS + " not set and using default " + DEFAULT_DME2_PER_ENDPOINT_TIMEOUT_MS); } try { - dme2ReplyHandlerTimeoutMs = Long.parseLong(props.getProperty("DME2_REPLY_HANDLER_TIMEOUT_MS")); + dme2ReplyHandlerTimeoutMs = Long.parseLong(props.getProperty(DME2_REPLY_HANDLER_TIMEOUT_MS)); } catch (NumberFormatException nfe) { try { - long dme2EpReadTimeoutMs = Long.parseLong(props.getProperty("AFT_DME2_EP_READ_TIMEOUT_MS")); - long dme2EpConnTimeoutMs = Long.parseLong(props.getProperty("AFT_DME2_EP_CONN_TIMEOUT")); + long dme2EpReadTimeoutMs = Long.parseLong(props.getProperty(AFT_DME2_EP_READ_TIMEOUT_MS)); + long dme2EpConnTimeoutMs = Long.parseLong(props.getProperty(AFT_DME2_EP_CONN_TIMEOUT)); dme2ReplyHandlerTimeoutMs = timeoutMs + dme2EpReadTimeoutMs + dme2EpConnTimeoutMs; getLog().debug( "DME2_REPLY_HANDLER_TIMEOUT_MS not set and using default from timeoutMs, AFT_DME2_EP_READ_TIMEOUT_MS and AFT_DME2_EP_CONN_TIMEOUT " @@ -518,9 +550,9 @@ public class MRConsumerImpl extends MRBaseClient implements MRConsumer { sender.setPayload(""); if (handlers != null && handlers.equalsIgnoreCase("yes")) { sender.addHeader("AFT_DME2_EXCHANGE_REQUEST_HANDLERS", - props.getProperty("AFT_DME2_EXCHANGE_REQUEST_HANDLERS")); - sender.addHeader("AFT_DME2_EXCHANGE_REPLY_HANDLERS", props.getProperty("AFT_DME2_EXCHANGE_REPLY_HANDLERS")); - sender.addHeader("AFT_DME2_REQ_TRACE_ON", props.getProperty("AFT_DME2_REQ_TRACE_ON")); + props.getProperty(AFT_DME2_EXCHANGE_REQUEST_HANDLERS)); + sender.addHeader("AFT_DME2_EXCHANGE_REPLY_HANDLERS", props.getProperty(AFT_DME2_EXCHANGE_REPLY_HANDLERS)); + sender.addHeader("AFT_DME2_REQ_TRACE_ON", props.getProperty(AFT_DME2_REQ_TRACE_ON)); } else { sender.addHeader("AFT_DME2_EXCHANGE_REPLY_HANDLERS", "com.att.nsa.mr.dme.client.HeaderReplyHandler"); } @@ -548,7 +580,7 @@ public class MRConsumerImpl extends MRBaseClient implements MRConsumer { } adds.append("filter=").append(URLEncoder.encode(fFilter, "UTF-8")); } catch (UnsupportedEncodingException e) { - log.error("exception at createUrlPath () : ", e); + logger.error("exception at createUrlPath () : ", e); } } @@ -560,10 +592,10 @@ public class MRConsumerImpl extends MRBaseClient implements MRConsumer { } private String readRoute(String routeKey) { - try(InputStream input = new FileInputStream(MRClientFactory.routeFilePath)) { + try (InputStream input = new FileInputStream(MRClientFactory.routeFilePath)) { MRClientFactory.prop.load(input); } catch (Exception ex) { - log.error("Reply Router Error " + ex); + logger.error("Reply Router Error " + ex); } return MRClientFactory.prop.getProperty(routeKey); } diff --git a/src/main/java/org/onap/dmaap/mr/client/impl/MRFormat.java b/src/main/java/org/onap/dmaap/mr/client/impl/MRFormat.java index 538f1e3..0ebebe5 100644 --- a/src/main/java/org/onap/dmaap/mr/client/impl/MRFormat.java +++ b/src/main/java/org/onap/dmaap/mr/client/impl/MRFormat.java @@ -4,11 +4,13 @@ * ================================================================================ * Copyright © 2017 AT&T Intellectual Property. All rights reserved. * ================================================================================ + * Modifications Copyright © 2021 Orange. + * ================================================================================ * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * http://www.apache.org/licenses/LICENSE-2.0 - * + * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. @@ -17,36 +19,39 @@ * ============LICENSE_END========================================================= * * ECOMP is a trademark and service mark of AT&T Intellectual Property. - * + * *******************************************************************************/ + package org.onap.dmaap.mr.client.impl; -enum MRFormat -{ - /** - * Messages are sent using MR's message format. - */ - CAMBRIA - { - @Override - public String toString() { return "application/cambria"; } - }, +enum MRFormat { + /** + * Messages are sent using MR's message format. + */ + CAMBRIA { + @Override + public String toString() { + return "application/cambria"; + } + }, - /** - * Messages are sent using MR's message format with compression. - */ - CAMBRIA_ZIP - { - @Override - public String toString() { return "application/cambria-zip"; } - }, + /** + * Messages are sent using MR's message format with compression. + */ + CAMBRIA_ZIP { + @Override + public String toString() { + return "application/cambria-zip"; + } + }, - /** - * messages are sent as simple JSON objects. - */ - JSON - { - @Override - public String toString() { return "application/json"; } - } + /** + * messages are sent as simple JSON objects. + */ + JSON { + @Override + public String toString() { + return "application/json"; + } + } } diff --git a/src/main/java/org/onap/dmaap/mr/client/impl/MRMetaClient.java b/src/main/java/org/onap/dmaap/mr/client/impl/MRMetaClient.java index c1e2d12..414178d 100644 --- a/src/main/java/org/onap/dmaap/mr/client/impl/MRMetaClient.java +++ b/src/main/java/org/onap/dmaap/mr/client/impl/MRMetaClient.java @@ -4,11 +4,13 @@ * ================================================================================ * Copyright © 2017 AT&T Intellectual Property. All rights reserved. * ================================================================================ + * Modifications Copyright © 2021 Orange. + * ================================================================================ * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * http://www.apache.org/licenses/LICENSE-2.0 - * + * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. @@ -17,256 +19,212 @@ * ============LICENSE_END========================================================= * * ECOMP is a trademark and service mark of AT&T Intellectual Property. - * + * *******************************************************************************/ + package org.onap.dmaap.mr.client.impl; +import com.att.nsa.apiClient.credentials.ApiCredential; +import com.att.nsa.apiClient.http.HttpException; +import com.att.nsa.apiClient.http.HttpObjectNotFoundException; import java.io.IOException; import java.net.MalformedURLException; import java.util.Collection; import java.util.Set; import java.util.TreeSet; - import org.json.JSONArray; import org.json.JSONException; import org.json.JSONObject; - -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; - -import com.att.nsa.apiClient.credentials.ApiCredential; -import com.att.nsa.apiClient.http.HttpException; -import com.att.nsa.apiClient.http.HttpObjectNotFoundException; import org.onap.dmaap.mr.client.MRIdentityManager; import org.onap.dmaap.mr.client.MRTopicManager; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; -public class MRMetaClient extends MRBaseClient implements MRTopicManager, MRIdentityManager -{ - private static final String BASE_URI_TOPIC = "/topics"; - private static final String BASE_URI_APIKEY = "/apiKeys"; - - private static final String PARAM_DESCRIPTION = "description"; - private static final String PARAM_EMAIL = "email"; - - private static final Logger logger = LoggerFactory.getLogger(MRMetaClient.class); - public MRMetaClient ( Collection baseUrls ) throws MalformedURLException - { - super ( baseUrls ); - } - - @Override - public Set getTopics () throws IOException - { - final TreeSet set = new TreeSet<> (); - try - { - final JSONObject topicSet = get ( BASE_URI_TOPIC ); - final JSONArray a = topicSet.getJSONArray ( "topics" ); - for ( int i=0; i getAllowedProducers () - { - final JSONObject acl = topicData.optJSONObject ( "writerAcl" ); - if ( acl != null && acl.optBoolean ( "enabled", true ) ) - { - return jsonArrayToSet ( acl.optJSONArray ( "users" ) ); - } - return null; - } - - @Override - public Set getAllowedConsumers () - { - final JSONObject acl = topicData.optJSONObject ( "readerAcl" ); - if ( acl != null && acl.optBoolean ( "enabled", true ) ) - { - return jsonArrayToSet ( acl.optJSONArray ( "users" ) ); - } - return null; - } - }; - } - catch ( JSONException e ) - { - throw new IOException ( e ); - } - catch ( HttpException e ) - { - throw new IOException ( e ); - } - } - - @Override - public void createTopic ( String topicName, String topicDescription, int partitionCount, int replicationCount ) throws HttpException, IOException - { - final JSONObject o = new JSONObject (); - o.put ( "topicName", topicName ); - o.put ( "topicDescription", topicDescription ); - o.put ( "partitionCount", partitionCount ); - o.put ( "replicationCount", replicationCount ); - post ( BASE_URI_TOPIC + "/create", o, false ); - } - - @Override - public void deleteTopic ( String topic ) throws HttpException, IOException - { - delete ( BASE_URI_TOPIC + "/" + MRConstants.escape ( topic ) ); - } - - @Override - public boolean isOpenForProducing ( String topic ) throws HttpObjectNotFoundException, IOException - { - return null == getAllowedProducers ( topic ); - } - - @Override - public Set getAllowedProducers ( String topic ) throws HttpObjectNotFoundException, IOException - { - return getTopicMetadata ( topic ).getAllowedProducers (); - } - - @Override - public void allowProducer ( String topic, String apiKey ) throws HttpObjectNotFoundException, HttpException, IOException - { - put ( BASE_URI_TOPIC + "/" + MRConstants.escape ( topic ) + "/producers/" + MRConstants.escape ( apiKey ), new JSONObject() ); - } - - @Override - public void revokeProducer ( String topic, String apiKey ) throws HttpException, IOException - { - delete ( BASE_URI_TOPIC + "/" + MRConstants.escape ( topic ) + "/producers/" + MRConstants.escape ( apiKey ) ); - } - - @Override - public boolean isOpenForConsuming ( String topic ) throws HttpObjectNotFoundException, IOException - { - return null == getAllowedConsumers ( topic ); - } - - @Override - public Set getAllowedConsumers ( String topic ) throws HttpObjectNotFoundException, IOException - { - return getTopicMetadata ( topic ).getAllowedConsumers (); - } - - @Override - public void allowConsumer ( String topic, String apiKey ) throws HttpObjectNotFoundException, HttpException, IOException - { - put ( BASE_URI_TOPIC + "/" + MRConstants.escape ( topic ) + "/consumers/" + MRConstants.escape ( apiKey ), new JSONObject() ); - } - - @Override - public void revokeConsumer ( String topic, String apiKey ) throws HttpException, IOException - { - delete ( BASE_URI_TOPIC + "/" + MRConstants.escape ( topic ) + "/consumers/" + MRConstants.escape ( apiKey ) ); - } - - @Override - public ApiCredential createApiKey ( String email, String description ) throws HttpException, MRApiException, IOException - { - try - { - final JSONObject o = new JSONObject (); - o.put ( PARAM_EMAIL, email ); - o.put ( PARAM_DESCRIPTION, description ); - final JSONObject reply = post ( BASE_URI_APIKEY + "/create", o, true ); - return new ApiCredential ( reply.getString ( "key" ), reply.getString ( "secret" ) ); - } - catch ( JSONException e ) - { - // the response doesn't meet our expectation - throw new MRApiException ( "The API key response is incomplete.", e ); - } - } - - @Override - public ApiKey getApiKey ( String apiKey ) throws HttpObjectNotFoundException, HttpException, IOException - { - final JSONObject keyEntry = get ( BASE_URI_APIKEY + "/" + MRConstants.escape ( apiKey ) ); - if ( keyEntry == null ) - { - return null; - } - - return new ApiKey () - { - @Override - public String getEmail () - { - final JSONObject aux = keyEntry.optJSONObject ( "aux" ); - if ( aux != null ) - { - return aux.optString ( PARAM_EMAIL ); - } - return null; - } - - @Override - public String getDescription () - { - final JSONObject aux = keyEntry.optJSONObject ( "aux" ); - if ( aux != null ) - { - return aux.optString ( PARAM_DESCRIPTION ); - } - return null; - } - }; - } - - @Override - public void updateCurrentApiKey ( String email, String description ) throws HttpObjectNotFoundException, HttpException, IOException - { - final JSONObject o = new JSONObject (); - if ( email != null ) o.put ( PARAM_EMAIL, email ); - if ( description != null ) o.put ( PARAM_DESCRIPTION, description ); - patch ( BASE_URI_APIKEY + "/" + MRConstants.escape ( getCurrentApiKey() ), o ); - } - - @Override - public void deleteCurrentApiKey () throws HttpException, IOException - { - delete ( BASE_URI_APIKEY + "/" + MRConstants.escape ( getCurrentApiKey() ) ); - } +public class MRMetaClient extends MRBaseClient implements MRTopicManager, MRIdentityManager { + private static final String BASE_URI_TOPIC = "/topics"; + private static final String BASE_URI_APIKEY = "/apiKeys"; + + private static final String PARAM_DESCRIPTION = "description"; + private static final String PARAM_EMAIL = "email"; + + private static final Logger logger = LoggerFactory.getLogger(MRMetaClient.class); + + public MRMetaClient(Collection baseUrls) throws MalformedURLException { + super(baseUrls); + } + + @Override + public Set getTopics() throws IOException { + final TreeSet set = new TreeSet<>(); + try { + final JSONObject topicSet = get(BASE_URI_TOPIC); + final JSONArray a = topicSet.getJSONArray("topics"); + for (int i = 0; i < a.length(); i++) { + set.add(a.getString(i)); + } + } catch (HttpObjectNotFoundException e) { + getLog().warn("No /topics endpoint on service."); + logger.error("HttpObjectNotFoundException: ", e); + } catch (JSONException e) { + getLog().warn("Bad /topics result from service."); + logger.error("JSONException: ", e); + } catch (HttpException e) { + throw new IOException(e); + } + return set; + } + + @Override + public TopicInfo getTopicMetadata(String topic) throws HttpObjectNotFoundException, IOException { + try { + final JSONObject topicData = get(BASE_URI_TOPIC + "/" + MRConstants.escape(topic)); + return new TopicInfo() { + @Override + public String getOwner() { + return topicData.optString("owner", null); + } + + @Override + public String getDescription() { + return topicData.optString(PARAM_DESCRIPTION, null); + } + + @Override + public Set getAllowedProducers() { + final JSONObject acl = topicData.optJSONObject("writerAcl"); + if (acl != null && acl.optBoolean("enabled", true)) { + return jsonArrayToSet(acl.optJSONArray("users")); + } + return null; + } + + @Override + public Set getAllowedConsumers() { + final JSONObject acl = topicData.optJSONObject("readerAcl"); + if (acl != null && acl.optBoolean("enabled", true)) { + return jsonArrayToSet(acl.optJSONArray("users")); + } + return null; + } + }; + } catch (JSONException e) { + throw new IOException(e); + } catch (HttpException e) { + throw new IOException(e); + } + } + + @Override + public void createTopic(String topicName, String topicDescription, int partitionCount, int replicationCount) throws HttpException, IOException { + final JSONObject o = new JSONObject(); + o.put("topicName", topicName); + o.put("topicDescription", topicDescription); + o.put("partitionCount", partitionCount); + o.put("replicationCount", replicationCount); + post(BASE_URI_TOPIC + "/create", o, false); + } + + @Override + public void deleteTopic(String topic) throws HttpException, IOException { + delete(BASE_URI_TOPIC + "/" + MRConstants.escape(topic)); + } + + @Override + public boolean isOpenForProducing(String topic) throws HttpObjectNotFoundException, IOException { + return null == getAllowedProducers(topic); + } + + @Override + public Set getAllowedProducers(String topic) throws HttpObjectNotFoundException, IOException { + return getTopicMetadata(topic).getAllowedProducers(); + } + + @Override + public void allowProducer(String topic, String apiKey) throws HttpObjectNotFoundException, HttpException, IOException { + put(BASE_URI_TOPIC + "/" + MRConstants.escape(topic) + "/producers/" + MRConstants.escape(apiKey), new JSONObject()); + } + + @Override + public void revokeProducer(String topic, String apiKey) throws HttpException, IOException { + delete(BASE_URI_TOPIC + "/" + MRConstants.escape(topic) + "/producers/" + MRConstants.escape(apiKey)); + } + + @Override + public boolean isOpenForConsuming(String topic) throws HttpObjectNotFoundException, IOException { + return null == getAllowedConsumers(topic); + } + + @Override + public Set getAllowedConsumers(String topic) throws HttpObjectNotFoundException, IOException { + return getTopicMetadata(topic).getAllowedConsumers(); + } + + @Override + public void allowConsumer(String topic, String apiKey) throws HttpObjectNotFoundException, HttpException, IOException { + put(BASE_URI_TOPIC + "/" + MRConstants.escape(topic) + "/consumers/" + MRConstants.escape(apiKey), new JSONObject()); + } + + @Override + public void revokeConsumer(String topic, String apiKey) throws HttpException, IOException { + delete(BASE_URI_TOPIC + "/" + MRConstants.escape(topic) + "/consumers/" + MRConstants.escape(apiKey)); + } + + @Override + public ApiCredential createApiKey(String email, String description) throws HttpException, MRApiException, IOException { + try { + final JSONObject o = new JSONObject(); + o.put(PARAM_EMAIL, email); + o.put(PARAM_DESCRIPTION, description); + final JSONObject reply = post(BASE_URI_APIKEY + "/create", o, true); + return new ApiCredential(reply.getString("key"), reply.getString("secret")); + } catch (JSONException e) { + // the response doesn't meet our expectation + throw new MRApiException("The API key response is incomplete.", e); + } + } + + @Override + public ApiKey getApiKey(String apiKey) throws HttpObjectNotFoundException, HttpException, IOException { + final JSONObject keyEntry = get(BASE_URI_APIKEY + "/" + MRConstants.escape(apiKey)); + if (keyEntry == null) { + return null; + } + + return new ApiKey() { + @Override + public String getEmail() { + final JSONObject aux = keyEntry.optJSONObject("aux"); + if (aux != null) { + return aux.optString(PARAM_EMAIL); + } + return null; + } + + @Override + public String getDescription() { + final JSONObject aux = keyEntry.optJSONObject("aux"); + if (aux != null) { + return aux.optString(PARAM_DESCRIPTION); + } + return null; + } + }; + } + + @Override + public void updateCurrentApiKey(String email, String description) throws HttpObjectNotFoundException, HttpException, IOException { + final JSONObject o = new JSONObject(); + if (email != null) { + o.put(PARAM_EMAIL, email); + } + if (description != null) { + o.put(PARAM_DESCRIPTION, description); + } + patch(BASE_URI_APIKEY + "/" + MRConstants.escape(getCurrentApiKey()), o); + } + + @Override + public void deleteCurrentApiKey() throws HttpException, IOException { + delete(BASE_URI_APIKEY + "/" + MRConstants.escape(getCurrentApiKey())); + } } diff --git a/src/main/java/org/onap/dmaap/mr/client/impl/MRSimplerBatchPublisher.java b/src/main/java/org/onap/dmaap/mr/client/impl/MRSimplerBatchPublisher.java index bd140cd..74fec8a 100644 --- a/src/main/java/org/onap/dmaap/mr/client/impl/MRSimplerBatchPublisher.java +++ b/src/main/java/org/onap/dmaap/mr/client/impl/MRSimplerBatchPublisher.java @@ -4,11 +4,13 @@ * ================================================================================ * Copyright © 2017 AT&T Intellectual Property. All rights reserved. * ================================================================================ + * Modifications Copyright © 2021 Orange. + * ================================================================================ * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * http://www.apache.org/licenses/LICENSE-2.0 - * + * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. @@ -17,10 +19,13 @@ * ============LICENSE_END========================================================= * * ECOMP is a trademark and service mark of AT&T Intellectual Property. - * + * *******************************************************************************/ + package org.onap.dmaap.mr.client.impl; +import com.att.aft.dme2.api.DME2Client; +import com.att.aft.dme2.api.DME2Exception; import java.io.ByteArrayOutputStream; import java.io.IOException; import java.io.OutputStream; @@ -33,342 +38,353 @@ import java.util.LinkedList; import java.util.List; import java.util.Map; import java.util.Properties; + import java.util.concurrent.LinkedBlockingQueue; import java.util.concurrent.ScheduledThreadPoolExecutor; import java.util.concurrent.TimeUnit; import java.util.zip.GZIPOutputStream; - import javax.ws.rs.core.MultivaluedMap; - -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; - import org.apache.http.HttpException; import org.apache.http.HttpStatus; import org.json.JSONArray; import org.json.JSONObject; import org.json.JSONTokener; - -import com.att.aft.dme2.api.DME2Client; -import com.att.aft.dme2.api.DME2Exception; import org.onap.dmaap.mr.client.HostSelector; import org.onap.dmaap.mr.client.MRBatchingPublisher; +import org.onap.dmaap.mr.client.ProtocolType; import org.onap.dmaap.mr.client.response.MRPublisherResponse; -import org.onap.dmaap.mr.test.clients.ProtocolTypeConstants; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; public class MRSimplerBatchPublisher extends MRBaseClient implements MRBatchingPublisher { - private static final Logger logger = LoggerFactory.getLogger(MRSimplerBatchPublisher.class); - - private static final String PROPS_PROTOCOL = "Protocol"; - private static final String PROPS_PARTITION = "partition"; - private static final String PROPS_CONTENT_TYPE = "contenttype"; - - private static final String CONTENT_TYPE_CAMBRIA_ZIP = "application/cambria-zip"; - private static final String CONTENT_TYPE_CAMBRIA = "application/cambria"; - private static final String CONTENT_TYPE_JSON = "application/json"; - private static final String CONTENT_TYPE_TEXT = "text/plain"; - - private static final String JSON_STATUS = "status"; - - public static class Builder { - - public Builder againstUrls(Collection baseUrls) { - fUrls = baseUrls; - return this; - } - - public Builder againstUrlsOrServiceName ( Collection baseUrls, Collection serviceName, String transportype ) - { - fUrls = baseUrls; - fServiceName = serviceName; - fTransportype = transportype; - return this; - } - - public Builder onTopic(String topic) { - fTopic = topic; - return this; - } - - public Builder batchTo(int maxBatchSize, long maxBatchAgeMs) { - fMaxBatchSize = maxBatchSize; - fMaxBatchAgeMs = maxBatchAgeMs; - return this; - } - - public Builder compress(boolean compress) { - fCompress = compress; - return this; - } - - public Builder httpThreadTime(int threadOccuranceTime) { - this.threadOccuranceTime = threadOccuranceTime; - return this; - } - - public Builder allowSelfSignedCertificates(boolean allowSelfSignedCerts) { - fAllowSelfSignedCerts = allowSelfSignedCerts; - return this; - } - - public Builder withResponse(boolean withResponse) { - fWithResponse = withResponse; - return this; - } - - public MRSimplerBatchPublisher build() { - if (!fWithResponse) { - try { - return new MRSimplerBatchPublisher(fUrls, fTopic, fMaxBatchSize, fMaxBatchAgeMs, fCompress, - fAllowSelfSignedCerts, threadOccuranceTime); - } catch (MalformedURLException e) { - throw new IllegalArgumentException(e); - } - } else { - try { - return new MRSimplerBatchPublisher(fUrls, fTopic, fMaxBatchSize, fMaxBatchAgeMs, fCompress, - fAllowSelfSignedCerts, fMaxBatchSize); - } catch (MalformedURLException e) { - throw new IllegalArgumentException(e); - } - } - - } - - private Collection fUrls; - private Collection fServiceName; - private String fTransportype; - private String fTopic; - private int fMaxBatchSize = 100; - - private long fMaxBatchAgeMs = 1000; - private boolean fCompress = false; - private int threadOccuranceTime = 50; - private boolean fAllowSelfSignedCerts = false; - private boolean fWithResponse = false; - - }; - - @Override - public int send(String partition, String msg) { - return send(new message(partition, msg)); - } - - @Override - public int send(String msg) { - return send(new message(null, msg)); - } - - @Override - public int send(message msg) { - final LinkedList list = new LinkedList<>(); - list.add(msg); - return send(list); - } - - @Override - public synchronized int send(Collection msgs) { - if (fClosed) { - throw new IllegalStateException("The publisher was closed."); - } - - for (message userMsg : msgs) { - fPending.add(new TimestampedMessage(userMsg)); - } - return getPendingMessageCount(); - } - - @Override - public synchronized int getPendingMessageCount() { - return fPending.size(); - } - - @Override - public void close() { - try { - final List remains = close(Long.MAX_VALUE, TimeUnit.MILLISECONDS); - if (remains.isEmpty()) { - getLog().warn("Closing publisher with {} messages unsent. Consider using MRBatchingPublisher.close( long timeout, TimeUnit timeoutUnits ) to recapture unsent messages on close.", - remains.size()); - } - } catch (InterruptedException e) { - getLog().warn("Possible message loss. " + e.getMessage(), e); - Thread.currentThread().interrupt(); - } catch (IOException e) { - getLog().warn("Possible message loss. " + e.getMessage(), e); - } - } - - @Override - public List close(long time, TimeUnit unit) throws IOException, InterruptedException { - synchronized (this) { - fClosed = true; - - // stop the background sender - fExec.setContinueExistingPeriodicTasksAfterShutdownPolicy(false); - fExec.setExecuteExistingDelayedTasksAfterShutdownPolicy(false); - fExec.shutdown(); - } - - final long now = Clock.now(); - final long waitInMs = TimeUnit.MILLISECONDS.convert(time, unit); - final long timeoutAtMs = now + waitInMs; - - while (Clock.now() < timeoutAtMs && getPendingMessageCount() > 0) { - send(true); - Thread.sleep(250); - } - - synchronized (this) { - final LinkedList result = new LinkedList<>(); - fPending.drainTo(result); - return result; - } - } - - /** - * Possibly send a batch to the MR server. This is called by the background - * thread and the close() method - * - * @param force - */ - private synchronized void send(boolean force) { - if ((force || shouldSendNow()) && !sendBatch()) { - getLog().warn("Send failed, " + fPending.size() + " message to send."); - - // note the time for back-off - fDontSendUntilMs = sfWaitAfterError + Clock.now(); - } - } - - private synchronized boolean shouldSendNow() { - boolean shouldSend = false; - if (fPending.size()>0) { - final long nowMs = Clock.now(); - - shouldSend = (fPending.size() >= fMaxBatchSize); - if (!shouldSend) { - final long sendAtMs = fPending.peek().timestamp + fMaxBatchAgeMs; - shouldSend = sendAtMs <= nowMs; - } - - // however, wait after an error - shouldSend = shouldSend && nowMs >= fDontSendUntilMs; - } - return shouldSend; - } - - /** - * Method to parse published JSON Objects and Arrays - * - * @return JSONArray - */ - private JSONArray parseJSON() { - JSONArray jsonArray = new JSONArray(); - for (TimestampedMessage m : fPending) { - JSONTokener jsonTokener = new JSONTokener(m.fMsg); - JSONObject jsonObject = null; - JSONArray tempjsonArray = null; - final char firstChar = jsonTokener.next(); - jsonTokener.back(); - if ('[' == firstChar) { - tempjsonArray = new JSONArray(jsonTokener); - if (null != tempjsonArray) { - for (int i = 0; i < tempjsonArray.length(); i++) { - jsonArray.put(tempjsonArray.getJSONObject(i)); - } - } - } else { - jsonObject = new JSONObject(jsonTokener); - jsonArray.put(jsonObject); - } - - } - return jsonArray; - } - - private void logTime(long startMs, String dmeResponse) { - if (getLog().isInfoEnabled()) { - getLog().info("MR reply ok (" + (Clock.now() - startMs) + " ms):" + dmeResponse); - } - } - - private synchronized boolean sendBatch() { - // it's possible for this call to be made with an empty list. in this - // case, just return. - if (fPending.isEmpty()) { - return true; - } - - final long nowMs = Clock.now(); - - if (this.fHostSelector != null) { - host = this.fHostSelector.selectBaseHost(); - } - - final String httpurl = MRConstants.makeUrl(host, fTopic, props.getProperty(PROPS_PROTOCOL), - props.getProperty(PROPS_PARTITION)); - - try { - - final ByteArrayOutputStream baseStream = new ByteArrayOutputStream(); - OutputStream os = baseStream; - final String contentType = props.getProperty(PROPS_CONTENT_TYPE); - if (contentType.equalsIgnoreCase(CONTENT_TYPE_JSON)) { - JSONArray jsonArray = parseJSON(); - os.write(jsonArray.toString().getBytes()); - os.close(); - - } else if (contentType.equalsIgnoreCase(CONTENT_TYPE_TEXT)) { - for (TimestampedMessage m : fPending) { - os.write(m.fMsg.getBytes()); - os.write('\n'); - } - os.close(); - } else if (contentType.equalsIgnoreCase(CONTENT_TYPE_CAMBRIA) - || (contentType.equalsIgnoreCase(CONTENT_TYPE_CAMBRIA_ZIP))) { - if (contentType.equalsIgnoreCase(CONTENT_TYPE_CAMBRIA_ZIP)) { - os = new GZIPOutputStream(baseStream); - } - for (TimestampedMessage m : fPending) { - - os.write(("" + m.fPartition.length()).getBytes()); - os.write('.'); - os.write(("" + m.fMsg.length()).getBytes()); - os.write('.'); - os.write(m.fPartition.getBytes()); - os.write(m.fMsg.getBytes()); - os.write('\n'); - } - os.close(); - } else { - for (TimestampedMessage m : fPending) { - os.write(m.fMsg.getBytes()); - - } - os.close(); - } - - final long startMs = Clock.now(); - if (ProtocolTypeConstants.DME2.getValue().equalsIgnoreCase(protocolFlag)) { - - DME2Configue(); - - this.wait(5); - getLog().info(String - .format("sending %d msgs to %s%s. Oldest: %d ms", fPending.size(), url, subContextPath, - nowMs - fPending.peek().timestamp)); - sender.setPayload(os.toString()); - String dmeResponse = sender.sendAndWait(5000L); - - logTime(startMs, dmeResponse); - fPending.clear(); - return true; - } - - if (ProtocolTypeConstants.AUTH_KEY.getValue().equalsIgnoreCase(protocolFlag)) { - getLog().info("sending {} msgs to {}. Oldest: {} ms", fPending.size(), httpurl, - nowMs - fPending.peek().timestamp); + private static final Logger logger = LoggerFactory.getLogger(MRSimplerBatchPublisher.class); + + private static final String PASSWORD = "password"; + private static final String USERNAME = "username"; + private static final String DME2PREFERRED_ROUTER_FILE_PATH = "DME2preferredRouterFilePath"; + private static final String SERVICE_NAME = "ServiceName"; + private static final String PARTNER = "Partner"; + private static final String ROUTE_OFFER = "routeOffer"; + private static final String PROTOCOL = "Protocol"; + private static final String METHOD_TYPE = "MethodType"; + private static final String CONTENT_TYPE = "contenttype"; + private static final String LATITUDE = "Latitude"; + private static final String LONGITUDE = "Longitude"; + private static final String AFT_ENVIRONMENT = "AFT_ENVIRONMENT"; + private static final String VERSION = "Version"; + private static final String ENVIRONMENT = "Environment"; + private static final String SUB_CONTEXT_PATH = "SubContextPath"; + private static final String SESSION_STICKINESS_REQUIRED = "sessionstickinessrequired"; + private static final String PARTITION = "partition"; + private static final String AFT_DME2_EP_READ_TIMEOUT_MS = "AFT_DME2_EP_READ_TIMEOUT_MS"; + private static final String AFT_DME2_ROUNDTRIP_TIMEOUT_MS = "AFT_DME2_ROUNDTRIP_TIMEOUT_MS"; + private static final String AFT_DME2_EP_CONN_TIMEOUT = "AFT_DME2_EP_CONN_TIMEOUT"; + private static final String AFT_DME2_EXCHANGE_REQUEST_HANDLERS = "AFT_DME2_EXCHANGE_REQUEST_HANDLERS"; + private static final String AFT_DME2_EXCHANGE_REPLY_HANDLERS = "AFT_DME2_EXCHANGE_REPLY_HANDLERS"; + private static final String AFT_DME2_REQ_TRACE_ON = "AFT_DME2_REQ_TRACE_ON"; + + private static final String CONTENT_TYPE_TEXT = "text/plain"; + + private static final String JSON_STATUS = "status"; + + public static class Builder { + + public Builder againstUrls(Collection baseUrls) { + fUrls = baseUrls; + return this; + } + + public Builder againstUrlsOrServiceName(Collection baseUrls, Collection serviceName, String transportype) { + fUrls = baseUrls; + return this; + } + + public Builder onTopic(String topic) { + fTopic = topic; + return this; + } + + public Builder batchTo(int maxBatchSize, long maxBatchAgeMs) { + fMaxBatchSize = maxBatchSize; + fMaxBatchAgeMs = maxBatchAgeMs; + return this; + } + + public Builder compress(boolean compress) { + fCompress = compress; + return this; + } + + public Builder httpThreadTime(int threadOccurrenceTime) { + this.threadOccurrenceTime = threadOccurrenceTime; + return this; + } + + public Builder allowSelfSignedCertificates(boolean allowSelfSignedCerts) { + fAllowSelfSignedCerts = allowSelfSignedCerts; + return this; + } + + public Builder withResponse(boolean withResponse) { + fWithResponse = withResponse; + return this; + } + + public MRSimplerBatchPublisher build() { + if (!fWithResponse) { + try { + return new MRSimplerBatchPublisher(fUrls, fTopic, fMaxBatchSize, fMaxBatchAgeMs, fCompress, + fAllowSelfSignedCerts, threadOccurrenceTime); + } catch (MalformedURLException e) { + throw new IllegalArgumentException(e); + } + } else { + try { + return new MRSimplerBatchPublisher(fUrls, fTopic, fMaxBatchSize, fMaxBatchAgeMs, fCompress, + fAllowSelfSignedCerts, fMaxBatchSize); + } catch (MalformedURLException e) { + throw new IllegalArgumentException(e); + } + } + + } + + private Collection fUrls; + private String fTopic; + private int fMaxBatchSize = 100; + + private long fMaxBatchAgeMs = 1000; + private boolean fCompress = false; + private int threadOccurrenceTime = 50; + private boolean fAllowSelfSignedCerts = false; + private boolean fWithResponse = false; + + } + + @Override + public int send(String partition, String msg) { + return send(new Message(partition, msg)); + } + + @Override + public int send(String msg) { + return send(new Message(null, msg)); + } + + @Override + public int send(Message msg) { + final LinkedList list = new LinkedList<>(); + list.add(msg); + return send(list); + } + + @Override + public synchronized int send(Collection msgs) { + if (fClosed) { + throw new IllegalStateException("The publisher was closed."); + } + + for (Message userMsg : msgs) { + fPending.add(new TimestampedMessage(userMsg)); + } + return getPendingMessageCount(); + } + + @Override + public synchronized int getPendingMessageCount() { + return fPending.size(); + } + + @Override + public void close() { + try { + final List remains = close(Long.MAX_VALUE, TimeUnit.MILLISECONDS); + if (remains.isEmpty()) { + getLog().warn("Closing publisher with {} messages unsent. Consider using MRBatchingPublisher.close( long timeout, TimeUnit timeoutUnits ) to recapture unsent messages on close.", + remains.size()); + } + } catch (InterruptedException e) { + getLog().warn("Possible message loss. " + e.getMessage(), e); + Thread.currentThread().interrupt(); + } catch (IOException e) { + getLog().warn("Possible message loss. " + e.getMessage(), e); + } + } + + @Override + public List close(long time, TimeUnit unit) throws IOException, InterruptedException { + synchronized (this) { + fClosed = true; + + // stop the background sender + fExec.setContinueExistingPeriodicTasksAfterShutdownPolicy(false); + fExec.setExecuteExistingDelayedTasksAfterShutdownPolicy(false); + fExec.shutdown(); + } + + final long now = Clock.now(); + final long waitInMs = TimeUnit.MILLISECONDS.convert(time, unit); + final long timeoutAtMs = now + waitInMs; + + while (Clock.now() < timeoutAtMs && getPendingMessageCount() > 0) { + send(true); + Thread.sleep(250); + } + + synchronized (this) { + final LinkedList result = new LinkedList<>(); + fPending.drainTo(result); + return result; + } + } + + /** + * Possibly send a batch to the MR server. This is called by the background + * thread and the close() method + * + * @param force + */ + private synchronized void send(boolean force) { + if ((force || shouldSendNow()) && !sendBatch()) { + getLog().warn("Send failed, {} message to send.", fPending.size()); + // note the time for back-off + fDontSendUntilMs = SF_WAIT_AFTER_ERROR + Clock.now(); + } + } + + private synchronized boolean shouldSendNow() { + boolean shouldSend = false; + if (!fPending.isEmpty()) { + final long nowMs = Clock.now(); + + shouldSend = (fPending.size() >= fMaxBatchSize); + if (!shouldSend) { + final long sendAtMs = fPending.peek().timestamp + fMaxBatchAgeMs; + shouldSend = sendAtMs <= nowMs; + } + + // however, wait after an error + shouldSend = shouldSend && nowMs >= fDontSendUntilMs; + } + return shouldSend; + } + + /** + * Method to parse published JSON Objects and Arrays. + * + * @return JSONArray + */ + private JSONArray parseJSON() { + JSONArray jsonArray = new JSONArray(); + for (TimestampedMessage m : fPending) { + JSONTokener jsonTokener = new JSONTokener(m.fMsg); + JSONObject jsonObject = null; + JSONArray tempjsonArray = null; + final char firstChar = jsonTokener.next(); + jsonTokener.back(); + if ('[' == firstChar) { + tempjsonArray = new JSONArray(jsonTokener); + for (int i = 0; i < tempjsonArray.length(); i++) { + jsonArray.put(tempjsonArray.getJSONObject(i)); + } + } else { + jsonObject = new JSONObject(jsonTokener); + jsonArray.put(jsonObject); + } + + } + return jsonArray; + } + + private void logTime(long startMs, String dmeResponse) { + if (getLog().isInfoEnabled()) { + getLog().info("MR reply ok ({} ms):{}", (Clock.now() - startMs), dmeResponse); + } + } + + private void logSendMessage(int nbMessage, String dest, long time) { + if (getLog().isInfoEnabled()) { + getLog().info("sending {} msgs to {}. Oldest: {} ms", nbMessage, dest, time); + } + } + + private synchronized boolean sendBatch() { + // it's possible for this call to be made with an empty list. in this + // case, just return. + if (fPending.isEmpty()) { + return true; + } + + final long nowMs = Clock.now(); + + if (this.fHostSelector != null) { + host = this.fHostSelector.selectBaseHost(); + } + + final String httpurl = MRConstants.makeUrl(host, fTopic, props.getProperty(PROTOCOL), + props.getProperty(PARTITION)); + + try { + + final ByteArrayOutputStream baseStream = new ByteArrayOutputStream(); + OutputStream os = baseStream; + final String contentType = props.getProperty(CONTENT_TYPE); + if (contentType.equalsIgnoreCase(MRFormat.JSON.toString())) { + JSONArray jsonArray = parseJSON(); + os.write(jsonArray.toString().getBytes()); + os.close(); + + } else if (contentType.equalsIgnoreCase(CONTENT_TYPE_TEXT)) { + for (TimestampedMessage m : fPending) { + os.write(m.fMsg.getBytes()); + os.write('\n'); + } + os.close(); + } else if (contentType.equalsIgnoreCase(MRFormat.CAMBRIA.toString()) + || (contentType.equalsIgnoreCase(MRFormat.CAMBRIA_ZIP.toString()))) { + if (contentType.equalsIgnoreCase(MRFormat.CAMBRIA_ZIP.toString())) { + os = new GZIPOutputStream(baseStream); + } + for (TimestampedMessage m : fPending) { + + os.write(("" + m.fPartition.length()).getBytes()); + os.write('.'); + os.write(("" + m.fMsg.length()).getBytes()); + os.write('.'); + os.write(m.fPartition.getBytes()); + os.write(m.fMsg.getBytes()); + os.write('\n'); + } + os.close(); + } else { + for (TimestampedMessage m : fPending) { + os.write(m.fMsg.getBytes()); + + } + os.close(); + } + + final long startMs = Clock.now(); + if (ProtocolType.DME2.getValue().equalsIgnoreCase(protocolFlag)) { + + configureDME2(); + + this.wait(5); + if (fPending.peek() != null) { + logSendMessage(fPending.size(), url + subContextPath, nowMs - fPending.peek().timestamp); + } + sender.setPayload(os.toString()); + String dmeResponse = sender.sendAndWait(5000L); + + logTime(startMs, dmeResponse); + fPending.clear(); + return true; + } + + if (ProtocolType.AUTH_KEY.getValue().equalsIgnoreCase(protocolFlag)) { + if (fPending.peek() != null) { + logSendMessage(fPending.size(), httpurl, nowMs - fPending.peek().timestamp); + } final JSONObject result = postAuth(new PostAuthDataObject().setPath(httpurl).setData(baseStream.toByteArray()) .setContentType(contentType).setAuthKey(authKey).setAuthDate(authDate) @@ -379,550 +395,563 @@ public class MRSimplerBatchPublisher extends MRBaseClient implements MRBatchingP if (result.getInt(JSON_STATUS) < 200 || result.getInt(JSON_STATUS) > 299) { return false; } - logTime(startMs, result.toString()); + logTime(startMs, result.toString()); fPending.clear(); return true; } - if (ProtocolTypeConstants.AAF_AUTH.getValue().equalsIgnoreCase(protocolFlag)) { - getLog().info("sending {} msgs to {}. Oldest: {} ms", fPending.size(), httpurl, - nowMs - fPending.peek().timestamp); - final JSONObject result = post(httpurl, baseStream.toByteArray(), contentType, username, password, - protocolFlag); - - // Here we are checking for error response. If HTTP status - // code is not within the http success response code - // then we consider this as error and return false - if (result.getInt(JSON_STATUS) < 200 || result.getInt(JSON_STATUS) > 299) { - return false; - } - logTime(startMs, result.toString()); - fPending.clear(); - return true; - } - - if (ProtocolTypeConstants.HTTPNOAUTH.getValue().equalsIgnoreCase(protocolFlag)) { - getLog().info("sending {} msgs to {}. Oldest: {} ms", fPending.size(), httpurl, - nowMs - fPending.peek().timestamp); - final JSONObject result = postNoAuth(httpurl, baseStream.toByteArray(), contentType); - - // Here we are checking for error response. If HTTP status - // code is not within the http success response code - // then we consider this as error and return false - if (result.getInt(JSON_STATUS) < 200 || result.getInt(JSON_STATUS) > 299) { - return false; - } - logTime(startMs, result.toString()); - fPending.clear(); - return true; - } - } catch (Exception x) { - getLog().warn(x.getMessage(), x); - } - return false; - } - - public synchronized MRPublisherResponse sendBatchWithResponse() { - // it's possible for this call to be made with an empty list. in this - // case, just return. - if (fPending.isEmpty()) { - pubResponse.setResponseCode(String.valueOf(HttpStatus.SC_BAD_REQUEST)); - pubResponse.setResponseMessage("No Messages to send"); - return pubResponse; - } - - final long nowMs = Clock.now(); - - host = this.fHostSelector.selectBaseHost(); - - final String httpurl = MRConstants.makeUrl(host, fTopic, props.getProperty(PROPS_PROTOCOL), - props.getProperty(PROPS_PARTITION)); - OutputStream os = null; - try { - - final ByteArrayOutputStream baseStream = new ByteArrayOutputStream(); - os = baseStream; - final String contentType = props.getProperty(PROPS_CONTENT_TYPE); - if (contentType.equalsIgnoreCase(CONTENT_TYPE_JSON)) { - JSONArray jsonArray = parseJSON(); - os.write(jsonArray.toString().getBytes()); - } else if (contentType.equalsIgnoreCase(CONTENT_TYPE_TEXT)) { - for (TimestampedMessage m : fPending) { - os.write(m.fMsg.getBytes()); - os.write('\n'); - } - } else if (contentType.equalsIgnoreCase(CONTENT_TYPE_CAMBRIA) - || (contentType.equalsIgnoreCase(CONTENT_TYPE_CAMBRIA_ZIP))) { - if (contentType.equalsIgnoreCase(CONTENT_TYPE_CAMBRIA_ZIP)) { - os = new GZIPOutputStream(baseStream); - } - for (TimestampedMessage m : fPending) { - - os.write(("" + m.fPartition.length()).getBytes()); - os.write('.'); - os.write(("" + m.fMsg.length()).getBytes()); - os.write('.'); - os.write(m.fPartition.getBytes()); - os.write(m.fMsg.getBytes()); - os.write('\n'); - } - os.close(); - } else { - for (TimestampedMessage m : fPending) { - os.write(m.fMsg.getBytes()); - - } - } - - final long startMs = Clock.now(); - if (ProtocolTypeConstants.DME2.getValue().equalsIgnoreCase(protocolFlag)) { - - try { - DME2Configue(); - - this.wait(5); - getLog().info("sending {} msgs to {}{}. Oldest: {} ms", fPending.size(), url, subContextPath, - nowMs - fPending.peek().timestamp); - sender.setPayload(os.toString()); - - String dmeResponse = sender.sendAndWait(5000L); - - pubResponse = createMRPublisherResponse(dmeResponse, pubResponse); - - if (Integer.valueOf(pubResponse.getResponseCode()) < 200 - || Integer.valueOf(pubResponse.getResponseCode()) > 299) { - - return pubResponse; - } - final String logLine = String.valueOf((Clock.now() - startMs)) + dmeResponse.toString(); - getLog().info(logLine); - fPending.clear(); - - } catch (DME2Exception x) { - getLog().warn(x.getMessage(), x); - pubResponse.setResponseCode(x.getErrorCode()); - pubResponse.setResponseMessage(x.getErrorMessage()); - } catch (URISyntaxException x) { - - getLog().warn(x.getMessage(), x); - pubResponse.setResponseCode(String.valueOf(HttpStatus.SC_BAD_REQUEST)); - pubResponse.setResponseMessage(x.getMessage()); - } catch (Exception x) { - - pubResponse.setResponseCode(String.valueOf(HttpStatus.SC_INTERNAL_SERVER_ERROR)); - pubResponse.setResponseMessage(x.getMessage()); - logger.error("exception: ", x); - - } - - return pubResponse; - } - - if (ProtocolTypeConstants.AUTH_KEY.getValue().equalsIgnoreCase(protocolFlag)) { - getLog().info("sending {} msgs to {}. Oldest: {} ms", fPending.size(), httpurl, - nowMs - fPending.peek().timestamp); - final String result = postAuthwithResponse(httpurl, baseStream.toByteArray(), contentType, authKey, - authDate, username, password, protocolFlag); - // Here we are checking for error response. If HTTP status - // code is not within the http success response code - // then we consider this as error and return false - - pubResponse = createMRPublisherResponse(result, pubResponse); - - if (Integer.valueOf(pubResponse.getResponseCode()) < 200 - || Integer.valueOf(pubResponse.getResponseCode()) > 299) { - - return pubResponse; - } - - logTime(startMs, result); - fPending.clear(); - return pubResponse; - } - - if (ProtocolTypeConstants.AAF_AUTH.getValue().equalsIgnoreCase(protocolFlag)) { - getLog().info("sending {} msgs to {}. Oldest: {} ms", fPending.size(), httpurl, - nowMs - fPending.peek().timestamp); - final String result = postWithResponse(httpurl, baseStream.toByteArray(), contentType, username, - password, protocolFlag); - - // Here we are checking for error response. If HTTP status - // code is not within the http success response code - // then we consider this as error and return false - pubResponse = createMRPublisherResponse(result, pubResponse); - - if (Integer.valueOf(pubResponse.getResponseCode()) < 200 - || Integer.valueOf(pubResponse.getResponseCode()) > 299) { - - return pubResponse; - } - - final String logLine = String.valueOf((Clock.now() - startMs)); - getLog().info(logLine); - fPending.clear(); - return pubResponse; - } - - if (ProtocolTypeConstants.HTTPNOAUTH.getValue().equalsIgnoreCase(protocolFlag)) { - getLog().info("sending {} msgs to {}. Oldest: {} ms", fPending.size(), httpurl, - nowMs - fPending.peek().timestamp); - final String result = postNoAuthWithResponse(httpurl, baseStream.toByteArray(), contentType); - - // Here we are checking for error response. If HTTP status - // code is not within the http success response code - // then we consider this as error and return false - pubResponse = createMRPublisherResponse(result, pubResponse); - - if (Integer.valueOf(pubResponse.getResponseCode()) < 200 - || Integer.valueOf(pubResponse.getResponseCode()) > 299) { - - return pubResponse; - } - - final String logLine = String.valueOf((Clock.now() - startMs)); - getLog().info(logLine); - fPending.clear(); - return pubResponse; - } - } catch (IllegalArgumentException | HttpException x) { - getLog().warn(x.getMessage(), x); - pubResponse.setResponseCode(String.valueOf(HttpStatus.SC_BAD_REQUEST)); - pubResponse.setResponseMessage(x.getMessage()); - - } catch (IOException x) { - getLog().warn(x.getMessage(), x); - pubResponse.setResponseCode(String.valueOf(HttpStatus.SC_INTERNAL_SERVER_ERROR)); - pubResponse.setResponseMessage(x.getMessage()); - } catch (Exception x) { - getLog().warn(x.getMessage(), x); - - pubResponse.setResponseCode(String.valueOf(HttpStatus.SC_INTERNAL_SERVER_ERROR)); - pubResponse.setResponseMessage(x.getMessage()); - - } - - finally { - if (!fPending.isEmpty()) { - getLog().warn("Send failed, " + fPending.size() + " message to send."); - pubResponse.setPendingMsgs(fPending.size()); - } - if (os != null) { - try { - os.close(); - } catch (Exception x) { - getLog().warn(x.getMessage(), x); - pubResponse.setResponseCode(String.valueOf(HttpStatus.SC_INTERNAL_SERVER_ERROR)); - pubResponse.setResponseMessage("Error in closing Output Stream"); - } - } - } - - return pubResponse; - } - - public MRPublisherResponse createMRPublisherResponse(String reply, MRPublisherResponse mrPubResponse) { - - if (reply.isEmpty()) { - - mrPubResponse.setResponseCode(String.valueOf(HttpStatus.SC_BAD_REQUEST)); - mrPubResponse.setResponseMessage("Please verify the Producer properties"); - } else if (reply.startsWith("{")) { - JSONObject jObject = new JSONObject(reply); - if (jObject.has("message") && jObject.has(JSON_STATUS)) { - String message = jObject.getString("message"); - if (null != message) { - mrPubResponse.setResponseMessage(message); - } - mrPubResponse.setResponseCode(Integer.toString(jObject.getInt(JSON_STATUS))); - } else { - mrPubResponse.setResponseCode(String.valueOf(HttpStatus.SC_OK)); - mrPubResponse.setResponseMessage(reply); - } - } else if (reply.startsWith("<")) { - String responseCode = getHTTPErrorResponseCode(reply); - if (responseCode.contains("403")) { - responseCode = "403"; - } - mrPubResponse.setResponseCode(responseCode); - mrPubResponse.setResponseMessage(getHTTPErrorResponseMessage(reply)); - } - - return mrPubResponse; - } - - private final String fTopic; - private final int fMaxBatchSize; - private final long fMaxBatchAgeMs; - private final boolean fCompress; - private int threadOccuranceTime; - private boolean fClosed; - private String username; - private String password; - private String host; - - // host selector - private HostSelector fHostSelector = null; - - private final LinkedBlockingQueue fPending; - private long fDontSendUntilMs; - private final ScheduledThreadPoolExecutor fExec; - - private String latitude; - private String longitude; - private String version; - private String serviceName; - private String env; - private String partner; - private String routeOffer; - private String subContextPath; - private String protocol; - private String methodType; - private String url; - private String dmeuser; - private String dmepassword; - private String contentType; - private static final long sfWaitAfterError = 10000; - private HashMap DMETimeOuts; - private DME2Client sender; - public String protocolFlag = ProtocolTypeConstants.DME2.getValue(); - private String authKey; - private String authDate; - private String handlers; - private Properties props; - public static String routerFilePath; - protected static final Map headers = new HashMap(); - public static MultivaluedMap headersMap; - - private MRPublisherResponse pubResponse; - - public MRPublisherResponse getPubResponse() { - return pubResponse; - } - - public void setPubResponse(MRPublisherResponse pubResponse) { - this.pubResponse = pubResponse; - } - - public static String getRouterFilePath() { - return routerFilePath; - } - - public static void setRouterFilePath(String routerFilePath) { - MRSimplerBatchPublisher.routerFilePath = routerFilePath; - } - - public Properties getProps() { - return props; - } - - public void setProps(Properties props) { - this.props = props; - setClientConfig(DmaapClientUtil.getClientConfig(props)); - } - - public String getProtocolFlag() { - return protocolFlag; - } - - public void setProtocolFlag(String protocolFlag) { - this.protocolFlag = protocolFlag; - } - - private void DME2Configue() throws Exception { - try { - - latitude = props.getProperty("Latitude"); - longitude = props.getProperty("Longitude"); - version = props.getProperty("Version"); - serviceName = props.getProperty("ServiceName"); - env = props.getProperty("Environment"); - partner = props.getProperty("Partner"); - routeOffer = props.getProperty("routeOffer"); - subContextPath = props.getProperty("SubContextPath") + fTopic; - - protocol = props.getProperty(PROPS_PROTOCOL); - methodType = props.getProperty("MethodType"); - dmeuser = props.getProperty("username"); - dmepassword = props.getProperty("password"); - contentType = props.getProperty(PROPS_CONTENT_TYPE); - handlers = props.getProperty("sessionstickinessrequired"); - routerFilePath = props.getProperty("DME2preferredRouterFilePath"); - - /** - * Changes to DME2Client url to use Partner for auto failover - * between data centers When Partner value is not provided use the - * routeOffer value for auto failover within a cluster - */ - - String partitionKey = props.getProperty(PROPS_PARTITION); - - if (partner != null && !partner.isEmpty()) { - url = protocol + "://" + serviceName + "?version=" + version + "&envContext=" + env + "&partner=" - + partner; - if (partitionKey != null && !partitionKey.equalsIgnoreCase("")) { - url = url + "&partitionKey=" + partitionKey; - } - } else if (routeOffer != null && !routeOffer.isEmpty()) { - url = protocol + "://" + serviceName + "?version=" + version + "&envContext=" + env + "&routeoffer=" - + routeOffer; - if (partitionKey != null && !partitionKey.equalsIgnoreCase("")) { - url = url + "&partitionKey=" + partitionKey; - } - } - - DMETimeOuts = new HashMap(); - DMETimeOuts.put("AFT_DME2_EP_READ_TIMEOUT_MS", props.getProperty("AFT_DME2_EP_READ_TIMEOUT_MS")); - DMETimeOuts.put("AFT_DME2_ROUNDTRIP_TIMEOUT_MS", props.getProperty("AFT_DME2_ROUNDTRIP_TIMEOUT_MS")); - DMETimeOuts.put("AFT_DME2_EP_CONN_TIMEOUT", props.getProperty("AFT_DME2_EP_CONN_TIMEOUT")); - DMETimeOuts.put("Content-Type", contentType); - System.setProperty("AFT_LATITUDE", latitude); - System.setProperty("AFT_LONGITUDE", longitude); - System.setProperty("AFT_ENVIRONMENT", props.getProperty("AFT_ENVIRONMENT")); - // System.setProperty("DME2.DEBUG", "true"); - - // SSL changes - // System.setProperty("AFT_DME2_CLIENT_SSL_INCLUDE_PROTOCOLS", - - System.setProperty("AFT_DME2_CLIENT_SSL_INCLUDE_PROTOCOLS", "TLSv1.1,TLSv1.2"); - System.setProperty("AFT_DME2_CLIENT_IGNORE_SSL_CONFIG", "false"); - System.setProperty("AFT_DME2_CLIENT_KEYSTORE_PASSWORD", "changeit"); - - // SSL changes - - sender = new DME2Client(new URI(url), 5000L); - - sender.setAllowAllHttpReturnCodes(true); - sender.setMethod(methodType); - sender.setSubContext(subContextPath); - sender.setCredentials(dmeuser, dmepassword); - sender.setHeaders(DMETimeOuts); - if (handlers != null &&handlers.equalsIgnoreCase("yes")) { - sender.addHeader("AFT_DME2_EXCHANGE_REQUEST_HANDLERS", - props.getProperty("AFT_DME2_EXCHANGE_REQUEST_HANDLERS")); - sender.addHeader("AFT_DME2_EXCHANGE_REPLY_HANDLERS", - props.getProperty("AFT_DME2_EXCHANGE_REPLY_HANDLERS")); - sender.addHeader("AFT_DME2_REQ_TRACE_ON", props.getProperty("AFT_DME2_REQ_TRACE_ON")); - } else { - sender.addHeader("AFT_DME2_EXCHANGE_REPLY_HANDLERS", "com.att.nsa.mr.dme.client.HeaderReplyHandler"); - } - } catch (DME2Exception x) { - getLog().warn(x.getMessage(), x); - throw new DME2Exception(x.getErrorCode(), x.getErrorMessage()); - } catch (URISyntaxException x) { - - getLog().warn(x.getMessage(), x); - throw new URISyntaxException(url, x.getMessage()); - } catch (Exception x) { - - getLog().warn(x.getMessage(), x); - throw new IllegalArgumentException(x.getMessage()); - } - } - - private MRSimplerBatchPublisher(Collection hosts, String topic, int maxBatchSize, long maxBatchAgeMs, - boolean compress) throws MalformedURLException { - super(hosts); - - if (topic == null || topic.length() < 1) { - throw new IllegalArgumentException("A topic must be provided."); - } - - fHostSelector = new HostSelector(hosts, null); - fClosed = false; - fTopic = topic; - fMaxBatchSize = maxBatchSize; - fMaxBatchAgeMs = maxBatchAgeMs; - fCompress = compress; - - fPending = new LinkedBlockingQueue<>(); - fDontSendUntilMs = 0; - fExec = new ScheduledThreadPoolExecutor(1); - pubResponse = new MRPublisherResponse(); - - } - - private MRSimplerBatchPublisher(Collection hosts, String topic, int maxBatchSize, long maxBatchAgeMs, - boolean compress, boolean allowSelfSignedCerts, int httpThreadOccurnace) throws MalformedURLException { - super(hosts); - - if (topic == null || topic.length() < 1) { - throw new IllegalArgumentException("A topic must be provided."); - } - - fHostSelector = new HostSelector(hosts, null); - fClosed = false; - fTopic = topic; - fMaxBatchSize = maxBatchSize; - fMaxBatchAgeMs = maxBatchAgeMs; - fCompress = compress; - threadOccuranceTime = httpThreadOccurnace; - fPending = new LinkedBlockingQueue<>(); - fDontSendUntilMs = 0; - fExec = new ScheduledThreadPoolExecutor(1); - fExec.scheduleAtFixedRate(new Runnable() { - @Override - public void run() { - send(false); - } - }, 100, threadOccuranceTime, TimeUnit.MILLISECONDS); - pubResponse = new MRPublisherResponse(); - } - - private static class TimestampedMessage extends message { - public TimestampedMessage(message m) { - super(m); - timestamp = Clock.now(); - } - - public final long timestamp; - } - - public String getUsername() { - return username; - } - - public void setUsername(String username) { - this.username = username; - } - - public String getPassword() { - return password; - } - - public void setPassword(String password) { - this.password = password; - } - - public String getHost() { - return host; - } - - public void setHost(String host) { - this.host = host; - } - - public String getContentType() { - return contentType; - } - - public void setContentType(String contentType) { - this.contentType = contentType; - } - - public String getAuthKey() { - return authKey; - } - - public void setAuthKey(String authKey) { - this.authKey = authKey; - } - - public String getAuthDate() { - return authDate; - } - - public void setAuthDate(String authDate) { - this.authDate = authDate; - } + if (ProtocolType.AAF_AUTH.getValue().equalsIgnoreCase(protocolFlag)) { + if (fPending.peek() != null) { + logSendMessage(fPending.size(), httpurl, nowMs - fPending.peek().timestamp); + } + final JSONObject result = post(httpurl, baseStream.toByteArray(), contentType, username, password, + protocolFlag); + + // Here we are checking for error response. If HTTP status + // code is not within the http success response code + // then we consider this as error and return false + if (result.getInt(JSON_STATUS) < 200 || result.getInt(JSON_STATUS) > 299) { + return false; + } + logTime(startMs, result.toString()); + fPending.clear(); + return true; + } + + if (ProtocolType.HTTPNOAUTH.getValue().equalsIgnoreCase(protocolFlag)) { + if (fPending.peek() != null) { + logSendMessage(fPending.size(), httpurl, nowMs - fPending.peek().timestamp); + } + final JSONObject result = postNoAuth(httpurl, baseStream.toByteArray(), contentType); + + // Here we are checking for error response. If HTTP status + // code is not within the http success response code + // then we consider this as error and return false + if (result.getInt(JSON_STATUS) < 200 || result.getInt(JSON_STATUS) > 299) { + return false; + } + logTime(startMs, result.toString()); + fPending.clear(); + return true; + } + } catch (InterruptedException e) { + getLog().warn("Interrupted!", e); + // Restore interrupted state... + Thread.currentThread().interrupt(); + } catch (Exception x) { + getLog().warn(x.getMessage(), x); + } + return false; + } + + public synchronized MRPublisherResponse sendBatchWithResponse() { + // it's possible for this call to be made with an empty list. in this + // case, just return. + if (fPending.isEmpty()) { + pubResponse.setResponseCode(String.valueOf(HttpStatus.SC_BAD_REQUEST)); + pubResponse.setResponseMessage("No Messages to send"); + return pubResponse; + } + + final long nowMs = Clock.now(); + + host = this.fHostSelector.selectBaseHost(); + + final String httpUrl = MRConstants.makeUrl(host, fTopic, props.getProperty(PROTOCOL), + props.getProperty(PARTITION)); + OutputStream os = null; + try (ByteArrayOutputStream baseStream = new ByteArrayOutputStream()) { + os = baseStream; + final String propsContentType = props.getProperty(CONTENT_TYPE); + if (propsContentType.equalsIgnoreCase(MRFormat.JSON.toString())) { + JSONArray jsonArray = parseJSON(); + os.write(jsonArray.toString().getBytes()); + } else if (propsContentType.equalsIgnoreCase(CONTENT_TYPE_TEXT)) { + for (TimestampedMessage m : fPending) { + os.write(m.fMsg.getBytes()); + os.write('\n'); + } + } else if (propsContentType.equalsIgnoreCase(MRFormat.CAMBRIA.toString()) + || (propsContentType.equalsIgnoreCase(MRFormat.CAMBRIA_ZIP.toString()))) { + if (propsContentType.equalsIgnoreCase(MRFormat.CAMBRIA_ZIP.toString())) { + os = new GZIPOutputStream(baseStream); + } + for (TimestampedMessage m : fPending) { + os.write(("" + m.fPartition.length()).getBytes()); + os.write('.'); + os.write(("" + m.fMsg.length()).getBytes()); + os.write('.'); + os.write(m.fPartition.getBytes()); + os.write(m.fMsg.getBytes()); + os.write('\n'); + } + os.close(); + } else { + for (TimestampedMessage m : fPending) { + os.write(m.fMsg.getBytes()); + + } + } + + final long startMs = Clock.now(); + if (ProtocolType.DME2.getValue().equalsIgnoreCase(protocolFlag)) { + + try { + configureDME2(); + + this.wait(5); + + if (fPending.peek() != null) { + logSendMessage(fPending.size(), url + subContextPath, nowMs - fPending.peek().timestamp); + } + sender.setPayload(os.toString()); + + String dmeResponse = sender.sendAndWait(5000L); + + pubResponse = createMRPublisherResponse(dmeResponse, pubResponse); + + if (Integer.parseInt(pubResponse.getResponseCode()) < 200 + || Integer.parseInt(pubResponse.getResponseCode()) > 299) { + + return pubResponse; + } + final String logLine = String.valueOf((Clock.now() - startMs)) + dmeResponse.toString(); + getLog().info(logLine); + fPending.clear(); + + } catch (DME2Exception x) { + getLog().warn(x.getMessage(), x); + pubResponse.setResponseCode(x.getErrorCode()); + pubResponse.setResponseMessage(x.getErrorMessage()); + } catch (URISyntaxException x) { + + getLog().warn(x.getMessage(), x); + pubResponse.setResponseCode(String.valueOf(HttpStatus.SC_BAD_REQUEST)); + pubResponse.setResponseMessage(x.getMessage()); + } catch (InterruptedException e) { + throw e; + } catch (Exception x) { + + pubResponse.setResponseCode(String.valueOf(HttpStatus.SC_INTERNAL_SERVER_ERROR)); + pubResponse.setResponseMessage(x.getMessage()); + logger.error("exception: ", x); + + } + + return pubResponse; + } + + if (ProtocolType.AUTH_KEY.getValue().equalsIgnoreCase(protocolFlag)) { + if (fPending.peek() != null) { + logSendMessage(fPending.size(), httpUrl, nowMs - fPending.peek().timestamp); + } + final String result = postAuthwithResponse(httpUrl, baseStream.toByteArray(), contentType, authKey, + authDate, username, password, protocolFlag); + // Here we are checking for error response. If HTTP status + // code is not within the http success response code + // then we consider this as error and return false + + pubResponse = createMRPublisherResponse(result, pubResponse); + + if (Integer.parseInt(pubResponse.getResponseCode()) < 200 + || Integer.parseInt(pubResponse.getResponseCode()) > 299) { + + return pubResponse; + } + + logTime(startMs, result); + fPending.clear(); + return pubResponse; + } + + if (ProtocolType.AAF_AUTH.getValue().equalsIgnoreCase(protocolFlag)) { + if (fPending.peek() != null) { + logSendMessage(fPending.size(), httpUrl, nowMs - fPending.peek().timestamp); + } + final String result = postWithResponse(httpUrl, baseStream.toByteArray(), contentType, username, + password, protocolFlag); + + // Here we are checking for error response. If HTTP status + // code is not within the http success response code + // then we consider this as error and return false + pubResponse = createMRPublisherResponse(result, pubResponse); + + if (Integer.parseInt(pubResponse.getResponseCode()) < 200 + || Integer.parseInt(pubResponse.getResponseCode()) > 299) { + + return pubResponse; + } + + final String logLine = String.valueOf((Clock.now() - startMs)); + getLog().info(logLine); + fPending.clear(); + return pubResponse; + } + + if (ProtocolType.HTTPNOAUTH.getValue().equalsIgnoreCase(protocolFlag)) { + if (fPending.peek() != null) { + logSendMessage(fPending.size(), httpUrl, nowMs - fPending.peek().timestamp); + } + final String result = postNoAuthWithResponse(httpUrl, baseStream.toByteArray(), contentType); + + // Here we are checking for error response. If HTTP status + // code is not within the http success response code + // then we consider this as error and return false + pubResponse = createMRPublisherResponse(result, pubResponse); + + if (Integer.parseInt(pubResponse.getResponseCode()) < 200 + || Integer.parseInt(pubResponse.getResponseCode()) > 299) { + + return pubResponse; + } + + final String logLine = String.valueOf((Clock.now() - startMs)); + getLog().info(logLine); + fPending.clear(); + return pubResponse; + } + } catch (IllegalArgumentException | HttpException x) { + getLog().warn(x.getMessage(), x); + pubResponse.setResponseCode(String.valueOf(HttpStatus.SC_BAD_REQUEST)); + pubResponse.setResponseMessage(x.getMessage()); + + } catch (IOException x) { + getLog().warn(x.getMessage(), x); + pubResponse.setResponseCode(String.valueOf(HttpStatus.SC_INTERNAL_SERVER_ERROR)); + pubResponse.setResponseMessage(x.getMessage()); + } catch (InterruptedException e) { + getLog().warn("Interrupted!", e); + // Restore interrupted state... + Thread.currentThread().interrupt(); + } catch (Exception x) { + getLog().warn(x.getMessage(), x); + + pubResponse.setResponseCode(String.valueOf(HttpStatus.SC_INTERNAL_SERVER_ERROR)); + pubResponse.setResponseMessage(x.getMessage()); + + } finally { + if (!fPending.isEmpty()) { + getLog().warn("Send failed, " + fPending.size() + " message to send."); + pubResponse.setPendingMsgs(fPending.size()); + } + if (os != null) { + try { + os.close(); + } catch (Exception x) { + getLog().warn(x.getMessage(), x); + pubResponse.setResponseCode(String.valueOf(HttpStatus.SC_INTERNAL_SERVER_ERROR)); + pubResponse.setResponseMessage("Error in closing Output Stream"); + } + } + } + + return pubResponse; + } + + public MRPublisherResponse createMRPublisherResponse(String reply, MRPublisherResponse mrPubResponse) { + + if (reply.isEmpty()) { + + mrPubResponse.setResponseCode(String.valueOf(HttpStatus.SC_BAD_REQUEST)); + mrPubResponse.setResponseMessage("Please verify the Producer properties"); + } else if (reply.startsWith("{")) { + JSONObject jObject = new JSONObject(reply); + if (jObject.has("message") && jObject.has(JSON_STATUS)) { + String message = jObject.getString("message"); + if (null != message) { + mrPubResponse.setResponseMessage(message); + } + mrPubResponse.setResponseCode(Integer.toString(jObject.getInt(JSON_STATUS))); + } else { + mrPubResponse.setResponseCode(String.valueOf(HttpStatus.SC_OK)); + mrPubResponse.setResponseMessage(reply); + } + } else if (reply.startsWith("<")) { + String responseCode = getHTTPErrorResponseCode(reply); + if (responseCode.contains("403")) { + responseCode = "403"; + } + mrPubResponse.setResponseCode(responseCode); + mrPubResponse.setResponseMessage(getHTTPErrorResponseMessage(reply)); + } + + return mrPubResponse; + } + + private final String fTopic; + private final int fMaxBatchSize; + private final long fMaxBatchAgeMs; + private final boolean fCompress; + private int threadOccurrenceTime; + private boolean fClosed; + private String username; + private String password; + private String host; + + // host selector + private HostSelector fHostSelector = null; + + private final LinkedBlockingQueue fPending; + private long fDontSendUntilMs; + private final ScheduledThreadPoolExecutor fExec; + + private String latitude; + private String longitude; + private String version; + private String serviceName; + private String env; + private String partner; + private String routeOffer; + private String subContextPath; + private String protocol; + private String methodType; + private String url; + private String dmeuser; + private String dmepassword; + private String contentType; + private static final long SF_WAIT_AFTER_ERROR = 10000; + private HashMap DMETimeOuts; + private DME2Client sender; + public String protocolFlag = ProtocolType.DME2.getValue(); + private String authKey; + private String authDate; + private String handlers; + private Properties props; + public static String routerFilePath; + protected static final Map headers = new HashMap(); + public static MultivaluedMap headersMap; + + private MRPublisherResponse pubResponse; + + public MRPublisherResponse getPubResponse() { + return pubResponse; + } + + public void setPubResponse(MRPublisherResponse pubResponse) { + this.pubResponse = pubResponse; + } + + public static String getRouterFilePath() { + return routerFilePath; + } + + public static void setRouterFilePath(String routerFilePath) { + MRSimplerBatchPublisher.routerFilePath = routerFilePath; + } + + public Properties getProps() { + return props; + } + + public void setProps(Properties props) { + this.props = props; + setClientConfig(DmaapClientUtil.getClientConfig(props)); + } + + public String getProtocolFlag() { + return protocolFlag; + } + + public void setProtocolFlag(String protocolFlag) { + this.protocolFlag = protocolFlag; + } + + private void configureDME2() throws Exception { + try { + + latitude = props.getProperty(LATITUDE); + longitude = props.getProperty(LONGITUDE); + version = props.getProperty(VERSION); + serviceName = props.getProperty(SERVICE_NAME); + env = props.getProperty(ENVIRONMENT); + partner = props.getProperty(PARTNER); + routeOffer = props.getProperty(ROUTE_OFFER); + subContextPath = props.getProperty(SUB_CONTEXT_PATH) + fTopic; + + protocol = props.getProperty(PROTOCOL); + methodType = props.getProperty(METHOD_TYPE); + dmeuser = props.getProperty(USERNAME); + dmepassword = props.getProperty(PASSWORD); + contentType = props.getProperty(CONTENT_TYPE); + handlers = props.getProperty(SESSION_STICKINESS_REQUIRED); + + MRSimplerBatchPublisher.routerFilePath = props.getProperty(DME2PREFERRED_ROUTER_FILE_PATH); + + /* + * Changes to DME2Client url to use Partner for auto failover + * between data centers When Partner value is not provided use the + * routeOffer value for auto failover within a cluster + */ + + String partitionKey = props.getProperty(PARTITION); + + if (partner != null && !partner.isEmpty()) { + url = protocol + "://" + serviceName + "?version=" + version + "&envContext=" + env + "&partner=" + + partner; + if (partitionKey != null && !partitionKey.equalsIgnoreCase("")) { + url = url + "&partitionKey=" + partitionKey; + } + } else if (routeOffer != null && !routeOffer.isEmpty()) { + url = protocol + "://" + serviceName + "?version=" + version + "&envContext=" + env + "&routeoffer=" + + routeOffer; + if (partitionKey != null && !partitionKey.equalsIgnoreCase("")) { + url = url + "&partitionKey=" + partitionKey; + } + } + + DMETimeOuts = new HashMap<>(); + DMETimeOuts.put("AFT_DME2_EP_READ_TIMEOUT_MS", props.getProperty(AFT_DME2_EP_READ_TIMEOUT_MS)); + DMETimeOuts.put("AFT_DME2_ROUNDTRIP_TIMEOUT_MS", props.getProperty(AFT_DME2_ROUNDTRIP_TIMEOUT_MS)); + DMETimeOuts.put("AFT_DME2_EP_CONN_TIMEOUT", props.getProperty(AFT_DME2_EP_CONN_TIMEOUT)); + DMETimeOuts.put("Content-Type", contentType); + System.setProperty("AFT_LATITUDE", latitude); + System.setProperty("AFT_LONGITUDE", longitude); + System.setProperty("AFT_ENVIRONMENT", props.getProperty(AFT_ENVIRONMENT)); + // System.setProperty("DME2.DEBUG", "true"); + + // SSL changes + // System.setProperty("AFT_DME2_CLIENT_SSL_INCLUDE_PROTOCOLS", + + System.setProperty("AFT_DME2_CLIENT_SSL_INCLUDE_PROTOCOLS", "TLSv1.1,TLSv1.2"); + System.setProperty("AFT_DME2_CLIENT_IGNORE_SSL_CONFIG", "false"); + System.setProperty("AFT_DME2_CLIENT_KEYSTORE_PASSWORD", "changeit"); + + // SSL changes + + sender = new DME2Client(new URI(url), 5000L); + + sender.setAllowAllHttpReturnCodes(true); + sender.setMethod(methodType); + sender.setSubContext(subContextPath); + sender.setCredentials(dmeuser, dmepassword); + sender.setHeaders(DMETimeOuts); + if ("yes".equalsIgnoreCase(handlers)) { + sender.addHeader("AFT_DME2_EXCHANGE_REQUEST_HANDLERS", + props.getProperty(AFT_DME2_EXCHANGE_REQUEST_HANDLERS)); + sender.addHeader("AFT_DME2_EXCHANGE_REPLY_HANDLERS", + props.getProperty(AFT_DME2_EXCHANGE_REPLY_HANDLERS)); + sender.addHeader("AFT_DME2_REQ_TRACE_ON", props.getProperty(AFT_DME2_REQ_TRACE_ON)); + } else { + sender.addHeader("AFT_DME2_EXCHANGE_REPLY_HANDLERS", "com.att.nsa.mr.dme.client.HeaderReplyHandler"); + } + } catch (DME2Exception x) { + getLog().warn(x.getMessage(), x); + throw new DME2Exception(x.getErrorCode(), x.getErrorMessage()); + } catch (URISyntaxException x) { + + getLog().warn(x.getMessage(), x); + throw new URISyntaxException(url, x.getMessage()); + } catch (Exception x) { + + getLog().warn(x.getMessage(), x); + throw new IllegalArgumentException(x.getMessage()); + } + } + + private MRSimplerBatchPublisher(Collection hosts, String topic, int maxBatchSize, long maxBatchAgeMs, + boolean compress) throws MalformedURLException { + super(hosts); + + if (topic == null || topic.length() < 1) { + throw new IllegalArgumentException("A topic must be provided."); + } + + fHostSelector = new HostSelector(hosts, null); + fClosed = false; + fTopic = topic; + fMaxBatchSize = maxBatchSize; + fMaxBatchAgeMs = maxBatchAgeMs; + fCompress = compress; + + fPending = new LinkedBlockingQueue<>(); + fDontSendUntilMs = 0; + fExec = new ScheduledThreadPoolExecutor(1); + pubResponse = new MRPublisherResponse(); + + } + + private MRSimplerBatchPublisher(Collection hosts, String topic, int maxBatchSize, long maxBatchAgeMs, + boolean compress, boolean allowSelfSignedCerts, int httpThreadOccurrence) throws MalformedURLException { + super(hosts); + + if (topic == null || topic.length() < 1) { + throw new IllegalArgumentException("A topic must be provided."); + } + + fHostSelector = new HostSelector(hosts, null); + fClosed = false; + fTopic = topic; + fMaxBatchSize = maxBatchSize; + fMaxBatchAgeMs = maxBatchAgeMs; + fCompress = compress; + threadOccurrenceTime = httpThreadOccurrence; + fPending = new LinkedBlockingQueue<>(); + fDontSendUntilMs = 0; + fExec = new ScheduledThreadPoolExecutor(1); + fExec.scheduleAtFixedRate(new Runnable() { + @Override + public void run() { + send(false); + } + }, 100, threadOccurrenceTime, TimeUnit.MILLISECONDS); + pubResponse = new MRPublisherResponse(); + } + + private static class TimestampedMessage extends Message { + public TimestampedMessage(Message message) { + super(message); + timestamp = Clock.now(); + } + + public final long timestamp; + } + + public String getUsername() { + return username; + } + + public void setUsername(String username) { + this.username = username; + } + + public String getPassword() { + return password; + } + + public void setPassword(String password) { + this.password = password; + } + + public String getHost() { + return host; + } + + public void setHost(String host) { + this.host = host; + } + + public String getContentType() { + return contentType; + } + + public void setContentType(String contentType) { + this.contentType = contentType; + } + + public String getAuthKey() { + return authKey; + } + + public void setAuthKey(String authKey) { + this.authKey = authKey; + } + + public String getAuthDate() { + return authDate; + } + + public void setAuthDate(String authDate) { + this.authDate = authDate; + } } diff --git a/src/main/java/org/onap/dmaap/mr/client/response/MRConsumerResponse.java b/src/main/java/org/onap/dmaap/mr/client/response/MRConsumerResponse.java index 5dc3da0..6b52374 100644 --- a/src/main/java/org/onap/dmaap/mr/client/response/MRConsumerResponse.java +++ b/src/main/java/org/onap/dmaap/mr/client/response/MRConsumerResponse.java @@ -4,11 +4,13 @@ * ================================================================================ * Copyright © 2017 AT&T Intellectual Property. All rights reserved. * ================================================================================ + * Modifications Copyright © 2021 Orange. + * ================================================================================ * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * http://www.apache.org/licenses/LICENSE-2.0 - * + * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. @@ -17,44 +19,41 @@ * ============LICENSE_END========================================================= * * ECOMP is a trademark and service mark of AT&T Intellectual Property. - * + * *******************************************************************************/ + package org.onap.dmaap.mr.client.response; public class MRConsumerResponse { - - private String responseCode; - - private String responseMessage; - - private Iterable actualMessages; + private String responseCode; - + private String responseMessage; - public String getResponseCode() { - return responseCode; - } + private Iterable actualMessages; - public void setResponseCode(String responseCode) { - this.responseCode = responseCode; - } + public String getResponseCode() { + return responseCode; + } - public String getResponseMessage() { - return responseMessage; - } + public void setResponseCode(String responseCode) { + this.responseCode = responseCode; + } - public void setResponseMessage(String responseMessage) { - this.responseMessage = responseMessage; - } + public String getResponseMessage() { + return responseMessage; + } - public Iterable getActualMessages() { - return actualMessages; - } + public void setResponseMessage(String responseMessage) { + this.responseMessage = responseMessage; + } - public void setActualMessages(Iterable actualMessages) { - this.actualMessages = actualMessages; - } + public Iterable getActualMessages() { + return actualMessages; + } + public void setActualMessages(Iterable actualMessages) { + this.actualMessages = actualMessages; + } } diff --git a/src/main/java/org/onap/dmaap/mr/client/response/MRPublisherResponse.java b/src/main/java/org/onap/dmaap/mr/client/response/MRPublisherResponse.java index f0630be..97cc39a 100644 --- a/src/main/java/org/onap/dmaap/mr/client/response/MRPublisherResponse.java +++ b/src/main/java/org/onap/dmaap/mr/client/response/MRPublisherResponse.java @@ -4,11 +4,13 @@ * ================================================================================ * Copyright © 2017 AT&T Intellectual Property. All rights reserved. * ================================================================================ + * Modifications Copyright © 2021 Orange. + * ================================================================================ * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * http://www.apache.org/licenses/LICENSE-2.0 - * + * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. @@ -17,51 +19,52 @@ * ============LICENSE_END========================================================= * * ECOMP is a trademark and service mark of AT&T Intellectual Property. - * + * *******************************************************************************/ + package org.onap.dmaap.mr.client.response; /** - * Response for Publisher - * @author author + * Response for Publisher. * + * @author author */ public class MRPublisherResponse { - private String responseCode; + private String responseCode; - private String responseMessage; - - private int pendingMsgs; + private String responseMessage; - public String getResponseCode() { - return responseCode; - } + private int pendingMsgs; - public void setResponseCode(String responseCode) { - this.responseCode = responseCode; - } + public String getResponseCode() { + return responseCode; + } - public String getResponseMessage() { - return responseMessage; - } + public void setResponseCode(String responseCode) { + this.responseCode = responseCode; + } - public void setResponseMessage(String responseMessage) { - this.responseMessage = responseMessage; - } + public String getResponseMessage() { + return responseMessage; + } + + public void setResponseMessage(String responseMessage) { + this.responseMessage = responseMessage; + } - public int getPendingMsgs() { - return pendingMsgs; - } + public int getPendingMsgs() { + return pendingMsgs; + } - public void setPendingMsgs(int pendingMsgs) { - this.pendingMsgs = pendingMsgs; - } - - @Override - public String toString() { + public void setPendingMsgs(int pendingMsgs) { + this.pendingMsgs = pendingMsgs; + } + + @Override + public String toString() { return "Response Code:" + this.responseCode + "," + "Response Message:" + this.responseMessage + "," + "Pending Messages Count" + this.pendingMsgs; } - + } diff --git a/src/main/java/org/onap/dmaap/mr/dme/client/DefaultLoggingFailoverFaultHandler.java b/src/main/java/org/onap/dmaap/mr/dme/client/DefaultLoggingFailoverFaultHandler.java deleted file mode 100644 index a44d858..0000000 --- a/src/main/java/org/onap/dmaap/mr/dme/client/DefaultLoggingFailoverFaultHandler.java +++ /dev/null @@ -1,52 +0,0 @@ -/******************************************************************************* - * ============LICENSE_START======================================================= - * org.onap.dmaap - * ================================================================================ - * Copyright © 2017 AT&T Intellectual Property. All rights reserved. - * ================================================================================ - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * ============LICENSE_END========================================================= - * - * ECOMP is a trademark and service mark of AT&T Intellectual Property. - * - *******************************************************************************/ -package org.onap.dmaap.mr.dme.client; - - - -import java.util.logging.Level; -import java.util.logging.Logger; - - -//import com.att.aft.dme2.api.util.DME2Constants; -//import com.att.aft.dme2.api.util.DME2ExchangeFaultContext; -//import com.att.aft.dme2.api.util.LogMessage; -//import com.att.aft.dme2.api.util.LogUtil; -public class DefaultLoggingFailoverFaultHandler /*implements DME2FailoverFaultHandler*/ { - //TODO: This code may be enable in the future when we implement DME2FailoverFaultHandler interface - /** The logger. */ - - -// @Override - -// // LogUtil.INSTANCE.report(logger, Level.WARNING, LogMessage.SEP_FAILOVER, context.getService(),context.getRequestURL(),context.getRouteOffer(),context.getResponseCode(),context.getException()); -// } -// @Override -// /** -// * The DME2Exchange already has a log message when the route offer is failed over. We dont need to log it again here. -// */ - -// //noop -// - -} - diff --git a/src/main/java/org/onap/dmaap/mr/dme/client/HeaderReplyHandler.java b/src/main/java/org/onap/dmaap/mr/dme/client/HeaderReplyHandler.java index 9197ca4..7d6c971 100644 --- a/src/main/java/org/onap/dmaap/mr/dme/client/HeaderReplyHandler.java +++ b/src/main/java/org/onap/dmaap/mr/dme/client/HeaderReplyHandler.java @@ -4,11 +4,13 @@ * ================================================================================ * Copyright © 2017 AT&T Intellectual Property. All rights reserved. * ================================================================================ + * Modifications Copyright © 2021 Orange. + * ================================================================================ * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * http://www.apache.org/licenses/LICENSE-2.0 - * + * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. @@ -17,40 +19,41 @@ * ============LICENSE_END========================================================= * * ECOMP is a trademark and service mark of AT&T Intellectual Property. - * + * *******************************************************************************/ -package org.onap.dmaap.mr.dme.client; - -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; +package org.onap.dmaap.mr.dme.client; import com.att.aft.dme2.api.util.DME2ExchangeFaultContext; import com.att.aft.dme2.api.util.DME2ExchangeReplyHandler; import com.att.aft.dme2.api.util.DME2ExchangeResponseContext; import org.onap.dmaap.mr.client.MRClientFactory; - +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + public class HeaderReplyHandler implements DME2ExchangeReplyHandler { - - private Logger fLog = LoggerFactory.getLogger ( this.getClass().getName () ); - - - @Override public void handleFault(DME2ExchangeFaultContext responseData) { - // TODO Auto-generated method stub - - } - @Override public void handleEndpointFault(DME2ExchangeFaultContext responseData) { - // TODO Auto-generated method stub - - } -@Override public void handleReply(DME2ExchangeResponseContext responseData) { - - if(responseData != null) { - MRClientFactory.DME2HeadersMap=responseData.getResponseHeaders(); - if (responseData.getResponseHeaders().get("transactionId")!=null) - fLog.info("Transaction Id : " + responseData.getResponseHeaders().get("transactionId")); - - } -} + + private static final Logger logger = LoggerFactory.getLogger(HeaderReplyHandler.class); + + @Override + public void handleFault(DME2ExchangeFaultContext responseData) { + + } + + @Override + public void handleEndpointFault(DME2ExchangeFaultContext responseData) { + + } + + @Override + public void handleReply(DME2ExchangeResponseContext responseData) { + if (responseData != null) { + MRClientFactory.DME2HeadersMap = responseData.getResponseHeaders(); + if (responseData.getResponseHeaders().get("transactionId") != null) { + logger.info("Transaction Id : " + responseData.getResponseHeaders().get("transactionId")); + } + + } + } } diff --git a/src/main/java/org/onap/dmaap/mr/dme/client/PreferredRouteReplyHandler.java b/src/main/java/org/onap/dmaap/mr/dme/client/PreferredRouteReplyHandler.java index 70e0d1b..1b13c8e 100644 --- a/src/main/java/org/onap/dmaap/mr/dme/client/PreferredRouteReplyHandler.java +++ b/src/main/java/org/onap/dmaap/mr/dme/client/PreferredRouteReplyHandler.java @@ -4,11 +4,13 @@ * ================================================================================ * Copyright © 2017 AT&T Intellectual Property. All rights reserved. * ================================================================================ + * Modifications Copyright © 2021 Orange. + * ================================================================================ * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * http://www.apache.org/licenses/LICENSE-2.0 - * + * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. @@ -17,55 +19,57 @@ * ============LICENSE_END========================================================= * * ECOMP is a trademark and service mark of AT&T Intellectual Property. - * + * *******************************************************************************/ -package org.onap.dmaap.mr.dme.client; -import java.io.File; -import java.io.FileWriter; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; +package org.onap.dmaap.mr.dme.client; import com.att.aft.dme2.api.util.DME2ExchangeFaultContext; import com.att.aft.dme2.api.util.DME2ExchangeReplyHandler; import com.att.aft.dme2.api.util.DME2ExchangeResponseContext; +import java.io.File; +import java.io.FileWriter; import org.onap.dmaap.mr.client.MRClientFactory; import org.onap.dmaap.mr.client.impl.MRSimplerBatchPublisher; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; public class PreferredRouteReplyHandler implements DME2ExchangeReplyHandler { - private Logger fLog = LoggerFactory.getLogger ( this.getClass().getName () ); - @Override public void handleReply(DME2ExchangeResponseContext responseData) { - - if(responseData != null) { - MRClientFactory.DME2HeadersMap=responseData.getResponseHeaders(); - if (responseData.getResponseHeaders().get("transactionId")!=null) - - fLog.info("Transaction_Id : " + responseData.getResponseHeaders().get("transactionId")); - - if(responseData.getRouteOffer() != null ){ - routeWriter("preferredRouteKey",responseData.getRouteOffer()); - - } - } -} - - @Override public void handleFault(DME2ExchangeFaultContext responseData) { - // TODO Auto-generated method stub - //StaticCache.getInstance().setHandleFaultInvoked(true); - } - @Override public void handleEndpointFault(DME2ExchangeFaultContext responseData) { - // TODO Auto-generated method stub - - } - public void routeWriter(String routeKey, String routeValue){ - try(FileWriter routeWriter=new FileWriter(new File (MRSimplerBatchPublisher.routerFilePath))){ - routeWriter.write(routeKey+"="+routeValue); - routeWriter.close(); - - }catch(Exception ex){ - fLog.error("Reply Router Error " + ex); - } - - } + private static final Logger logger = LoggerFactory.getLogger(PreferredRouteReplyHandler.class); + + @Override + public void handleReply(DME2ExchangeResponseContext responseData) { + + if (responseData != null) { + MRClientFactory.DME2HeadersMap = responseData.getResponseHeaders(); + if (responseData.getResponseHeaders().get("transactionId") != null) { + logger.info("Transaction_Id : " + responseData.getResponseHeaders().get("transactionId")); + } + + if (responseData.getRouteOffer() != null) { + routeWriter("preferredRouteKey", responseData.getRouteOffer()); + } + } + } + + @Override + public void handleFault(DME2ExchangeFaultContext responseData) { + + } + + @Override + public void handleEndpointFault(DME2ExchangeFaultContext responseData) { + + } + + public void routeWriter(String routeKey, String routeValue) { + + try (FileWriter routeWriter = new FileWriter(new File(MRSimplerBatchPublisher.routerFilePath))) { + routeWriter.write(routeKey + "=" + routeValue); + } catch (Exception ex) { + logger.error("Reply Router Error " + ex); + } + + } } diff --git a/src/main/java/org/onap/dmaap/mr/dme/client/PreferredRouteRequestHandler.java b/src/main/java/org/onap/dmaap/mr/dme/client/PreferredRouteRequestHandler.java index dd0b286..bb5309f 100644 --- a/src/main/java/org/onap/dmaap/mr/dme/client/PreferredRouteRequestHandler.java +++ b/src/main/java/org/onap/dmaap/mr/dme/client/PreferredRouteRequestHandler.java @@ -4,11 +4,13 @@ * ================================================================================ * Copyright © 2017 AT&T Intellectual Property. All rights reserved. * ================================================================================ + * Modifications Copyright © 2021 Orange. + * ================================================================================ * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * http://www.apache.org/licenses/LICENSE-2.0 - * + * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. @@ -17,38 +19,34 @@ * ============LICENSE_END========================================================= * * ECOMP is a trademark and service mark of AT&T Intellectual Property. - * + * *******************************************************************************/ -package org.onap.dmaap.mr.dme.client; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; +package org.onap.dmaap.mr.dme.client; import com.att.aft.dme2.api.util.DME2ExchangeRequestContext; import com.att.aft.dme2.api.util.DME2ExchangeRequestHandler; import org.onap.dmaap.mr.client.MRClientFactory; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; public class PreferredRouteRequestHandler implements DME2ExchangeRequestHandler { - private Logger logger = LoggerFactory.getLogger(this.getClass().getName()); - - @Override - public void handleRequest(DME2ExchangeRequestContext requestData) { - - if (requestData != null) { - - requestData.setPreferredRouteOffer(readRoute("preferredRouteKey")); - } - } - - public String readRoute(String routeKey) { - - try { - - MRClientFactory.prop.load(MRClientFactory.routeReader); - } catch (Exception ex) { - logger.error("Request Router Error ", ex); - } - return MRClientFactory.prop.getProperty(routeKey); - } + private static final Logger logger = LoggerFactory.getLogger(PreferredRouteRequestHandler.class); + + @Override + public void handleRequest(DME2ExchangeRequestContext requestData) { + if (requestData != null) { + requestData.setPreferredRouteOffer(readRoute("preferredRouteKey")); + } + } + + public String readRoute(String routeKey) { + try { + MRClientFactory.prop.load(MRClientFactory.routeReader); + } catch (Exception ex) { + logger.error("Request Router Error ", ex); + } + return MRClientFactory.prop.getProperty(routeKey); + } } diff --git a/src/main/java/org/onap/dmaap/mr/dme/client/SimpleExampleConsumer.java b/src/main/java/org/onap/dmaap/mr/dme/client/SimpleExampleConsumer.java deleted file mode 100644 index 76abb7e..0000000 --- a/src/main/java/org/onap/dmaap/mr/dme/client/SimpleExampleConsumer.java +++ /dev/null @@ -1,88 +0,0 @@ -/******************************************************************************* - * ============LICENSE_START======================================================= - * org.onap.dmaap - * ================================================================================ - * Copyright © 2017 AT&T Intellectual Property. All rights reserved. - * ================================================================================ - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * ============LICENSE_END========================================================= - * - * ECOMP is a trademark and service mark of AT&T Intellectual Property. - * - *******************************************************************************/ - -package org.onap.dmaap.mr.dme.client; - -import java.util.Map; - -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; - -import javax.ws.rs.core.MultivaluedMap; - -import org.onap.dmaap.mr.client.MRClientFactory; -import org.onap.dmaap.mr.client.MRConsumer; - -import java.util.List; - -public class SimpleExampleConsumer { - - private static final Logger logger = LoggerFactory.getLogger(SimpleExampleConsumer.class); - - private SimpleExampleConsumer() { - } - - public static void main(String[] args) { - - long count = 0; - long nextReport = 5000; - String key; - - final long startMs = System.currentTimeMillis(); - - try { - - final MRConsumer cc = MRClientFactory.createConsumer("D:\\SG\\consumer.properties"); - while (true) { - for (String msg : cc.fetch()) { - logger.debug("Message Received: " + msg); - } - // Header for DME2 Call. - MultivaluedMap headersMap = MRClientFactory.getHTTPHeadersMap(); - for (MultivaluedMap.Entry> entry : headersMap.entrySet()) { - key = entry.getKey(); - logger.debug("Header Key " + key); - logger.debug("Header Value " + headersMap.get(key)); - } - // Header for HTTP Call. - - Map dme2headersMap = MRClientFactory.DME2HeadersMap; - for (Map.Entry entry : dme2headersMap.entrySet()) { - key = entry.getKey(); - logger.debug("Header Key " + key); - logger.debug("Header Value " + dme2headersMap.get(key)); - } - - if (count > nextReport) { - nextReport += 5000; - - final long endMs = System.currentTimeMillis(); - final long elapsedMs = endMs - startMs; - final double elapsedSec = elapsedMs / 1000.0; - final double eps = count / elapsedSec; - } - } - } catch (Exception x) { - logger.error("Exception in SimpleExampleConsumer", x); - } - } -} diff --git a/src/main/java/org/onap/dmaap/mr/dme/client/SimpleExamplePublisher.java b/src/main/java/org/onap/dmaap/mr/dme/client/SimpleExamplePublisher.java deleted file mode 100644 index b5d83bb..0000000 --- a/src/main/java/org/onap/dmaap/mr/dme/client/SimpleExamplePublisher.java +++ /dev/null @@ -1,128 +0,0 @@ -/******************************************************************************* - * ============LICENSE_START======================================================= - * org.onap.dmaap - * ================================================================================ - * Copyright © 2017 AT&T Intellectual Property. All rights reserved. - * ================================================================================ - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * ============LICENSE_END========================================================= - * - * ECOMP is a trademark and service mark of AT&T Intellectual Property. - * - *******************************************************************************/ - -package org.onap.dmaap.mr.dme.client; - - -import java.io.IOException; -import java.util.Map; -import javax.ws.rs.core.MultivaluedMap; -import org.json.JSONObject; -import org.onap.dmaap.mr.client.MRBatchingPublisher; -import org.onap.dmaap.mr.client.MRClientFactory; - -/** - * An example of how to use the Java publisher. - * - * @author author - */ -public class SimpleExamplePublisher { - static String content = null; - static String messageSize = null; - static String transport = null; - static String messageCount = null; - - public void publishMessage(String producerFilePath) throws IOException, InterruptedException { - - // create our publisher - - // publish some messages - - - StringBuilder sb = new StringBuilder(); - final MRBatchingPublisher pub = MRClientFactory.createBatchingPublisher(producerFilePath); - - if (content.equalsIgnoreCase("text/plain")) { - for (int i = 0; i < Integer.parseInt(messageCount); i++) { - for (int j = 0; j < Integer.parseInt(messageSize); j++) { - sb.append("T"); - } - - pub.send(sb.toString()); - } - } else if (content.equalsIgnoreCase("application/cambria")) { - for (int i = 0; i < Integer.parseInt(messageCount); i++) { - for (int j = 0; j < Integer.parseInt(messageSize); j++) { - sb.append("C"); - } - - pub.send("Key", sb.toString()); - } - } else if (content.equalsIgnoreCase("application/json")) { - for (int i = 0; i < Integer.parseInt(messageCount); i++) { - - final JSONObject msg12 = new JSONObject(); - msg12.put("Name", "DMaaP Reference Client to Test jason Message"); - - pub.send(msg12.toString()); - - } - } - - // ... - - // close the publisher to make sure everything's sent before exiting. - // The batching - // publisher interface allows the app to get the set of unsent messages. - // It could - // write them to disk, for example, to try to send them later. - /* final List stuck = pub.close(20, TimeUnit.SECONDS); - if (stuck.size() > 0) { - System.err.println(stuck.size() + " messages unsent"); - } else { - System.out.println("Clean exit; all messages sent."); - }*/ - - if (transport.equalsIgnoreCase("HTTP")) { - MultivaluedMap headersMap = MRClientFactory.getHTTPHeadersMap(); - for (String key : headersMap.keySet()) { - System.out.println("Header Key " + key); - System.out.println("Header Value " + headersMap.get(key)); - } - } else { - Map dme2headersMap = MRClientFactory.DME2HeadersMap; - for (String key : dme2headersMap.keySet()) { - System.out.println("Header Key " + key); - System.out.println("Header Value " + dme2headersMap.get(key)); - } - } - - } - - public static void main(String[] args) throws InterruptedException, Exception { - - String producerFilePath = args[0]; - content = args[1]; - messageSize = args[2]; - transport = args[3]; - messageCount = args[4]; - - - - - - SimpleExamplePublisher publisher = new SimpleExamplePublisher(); - - publisher.publishMessage("D:\\SG\\producer.properties"); - } - -} diff --git a/src/main/java/org/onap/dmaap/mr/test/clients/ConsolePublisher.java b/src/main/java/org/onap/dmaap/mr/test/clients/ConsolePublisher.java deleted file mode 100644 index d8b1979..0000000 --- a/src/main/java/org/onap/dmaap/mr/test/clients/ConsolePublisher.java +++ /dev/null @@ -1,95 +0,0 @@ -/******************************************************************************* - * ============LICENSE_START======================================================= - * org.onap.dmaap - * ================================================================================ - * Copyright © 2017 AT&T Intellectual Property. All rights reserved. - * ================================================================================ - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * ============LICENSE_END========================================================= - * - * ECOMP is a trademark and service mark of AT&T Intellectual Property. - * - *******************************************************************************/ - -package org.onap.dmaap.mr.test.clients; - -import java.io.BufferedReader; -import java.io.IOException; -import java.io.InputStreamReader; -import java.util.List; -import java.util.UUID; -import java.util.concurrent.TimeUnit; - -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; - -import org.onap.dmaap.mr.client.MRBatchingPublisher; -import org.onap.dmaap.mr.client.MRClientFactory; -import org.onap.dmaap.mr.client.MRPublisher.message; - -/** - * A simple publisher that reads from std in, sending each line as a message. - * @author author - */ -public class ConsolePublisher -{ - - private static final Logger logger = LoggerFactory.getLogger(ConsolePublisher.class); - private ConsolePublisher() { - } - public static void main ( String[] args ) throws IOException //throws IOException, InterruptedException - { - // read the hosts(s) from the command line - final String hosts = args.length > 0 ? args[0] : "mr1.onap.com,mr2.onap.com,mr3.onap.com"; - - // read the topic name from the command line - final String topic = args.length > 1 ? args[1] : "TEST-TOPIC"; - - // read the topic name from the command line - final String partition = args.length > 2 ? args[2] : UUID.randomUUID ().toString (); - - // set up some batch limits and the compression flag - final int maxBatchSize = 100; - final long maxAgeMs = 250; - final boolean withGzip = false; - - // create our publisher - final MRBatchingPublisher pub = MRClientFactory.createBatchingPublisher ( hosts, topic, maxBatchSize, maxAgeMs, withGzip ); - - final BufferedReader cin = new BufferedReader ( new InputStreamReader ( System.in ) ); - try - { - String line = null; - while ( ( line = cin.readLine () ) != null ) - { - pub.send ( partition, line ); - } - } - finally - { - List leftovers = null; - try - { - leftovers = pub.close ( 10, TimeUnit.SECONDS ); - } - catch ( InterruptedException e ) - { - logger.error( "Send on close interrupted." ); - Thread.currentThread().interrupt(); - } - for ( message m : leftovers ) - { - logger.error( "Unsent message: " + m.fMsg ); - } - } - } -} diff --git a/src/main/java/org/onap/dmaap/mr/test/clients/ProtocolTypeConstants.java b/src/main/java/org/onap/dmaap/mr/test/clients/ProtocolTypeConstants.java deleted file mode 100644 index 6ece7f7..0000000 --- a/src/main/java/org/onap/dmaap/mr/test/clients/ProtocolTypeConstants.java +++ /dev/null @@ -1,44 +0,0 @@ -/******************************************************************************* - * ============LICENSE_START======================================================= - * org.onap.dmaap - * ================================================================================ - * Copyright © 2017 AT&T Intellectual Property. All rights reserved. - * ================================================================================ - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * ============LICENSE_END========================================================= - * - * ECOMP is a trademark and service mark of AT&T Intellectual Property. - * - *******************************************************************************/ -/** - * - */ -package org.onap.dmaap.mr.test.clients; - -/** - * @author author - * - */ -public enum ProtocolTypeConstants { - - DME2("DME2"), AAF_AUTH("HTTPAAF"), AUTH_KEY("HTTPAUTH"), HTTPNOAUTH("HTTPNOAUTH"); - - private String value; - - private ProtocolTypeConstants(String value) { - this.value = value; - } - - public String getValue() { - return value; - } -} diff --git a/src/main/java/org/onap/dmaap/mr/test/clients/SampleConsumer.java b/src/main/java/org/onap/dmaap/mr/test/clients/SampleConsumer.java deleted file mode 100644 index eb96780..0000000 --- a/src/main/java/org/onap/dmaap/mr/test/clients/SampleConsumer.java +++ /dev/null @@ -1,87 +0,0 @@ -/******************************************************************************* - * ============LICENSE_START======================================================= - * org.onap.dmaap - * ================================================================================ - * Copyright © 2017 AT&T Intellectual Property. All rights reserved. - * ================================================================================ - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * ============LICENSE_END========================================================= - * - * ECOMP is a trademark and service mark of AT&T Intellectual Property. - * - *******************************************************************************/ -package org.onap.dmaap.mr.test.clients; - -import java.util.LinkedList; - -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; - -import org.onap.dmaap.mr.client.MRClientFactory; -import org.onap.dmaap.mr.client.MRConsumer; - -public class SampleConsumer { - private SampleConsumer() { - } - public static void main ( String[] args ) - { - final Logger log = LoggerFactory.getLogger(SampleConsumer.class); - - - log.info("Sample Consumer Class executing"); - final String topic = "org.onap.dmaap.mr.testingTopic"; - final String url = ( args.length > 1 ? args[1] : "localhost:8181" ); - final String group = ( args.length > 2 ? args[2] :"grp" ); - - final String id = ( args.length > 3 ? args[3] : "1" ); - - long count = 0; - long nextReport = 5000; - - final long startMs = System.currentTimeMillis (); - - final LinkedList urlList = new LinkedList<> (); - for ( String u : url.split ( "," ) ) - { - urlList.add ( u ); - } - - final MRConsumer cc = MRClientFactory.createConsumer ( urlList, topic, group, id, 10*1000, 1000, null, "CG0TXc2Aa3v8LfBk", "pj2rhxJWKP23pgy8ahMnjH88" ); - try - { - while ( true ) - { - for ( String msg : cc.fetch () ) - { - log.info ( "" + (++count) + ": " + msg ); - } - - if ( count > nextReport ) - { - nextReport += 5000; - - final long endMs = System.currentTimeMillis (); - final long elapsedMs = endMs - startMs; - final double elapsedSec = elapsedMs / 1000.0; - final double eps = count / elapsedSec; - log.info ( "Consumed " + count + " in " + elapsedSec + "; " + eps + " eps" ); - } - log.info ( "" + (++count) + ": consumed message" ); - } - } - catch ( Exception x ) - { - log.error( x.getClass().getName () + ": " + x.getMessage () ); - throw new IllegalArgumentException(x); - } - } -} diff --git a/src/main/java/org/onap/dmaap/mr/test/clients/SamplePublisher.java b/src/main/java/org/onap/dmaap/mr/test/clients/SamplePublisher.java deleted file mode 100644 index f857afd..0000000 --- a/src/main/java/org/onap/dmaap/mr/test/clients/SamplePublisher.java +++ /dev/null @@ -1,85 +0,0 @@ -/******************************************************************************* - * ============LICENSE_START======================================================= - * org.onap.dmaap - * ================================================================================ - * Copyright © 2017 AT&T Intellectual Property. All rights reserved. - * ================================================================================ - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * ============LICENSE_END========================================================= - * - * ECOMP is a trademark and service mark of AT&T Intellectual Property. - * - *******************************************************************************/ -package org.onap.dmaap.mr.test.clients; - -import java.io.IOException; -import java.util.List; -import java.util.concurrent.TimeUnit; - -import org.json.JSONObject; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; - -import org.onap.dmaap.mr.client.MRBatchingPublisher; -import org.onap.dmaap.mr.client.MRClientBuilders.PublisherBuilder; -import org.onap.dmaap.mr.client.MRPublisher.message; - -public class SamplePublisher { - public static void main ( String[] args ) throws IOException, InterruptedException - { - final Logger LOG = LoggerFactory.getLogger(SampleConsumer.class); - // read the hosts(s) from the command line - final String hosts = ( args.length > 0 ? args[0] : "localhost:8181" ); - - // read the topic name from the command line - - final String topic = ( args.length > 1 ? args[1] : "org.onap.dmaap.mr.testingTopic" ); - - // set up some batch limits and the compression flag - final int maxBatchSize = 100; - final int maxAgeMs = 250; - final boolean withGzip = false; - - // create our publisher - - final MRBatchingPublisher pub = new PublisherBuilder (). - usingHosts ( hosts ). - onTopic ( topic ).limitBatch(maxBatchSize, maxAgeMs). - authenticatedBy ( "CG0TXc2Aa3v8LfBk", "pj2rhxJWKP23pgy8ahMnjH88" ). - build () - ; - // publish some messages - final JSONObject msg1 = new JSONObject (); - msg1.put ( "name", "tttttttttttttttt" ); - msg1.put ( "greeting", "ooooooooooooooooo" ); - pub.send ( "MyPartitionKey", msg1.toString () ); - - final JSONObject msg2 = new JSONObject (); - msg2.put ( "now", System.currentTimeMillis () ); - pub.send ( "MyOtherPartitionKey", msg2.toString () ); - - // ... - - // close the publisher to make sure everything's sent before exiting. The batching - // publisher interface allows the app to get the set of unsent messages. It could - // write them to disk, for example, to try to send them later. - final List stuck = pub.close ( 20, TimeUnit.SECONDS ); - if ( stuck.isEmpty()) - { - LOG.warn ( stuck.size() + " messages unsent" ); - } - else - { - LOG.info ( "Clean exit; all messages sent." ); - } - } -} diff --git a/src/main/java/org/onap/dmaap/mr/test/clients/SimpleExampleConsumer.java b/src/main/java/org/onap/dmaap/mr/test/clients/SimpleExampleConsumer.java deleted file mode 100644 index a5c0c3a..0000000 --- a/src/main/java/org/onap/dmaap/mr/test/clients/SimpleExampleConsumer.java +++ /dev/null @@ -1,84 +0,0 @@ -/******************************************************************************* - * ============LICENSE_START======================================================= - * org.onap.dmaap - * ================================================================================ - * Copyright © 2017 AT&T Intellectual Property. All rights reserved. - * ================================================================================ - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * ============LICENSE_END========================================================= - * - * ECOMP is a trademark and service mark of AT&T Intellectual Property. - * - *******************************************************************************/ - -package org.onap.dmaap.mr.test.clients; - -import java.io.File; -import java.io.FileReader; -import java.io.FileWriter; -import java.util.Properties; - -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; - -import org.onap.dmaap.mr.client.MRClientFactory; -import org.onap.dmaap.mr.client.MRConsumer; - -public class SimpleExampleConsumer { - - static FileWriter routeWriter = null; - static Properties props = null; - static FileReader routeReader = null; - - public static void main(String[] args) { - final Logger LOG = LoggerFactory.getLogger(SimpleExampleConsumer.class); - - long count = 0; - long nextReport = 5000; - - final long startMs = System.currentTimeMillis(); - - try { - String routeFilePath = "/src/main/resources/dme2/preferredRoute.txt"; - - File fo = new File(routeFilePath); - if (!fo.exists()) { - routeWriter = new FileWriter(new File(routeFilePath)); - } - routeReader = new FileReader(new File(routeFilePath)); - props = new Properties(); - final MRConsumer cc = MRClientFactory.createConsumer("/src/main/resources/dme2/consumer.properties"); - int i = 0; - while (i < 10) { - Thread.sleep(2); - i++; - for (String msg : cc.fetch()) { - - System.out.println(msg); - } - - if (count > nextReport) { - nextReport += 5000; - - final long endMs = System.currentTimeMillis(); - final long elapsedMs = endMs - startMs; - final double elapsedSec = elapsedMs / 1000.0; - final double eps = count / elapsedSec; - System.out.println("Consumed " + count + " in " + elapsedSec + "; " + eps + " eps"); - } - } - } catch (Exception x) { - System.err.println(x.getClass().getName() + ": " + x.getMessage()); - LOG.error("exception: ", x); - } - } -} diff --git a/src/main/java/org/onap/dmaap/mr/test/clients/SimpleExampleConsumerWithReturnResponse.java b/src/main/java/org/onap/dmaap/mr/test/clients/SimpleExampleConsumerWithReturnResponse.java deleted file mode 100644 index f7341ec..0000000 --- a/src/main/java/org/onap/dmaap/mr/test/clients/SimpleExampleConsumerWithReturnResponse.java +++ /dev/null @@ -1,98 +0,0 @@ -/******************************************************************************* - * ============LICENSE_START======================================================= - * org.onap.dmaap - * ================================================================================ - * Copyright © 2017 AT&T Intellectual Property. All rights reserved. - * ================================================================================ - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * ============LICENSE_END========================================================= - * - * ECOMP is a trademark and service mark of AT&T Intellectual Property. - * - *******************************************************************************/ -package org.onap.dmaap.mr.test.clients; - -import java.io.File; -import java.io.FileReader; -import java.io.FileWriter; -import java.util.Properties; - -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; - -import org.onap.dmaap.mr.client.MRClientFactory; -import org.onap.dmaap.mr.client.MRConsumer; -import org.onap.dmaap.mr.client.response.MRConsumerResponse; - -public class SimpleExampleConsumerWithReturnResponse { - - private static final Logger LOG = LoggerFactory.getLogger(SimpleExampleConsumerWithReturnResponse.class); - - static FileWriter routeWriter= null; - static Properties props=null; - static FileReader routeReader=null; - public static void main ( String[] args ) - { - - long count = 0; - long nextReport = 5000; - // remove while true and limite execution time in seconds - int timeMax = 86400; // one day - long endDate = System.currentTimeMillis() + timeMax*1000; - - final long startMs = System.currentTimeMillis (); - - try - { - String routeFilePath="src/main/resources/dme2/preferredRoute.txt"; - - - File fo= new File(routeFilePath); - if(!fo.exists()){ - routeWriter=new FileWriter(new File (routeFilePath)); - } - routeReader= new FileReader(new File (routeFilePath)); - props= new Properties(); - final MRConsumer cc = MRClientFactory.createConsumer ( "src/main/resources/dme2/consumer.properties" ); - while ( System.currentTimeMillis() < endDate ) - { - MRConsumerResponse mrConsumerResponse = cc.fetchWithReturnConsumerResponse(); - System.out.println("mrConsumerResponse code :"+mrConsumerResponse.getResponseCode()); - - System.out.println("mrConsumerResponse Message :"+mrConsumerResponse.getResponseMessage()); - - System.out.println("mrConsumerResponse ActualMessage :"+mrConsumerResponse.getActualMessages()); - /*for ( String msg : mrConsumerResponse.getActualMessages() ) - { - //System.out.println ( "" + (++count) + ": " + msg ); - System.out.println(msg); - }*/ - if ( count > nextReport ) - { - nextReport += 5000; - - final long endMs = System.currentTimeMillis (); - final long elapsedMs = endMs - startMs; - final double elapsedSec = elapsedMs / 1000.0; - final double eps = count / elapsedSec; - System.out.println ( "Consumed " + count + " in " + elapsedSec + "; " + eps + " eps" ); - } - } - } - catch ( Exception x ) - { - System.err.println ( x.getClass().getName () + ": " + x.getMessage () ); - LOG.error("exception: ", x); - } - } - -} diff --git a/src/main/java/org/onap/dmaap/mr/test/clients/SimpleExamplePublisher.java b/src/main/java/org/onap/dmaap/mr/test/clients/SimpleExamplePublisher.java deleted file mode 100644 index 50fd22c..0000000 --- a/src/main/java/org/onap/dmaap/mr/test/clients/SimpleExamplePublisher.java +++ /dev/null @@ -1,97 +0,0 @@ -/******************************************************************************* - * ============LICENSE_START======================================================= - * org.onap.dmaap - * ================================================================================ - * Copyright © 2017 AT&T Intellectual Property. All rights reserved. - * ================================================================================ - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * ============LICENSE_END========================================================= - * - * ECOMP is a trademark and service mark of AT&T Intellectual Property. - * - *******************************************************************************/ - -package org.onap.dmaap.mr.test.clients; - -import java.io.File; -import java.io.FileReader; -import java.io.FileWriter; -import java.io.IOException; -import java.util.List; -import java.util.Properties; -import java.util.concurrent.TimeUnit; - -import org.json.JSONObject; - -import org.onap.dmaap.mr.client.MRBatchingPublisher; -import org.onap.dmaap.mr.client.MRClientFactory; -import org.onap.dmaap.mr.client.MRPublisher.message; - -/** - * An example of how to use the Java publisher. - * @author author - */ -public class SimpleExamplePublisher -{ - static FileWriter routeWriter= null; - static Properties props=null; - static FileReader routeReader=null; - public void publishMessage ( String producerFilePath ) throws IOException, InterruptedException, Exception - { - - // create our publisher - final MRBatchingPublisher pub = MRClientFactory.createBatchingPublisher (producerFilePath); - // publish some messages - final JSONObject msg1 = new JSONObject (); - msg1.put ( "Name", "Sprint" ); - - pub.send ( "First cambria messge" ); - pub.send ( "MyPartitionKey", msg1.toString () ); - - final JSONObject msg2 = new JSONObject (); - - - - // ... - - // close the publisher to make sure everything's sent before exiting. The batching - // publisher interface allows the app to get the set of unsent messages. It could - // write them to disk, for example, to try to send them later. - final List stuck = pub.close ( 20, TimeUnit.SECONDS ); - if ( stuck.isEmpty() ) - { - System.err.println ( stuck.size() + " messages unsent" ); - } - else - { - System.out.println ( "Clean exit; all messages sent." ); - } - } - - public static void main(String []args) throws InterruptedException, Exception{ - - String routeFilePath="/src/main/resources/dme2/preferredRoute.txt"; - - SimpleExamplePublisher publisher = new SimpleExamplePublisher(); - - - File fo= new File(routeFilePath); - if(!fo.exists()){ - routeWriter=new FileWriter(new File (routeFilePath)); - } - routeReader= new FileReader(new File (routeFilePath)); - props= new Properties(); - publisher.publishMessage("/src/main/resources/dme2/producer.properties"); - } - -} - diff --git a/src/main/java/org/onap/dmaap/mr/test/clients/SimpleExamplePublisherWithResponse.java b/src/main/java/org/onap/dmaap/mr/test/clients/SimpleExamplePublisherWithResponse.java deleted file mode 100644 index d2b77ef..0000000 --- a/src/main/java/org/onap/dmaap/mr/test/clients/SimpleExamplePublisherWithResponse.java +++ /dev/null @@ -1,82 +0,0 @@ -/******************************************************************************* - * ============LICENSE_START======================================================= - * org.onap.dmaap - * ================================================================================ - * Copyright © 2017 AT&T Intellectual Property. All rights reserved. - * ================================================================================ - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * ============LICENSE_END========================================================= - * - * ECOMP is a trademark and service mark of AT&T Intellectual Property. - * - *******************************************************************************/ -package org.onap.dmaap.mr.test.clients; -import java.io.File; -import java.io.FileReader; -import java.io.FileWriter; -import java.io.IOException; -import java.util.Properties; -import org.json.JSONObject; -import org.onap.dmaap.mr.client.MRBatchingPublisher; -import org.onap.dmaap.mr.client.MRClientFactory; -import org.onap.dmaap.mr.client.response.MRPublisherResponse; - /** - *An example of how to use the Java publisher. - * @author author - * - */ - public class SimpleExamplePublisherWithResponse - { - static FileWriter routeWriter= null; - static Properties props=null; - static FileReader routeReader=null; - - public static void main(String []args) throws InterruptedException, Exception{ - - String routeFilePath="src/main/resources/dme2/preferredRoute.txt"; - String msgCount = args[0]; - SimpleExamplePublisherWithResponse publisher = new SimpleExamplePublisherWithResponse(); - File fo= new File(routeFilePath); - if(!fo.exists()){ - routeWriter=new FileWriter(new File (routeFilePath)); - } - routeReader= new FileReader(new File (routeFilePath)); - props= new Properties(); - int i=0; - while (i< Integer.valueOf(msgCount)) - { - publisher.publishMessage("src/main/resources/dme2/producer.properties",Integer.valueOf(msgCount)); - i++; - } - } - - public void publishMessage ( String producerFilePath , int count ) throws IOException, InterruptedException - { - // create our publisher - final MRBatchingPublisher pub = MRClientFactory.createBatchingPublisher (producerFilePath,true); - // publish some messages - final JSONObject msg1 = new JSONObject (); - - msg1.put ( "Partition:1", "Message:"+count); - msg1.put ( "greeting", "Hello .." ); - - - pub.send ( "1", msg1.toString()); - pub.send ( "1", msg1.toString()); - - MRPublisherResponse res= pub.sendBatchWithResponse(); - - System.out.println("Pub response->"+res.toString()); - } - - - } diff --git a/src/main/java/org/onap/dmaap/mr/test/support/MRBatchingPublisherMock.java b/src/main/java/org/onap/dmaap/mr/test/support/MRBatchingPublisherMock.java deleted file mode 100644 index 3e64c35..0000000 --- a/src/main/java/org/onap/dmaap/mr/test/support/MRBatchingPublisherMock.java +++ /dev/null @@ -1,184 +0,0 @@ -/******************************************************************************* - * ============LICENSE_START======================================================= - * org.onap.dmaap - * ================================================================================ - * Copyright © 2017 AT&T Intellectual Property. All rights reserved. - * ================================================================================ - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * ============LICENSE_END========================================================= - * - * ECOMP is a trademark and service mark of AT&T Intellectual Property. - * - *******************************************************************************/ -package org.onap.dmaap.mr.test.support; - -import java.util.Collection; -import java.util.LinkedList; -import java.util.List; -import java.util.concurrent.TimeUnit; - -import org.slf4j.Logger; - -import org.onap.dmaap.mr.client.MRBatchingPublisher; -import org.onap.dmaap.mr.client.response.MRPublisherResponse; - -/** - * A helper for unit testing systems that use a MRPublisher. When setting - * up your test, inject an instance into MRClientFactory to have it return - * the mock client. - * - * @author author - * - */ -public class MRBatchingPublisherMock implements MRBatchingPublisher -{ - public class Entry - { - public Entry ( String partition, String msg ) - { - fPartition = partition; - fMessage = msg; - } - - @Override - public String toString () - { - return fMessage; - } - - public final String fPartition; - public final String fMessage; - } - - public MRBatchingPublisherMock () - { - fCaptures = new LinkedList<> (); - } - - public interface Listener - { - void onMessage ( Entry e ); - } - public void addListener ( Listener listener ) - { - fListeners.add ( listener ); - } - - public List getCaptures () - { - return getCaptures ( new MessageFilter () { @Override public boolean match ( String msg ) { return true; } } ); - } - - public interface MessageFilter - { - boolean match ( String msg ); - } - - public List getCaptures ( MessageFilter filter ) - { - final LinkedList result = new LinkedList<> (); - for ( Entry capture : fCaptures ) - { - if ( filter.match ( capture.fMessage ) ) - { - result.add ( capture ); - } - } - return result; - } - - public int received () - { - return fCaptures.size(); - } - - public void reset () - { - fCaptures.clear (); - } - - @Override - public int send ( String partition, String msg ) - { - final Entry e = new Entry ( partition, msg ); - - fCaptures.add ( e ); - for ( Listener l : fListeners ) - { - l.onMessage ( e ); - } - return 1; - } - - @Override - public int send ( message msg ) - { - return send ( msg.fPartition, msg.fMsg ); - } - @Override - public int send ( String msg ) - { - return 1; - - } - - @Override - public int send ( Collection msgs ) - { - int sum = 0; - for ( message m : msgs ) - { - sum += send ( m ); - } - return sum; - } - - @Override - public int getPendingMessageCount () - { - return 0; - } - - @Override - public List close ( long timeout, TimeUnit timeoutUnits ) - { - return new LinkedList<> (); - } - - @Override - public void close () - { - } - - @Override - public void setApiCredentials ( String apiKey, String apiSecret ) - { - } - - @Override - public void clearApiCredentials () - { - } - - @Override - public void logTo ( Logger log ) - { - } - - private final LinkedList fCaptures; - private LinkedList fListeners = new LinkedList<> (); - @Override - public MRPublisherResponse sendBatchWithResponse() { - // TODO Auto-generated method stub - return null; - } -} diff --git a/src/main/java/org/onap/dmaap/mr/test/support/MRConsumerMock.java b/src/main/java/org/onap/dmaap/mr/test/support/MRConsumerMock.java deleted file mode 100644 index afa36ea..0000000 --- a/src/main/java/org/onap/dmaap/mr/test/support/MRConsumerMock.java +++ /dev/null @@ -1,169 +0,0 @@ -/******************************************************************************* - * ============LICENSE_START======================================================= - * org.onap.dmaap - * ================================================================================ - * Copyright © 2017 AT&T Intellectual Property. All rights reserved. - * ================================================================================ - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * ============LICENSE_END========================================================= - * - * ECOMP is a trademark and service mark of AT&T Intellectual Property. - * - *******************************************************************************/ -package org.onap.dmaap.mr.test.support; - -import java.io.IOException; -import java.util.LinkedList; -import java.util.List; - -import org.slf4j.Logger; - -import org.onap.dmaap.mr.client.MRConsumer; -import org.onap.dmaap.mr.client.response.MRConsumerResponse; - -/** - * A helper for unit testing systems that use a MRConsumer. When setting - * up your test, inject an instance into MRClientFactory to have it return - * the mock client. - * - * @author author - * - */ -public class MRConsumerMock implements MRConsumer -{ - public class Entry - { - public Entry ( long waitMs, int statusCode, List msgs ) - { - fWaitMs = waitMs; - fStatusCode = statusCode; - fStatusMsg = null; - fMsgs = new LinkedList<> ( msgs ); - } - - public Entry ( long waitMs, int statusCode, String statusMsg ) - { - fWaitMs = waitMs; - fStatusCode = statusCode; - fStatusMsg = statusMsg; - fMsgs = null; - } - - public LinkedList run () throws IOException - { - try - { - Thread.sleep ( fWaitMs ); - if ( fStatusCode >= 200 && fStatusCode <= 299 ) - { - return fMsgs; - } - throw new IOException ( "" + fStatusCode + " " + fStatusMsg ); - } - catch ( InterruptedException e ) - { - Thread.currentThread().interrupt(); - throw new IOException ( e ); - } - } - - private final long fWaitMs; - private final int fStatusCode; - private final String fStatusMsg; - private final LinkedList fMsgs; - } - - public MRConsumerMock () - { - fReplies = new LinkedList<> (); - } - - @Override - public void close () - { - } - - @Override - public void setApiCredentials ( String apiKey, String apiSecret ) - { - } - - @Override - public void clearApiCredentials () - { - } - - public synchronized void add ( Entry e ) - { - fReplies.add ( e ); - } - - public void addImmediateMsg ( String msg ) - { - addDelayedMsg ( 0, msg ); - } - - public void addDelayedMsg ( long delay, String msg ) - { - final LinkedList list = new LinkedList<> (); - list.add ( msg ); - add ( new Entry ( delay, 200, list ) ); - } - - public void addImmediateMsgGroup ( List msgs ) - { - addDelayedMsgGroup ( 0, msgs ); - } - - public void addDelayedMsgGroup ( long delay, List msgs ) - { - final LinkedList list = new LinkedList<> ( msgs ); - add ( new Entry ( delay, 200, list ) ); - } - - public void addImmediateError ( int statusCode, String statusText ) - { - add ( new Entry ( 0, statusCode, statusText ) ); - } - - @Override - public Iterable fetch () throws IOException - { - return fetch ( -1, -1 ); - } - - @Override - public Iterable fetch ( int timeoutMs, int limit ) throws IOException - { - return fReplies.size () > 0 ? fReplies.removeFirst ().run() : new LinkedList(); - } - - @Override - public void logTo ( Logger log ) - { - } - - private final LinkedList fReplies; - - @Override - public MRConsumerResponse fetchWithReturnConsumerResponse() { - // TODO Auto-generated method stub - return null; - } - - @Override - public MRConsumerResponse fetchWithReturnConsumerResponse(int timeoutMs, - int limit) { - // TODO Auto-generated method stub - return null; - } -} diff --git a/src/main/java/org/onap/dmaap/mr/tools/ApiKeyCommand.java b/src/main/java/org/onap/dmaap/mr/tools/ApiKeyCommand.java index a2396d8..6a2bf37 100644 --- a/src/main/java/org/onap/dmaap/mr/tools/ApiKeyCommand.java +++ b/src/main/java/org/onap/dmaap/mr/tools/ApiKeyCommand.java @@ -4,11 +4,13 @@ * ================================================================================ * Copyright © 2017 AT&T Intellectual Property. All rights reserved. * ================================================================================ + * Modifications Copyright © 2021 Orange. + * ================================================================================ * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * http://www.apache.org/licenses/LICENSE-2.0 - * + * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. @@ -17,125 +19,102 @@ * ============LICENSE_END========================================================= * * ECOMP is a trademark and service mark of AT&T Intellectual Property. - * + * *******************************************************************************/ -package org.onap.dmaap.mr.tools; -import java.io.IOException; -import java.io.PrintStream; - -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; +package org.onap.dmaap.mr.tools; import com.att.nsa.apiClient.credentials.ApiCredential; import com.att.nsa.apiClient.http.HttpException; import com.att.nsa.apiClient.http.HttpObjectNotFoundException; import com.att.nsa.cmdtool.Command; import com.att.nsa.cmdtool.CommandNotReadyException; +import java.io.IOException; +import java.io.PrintStream; +import org.onap.dmaap.mr.client.MRClient.MRApiException; import org.onap.dmaap.mr.client.MRClientFactory; import org.onap.dmaap.mr.client.MRIdentityManager; -import org.onap.dmaap.mr.client.MRClient.MRApiException; import org.onap.dmaap.mr.client.MRIdentityManager.ApiKey; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +public class ApiKeyCommand implements Command { + final Logger logger = LoggerFactory.getLogger(ApiKeyCommand.class); -public class ApiKeyCommand implements Command -{ - final Logger log = LoggerFactory.getLogger(ApiKeyCommand.class); - @Override - public String[] getMatches () - { - return new String[]{ - "key (create|update) (\\S*) (\\S*)", - "key (list) (\\S*)", - "key (revoke)", - }; - } + @Override + public String[] getMatches() { + return new String[] { + "key (create|update) (\\S*) (\\S*)", + "key (list) (\\S*)", + "key (revoke)", + }; + } - @Override - public void checkReady ( MRCommandContext context ) throws CommandNotReadyException - { - if ( !context.checkClusterReady () ) - { - throw new CommandNotReadyException ( "Use 'cluster' to specify a cluster to use." ); - } - } + @Override + public void checkReady(MRCommandContext context) throws CommandNotReadyException { + if (!context.checkClusterReady()) { + throw new CommandNotReadyException("Use 'cluster' to specify a cluster to use."); + } + } - @Override - public void execute ( String[] parts, MRCommandContext context, PrintStream out ) throws CommandNotReadyException - { - final MRIdentityManager tm = MRClientFactory.createIdentityManager ( context.getCluster(), context.getApiKey(), context.getApiPwd() ); - context.applyTracer ( tm ); + @Override + public void execute(String[] parts, MRCommandContext context, PrintStream out) throws CommandNotReadyException { + final MRIdentityManager tm = MRClientFactory.createIdentityManager(context.getCluster(), context.getApiKey(), context.getApiPwd()); + context.applyTracer(tm); - try - { - if ( parts[0].equals ( "list" ) ) - { - final ApiKey key = tm.getApiKey ( parts[1] ); - if ( key != null ) - { - out.println ( "email: " + key.getEmail () ); - out.println ( "description: " + key.getDescription () ); - } - else - { - out.println ( "No key returned" ); - } - } - else if ( parts[0].equals ( "create" ) ) - { - final ApiCredential ac = tm.createApiKey ( parts[1], parts[2] ); - if ( ac != null ) - { - out.println ( " key: " + ac.getApiKey () ); - out.println ( "secret: " + ac.getApiSecret () ); - } - else - { - out.println ( "No credential returned?" ); - } - } - else if ( parts[0].equals ( "update" ) ) - { - tm.updateCurrentApiKey ( parts[1], parts[2] ); - out.println ( "Updated" ); - } - else if ( parts[0].equals ( "revoke" ) ) - { - tm.deleteCurrentApiKey (); - out.println ( "Updated" ); - } - } - catch ( HttpObjectNotFoundException e ) - { - out.println ( "Object not found: " + e.getMessage () ); - log.error("HttpObjectNotFoundException: ", e); - } - catch ( HttpException e ) - { - out.println ( "HTTP exception: " + e.getMessage () ); - log.error("HttpException: ", e); - } - catch ( MRApiException e ) - { - out.println ( "API exception: " + e.getMessage () ); - log.error("MRApiException: ", e); - } - catch ( IOException e ) - { - out.println ( "IO exception: " + e.getMessage () ); - log.error("IOException: ", e); - } - finally - { - tm.close (); - } - } + try { + switch (parts[0]) { + case "list": + final ApiKey key = tm.getApiKey(parts[1]); + if (key != null) { + out.println("email: " + key.getEmail()); + out.println("description: " + key.getDescription()); + } else { + out.println("No key returned"); + } + break; + case "create": + final ApiCredential ac = tm.createApiKey(parts[1], parts[2]); + if (ac != null) { + out.println(" key: " + ac.getApiKey()); + out.println("secret: " + ac.getApiSecret()); + } else { + out.println("No credential returned?"); + } + break; + case "update": + tm.updateCurrentApiKey(parts[1], parts[2]); + out.println("Updated"); + break; + case "revoke": + tm.deleteCurrentApiKey(); + out.println("Updated"); + break; + default: + throw new CommandNotReadyException("The command " + parts[0] + " is not available"); + } + } catch (HttpObjectNotFoundException e) { + out.println("Object not found: " + e.getMessage()); + logger.error("HttpObjectNotFoundException: ", e); + } catch (HttpException e) { + out.println("HTTP exception: " + e.getMessage()); + logger.error("HttpException: ", e); + } catch (MRApiException e) { + out.println("API exception: " + e.getMessage()); + logger.error("MRApiException: ", e); + } catch (IOException e) { + out.println("IO exception: " + e.getMessage()); + logger.error("IOException: ", e); + } finally { + tm.close(); + } + } - @Override - public void displayHelp ( PrintStream out ) - { - out.println ( "key create " ); - out.println ( "key update " ); - out.println ( "key list " ); - out.println ( "key revoke" ); - } + @Override + public void displayHelp(PrintStream out) { + out.println("key create "); + out.println("key update "); + out.println("key list "); + out.println("key revoke"); + } } diff --git a/src/main/java/org/onap/dmaap/mr/tools/AuthCommand.java b/src/main/java/org/onap/dmaap/mr/tools/AuthCommand.java index 26a70f0..b3657ee 100644 --- a/src/main/java/org/onap/dmaap/mr/tools/AuthCommand.java +++ b/src/main/java/org/onap/dmaap/mr/tools/AuthCommand.java @@ -4,11 +4,13 @@ * ================================================================================ * Copyright © 2017 AT&T Intellectual Property. All rights reserved. * ================================================================================ + * Modifications Copyright © 2021 Orange. + * ================================================================================ * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * http://www.apache.org/licenses/LICENSE-2.0 - * + * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. @@ -17,53 +19,45 @@ * ============LICENSE_END========================================================= * * ECOMP is a trademark and service mark of AT&T Intellectual Property. - * + * *******************************************************************************/ -package org.onap.dmaap.mr.tools; -import java.io.PrintStream; +package org.onap.dmaap.mr.tools; import com.att.nsa.cmdtool.Command; import com.att.nsa.cmdtool.CommandNotReadyException; -public class AuthCommand implements Command -{ - @Override - public void checkReady ( MRCommandContext context ) throws CommandNotReadyException - { - } +import java.io.PrintStream; + +public class AuthCommand implements Command { + @Override + public void checkReady(MRCommandContext context) throws CommandNotReadyException { + } - @Override - public void execute ( String[] parts, MRCommandContext context, PrintStream out ) throws CommandNotReadyException - { - if ( parts.length > 0 ) - { - context.setAuth ( parts[0], parts[1] ); - out.println ( "Now authenticating with " + parts[0] ); - } - else - { - context.clearAuth (); - out.println ( "No longer authenticating." ); - } - } + @Override + public void execute(String[] parts, MRCommandContext context, PrintStream out) throws CommandNotReadyException { + if (parts.length > 0) { + context.setAuth(parts[0], parts[1]); + out.println("Now authenticating with " + parts[0]); + } else { + context.clearAuth(); + out.println("No longer authenticating."); + } + } - @Override - public void displayHelp ( PrintStream out ) - { - out.println ( "auth " ); - out.println ( "\tuse these credentials on subsequent transactions" ); - out.println ( "noauth" ); - out.println ( "\tdo not use credentials on subsequent transactions" ); - } + @Override + public void displayHelp(PrintStream out) { + out.println("auth "); + out.println("\tuse these credentials on subsequent transactions"); + out.println("noauth"); + out.println("\tdo not use credentials on subsequent transactions"); + } - @Override - public String[] getMatches () - { - return new String[] - { - "auth (\\S*) (\\S*)", - "noauth" - }; - } + @Override + public String[] getMatches() { + return new String[] { + "auth (\\S*) (\\S*)", + "noauth" + }; + } } diff --git a/src/main/java/org/onap/dmaap/mr/tools/ClusterCommand.java b/src/main/java/org/onap/dmaap/mr/tools/ClusterCommand.java index c4ef5e4..60c0380 100644 --- a/src/main/java/org/onap/dmaap/mr/tools/ClusterCommand.java +++ b/src/main/java/org/onap/dmaap/mr/tools/ClusterCommand.java @@ -4,11 +4,13 @@ * ================================================================================ * Copyright © 2017 AT&T Intellectual Property. All rights reserved. * ================================================================================ + * Modifications Copyright © 2021 Orange. + * ================================================================================ * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * http://www.apache.org/licenses/LICENSE-2.0 - * + * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. @@ -17,64 +19,52 @@ * ============LICENSE_END========================================================= * * ECOMP is a trademark and service mark of AT&T Intellectual Property. - * + * *******************************************************************************/ -package org.onap.dmaap.mr.tools; -import java.io.PrintStream; +package org.onap.dmaap.mr.tools; import com.att.nsa.cmdtool.Command; import com.att.nsa.cmdtool.CommandNotReadyException; +import java.io.PrintStream; import org.onap.dmaap.mr.client.impl.MRConsumerImpl; -public class ClusterCommand implements Command -{ +public class ClusterCommand implements Command { - @Override - public String[] getMatches () - { - return new String[]{ - "cluster", - "cluster (\\S*)?", - }; - } + @Override + public String[] getMatches() { + return new String[] { + "cluster", + "cluster (\\S*)?", + }; + } - @Override - public void checkReady ( MRCommandContext context ) throws CommandNotReadyException - { - } + @Override + public void checkReady(MRCommandContext context) throws CommandNotReadyException { + } - @Override - public void execute ( String[] parts, MRCommandContext context, PrintStream out ) throws CommandNotReadyException - { - if ( parts.length == 0 ) - { - for ( String host : context.getCluster () ) - { - out.println ( host ); - } - } - else - { - context.clearCluster (); - for ( String part : parts ) - { - String[] hosts = part.trim().split ( "\\s+" ); - for ( String host : hosts ) - { - for ( String splitHost : MRConsumerImpl.stringToList(host) ) - { - context.addClusterHost ( splitHost ); - } - } - } - } - } + @Override + public void execute(String[] parts, MRCommandContext context, PrintStream out) throws CommandNotReadyException { + if (parts.length == 0) { + for (String host : context.getCluster()) { + out.println(host); + } + } else { + context.clearCluster(); + for (String part : parts) { + String[] hosts = part.trim().split("\\s+"); + for (String host : hosts) { + for (String splitHost : MRConsumerImpl.stringToList(host)) { + context.addClusterHost(splitHost); + } + } + } + } + } - @Override - public void displayHelp ( PrintStream out ) - { - out.println ( "cluster host1 host2 ..." ); - } + @Override + public void displayHelp(PrintStream out) { + out.println("cluster host1 host2 ..."); + } } diff --git a/src/main/java/org/onap/dmaap/mr/tools/MRCommandContext.java b/src/main/java/org/onap/dmaap/mr/tools/MRCommandContext.java index 5d13b30..0ccd6bf 100644 --- a/src/main/java/org/onap/dmaap/mr/tools/MRCommandContext.java +++ b/src/main/java/org/onap/dmaap/mr/tools/MRCommandContext.java @@ -4,11 +4,13 @@ * ================================================================================ * Copyright © 2017 AT&T Intellectual Property. All rights reserved. * ================================================================================ + * Modifications Copyright © 2021 Orange. + * ================================================================================ * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * http://www.apache.org/licenses/LICENSE-2.0 - * + * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. @@ -17,84 +19,87 @@ * ============LICENSE_END========================================================= * * ECOMP is a trademark and service mark of AT&T Intellectual Property. - * + * *******************************************************************************/ -package org.onap.dmaap.mr.tools; -import java.util.Collection; -import java.util.LinkedList; +package org.onap.dmaap.mr.tools; import com.att.nsa.apiClient.http.HttpClient; import com.att.nsa.apiClient.http.HttpTracer; import com.att.nsa.cmdtool.CommandContext; +import java.util.Collection; +import java.util.LinkedList; import org.onap.dmaap.mr.client.MRClient; -public class MRCommandContext implements CommandContext -{ - public MRCommandContext () - { - fApiKey = null; - fApiPwd = null; - - fCluster = new LinkedList<> (); - fCluster.add ( "localhost" ); - } - - @Override - public void requestShutdown () - { - fShutdown = true; - } - - @Override - public boolean shouldContinue () - { - return !fShutdown; - } - - public void setAuth ( String key, String pwd ) { fApiKey = key; fApiPwd = pwd; } - public void clearAuth () { setAuth(null,null); } - - public boolean checkClusterReady () - { - return ( fCluster.isEmpty()); - } - - public Collection getCluster () - { - return new LinkedList<> ( fCluster ); - } - - public void clearCluster () - { - fCluster.clear (); - } - - public void addClusterHost ( String host ) - { - fCluster.add ( host ); - } - - public String getApiKey () { return fApiKey; } - public String getApiPwd () { return fApiPwd; } - - public void useTracer ( HttpTracer t ) - { - fTracer = t; - } - public void noTracer () { fTracer = null; } - - public void applyTracer ( MRClient cc ) - { - if ( cc instanceof HttpClient && fTracer != null ) - { - ((HttpClient)cc).installTracer ( fTracer ); - } - } - - private boolean fShutdown; - private String fApiKey; - private String fApiPwd; - private final LinkedList fCluster; - private HttpTracer fTracer = null; +public class MRCommandContext implements CommandContext { + public MRCommandContext() { + fApiKey = null; + fApiPwd = null; + + fCluster = new LinkedList<>(); + fCluster.add("localhost"); + } + + @Override + public void requestShutdown() { + fShutdown = true; + } + + @Override + public boolean shouldContinue() { + return !fShutdown; + } + + public void setAuth(String key, String pwd) { + fApiKey = key; + fApiPwd = pwd; + } + + public void clearAuth() { + setAuth(null, null); + } + + public boolean checkClusterReady() { + return (fCluster.isEmpty()); + } + + public Collection getCluster() { + return new LinkedList<>(fCluster); + } + + public void clearCluster() { + fCluster.clear(); + } + + public void addClusterHost(String host) { + fCluster.add(host); + } + + public String getApiKey() { + return fApiKey; + } + + public String getApiPwd() { + return fApiPwd; + } + + public void useTracer(HttpTracer t) { + fTracer = t; + } + + public void noTracer() { + fTracer = null; + } + + public void applyTracer(MRClient cc) { + if (cc instanceof HttpClient && fTracer != null) { + ((HttpClient) cc).installTracer(fTracer); + } + } + + private boolean fShutdown; + private String fApiKey; + private String fApiPwd; + private final LinkedList fCluster; + private HttpTracer fTracer = null; } diff --git a/src/main/java/org/onap/dmaap/mr/tools/MRTool.java b/src/main/java/org/onap/dmaap/mr/tools/MRTool.java deleted file mode 100644 index a37fa79..0000000 --- a/src/main/java/org/onap/dmaap/mr/tools/MRTool.java +++ /dev/null @@ -1,49 +0,0 @@ -/******************************************************************************* - * ============LICENSE_START======================================================= - * org.onap.dmaap - * ================================================================================ - * Copyright © 2017 AT&T Intellectual Property. All rights reserved. - * ================================================================================ - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * ============LICENSE_END========================================================= - * - * ECOMP is a trademark and service mark of AT&T Intellectual Property. - * - *******************************************************************************/ -package org.onap.dmaap.mr.tools; - -import java.io.IOException; - -import com.att.nsa.cmdtool.CommandLineTool; -import org.onap.dmaap.mr.client.impl.MRClientVersionInfo; - -public class MRTool extends CommandLineTool -{ - protected MRTool () - { - super ( "MR Tool (" + MRClientVersionInfo.getVersion () + ")", "MR> " ); - - registerCommand ( new ApiKeyCommand () ); - registerCommand ( new AuthCommand () ); - registerCommand ( new ClusterCommand () ); - registerCommand ( new MessageCommand () ); - registerCommand ( new TopicCommand () ); - registerCommand ( new TraceCommand () ); - } - - public static void main ( String[] args ) throws IOException - { - final MRTool ct = new MRTool (); - final MRCommandContext ccc = new MRCommandContext (); - ct.runFromMain ( args, ccc ); - } -} diff --git a/src/main/java/org/onap/dmaap/mr/tools/MessageCommand.java b/src/main/java/org/onap/dmaap/mr/tools/MessageCommand.java index 451aed5..5d8bfb8 100644 --- a/src/main/java/org/onap/dmaap/mr/tools/MessageCommand.java +++ b/src/main/java/org/onap/dmaap/mr/tools/MessageCommand.java @@ -4,11 +4,13 @@ * ================================================================================ * Copyright © 2017 AT&T Intellectual Property. All rights reserved. * ================================================================================ + * Modifications Copyright © 2021 Orange. + * ================================================================================ * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * http://www.apache.org/licenses/LICENSE-2.0 - * + * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. @@ -17,114 +19,90 @@ * ============LICENSE_END========================================================= * * ECOMP is a trademark and service mark of AT&T Intellectual Property. - * + * *******************************************************************************/ + package org.onap.dmaap.mr.tools; +import com.att.nsa.cmdtool.Command; +import com.att.nsa.cmdtool.CommandNotReadyException; import java.io.IOException; import java.io.PrintStream; import java.util.List; import java.util.concurrent.TimeUnit; - -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; - -import com.att.nsa.cmdtool.Command; -import com.att.nsa.cmdtool.CommandNotReadyException; import org.onap.dmaap.mr.client.MRBatchingPublisher; import org.onap.dmaap.mr.client.MRClientFactory; import org.onap.dmaap.mr.client.MRConsumer; -import org.onap.dmaap.mr.client.MRPublisher.message; +import org.onap.dmaap.mr.client.MRPublisher.Message; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +public class MessageCommand implements Command { + final Logger logger = LoggerFactory.getLogger(MessageCommand.class); + + private static final String SENDING_PROBLEM_MESSAGE = "Problem sending message: "; -public class MessageCommand implements Command -{ - final Logger logger = LoggerFactory.getLogger(ApiKeyCommand.class); - @Override - public String[] getMatches () - { - return new String[]{ - "(post) (\\S*) (\\S*) (.*)", - "(read) (\\S*) (\\S*) (\\S*)", - }; - } + @Override + public String[] getMatches() { + return new String[] { + "(post) (\\S*) (\\S*) (.*)", + "(read) (\\S*) (\\S*) (\\S*)", + }; + } - @Override - public void checkReady ( MRCommandContext context ) throws CommandNotReadyException - { - if ( !context.checkClusterReady () ) - { - throw new CommandNotReadyException ( "Use 'cluster' to specify a cluster to use." ); - } - } + @Override + public void checkReady(MRCommandContext context) throws CommandNotReadyException { + if (!context.checkClusterReady()) { + throw new CommandNotReadyException("Use 'cluster' to specify a cluster to use."); + } + } - @Override - public void execute ( String[] parts, MRCommandContext context, PrintStream out ) throws CommandNotReadyException - { - if ( parts[0].equalsIgnoreCase ( "read" )) - { - final MRConsumer cc = MRClientFactory.createConsumer ( context.getCluster (), parts[1], parts[2], parts[3], - -1, -1, null, context.getApiKey(), context.getApiPwd() ); - context.applyTracer ( cc ); - try - { - for ( String msg : cc.fetch () ) - { - out.println ( msg ); - } - } - catch ( Exception e ) - { - out.println ( "Problem fetching messages: " + e.getMessage() ); - logger.error("Problem fetching messages: ", e); - } - finally - { - cc.close (); - } - } - else - { - final MRBatchingPublisher pub=ToolsUtil.createBatchPublisher(context, parts[1]); - try - { - pub.send ( parts[2], parts[3] ); - } - catch ( IOException e ) - { - out.println ( "Problem sending message: " + e.getMessage() ); - logger.error("Problem sending message: ", e); - } - finally - { - List left = null; - try - { - left = pub.close ( 500, TimeUnit.MILLISECONDS ); - } - catch ( IOException e ) - { - out.println ( "Problem sending message: " + e.getMessage() ); - logger.error("Problem sending message: ", e); - } - catch ( InterruptedException e ) - { - out.println ( "Problem sending message: " + e.getMessage() ); - logger.error("Problem sending message: ", e); - Thread.currentThread().interrupt(); - } - if ( left != null && left.isEmpty() ) - { - out.println ( left.size() + " messages not sent." ); - } - } - } - } + @Override + public void execute(String[] parts, MRCommandContext context, PrintStream out) throws CommandNotReadyException { + if (parts[0].equalsIgnoreCase("read")) { + final MRConsumer cc = MRClientFactory.createConsumer(context.getCluster(), parts[1], parts[2], parts[3], + -1, -1, null, context.getApiKey(), context.getApiPwd()); + context.applyTracer(cc); + try { + for (String msg : cc.fetch()) { + out.println(msg); + } + } catch (Exception e) { + out.println("Problem fetching messages: " + e.getMessage()); + logger.error("Problem fetching messages: ", e); + } finally { + cc.close(); + } + } else { + final MRBatchingPublisher pub = ToolsUtil.createBatchPublisher(context, parts[1]); + try { + pub.send(parts[2], parts[3]); + } catch (IOException e) { + out.println(SENDING_PROBLEM_MESSAGE + e.getMessage()); + logger.error(SENDING_PROBLEM_MESSAGE, e); + } finally { + List left = null; + try { + left = pub.close(500, TimeUnit.MILLISECONDS); + } catch (IOException e) { + out.println(SENDING_PROBLEM_MESSAGE + e.getMessage()); + logger.error(SENDING_PROBLEM_MESSAGE, e); + } catch (InterruptedException e) { + out.println(SENDING_PROBLEM_MESSAGE + e.getMessage()); + logger.error(SENDING_PROBLEM_MESSAGE, e); + Thread.currentThread().interrupt(); + } + if (left != null && !left.isEmpty()) { + out.println(left.size() + " messages not sent."); + } + } + } + } - @Override - public void displayHelp ( PrintStream out ) - { - out.println ( "post " ); - out.println ( "read " ); - } + @Override + public void displayHelp(PrintStream out) { + out.println("post "); + out.println("read "); + } } diff --git a/src/main/java/org/onap/dmaap/mr/tools/ToolsUtil.java b/src/main/java/org/onap/dmaap/mr/tools/ToolsUtil.java index 72e7fbf..ef9e103 100644 --- a/src/main/java/org/onap/dmaap/mr/tools/ToolsUtil.java +++ b/src/main/java/org/onap/dmaap/mr/tools/ToolsUtil.java @@ -4,12 +4,14 @@ * ================================================================================ * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. * ================================================================================ + * Modifications Copyright © 2021 Orange. + * ================================================================================ * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at - * + * * http://www.apache.org/licenses/LICENSE-2.0 - * + * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. @@ -28,13 +30,13 @@ public final class ToolsUtil { private ToolsUtil() { } - public static MRBatchingPublisher createBatchPublisher(MRCommandContext context,String topicName){ - - return new PublisherBuilder (). - usingHosts ( context.getCluster () ). - onTopic (topicName). - authenticatedBy ( context.getApiKey(), context.getApiPwd() ). - build (); - } + public static MRBatchingPublisher createBatchPublisher(MRCommandContext context, String topicName) { + + return new PublisherBuilder() + .usingHosts(context.getCluster()) + .onTopic(topicName) + .authenticatedBy(context.getApiKey(), context.getApiPwd()) + .build(); + } } diff --git a/src/main/java/org/onap/dmaap/mr/tools/TopicCommand.java b/src/main/java/org/onap/dmaap/mr/tools/TopicCommand.java index 278b04f..e8ad076 100644 --- a/src/main/java/org/onap/dmaap/mr/tools/TopicCommand.java +++ b/src/main/java/org/onap/dmaap/mr/tools/TopicCommand.java @@ -4,11 +4,13 @@ * ================================================================================ * Copyright © 2017 AT&T Intellectual Property. All rights reserved. * ================================================================================ + * Modifications Copyright © 2021 Orange. + * ================================================================================ * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * http://www.apache.org/licenses/LICENSE-2.0 - * + * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. @@ -17,205 +19,160 @@ * ============LICENSE_END========================================================= * * ECOMP is a trademark and service mark of AT&T Intellectual Property. - * + * *******************************************************************************/ -package org.onap.dmaap.mr.tools; - -import java.io.IOException; -import java.io.PrintStream; -import java.util.Set; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; +package org.onap.dmaap.mr.tools; import com.att.nsa.apiClient.http.HttpException; import com.att.nsa.apiClient.http.HttpObjectNotFoundException; import com.att.nsa.cmdtool.Command; import com.att.nsa.cmdtool.CommandNotReadyException; +import java.io.IOException; +import java.io.PrintStream; +import java.util.Set; import org.onap.dmaap.mr.client.MRClientFactory; import org.onap.dmaap.mr.client.MRTopicManager; import org.onap.dmaap.mr.client.MRTopicManager.TopicInfo; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +public class TopicCommand implements Command { + final Logger logger = LoggerFactory.getLogger(TopicCommand.class); + + private static final String REQUEST_ERROR_MESSAGE = "Problem with request: "; + private static final String IOEXCEPTION_MESSAGE = "IOException: "; + private static final String HTTP_EXCEPTION_MESSAGE = "HttpException: "; + + @Override + public String[] getMatches() { + return new String[] { + "topic (list)", + "topic (list) (\\S*)", + "topic (create) (\\S*) (\\S*) (\\S*)", + "topic (grant|revoke) (read|write) (\\S*) (\\S*)", + }; + } -public class TopicCommand implements Command -{ - final Logger logger = LoggerFactory.getLogger(ApiKeyCommand.class); - @Override - public String[] getMatches () - { - return new String[]{ - "topic (list)", - "topic (list) (\\S*)", - "topic (create) (\\S*) (\\S*) (\\S*)", - "topic (grant|revoke) (read|write) (\\S*) (\\S*)", - }; - } + @Override + public void checkReady(MRCommandContext context) throws CommandNotReadyException { + if (!context.checkClusterReady()) { + throw new CommandNotReadyException("Use 'cluster' to specify a cluster to use."); + } + } - @Override - public void checkReady ( MRCommandContext context ) throws CommandNotReadyException - { - if ( !context.checkClusterReady () ) - { - throw new CommandNotReadyException ( "Use 'cluster' to specify a cluster to use." ); - } - } + @Override + public void execute(String[] parts, MRCommandContext context, PrintStream out) throws CommandNotReadyException { + final MRTopicManager tm = MRClientFactory.createTopicManager(context.getCluster(), context.getApiKey(), context.getApiPwd()); + context.applyTracer(tm); - @Override - public void execute ( String[] parts, MRCommandContext context, PrintStream out ) throws CommandNotReadyException - { - final MRTopicManager tm = MRClientFactory.createTopicManager ( context.getCluster(), context.getApiKey(), context.getApiPwd() ); - context.applyTracer ( tm ); + try { + switch (parts[0]) { + case "list": + try { + if (parts.length == 1) { + for (String topic : tm.getTopics()) { + out.println(topic); + } + } else { + final TopicInfo ti = tm.getTopicMetadata(parts[1]); - try - { - if ( parts[0].equals ( "list" ) ) - { - try - { - if ( parts.length == 1 ) - { - for ( String topic : tm.getTopics () ) - { - out.println ( topic ); - } - } - else - { - final TopicInfo ti = tm.getTopicMetadata ( parts[1] ); + final String owner = ti.getOwner(); + out.println(" owner: " + (owner == null ? "" : owner)); - final String owner = ti.getOwner (); - out.println ( " owner: " + ( owner == null ? "" : owner ) ); + final String desc = ti.getDescription(); + out.println("description: " + (desc == null ? "" : desc)); - final String desc = ti.getDescription (); - out.println ( "description: " + ( desc == null ? "" : desc ) ); + final Set prods = ti.getAllowedProducers(); + if (prods != null) { + out.println(" write ACL: "); + for (String key : prods) { + out.println("\t" + key); + } + } else { + out.println(" write ACL: "); + } - final Set prods = ti.getAllowedProducers (); - if ( prods != null ) - { - out.println ( " write ACL: " ); - for ( String key : prods ) - { - out.println ( "\t" + key ); - } - } - else - { - out.println ( " write ACL: " ); - } + final Set cons = ti.getAllowedConsumers(); + if (cons != null) { + out.println(" read ACL: "); + for (String key : cons) { + out.println("\t" + key); + } + } else { + out.println(" read ACL: "); + } + } + } catch (IOException x) { + out.println(REQUEST_ERROR_MESSAGE + x.getMessage()); + logger.error(IOEXCEPTION_MESSAGE, x); + } catch (HttpObjectNotFoundException e) { + out.println("Not found: " + e.getMessage()); + logger.error("HttpObjectNotFoundException: ", e); + } + break; + case "create": + try { + final int partitions = Integer.parseInt(parts[2]); + final int replicas = Integer.parseInt(parts[3]); - final Set cons = ti.getAllowedConsumers (); - if ( cons != null ) - { - out.println ( " read ACL: " ); - for ( String key : cons ) - { - out.println ( "\t" + key ); - } - } - else - { - out.println ( " read ACL: " ); - } - } - } - catch ( IOException x ) - { - out.println ( "Problem with request: " + x.getMessage () ); - logger.error("IOException: ", x); - } - catch ( HttpObjectNotFoundException e ) - { - out.println ( "Not found: " + e.getMessage () ); - logger.error("HttpObjectNotFoundException: ", e); - } - } - else if ( parts[0].equals ( "create" ) ) - { - try - { - final int partitions = Integer.parseInt ( parts[2] ); - final int replicas = Integer.parseInt ( parts[3] ); - - tm.createTopic ( parts[1], "", partitions, replicas ); - } - catch ( HttpException e ) - { - out.println ( "Problem with request: " + e.getMessage () ); - logger.error("HttpException: ", e); - } - catch ( IOException e ) - { - out.println ( "Problem with request: " + e.getMessage () ); - logger.error("IOException: ", e); - } - catch ( NumberFormatException e ) - { - out.println ( "Problem with request: " + e.getMessage () ); - logger.error("NumberFormatException: ", e); - } - } - else if ( parts[0].equals ( "grant" ) ) - { - try - { - if ( parts[1].equals ( "write" ) ) - { - tm.allowProducer ( parts[2], parts[3] ); - } - else if ( parts[1].equals ( "read" ) ) - { - tm.allowConsumer ( parts[2], parts[3] ); - } - } - catch ( HttpException e ) - { - out.println ( "Problem with request: " + e.getMessage () ); - logger.error("HttpException: ", e); - } - catch ( IOException e ) - { - out.println ( "Problem with request: " + e.getMessage () ); - logger.error("IOException: ", e); - } - } - else if ( parts[0].equals ( "revoke" ) ) - { - try - { - if ( parts[1].equals ( "write" ) ) - { - tm.revokeProducer ( parts[2], parts[3] ); - } - else if ( parts[1].equals ( "read" ) ) - { - tm.revokeConsumer ( parts[2], parts[3] ); - } - } - catch ( HttpException e ) - { - out.println ( "Problem with request: " + e.getMessage () ); - logger.error("HttpException: ", e); - } - catch ( IOException e ) - { - out.println ( "Problem with request: " + e.getMessage () ); - logger.error("IOException: ", e); - } - } - } - finally - { - tm.close (); - } - } + tm.createTopic(parts[1], "", partitions, replicas); + } catch (HttpException e) { + out.println(REQUEST_ERROR_MESSAGE + e.getMessage()); + logger.error(HTTP_EXCEPTION_MESSAGE, e); + } catch (IOException e) { + out.println(REQUEST_ERROR_MESSAGE + e.getMessage()); + logger.error(IOEXCEPTION_MESSAGE, e); + } catch (NumberFormatException e) { + out.println(REQUEST_ERROR_MESSAGE + e.getMessage()); + logger.error("NumberFormatException: ", e); + } + break; + case "grant": + try { + if (parts[1].equals("write")) { + tm.allowProducer(parts[2], parts[3]); + } else if (parts[1].equals("read")) { + tm.allowConsumer(parts[2], parts[3]); + } + } catch (HttpException e) { + out.println(REQUEST_ERROR_MESSAGE + e.getMessage()); + logger.error(HTTP_EXCEPTION_MESSAGE, e); + } catch (IOException e) { + out.println(REQUEST_ERROR_MESSAGE + e.getMessage()); + logger.error(IOEXCEPTION_MESSAGE, e); + } + break; + case "revoke": + try { + if (parts[1].equals("write")) { + tm.revokeProducer(parts[2], parts[3]); + } else if (parts[1].equals("read")) { + tm.revokeConsumer(parts[2], parts[3]); + } + } catch (HttpException e) { + out.println(REQUEST_ERROR_MESSAGE + e.getMessage()); + logger.error(HTTP_EXCEPTION_MESSAGE, e); + } catch (IOException e) { + out.println(REQUEST_ERROR_MESSAGE + e.getMessage()); + logger.error(IOEXCEPTION_MESSAGE, e); + } + break; + default: + throw new CommandNotReadyException("The command " + parts[0] + " is not available"); + } + } finally { + tm.close(); + } + } - @Override - public void displayHelp ( PrintStream out ) - { - out.println ( "topic list" ); - out.println ( "topic list " ); - out.println ( "topic create " ); - out.println ( "topic grant write|read " ); - out.println ( "topic revoke write|read " ); - } + @Override + public void displayHelp(PrintStream out) { + out.println("topic list"); + out.println("topic list "); + out.println("topic create "); + out.println("topic grant write|read "); + out.println("topic revoke write|read "); + } } diff --git a/src/main/java/org/onap/dmaap/mr/tools/TraceCommand.java b/src/main/java/org/onap/dmaap/mr/tools/TraceCommand.java index 95edf5b..a167c0f 100644 --- a/src/main/java/org/onap/dmaap/mr/tools/TraceCommand.java +++ b/src/main/java/org/onap/dmaap/mr/tools/TraceCommand.java @@ -4,11 +4,13 @@ * ================================================================================ * Copyright © 2017 AT&T Intellectual Property. All rights reserved. * ================================================================================ + * Modifications Copyright © 2021 Orange. + * ================================================================================ * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * http://www.apache.org/licenses/LICENSE-2.0 - * + * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. @@ -17,102 +19,87 @@ * ============LICENSE_END========================================================= * * ECOMP is a trademark and service mark of AT&T Intellectual Property. - * + * *******************************************************************************/ + package org.onap.dmaap.mr.tools; +import com.att.nsa.apiClient.http.HttpTracer; +import com.att.nsa.cmdtool.Command; +import com.att.nsa.cmdtool.CommandNotReadyException; + import java.io.PrintStream; import java.net.URI; import java.util.List; import java.util.Map; -import com.att.nsa.apiClient.http.HttpTracer; -import com.att.nsa.cmdtool.Command; -import com.att.nsa.cmdtool.CommandNotReadyException; - -public class TraceCommand implements Command -{ - @Override - public void checkReady ( MRCommandContext context ) throws CommandNotReadyException - { - } +public class TraceCommand implements Command { + @Override + public void checkReady(MRCommandContext context) throws CommandNotReadyException { + } - @Override - public void execute ( String[] parts, MRCommandContext context, final PrintStream out ) throws CommandNotReadyException - { - if ( parts[0].equalsIgnoreCase ( "on" )) - { - context.useTracer ( new HttpTracer () - { - @Override - public void outbound ( URI uri, Map> headers, String method, byte[] entity ) - { - out.println ( kLineBreak ); - out.println ( ">>> " + method + " " + uri.toString() ); - for ( Map.Entry> e : headers.entrySet () ) - { - final StringBuffer vals = new StringBuffer (); - for ( String val : e.getValue () ) - { - if ( vals.length () > 0 ) vals.append ( ", " ); - vals.append ( val ); - } - out.println ( ">>> " + e.getKey () + ": " + vals.toString() ); - } - if ( entity != null ) - { - out.println (); - out.println ( new String ( entity ) ); - } - out.println ( kLineBreak ); - } + @Override + public void execute(String[] parts, MRCommandContext context, final PrintStream out) throws CommandNotReadyException { + if (parts[0].equalsIgnoreCase("on")) { + context.useTracer(new HttpTracer() { + @Override + public void outbound(URI uri, Map> headers, String method, byte[] entity) { + out.println(K_LINE_BREAK); + out.println(">>> " + method + " " + uri.toString()); + for (Map.Entry> e : headers.entrySet()) { + final StringBuilder vals = new StringBuilder(); + for (String val : e.getValue()) { + if (vals.length() > 0) vals.append(", "); + vals.append(val); + } + out.println(">>> " + e.getKey() + ": " + vals); + } + if (entity != null) { + out.println(); + out.println(new String(entity)); + } + out.println(K_LINE_BREAK); + } - @Override - public void inbound ( Map> headers, int statusCode, String responseLine, byte[] entity ) - { - out.println ( kLineBreak ); - out.println ( "<<< " + responseLine ); - for ( Map.Entry> e : headers.entrySet () ) - { - final StringBuffer vals = new StringBuffer (); - for ( String val : e.getValue () ) - { - if ( vals.length () > 0 ) vals.append ( ", " ); - vals.append ( val ); - } - out.println ( "<<< " + e.getKey () + ": " + vals.toString() ); - } - if ( entity != null ) - { - out.println (); - out.println ( new String ( entity ) ); - } - out.println ( kLineBreak ); - } - } ); - } - else - { - context.noTracer (); - } - } + @Override + public void inbound(Map> headers, int statusCode, String responseLine, byte[] entity) { + out.println(K_LINE_BREAK); + out.println("<<< " + responseLine); + for (Map.Entry> e : headers.entrySet()) { + final StringBuilder vals = new StringBuilder(); + for (String val : e.getValue()) { + if (vals.length() > 0) { + vals.append(", "); + } + vals.append(val); + } + out.println("<<< " + e.getKey() + ": " + vals); + } + if (entity != null) { + out.println(); + out.println(new String(entity)); + } + out.println(K_LINE_BREAK); + } + }); + } else { + context.noTracer(); + } + } - @Override - public void displayHelp ( PrintStream out ) - { - out.println ( "trace on|off" ); - out.println ( "\tWhen trace is on, HTTP interaction is printed to the console." ); - } + @Override + public void displayHelp(PrintStream out) { + out.println("trace on|off"); + out.println("\tWhen trace is on, HTTP interaction is printed to the console."); + } - @Override - public String[] getMatches () - { - return new String[] - { - "trace (on)", - "trace (off)" - }; - } + @Override + public String[] getMatches() { + return new String[] { + "trace (on)", + "trace (off)" + }; + } - private static final String kLineBreak = "======================================================================"; + private static final String K_LINE_BREAK = "======================================================================"; } diff --git a/src/main/java/org/onap/dmaap/mr/tools/ValidatorUtil.java b/src/main/java/org/onap/dmaap/mr/tools/ValidatorUtil.java index cdba1e0..d01c34f 100644 --- a/src/main/java/org/onap/dmaap/mr/tools/ValidatorUtil.java +++ b/src/main/java/org/onap/dmaap/mr/tools/ValidatorUtil.java @@ -4,11 +4,13 @@ * ================================================================================ * Copyright © 2017 AT&T Intellectual Property. All rights reserved. * ================================================================================ + * Modifications Copyright © 2021 Orange. + * ================================================================================ * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * http://www.apache.org/licenses/LICENSE-2.0 - * + * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. @@ -17,158 +19,200 @@ * ============LICENSE_END========================================================= * * ECOMP is a trademark and service mark of AT&T Intellectual Property. - * + * *******************************************************************************/ + package org.onap.dmaap.mr.tools; import java.util.Properties; - -import org.onap.dmaap.mr.test.clients.ProtocolTypeConstants; +import org.onap.dmaap.mr.client.ProtocolType; public class ValidatorUtil { - public static void validatePublisher(Properties props) { - String transportType = props.getProperty("TransportType"); - if (ProtocolTypeConstants.DME2.getValue().equalsIgnoreCase(transportType)) { - validateForDME2(props); - } else { - validateForNonDME2(props); - } - String maxBatchSize = props.getProperty("maxBatchSize"); - if (maxBatchSize == null || maxBatchSize.isEmpty()) { - throw new IllegalArgumentException ( "maxBatchSize is needed" ); - } - String maxAgeMs = props.getProperty("maxAgeMs"); - if (maxAgeMs == null || maxAgeMs.isEmpty()) { - throw new IllegalArgumentException ( "maxAgeMs is needed" ); - } - String messageSentThreadOccurance = props.getProperty("MessageSentThreadOccurance"); - if (messageSentThreadOccurance == null || messageSentThreadOccurance.isEmpty()) { - throw new IllegalArgumentException ( "MessageSentThreadOccurance is needed" ); - } - - } + private static final String ID = "id"; + private static final String AUTH_KEY = "authKey"; + private static final String AUTH_DATE = "authDate"; + private static final String PASSWORD = "password"; + private static final String USERNAME = "username"; + private static final String HOST = "host"; + private static final String DME2PREFERRED_ROUTER_FILE_PATH = "DME2preferredRouterFilePath"; + private static final String TOPIC = "topic"; + private static final String TRANSPORT_TYPE = "TransportType"; + private static final String MAX_BATCH_SIZE = "maxBatchSize"; + private static final String MAX_AGE_MS = "maxAgeMs"; + private static final String MESSAGE_SENT_THREAD_OCCURRENCE_OLD = "MessageSentThreadOccurance"; + private static final String MESSAGE_SENT_THREAD_OCCURRENCE = "MessageSentThreadOccurrence"; + private static final String GROUP = "group"; + private static final String SERVICE_NAME = "ServiceName"; + private static final String PARTNER = "Partner"; + private static final String ROUTE_OFFER = "routeOffer"; + private static final String PROTOCOL = "Protocol"; + private static final String METHOD_TYPE = "MethodType"; + private static final String CONTENT_TYPE = "contenttype"; + private static final String LATITUDE = "Latitude"; + private static final String LONGITUDE = "Longitude"; + private static final String AFT_ENVIRONMENT = "AFT_ENVIRONMENT"; + private static final String VERSION = "Version"; + private static final String ENVIRONMENT = "Environment"; + private static final String SUB_CONTEXT_PATH = "SubContextPath"; + private static final String SESSION_STICKINESS_REQUIRED = "sessionstickinessrequired"; + + public static final String IS_NEEDED = " is needed"; + + private ValidatorUtil() { + + } + + public static void validatePublisher(Properties props) { + String transportType = props.getProperty(TRANSPORT_TYPE); + if (ProtocolType.DME2.getValue().equalsIgnoreCase(transportType)) { + validateForDME2(props); + } else { + validateForNonDME2(props); + } + String maxBatchSize = props.getProperty(MAX_BATCH_SIZE, ""); + if (maxBatchSize.isEmpty()) { + throw new IllegalArgumentException(MAX_BATCH_SIZE + IS_NEEDED); + } + String maxAgeMs = props.getProperty(MAX_AGE_MS, ""); + if (maxAgeMs.isEmpty()) { + throw new IllegalArgumentException(MAX_AGE_MS + IS_NEEDED); + } + + String messageSentThreadOccurrence = props.getProperty(MESSAGE_SENT_THREAD_OCCURRENCE); + if (messageSentThreadOccurrence == null || messageSentThreadOccurrence.isEmpty()) { + messageSentThreadOccurrence = props.getProperty(MESSAGE_SENT_THREAD_OCCURRENCE_OLD); + } + if (messageSentThreadOccurrence == null || messageSentThreadOccurrence.isEmpty()) { + throw new IllegalArgumentException(MESSAGE_SENT_THREAD_OCCURRENCE + IS_NEEDED); + } + try { + Integer.parseInt(messageSentThreadOccurrence); + } catch (NumberFormatException e) { + throw new IllegalArgumentException(MESSAGE_SENT_THREAD_OCCURRENCE + " must be an integer"); + } + + } + + public static void validateSubscriber(Properties props) { + String transportType = props.getProperty(TRANSPORT_TYPE); + if (ProtocolType.DME2.getValue().equalsIgnoreCase(transportType)) { + validateForDME2(props); + } else { + validateForNonDME2(props); + } + String group = props.getProperty(GROUP, ""); + if (group.isEmpty()) { + throw new IllegalArgumentException(GROUP + IS_NEEDED); + } + String id = props.getProperty(ID, ""); + if (id.isEmpty()) { + throw new IllegalArgumentException("Consumer (" + ID + ")" + IS_NEEDED); + } + } + + private static void validateForDME2(Properties props) { + String serviceName = props.getProperty(SERVICE_NAME, ""); + if (serviceName.isEmpty()) { + throw new IllegalArgumentException(SERVICE_NAME + IS_NEEDED); + } + String topic = props.getProperty(TOPIC, ""); + if (topic.isEmpty()) { + throw new IllegalArgumentException(TOPIC + IS_NEEDED); + } + String username = props.getProperty(USERNAME, ""); + if (username.isEmpty()) { + throw new IllegalArgumentException(USERNAME + IS_NEEDED); + } + String password = props.getProperty(PASSWORD, ""); + if (password.isEmpty()) { + throw new IllegalArgumentException(PASSWORD + IS_NEEDED); + } + String dme2preferredRouterFilePath = props.getProperty(DME2PREFERRED_ROUTER_FILE_PATH, ""); + if (dme2preferredRouterFilePath.isEmpty()) { + throw new IllegalArgumentException(DME2PREFERRED_ROUTER_FILE_PATH + IS_NEEDED); + } + String partner = props.getProperty(PARTNER, ""); + String routeOffer = props.getProperty(ROUTE_OFFER, ""); + if (partner.isEmpty() && routeOffer.isEmpty()) { + throw new IllegalArgumentException(PARTNER + " or " + ROUTE_OFFER + IS_NEEDED); + } + String protocol = props.getProperty(PROTOCOL, ""); + if (protocol.isEmpty()) { + throw new IllegalArgumentException(PROTOCOL + IS_NEEDED); + } + String methodType = props.getProperty(METHOD_TYPE, ""); + if (methodType.isEmpty()) { + throw new IllegalArgumentException(METHOD_TYPE + IS_NEEDED); + } + String contentType = props.getProperty(CONTENT_TYPE, ""); + if (contentType.isEmpty()) { + throw new IllegalArgumentException(CONTENT_TYPE + IS_NEEDED); + } + String latitude = props.getProperty(LATITUDE, ""); + if (latitude.isEmpty()) { + throw new IllegalArgumentException(LATITUDE + IS_NEEDED); + } + String longitude = props.getProperty(LONGITUDE, ""); + if (longitude.isEmpty()) { + throw new IllegalArgumentException(LONGITUDE + IS_NEEDED); + } + String aftEnv = props.getProperty(AFT_ENVIRONMENT, ""); + if (aftEnv.isEmpty()) { + throw new IllegalArgumentException(AFT_ENVIRONMENT + IS_NEEDED); + } + String version = props.getProperty(VERSION, ""); + if (version.isEmpty()) { + throw new IllegalArgumentException(VERSION + IS_NEEDED); + } + String environment = props.getProperty(ENVIRONMENT, ""); + if (environment.isEmpty()) { + throw new IllegalArgumentException(ENVIRONMENT + IS_NEEDED); + } + String subContextPath = props.getProperty(SUB_CONTEXT_PATH, ""); + if (subContextPath.isEmpty()) { + throw new IllegalArgumentException(SUB_CONTEXT_PATH + IS_NEEDED); + } + String sessionstickinessrequired = props.getProperty(SESSION_STICKINESS_REQUIRED, ""); + if (sessionstickinessrequired.isEmpty()) { + throw new IllegalArgumentException(SESSION_STICKINESS_REQUIRED + IS_NEEDED); + } + } + + private static void validateForNonDME2(Properties props) { + String host = props.getProperty(HOST, ""); + if (host.isEmpty()) { + throw new IllegalArgumentException(HOST + IS_NEEDED); + } + String topic = props.getProperty(TOPIC, ""); + if (topic.isEmpty()) { + throw new IllegalArgumentException(TOPIC + IS_NEEDED); + } + String contenttype = props.getProperty(CONTENT_TYPE, ""); + if (contenttype.isEmpty()) { + throw new IllegalArgumentException(CONTENT_TYPE + IS_NEEDED); + } + String transportType = props.getProperty(TRANSPORT_TYPE); + if (!ProtocolType.HTTPNOAUTH.getValue().equalsIgnoreCase(transportType)) { + String username = props.getProperty(USERNAME, ""); + if (username.isEmpty()) { + throw new IllegalArgumentException(USERNAME + IS_NEEDED); + } + String password = props.getProperty(PASSWORD, ""); + if (password.isEmpty()) { + throw new IllegalArgumentException(PASSWORD + IS_NEEDED); + } + } + if (ProtocolType.AUTH_KEY.getValue().equalsIgnoreCase(transportType)) { + String authKey = props.getProperty(AUTH_KEY, ""); + if (authKey.isEmpty()) { + throw new IllegalArgumentException(AUTH_KEY + IS_NEEDED); + } + String authDate = props.getProperty(AUTH_DATE, ""); + if (authDate.isEmpty()) { + throw new IllegalArgumentException(AUTH_DATE + IS_NEEDED); + } + } + } - public static void validateSubscriber(Properties props) { - String transportType = props.getProperty("TransportType"); - if (ProtocolTypeConstants.DME2.getValue().equalsIgnoreCase(transportType)) { - validateForDME2(props); - } else { - validateForNonDME2(props); - } - String group = props.getProperty("group"); - if (group == null || group.isEmpty()) { - throw new IllegalArgumentException ( "group is needed" ); - } - String id = props.getProperty("id"); - if (id == null || id.isEmpty()) { - throw new IllegalArgumentException ( "Consumer (Id) is needed" ); - } - } - - private static void validateForDME2(Properties props) { - String serviceName = props.getProperty("ServiceName"); - if (serviceName == null || serviceName.isEmpty()) { - throw new IllegalArgumentException ( "Servicename is needed" ); - } - String topic = props.getProperty("topic"); - if (topic == null || topic.isEmpty()) { - throw new IllegalArgumentException ( "topic is needed" ); - } - String username = props.getProperty("username"); - if (username == null || username.isEmpty()) { - throw new IllegalArgumentException ( "username is needed" ); - } - String password = props.getProperty("password"); - if (password == null || password.isEmpty()) { - throw new IllegalArgumentException ( "password is needed" ); - } - String dME2preferredRouterFilePath = props.getProperty("DME2preferredRouterFilePath"); - if (dME2preferredRouterFilePath == null || dME2preferredRouterFilePath.isEmpty()) { - throw new IllegalArgumentException ( "DME2preferredRouterFilePath is needed" ); - } - String partner = props.getProperty("Partner"); - String routeOffer = props.getProperty("routeOffer"); - if ((partner == null || partner.isEmpty()) && (routeOffer == null || routeOffer.isEmpty())) { - throw new IllegalArgumentException ( "Partner or routeOffer is needed" ); - } - String protocol = props.getProperty("Protocol"); - if (protocol == null || protocol.isEmpty()) { - throw new IllegalArgumentException ( "Protocol is needed" ); - } - String methodType = props.getProperty("MethodType"); - if (methodType == null || methodType.isEmpty()) { - throw new IllegalArgumentException ( "MethodType is needed" ); - } - String contenttype = props.getProperty("contenttype"); - if (contenttype == null || contenttype.isEmpty()) { - throw new IllegalArgumentException ( "contenttype is needed" ); - } - String latitude = props.getProperty("Latitude"); - if (latitude == null || latitude.isEmpty()) { - throw new IllegalArgumentException ( "Latitude is needed" ); - } - String longitude = props.getProperty("Longitude"); - if (longitude == null || longitude.isEmpty()) { - throw new IllegalArgumentException ( "Longitude is needed" ); - } - String aftEnv = props.getProperty("AFT_ENVIRONMENT"); - if (aftEnv == null || aftEnv.isEmpty()) { - throw new IllegalArgumentException ( "AFT_ENVIRONMENT is needed" ); - } - String version = props.getProperty("Version"); - if (version == null || version.isEmpty()) { - throw new IllegalArgumentException ( "Version is needed" ); - } - String environment = props.getProperty("Environment"); - if (environment == null || environment.isEmpty()) { - throw new IllegalArgumentException ( "Environment is needed" ); - } - String subContextPath = props.getProperty("SubContextPath"); - if (subContextPath == null || subContextPath.isEmpty()) { - throw new IllegalArgumentException ( "SubContextPath is needed" ); - } - String sessionstickinessrequired = props.getProperty("sessionstickinessrequired"); - if (sessionstickinessrequired == null || sessionstickinessrequired.isEmpty()) { - throw new IllegalArgumentException ( "sessionstickinessrequired is needed" ); - } - } - - private static void validateForNonDME2(Properties props) { - String transportType = props.getProperty("TransportType"); - String host = props.getProperty("host"); - if (host == null || host.isEmpty()) { - throw new IllegalArgumentException ( "Servicename is needed" ); - } - String topic = props.getProperty("topic"); - if (topic == null || topic.isEmpty()) { - throw new IllegalArgumentException ( "topic is needed" ); - } - String contenttype = props.getProperty("contenttype"); - if (contenttype == null || contenttype.isEmpty()) { - throw new IllegalArgumentException ( "contenttype is needed" ); - } - if (!ProtocolTypeConstants.HTTPNOAUTH.getValue().equalsIgnoreCase(transportType)){ - String username = props.getProperty("username"); - if (username == null || username.isEmpty()) { - throw new IllegalArgumentException ( "username is needed" ); - } - String password = props.getProperty("password"); - if (password == null || password.isEmpty()) { - throw new IllegalArgumentException ( "password is needed" ); - } - } - if (ProtocolTypeConstants.AUTH_KEY.getValue().equalsIgnoreCase(transportType)) { - String authKey = props.getProperty("authKey"); - if (authKey == null || authKey.isEmpty()) { - throw new IllegalArgumentException ( "authKey is needed" ); - } - String authDate = props.getProperty("authDate"); - if (authDate == null || authDate.isEmpty()) { - throw new IllegalArgumentException ( "authDate is needed" ); - } - - } - } - } diff --git a/src/main/resources/dme2/consumer.properties b/src/main/resources/dme2/consumer.properties index 178b391..df8a07a 100644 --- a/src/main/resources/dme2/consumer.properties +++ b/src/main/resources/dme2/consumer.properties @@ -2,7 +2,9 @@ # ============LICENSE_START======================================================= # org.onap.dmaap # ================================================================================ -# Copyright © 2017 AT&T Intellectual Property. All rights reserved. +# Copyright © 2017 AT&T Intellectual Property. All rights reserved. +# ================================================================================ +# Modifications Copyright © 2021 Orange. # ================================================================================ # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. diff --git a/src/main/resources/dme2/producer.properties b/src/main/resources/dme2/producer.properties index 4818a3b..2594787 100644 --- a/src/main/resources/dme2/producer.properties +++ b/src/main/resources/dme2/producer.properties @@ -2,7 +2,9 @@ # ============LICENSE_START======================================================= # org.onap.dmaap # ================================================================================ -# Copyright © 2017 AT&T Intellectual Property. All rights reserved. +# Copyright © 2017 AT&T Intellectual Property. All rights reserved. +# ================================================================================ +# Modifications Copyright © 2021 Orange. # ================================================================================ # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. @@ -49,4 +51,4 @@ AFT_DME2_ROUNDTRIP_TIMEOUT_MS=240000 AFT_DME2_EP_READ_TIMEOUT_MS=50000 sessionstickinessrequired=NO DME2preferredRouterFilePath=/src/main/resources/dme2/preferredRoute.txt -MessageSentThreadOccurance=50 +MessageSentThreadOccurrence=50 diff --git a/src/test/java/org/onap/dmaap/mr/client/HostSelectorTest.java b/src/test/java/org/onap/dmaap/mr/client/HostSelectorTest.java index 549c541..3b1a9ac 100644 --- a/src/test/java/org/onap/dmaap/mr/client/HostSelectorTest.java +++ b/src/test/java/org/onap/dmaap/mr/client/HostSelectorTest.java @@ -4,12 +4,14 @@ * ================================================================================ * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. * ================================================================================ + * Modifications Copyright © 2021 Orange. + * ================================================================================ * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at - * + * * http://www.apache.org/licenses/LICENSE-2.0 - * + * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. @@ -20,46 +22,25 @@ package org.onap.dmaap.mr.client; -import static org.junit.Assert.assertTrue; -import org.junit.After; -import org.junit.Before; import org.junit.Test; -import org.onap.dmaap.mr.client.HostSelector; +import static org.junit.Assert.assertTrue; public class HostSelectorTest { - - @Before - public void setUp() throws Exception { - - } - - @After - public void tearDown() throws Exception { - - } - - - @Test - public void testSelectBaseHost() { - - HostSelector selector = new HostSelector("host"); - - selector.selectBaseHost(); - assertTrue(true); - - } + @Test + public void testSelectBaseHost() { - @Test - public void testReportReachabilityProblem() { - - HostSelector selector = new HostSelector("host"); - - selector.reportReachabilityProblem(100, null); - assertTrue(true); - + HostSelector selector = new HostSelector("host"); + selector.selectBaseHost(); + assertTrue(true); + } - } + @Test + public void testReportReachabilityProblem() { + HostSelector selector = new HostSelector("host"); + selector.reportReachabilityProblem(100, null); + assertTrue(true); + } } diff --git a/src/test/java/org/onap/dmaap/mr/client/JUnitTestSuite.java b/src/test/java/org/onap/dmaap/mr/client/JUnitTestSuite.java index 1ed519a..56f341e 100644 --- a/src/test/java/org/onap/dmaap/mr/client/JUnitTestSuite.java +++ b/src/test/java/org/onap/dmaap/mr/client/JUnitTestSuite.java @@ -4,12 +4,14 @@ * ================================================================================ * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. * ================================================================================ + * Modifications Copyright © 2021 Orange. + * ================================================================================ * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at - * + * * http://www.apache.org/licenses/LICENSE-2.0 - * + * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. @@ -21,7 +23,6 @@ package org.onap.dmaap.mr.client; import junit.framework.TestSuite; - import org.junit.runner.RunWith; import org.junit.runners.Suite; import org.junit.runners.Suite.SuiteClasses; @@ -29,16 +30,15 @@ import org.slf4j.Logger; import org.slf4j.LoggerFactory; @RunWith(Suite.class) -@SuiteClasses({ HostSelectorTest.class, MRClientBuildersTest.class, MRClientFactoryTest.class}) - +@SuiteClasses({HostSelectorTest.class, MRClientBuildersTest.class, MRClientFactoryTest.class}) public class JUnitTestSuite { - private static final Logger LOGGER = LoggerFactory.getLogger(JUnitTestSuite.class); + private static final Logger logger = LoggerFactory.getLogger(JUnitTestSuite.class); + + public static void main(String[] args) { + logger.info("Running the test suite"); - public static void main(String[] args) { - LOGGER.info("Running the test suite"); - - TestSuite tstSuite = new TestSuite(); - LOGGER.info("Total Test Counts " + tstSuite.countTestCases()); - } + TestSuite tstSuite = new TestSuite(); + logger.info("Total Test Counts " + tstSuite.countTestCases()); + } } diff --git a/src/test/java/org/onap/dmaap/mr/client/MRClientBuildersTest.java b/src/test/java/org/onap/dmaap/mr/client/MRClientBuildersTest.java index 80f6ec2..e704e73 100644 --- a/src/test/java/org/onap/dmaap/mr/client/MRClientBuildersTest.java +++ b/src/test/java/org/onap/dmaap/mr/client/MRClientBuildersTest.java @@ -5,13 +5,14 @@ * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. * ================================================================================ * Modifications Copyright © 2018 IBM. + * Modifications Copyright © 2021 Orange. * ================================================================================ * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at - * + * * http://www.apache.org/licenses/LICENSE-2.0 - * + * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. @@ -22,15 +23,14 @@ package org.onap.dmaap.mr.client; -import static org.junit.Assert.assertTrue; +import org.junit.After; +import org.junit.Before; +import org.junit.Test; import java.util.ArrayList; import java.util.Collection; -import org.junit.After; -import org.junit.Before; -import org.junit.Test; -import org.onap.dmaap.mr.client.MRClientBuilders; +import static org.junit.Assert.assertTrue; public class MRClientBuildersTest { diff --git a/src/test/java/org/onap/dmaap/mr/client/MRClientFactoryTest.java b/src/test/java/org/onap/dmaap/mr/client/MRClientFactoryTest.java index e800671..2203373 100644 --- a/src/test/java/org/onap/dmaap/mr/client/MRClientFactoryTest.java +++ b/src/test/java/org/onap/dmaap/mr/client/MRClientFactoryTest.java @@ -5,13 +5,14 @@ * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. * ================================================================================ * Modifications Copyright © 2018 IBM. + * Modifications Copyright © 2021 Orange. * ================================================================================ * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at - * + * * http://www.apache.org/licenses/LICENSE-2.0 - * + * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. @@ -22,15 +23,15 @@ package org.onap.dmaap.mr.client; -import static org.junit.Assert.assertTrue; +import org.junit.After; +import org.junit.Before; +import org.junit.Test; import java.io.IOException; import java.util.ArrayList; import java.util.Collection; -import org.junit.After; -import org.junit.Before; -import org.junit.Test; +import static org.junit.Assert.assertTrue; public class MRClientFactoryTest { @@ -71,177 +72,116 @@ public class MRClientFactoryTest { @Test public void testCreateConsumer3() { - MRClientFactory.createConsumer(hostSet, "testTopic", "filter"); assertTrue(true); - } @Test public void testCreateConsumer4() { - MRClientFactory.createConsumer(hostSet, "testTopic", "CG1", "22"); assertTrue(true); - } @Test public void testCreateConsumer5() { - MRClientFactory.createConsumer(hostSet, "testTopic", "CG1", "22", 100, 100); assertTrue(true); - } @Test public void testCreateConsumer6() { - MRClientFactory.createConsumer("hostList", "testTopic", "CG1", "22", 100, 100, "filter", "apikey", "apisecret"); assertTrue(true); - } @Test public void testCreateConsumer7() { - MRClientFactory.createConsumer(hostSet, "testTopic", "CG1", "22", 100, 100, "filter", "apikey", "apisecret"); assertTrue(true); - } @Test public void testCreateSimplePublisher() { - MRClientFactory.createSimplePublisher("hostList", "testTopic"); assertTrue(true); - } @Test public void testCreateBatchingPublisher1() { - MRClientFactory.createBatchingPublisher("hostList", "testTopic", 100, 10); assertTrue(true); - } @Test public void testCreateBatchingPublisher2() { - MRClientFactory.createBatchingPublisher("hostList", "testTopic", 100, 10, true); assertTrue(true); - } @Test public void testCreateBatchingPublisher3() { - MRClientFactory.createBatchingPublisher(hostArray, "testTopic", 100, 10, true); assertTrue(true); - } @Test public void testCreateBatchingPublisher4() { - - MRClientFactory.createBatchingPublisher(hostSet, "testTopic", 100, 10, true); + MRClientFactory.createBatchingPublisher(hostSet, "testTopic", 100, 10, true); assertTrue(true); - } @Test public void testCreateBatchingPublisher5() { - MRClientFactory.createBatchingPublisher("host", "testTopic", "username", "password", 100, 10, true, "protocolFlag"); assertTrue(true); - } - @Test - public void testCreateBatchingPublisher6() { - - try { - MRClientFactory.createBatchingPublisher("/producer"); - } catch (IOException e) { - // TODO Auto-generated catch block - e.printStackTrace(); - } - assertTrue(true); - + @Test(expected = IOException.class) + public void testCreateBatchingPublisher6() throws IOException { + MRClientFactory.createBatchingPublisher("/producer"); } - @Test - public void testCreateBatchingPublisher7() { - - try { - MRClientFactory.createBatchingPublisher("/producer", true); - } catch (IOException e) { - // TODO Auto-generated catch block - e.printStackTrace(); - } - assertTrue(true); - + @Test(expected = IOException.class) + public void testCreateBatchingPublisher7() throws IOException { + MRClientFactory.createBatchingPublisher("/producer", true); } @Test public void testCreateIdentityManager() { - MRClientFactory.createIdentityManager(hostSet, "apikey", "apisecret"); - assertTrue(true); - } @Test public void testCreateTopicManager() { - MRClientFactory.createTopicManager(hostSet, "apikey", "apisecret"); - assertTrue(true); - } - @Test - public void testCreateConsumer8() { - - try { - MRClientFactory.createConsumer("/consumer"); - } catch (IOException e) { - // TODO Auto-generated catch block - e.printStackTrace(); - } - - assertTrue(true); - + @Test(expected = IOException.class) + public void testCreateConsumer8() throws IOException { + MRClientFactory.createConsumer("/consumer"); } @Test public void testCreateConsumer9() { - MRClientFactory.createConsumer("host", "topic", "username", "password", "group", "23", "protocolFlag", "/consumer", 1, 2); - assertTrue(true); - } @Test public void testCreateConsumer10() { - MRClientFactory.createConsumer("host", "topic", "username", "password", "group", "23", 1, 2, "protocolFlag", "/consumer"); - assertTrue(true); - } - + @Test public void test$testInject() { - MRClientFactory.$testInject(null); assertTrue(true); - } } \ No newline at end of file diff --git a/src/test/java/org/onap/dmaap/mr/client/TestRunner.java b/src/test/java/org/onap/dmaap/mr/client/TestRunner.java index 2cc2c10..92c03cb 100644 --- a/src/test/java/org/onap/dmaap/mr/client/TestRunner.java +++ b/src/test/java/org/onap/dmaap/mr/client/TestRunner.java @@ -4,12 +4,14 @@ * ================================================================================ * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. * ================================================================================ + * Modifications Copyright © 2021 Orange. + * ================================================================================ * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at - * + * * http://www.apache.org/licenses/LICENSE-2.0 - * + * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. @@ -27,16 +29,16 @@ import org.slf4j.Logger; import org.slf4j.LoggerFactory; public class TestRunner { - private static final Logger LOGGER = LoggerFactory.getLogger(TestRunner.class); + private static final Logger logger = LoggerFactory.getLogger(TestRunner.class); + + public static void main(String[] args) { + // TODO Auto-generated method stub + Result result = JUnitCore.runClasses(JUnitTestSuite.class); + for (Failure failure : result.getFailures()) { + logger.info(failure.toString()); - public static void main(String[] args) { - // TODO Auto-generated method stub - Result result = JUnitCore.runClasses(JUnitTestSuite.class); - for (Failure failure : result.getFailures()) { - LOGGER.info(failure.toString()); - - } - LOGGER.info(String.valueOf(result.wasSuccessful())); - } + } + logger.info(String.valueOf(result.wasSuccessful())); + } } diff --git a/src/test/java/org/onap/dmaap/mr/client/impl/DMaapClientUtilTest.java b/src/test/java/org/onap/dmaap/mr/client/impl/DMaapClientUtilTest.java index 5d63759..ca4fb3b 100644 --- a/src/test/java/org/onap/dmaap/mr/client/impl/DMaapClientUtilTest.java +++ b/src/test/java/org/onap/dmaap/mr/client/impl/DMaapClientUtilTest.java @@ -4,11 +4,13 @@ * ================================================================================ * Copyright © 2018 IBM Intellectual Property. All rights reserved. * ================================================================================ + * Modifications Copyright © 2021 Orange. + * ================================================================================ * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * http://www.apache.org/licenses/LICENSE-2.0 - * + * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. @@ -17,20 +19,10 @@ * ============LICENSE_END========================================================= * * ECOMP is a trademark and service mark of AT&T Intellectual Property. - * + * *******************************************************************************/ -package org.onap.dmaap.mr.client.impl; - -import static org.junit.Assert.assertEquals; -import static org.mockito.Matchers.any; -import static org.mockito.Mockito.times; -import static org.mockito.Mockito.verify; -import java.util.Properties; - -import javax.ws.rs.client.Invocation.Builder; -import javax.ws.rs.client.WebTarget; -import javax.ws.rs.core.Response; +package org.onap.dmaap.mr.client.impl; import org.glassfish.jersey.client.ClientConfig; import org.glassfish.jersey.client.ClientProperties; @@ -40,6 +32,16 @@ import org.mockito.Mock; import org.mockito.Mockito; import org.mockito.MockitoAnnotations; +import javax.ws.rs.client.Invocation.Builder; +import javax.ws.rs.client.WebTarget; +import javax.ws.rs.core.Response; +import java.util.Properties; + +import static org.junit.Assert.assertEquals; +import static org.mockito.Matchers.any; +import static org.mockito.Mockito.times; +import static org.mockito.Mockito.verify; + public class DMaapClientUtilTest { @Mock Response response; @@ -47,56 +49,56 @@ public class DMaapClientUtilTest { Builder builder; @Mock WebTarget target; - private ClientConfig config=null; + private ClientConfig config = null; @Before - public void setup(){ + public void setup() { MockitoAnnotations.initMocks(this); } - + @Test public void testGetTarget() { - WebTarget actual = DmaapClientUtil.getTarget(getClientConfig(),"testpath"); - + WebTarget actual = DmaapClientUtil.getTarget(getClientConfig(), "testpath"); + assertEquals("testpath", actual.getUri().getPath()); } - + @Test public void testGetTargetWithParams() { - WebTarget actual = DmaapClientUtil.getTarget(getClientConfig(),"testpath", "testuser", "testpassword"); - + WebTarget actual = DmaapClientUtil.getTarget(getClientConfig(), "testpath", "testuser", "testpassword"); + assertEquals("testpath", actual.getUri().getPath()); } - + @Test public void testGetResponsewtCambriaAuth() { - Mockito.when(target.request()).thenReturn(builder); - Mockito.when(builder.header("X-CambriaAuth", "testuser")).thenReturn(builder); - Mockito.when(builder.header("X-CambriaDate", "testpassword")).thenReturn(builder); - Mockito.when(builder.get()).thenReturn(response); - + Mockito.when(target.request()).thenReturn(builder); + Mockito.when(builder.header("X-CambriaAuth", "testuser")).thenReturn(builder); + Mockito.when(builder.header("X-CambriaDate", "testpassword")).thenReturn(builder); + Mockito.when(builder.get()).thenReturn(response); + Response actual = DmaapClientUtil.getResponsewtCambriaAuth(target, "testuser", "testpassword"); assertEquals(response, actual); verify(target).request(); verify(builder, times(2)).header((String) any(), any()); } - + @Test public void testSetHttpClientProperties() { - Properties properties = new Properties(); - properties.setProperty(ClientProperties.PROXY_URI, "http://localhost:1234"); - ClientConfig cConfig = DmaapClientUtil.getClientConfig(properties); + Properties properties = new Properties(); + properties.setProperty(ClientProperties.PROXY_URI, "http://localhost:1234"); + ClientConfig cConfig = DmaapClientUtil.getClientConfig(properties); - assertEquals(cConfig.getConnectorProvider().getClass().getSimpleName(), "ApacheConnectorProvider"); + assertEquals("ApacheConnectorProvider", cConfig.getConnectorProvider().getClass().getSimpleName()); } - private ClientConfig getClientConfig(){ - if(config==null){ - config=DmaapClientUtil.getClientConfig(null); - } - return config; - - } + private ClientConfig getClientConfig() { + if (config == null) { + config = DmaapClientUtil.getClientConfig(null); + } + return config; + + } } diff --git a/src/test/java/org/onap/dmaap/mr/client/impl/MRBaseClientTest.java b/src/test/java/org/onap/dmaap/mr/client/impl/MRBaseClientTest.java index dc2c5ff..9d47192 100644 --- a/src/test/java/org/onap/dmaap/mr/client/impl/MRBaseClientTest.java +++ b/src/test/java/org/onap/dmaap/mr/client/impl/MRBaseClientTest.java @@ -4,11 +4,13 @@ * ================================================================================ * Copyright © 2017 AT&T Intellectual Property. All rights reserved. * ================================================================================ + * Modifications Copyright © 2021 Orange. + * ================================================================================ * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * http://www.apache.org/licenses/LICENSE-2.0 - * + * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. @@ -17,23 +19,10 @@ * ============LICENSE_END========================================================= * * ECOMP is a trademark and service mark of AT&T Intellectual Property. - * + * *******************************************************************************/ -package org.onap.dmaap.mr.client.impl; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertTrue; -import static org.mockito.Mockito.atLeast; -import static org.mockito.Mockito.verify; - -import java.net.MalformedURLException; -import java.util.Arrays; -import java.util.Collection; -import java.util.HashSet; - -import javax.ws.rs.core.MultivaluedMap; -import javax.ws.rs.core.Response; -import javax.ws.rs.core.Response.ResponseBuilder; +package org.onap.dmaap.mr.client.impl; import org.apache.http.HttpException; import org.glassfish.jersey.client.ClientConfig; @@ -50,447 +39,457 @@ import org.powermock.core.classloader.annotations.PowerMockIgnore; import org.powermock.core.classloader.annotations.PrepareForTest; import org.powermock.modules.junit4.PowerMockRunner; +import javax.ws.rs.core.MultivaluedMap; +import javax.ws.rs.core.Response; +import javax.ws.rs.core.Response.ResponseBuilder; +import java.net.MalformedURLException; +import java.util.Arrays; +import java.util.Collection; +import java.util.HashSet; + +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertTrue; +import static org.mockito.Mockito.atLeast; +import static org.mockito.Mockito.verify; + @RunWith(PowerMockRunner.class) @PowerMockIgnore({"org.apache.http.conn.ssl.*", "jdk.internal.reflect.*"}) -@PrepareForTest({ DmaapClientUtil.class }) +@PrepareForTest({DmaapClientUtil.class}) public class MRBaseClientTest { - // @InjectMocks - private MRBaseClient mrBaseClient; - private Collection hosts = new HashSet<>(Arrays.asList("localhost:8080")); - private String clientSignature = "topic" + "::" + "cg" + "::" + "cid"; - private ClientConfig config=null; - - @Before - public void setup() throws MalformedURLException { - mrBaseClient = new MRBaseClient(hosts, clientSignature); - PowerMockito.mockStatic(DmaapClientUtil.class); - } - - @Test - public void testGet() throws JSONException, HttpException { - - Response response = Mockito.mock(Response.class); - MultivaluedMap map = new StringKeyIgnoreCaseMultivaluedMap<>(); - map.add("transactionid", "transactionid"); - - Mockito.when(response.getStatus()).thenReturn(200); - Mockito.when(response.readEntity(String.class)).thenReturn("{\"test\":\"test\"}"); - Mockito.when(response.getHeaders()).thenReturn(map); - - Mockito.when( - DmaapClientUtil.getResponsewtCambriaAuth(DmaapClientUtil.getTarget(getClientConfig(),"/path"), "username", "password")) - .thenReturn(response); - - JSONObject result = mrBaseClient.get("/path", "username", "password", "HTTPAUTH"); - assertEquals(200, result.getInt("status")); - assertEquals("test", result.getString("test")); - verify(response, atLeast(1)).getStatus(); - verify(response).readEntity(String.class); - verify(response).getHeaders(); - } - - @Test - public void testGet_403() throws JSONException, HttpException { - ResponseBuilder responseBuilder = Response.status(403); - Mockito - .when(DmaapClientUtil.getResponsewtCambriaAuth(DmaapClientUtil.getTarget(getClientConfig(),"/path"), "username", - "password")) - .thenReturn( - responseBuilder.header("transactionid", "transactionid").entity("{\"test\":\"test\"}").build()); - JSONObject result = mrBaseClient.get("/path", "username", "password", "HTTPAUTH"); - assertEquals(403, result.getInt("status")); - } - - @Test - public void testGet_basicauth() throws JSONException, HttpException { - - Response response = Mockito.mock(Response.class); - MultivaluedMap map = new StringKeyIgnoreCaseMultivaluedMap<>(); - map.add("transactionid", "transactionid"); + // @InjectMocks + private MRBaseClient mrBaseClient; + private Collection hosts = new HashSet<>(Arrays.asList("localhost:8080")); + private String clientSignature = "topic" + "::" + "cg" + "::" + "cid"; + private ClientConfig config = null; + + @Before + public void setup() throws MalformedURLException { + mrBaseClient = new MRBaseClient(hosts, clientSignature); + PowerMockito.mockStatic(DmaapClientUtil.class); + } + + @Test + public void testGet() throws JSONException, HttpException { + + Response response = Mockito.mock(Response.class); + MultivaluedMap map = new StringKeyIgnoreCaseMultivaluedMap<>(); + map.add("transactionid", "transactionid"); + + Mockito.when(response.getStatus()).thenReturn(200); + Mockito.when(response.readEntity(String.class)).thenReturn("{\"test\":\"test\"}"); + Mockito.when(response.getHeaders()).thenReturn(map); + + Mockito.when( + DmaapClientUtil.getResponsewtCambriaAuth(DmaapClientUtil.getTarget(getClientConfig(), "/path"), "username", "password")) + .thenReturn(response); + + JSONObject result = mrBaseClient.get("/path", "username", "password", "HTTPAUTH"); + assertEquals(200, result.getInt("status")); + assertEquals("test", result.getString("test")); + verify(response, atLeast(1)).getStatus(); + verify(response).readEntity(String.class); + verify(response).getHeaders(); + } + + @Test + public void testGet_403() throws JSONException, HttpException { + ResponseBuilder responseBuilder = Response.status(403); + Mockito + .when(DmaapClientUtil.getResponsewtCambriaAuth(DmaapClientUtil.getTarget(getClientConfig(), "/path"), "username", + "password")) + .thenReturn( + responseBuilder.header("transactionid", "transactionid").entity("{\"test\":\"test\"}").build()); + JSONObject result = mrBaseClient.get("/path", "username", "password", "HTTPAUTH"); + assertEquals(403, result.getInt("status")); + } + + @Test + public void testGet_basicauth() throws JSONException, HttpException { + + Response response = Mockito.mock(Response.class); + MultivaluedMap map = new StringKeyIgnoreCaseMultivaluedMap<>(); + map.add("transactionid", "transactionid"); + + Mockito.when(response.getStatus()).thenReturn(200); + Mockito.when(response.readEntity(String.class)).thenReturn("{\"test\":\"test\"}"); + Mockito.when(response.getHeaders()).thenReturn(map); - Mockito.when(response.getStatus()).thenReturn(200); - Mockito.when(response.readEntity(String.class)).thenReturn("{\"test\":\"test\"}"); - Mockito.when(response.getHeaders()).thenReturn(map); + Mockito.when(DmaapClientUtil.getResponsewtBasicAuth(DmaapClientUtil.getTarget(getClientConfig(), "/path"), + Base64.encodeAsString("username:password"))).thenReturn(response); - Mockito.when(DmaapClientUtil.getResponsewtBasicAuth(DmaapClientUtil.getTarget(getClientConfig(),"/path"), - Base64.encodeAsString("username:password"))).thenReturn(response); + JSONObject result = mrBaseClient.get("/path", "username", "password", "HTTPAAF"); + assertEquals(200, result.getInt("status")); + verify(response, atLeast(1)).getStatus(); + verify(response).readEntity(String.class); + verify(response).getHeaders(); + + } - JSONObject result = mrBaseClient.get("/path", "username", "password", "HTTPAAF"); - assertEquals(200, result.getInt("status")); - verify(response, atLeast(1)).getStatus(); - verify(response).readEntity(String.class); - verify(response).getHeaders(); - - } + @Test(expected = HttpException.class) + public void testGet_error() throws JSONException, HttpException { - @Test(expected = HttpException.class) - public void testGet_error() throws JSONException, HttpException { + ResponseBuilder responseBuilder = Response.ok(); + Mockito.when(DmaapClientUtil.getResponsewtCambriaAuth(DmaapClientUtil.getTarget(getClientConfig(), "/path"), "username", + "password")) + .thenReturn( + responseBuilder.header("transactionid", "transactionid").entity("{\"test\":\"test\"}").build()); - ResponseBuilder responseBuilder = Response.ok(); - Mockito.when(DmaapClientUtil.getResponsewtCambriaAuth(DmaapClientUtil.getTarget(getClientConfig(),"/path"), "username", - "password")) - .thenReturn( - responseBuilder.header("transactionid", "transactionid").entity("{\"test\":\"test\"}").build()); + mrBaseClient.get("/path", null, null, "HTTPAUTH"); + } - mrBaseClient.get("/path", null, null, "HTTPAUTH"); - } + @Test + public void testGet_wrongjson() throws JSONException, HttpException { - @Test - public void testGet_wrongjson() throws JSONException, HttpException { + Response response = Mockito.mock(Response.class); + MultivaluedMap map = new StringKeyIgnoreCaseMultivaluedMap<>(); + map.add("transactionid", "transactionid"); - Response response = Mockito.mock(Response.class); - MultivaluedMap map = new StringKeyIgnoreCaseMultivaluedMap<>(); - map.add("transactionid", "transactionid"); + Mockito.when(response.getStatus()).thenReturn(200); + Mockito.when(response.readEntity(String.class)).thenReturn("[["); + Mockito.when(response.getHeaders()).thenReturn(map); - Mockito.when(response.getStatus()).thenReturn(200); - Mockito.when(response.readEntity(String.class)).thenReturn("[["); - Mockito.when(response.getHeaders()).thenReturn(map); + Mockito.when( + DmaapClientUtil.getResponsewtCambriaAuth(DmaapClientUtil.getTarget(getClientConfig(), "/path"), "username", "password")) + .thenReturn(response); - Mockito.when( - DmaapClientUtil.getResponsewtCambriaAuth(DmaapClientUtil.getTarget(getClientConfig(),"/path"), "username", "password")) - .thenReturn(response); + mrBaseClient.get("/path", "username", "password", "HTTPAUTH"); + verify(response, atLeast(1)).getStatus(); + verify(response).readEntity(String.class); + verify(response).getHeaders(); + } - mrBaseClient.get("/path", "username", "password", "HTTPAUTH"); - verify(response, atLeast(1)).getStatus(); - verify(response).readEntity(String.class); - verify(response).getHeaders(); - } + @Test + public void testGetResponse() throws JSONException, HttpException { - @Test - public void testGetResponse() throws JSONException, HttpException { + Response response = Mockito.mock(Response.class); + MultivaluedMap map = new StringKeyIgnoreCaseMultivaluedMap<>(); + map.add("transactionid", "transactionid"); - Response response = Mockito.mock(Response.class); - MultivaluedMap map = new StringKeyIgnoreCaseMultivaluedMap<>(); - map.add("transactionid", "transactionid"); + Mockito.when(response.getStatus()).thenReturn(200); + Mockito.when(response.readEntity(String.class)).thenReturn("{\"test\":\"test\"}"); + Mockito.when(response.getHeaders()).thenReturn(map); - Mockito.when(response.getStatus()).thenReturn(200); - Mockito.when(response.readEntity(String.class)).thenReturn("{\"test\":\"test\"}"); - Mockito.when(response.getHeaders()).thenReturn(map); - - Mockito.when( - DmaapClientUtil.getResponsewtCambriaAuth(DmaapClientUtil.getTarget(getClientConfig(),"/path"), "username", "password")) - .thenReturn(response); + Mockito.when( + DmaapClientUtil.getResponsewtCambriaAuth(DmaapClientUtil.getTarget(getClientConfig(), "/path"), "username", "password")) + .thenReturn(response); - mrBaseClient.getResponse("/path", "username", "password", "HTTPAUTH"); - assertTrue(true); + mrBaseClient.getResponse("/path", "username", "password", "HTTPAUTH"); + assertTrue(true); - } + } - @Test - public void testGetResponse_aaf() throws JSONException, HttpException { - - Response response = Mockito.mock(Response.class); - MultivaluedMap map = new StringKeyIgnoreCaseMultivaluedMap<>(); - map.add("transactionid", "transactionid"); - - Mockito.when(response.getStatus()).thenReturn(200); - Mockito.when(response.readEntity(String.class)).thenReturn("{\"test\":\"test\"}"); - Mockito.when(response.getHeaders()).thenReturn(map); - - Mockito.when(DmaapClientUtil.getResponsewtBasicAuth(DmaapClientUtil.getTarget(getClientConfig(),"/path"), - Base64.encodeAsString("username:password"))).thenReturn(response); - - mrBaseClient.getResponse("/path", "username", "password", "HTTPAAF"); - assertTrue(true); + @Test + public void testGetResponse_aaf() throws JSONException, HttpException { - } + Response response = Mockito.mock(Response.class); + MultivaluedMap map = new StringKeyIgnoreCaseMultivaluedMap<>(); + map.add("transactionid", "transactionid"); - @Test(expected = HttpException.class) - public void testGetResponse_error() throws JSONException, HttpException { + Mockito.when(response.getStatus()).thenReturn(200); + Mockito.when(response.readEntity(String.class)).thenReturn("{\"test\":\"test\"}"); + Mockito.when(response.getHeaders()).thenReturn(map); - ResponseBuilder responseBuilder = Response.ok(); - Mockito - .when(DmaapClientUtil.getResponsewtCambriaAuth(DmaapClientUtil.getTarget(getClientConfig(),"/path"), "username", - "password")) - .thenReturn( - responseBuilder.header("transactionid", "transactionid").entity("{\"test\":\"test\"}").build()); + Mockito.when(DmaapClientUtil.getResponsewtBasicAuth(DmaapClientUtil.getTarget(getClientConfig(), "/path"), + Base64.encodeAsString("username:password"))).thenReturn(response); - mrBaseClient.getResponse("/path", null, null, "HTTPAUTH"); - } + mrBaseClient.getResponse("/path", "username", "password", "HTTPAAF"); + assertTrue(true); - @Test - public void testAuthResponse() throws JSONException, HttpException { + } - Response response = Mockito.mock(Response.class); - MultivaluedMap map = new StringKeyIgnoreCaseMultivaluedMap<>(); - map.add("transactionid", "transactionid"); + @Test(expected = HttpException.class) + public void testGetResponse_error() throws JSONException, HttpException { - Mockito.when(response.getStatus()).thenReturn(200); - Mockito.when(response.readEntity(String.class)).thenReturn("{\"test\":\"test\"}"); - Mockito.when(response.getHeaders()).thenReturn(map); + ResponseBuilder responseBuilder = Response.ok(); + Mockito + .when(DmaapClientUtil.getResponsewtCambriaAuth(DmaapClientUtil.getTarget(getClientConfig(), "/path"), "username", + "password")) + .thenReturn( + responseBuilder.header("transactionid", "transactionid").entity("{\"test\":\"test\"}").build()); - Mockito.when( - DmaapClientUtil.getResponsewtCambriaAuth(DmaapClientUtil.getTarget(getClientConfig(),"/path"), "username", "password")) - .thenReturn(response); + mrBaseClient.getResponse("/path", null, null, "HTTPAUTH"); + } - mrBaseClient.getAuthResponse("/path", "username", "password", "username", "password", "HTTPAUTH"); - assertTrue(true); + @Test + public void testAuthResponse() throws JSONException, HttpException { - } + Response response = Mockito.mock(Response.class); + MultivaluedMap map = new StringKeyIgnoreCaseMultivaluedMap<>(); + map.add("transactionid", "transactionid"); - @Test(expected = HttpException.class) - public void testAuthResponsee_error() throws JSONException, HttpException { + Mockito.when(response.getStatus()).thenReturn(200); + Mockito.when(response.readEntity(String.class)).thenReturn("{\"test\":\"test\"}"); + Mockito.when(response.getHeaders()).thenReturn(map); - ResponseBuilder responseBuilder = Response.ok(); - Mockito - .when(DmaapClientUtil.getResponsewtCambriaAuth(DmaapClientUtil.getTarget(getClientConfig(),"/path"), "username", - "password")) - .thenReturn( - responseBuilder.header("transactionid", "transactionid").entity("{\"test\":\"test\"}").build()); + Mockito.when( + DmaapClientUtil.getResponsewtCambriaAuth(DmaapClientUtil.getTarget(getClientConfig(), "/path"), "username", "password")) + .thenReturn(response); - mrBaseClient.getAuthResponse("/path", null, null, null, null, "HTTPAUTH"); + mrBaseClient.getAuthResponse("/path", "username", "password", "username", "password", "HTTPAUTH"); + assertTrue(true); - } + } - @Test - public void testPostAuth() throws JSONException, HttpException { + @Test(expected = HttpException.class) + public void testAuthResponsee_error() throws JSONException, HttpException { - Response response = Mockito.mock(Response.class); - MultivaluedMap map = new StringKeyIgnoreCaseMultivaluedMap<>(); - map.add("transactionid", "transactionid"); + ResponseBuilder responseBuilder = Response.ok(); + Mockito + .when(DmaapClientUtil.getResponsewtCambriaAuth(DmaapClientUtil.getTarget(getClientConfig(), "/path"), "username", + "password")) + .thenReturn( + responseBuilder.header("transactionid", "transactionid").entity("{\"test\":\"test\"}").build()); - Mockito.when(response.getStatus()).thenReturn(200); - Mockito.when(response.readEntity(String.class)).thenReturn("{\"test\":\"test\"}"); - Mockito.when(response.getHeaders()).thenReturn(map); + mrBaseClient.getAuthResponse("/path", null, null, null, null, "HTTPAUTH"); - Mockito - .when(DmaapClientUtil.postResponsewtCambriaAuth(DmaapClientUtil.getTarget(getClientConfig(),"/path"), "username", - "password", new String("{\"test\":\"test\"}").getBytes(), "application/json")) - .thenReturn(response); + } - mrBaseClient.postAuth(new PostAuthDataObject().setPath("/path") - .setData( new String("{\"test\":\"test\"}").getBytes()) - .setContentType("application/json") - .setAuthKey("username") - .setAuthDate("password") - .setUsername("username") - .setPassword("password") - .setProtocolFlag("HTTPAUTH")); - assertTrue(true); + @Test + public void testPostAuth() throws JSONException, HttpException { - } + Response response = Mockito.mock(Response.class); + MultivaluedMap map = new StringKeyIgnoreCaseMultivaluedMap<>(); + map.add("transactionid", "transactionid"); - @Test(expected = HttpException.class) - public void testPostAuth_error() throws JSONException, HttpException { + Mockito.when(response.getStatus()).thenReturn(200); + Mockito.when(response.readEntity(String.class)).thenReturn("{\"test\":\"test\"}"); + Mockito.when(response.getHeaders()).thenReturn(map); - ResponseBuilder responseBuilder = Response.ok(); - Mockito - .when(DmaapClientUtil.postResponsewtCambriaAuth(DmaapClientUtil.getTarget(getClientConfig(),"/path"), "username", - "password", new String("{\"test\":\"test\"}").getBytes(), "application/json")) - .thenReturn( - responseBuilder.header("transactionid", "transactionid").entity("{\"test\":\"test\"}").build()); - - mrBaseClient.postAuth(new PostAuthDataObject().setPath("/path") - .setData( new String("{\"test\":\"test\"}").getBytes()) + Mockito + .when(DmaapClientUtil.postResponsewtCambriaAuth(DmaapClientUtil.getTarget(getClientConfig(), "/path"), "username", + "password", ("{\"test\":\"test\"}").getBytes(), "application/json")) + .thenReturn(response); + + mrBaseClient.postAuth(new PostAuthDataObject().setPath("/path") + .setData(("{\"test\":\"test\"}").getBytes()) + .setContentType("application/json") + .setAuthKey("username") + .setAuthDate("password") + .setUsername("username") + .setPassword("password") + .setProtocolFlag("HTTPAUTH")); + assertTrue(true); + + } + + @Test(expected = HttpException.class) + public void testPostAuth_error() throws JSONException, HttpException { + + ResponseBuilder responseBuilder = Response.ok(); + Mockito + .when(DmaapClientUtil.postResponsewtCambriaAuth(DmaapClientUtil.getTarget(getClientConfig(), "/path"), "username", + "password", ("{\"test\":\"test\"}").getBytes(), "application/json")) + .thenReturn( + responseBuilder.header("transactionid", "transactionid").entity("{\"test\":\"test\"}").build()); + + mrBaseClient.postAuth(new PostAuthDataObject().setPath("/path") + .setData(("{\"test\":\"test\"}").getBytes()) .setContentType("application/json") .setAuthKey(null) .setAuthDate(null) - .setUsername(null) + .setUsername(null) .setPassword(null) .setProtocolFlag("HTTPAUTH")); - } + } + + @Test + public void testGetNoAuthResponse() throws JSONException, HttpException { + + Response response = Mockito.mock(Response.class); + MultivaluedMap map = new StringKeyIgnoreCaseMultivaluedMap<>(); + map.add("transactionid", "transactionid"); + + Mockito.when(response.getStatus()).thenReturn(200); + Mockito.when(response.readEntity(String.class)).thenReturn("{\"test\":\"test\"}"); + Mockito.when(response.getHeaders()).thenReturn(map); - @Test - public void testGetNoAuthResponse() throws JSONException, HttpException { + Mockito.when(DmaapClientUtil.getResponsewtNoAuth(DmaapClientUtil.getTarget(getClientConfig(), "/path"))).thenReturn(response); - Response response = Mockito.mock(Response.class); - MultivaluedMap map = new StringKeyIgnoreCaseMultivaluedMap<>(); - map.add("transactionid", "transactionid"); + mrBaseClient.getNoAuthResponse("/path", "username", "password", "HTTPAUTH"); + assertTrue(true); - Mockito.when(response.getStatus()).thenReturn(200); - Mockito.when(response.readEntity(String.class)).thenReturn("{\"test\":\"test\"}"); - Mockito.when(response.getHeaders()).thenReturn(map); + } - Mockito.when(DmaapClientUtil.getResponsewtNoAuth(DmaapClientUtil.getTarget(getClientConfig(),"/path"))).thenReturn(response); + @Test + public void testPost() throws JSONException, HttpException { - mrBaseClient.getNoAuthResponse("/path", "username", "password", "HTTPAUTH"); - assertTrue(true); + Response response = Mockito.mock(Response.class); + MultivaluedMap map = new StringKeyIgnoreCaseMultivaluedMap<>(); + map.add("transactionid", "transactionid"); - } + Mockito.when(response.getStatus()).thenReturn(200); + Mockito.when(response.readEntity(String.class)).thenReturn("{\"test\":\"test\"}"); + Mockito.when(response.getHeaders()).thenReturn(map); - @Test - public void testPost() throws JSONException, HttpException { + Mockito.when(DmaapClientUtil.postResponsewtBasicAuth(DmaapClientUtil.getTarget(getClientConfig(), "/path"), + Base64.encodeAsString("username:password"), ("{\"test\":\"test\"}").getBytes(), "application/json")).thenReturn(response); - Response response = Mockito.mock(Response.class); - MultivaluedMap map = new StringKeyIgnoreCaseMultivaluedMap<>(); - map.add("transactionid", "transactionid"); + mrBaseClient.post("/path", ("{\"test\":\"test\"}").getBytes(), "application/json", "username", + "password", "HTTPAUTH"); + verify(response, atLeast(1)).getStatus(); + verify(response).readEntity(String.class); + verify(response).getHeaders(); - Mockito.when(response.getStatus()).thenReturn(200); - Mockito.when(response.readEntity(String.class)).thenReturn("{\"test\":\"test\"}"); - Mockito.when(response.getHeaders()).thenReturn(map); + } - Mockito.when(DmaapClientUtil.postResponsewtBasicAuth(DmaapClientUtil.getTarget(getClientConfig(),"/path"), - Base64.encodeAsString("username:password"), new String("{\"test\":\"test\"}").getBytes(), "application/json")).thenReturn(response); + @Test(expected = HttpException.class) + public void testPost_error() throws JSONException, HttpException { - mrBaseClient.post("/path", new String("{\"test\":\"test\"}").getBytes(), "application/json", "username", - "password", "HTTPAUTH"); - verify(response, atLeast(1)).getStatus(); - verify(response).readEntity(String.class); - verify(response).getHeaders(); + ResponseBuilder responseBuilder = Response.ok(); + Mockito + .when(DmaapClientUtil.getResponsewtBasicAuth(DmaapClientUtil.getTarget(getClientConfig(), "/path"), + Base64.encodeAsString("username:password"))) + .thenReturn( + responseBuilder.header("transactionid", "transactionid").entity("{\"test\":\"test\"}").build()); - } + mrBaseClient.post("/path", ("{\"test\":\"test\"}").getBytes(), "application/json", null, null, + "HTTPAUTH"); - @Test(expected = HttpException.class) - public void testPost_error() throws JSONException, HttpException { + } - ResponseBuilder responseBuilder = Response.ok(); - Mockito - .when(DmaapClientUtil.getResponsewtBasicAuth(DmaapClientUtil.getTarget(getClientConfig(),"/path"), - Base64.encodeAsString("username:password"))) - .thenReturn( - responseBuilder.header("transactionid", "transactionid").entity("{\"test\":\"test\"}").build()); + @Test + public void testPostAuthwithResponse() throws JSONException, HttpException { - mrBaseClient.post("/path", new String("{\"test\":\"test\"}").getBytes(), "application/json", null, null, - "HTTPAUTH"); + Response response = Mockito.mock(Response.class); + MultivaluedMap map = new StringKeyIgnoreCaseMultivaluedMap<>(); + map.add("transactionid", "transactionid"); - } + Mockito.when(response.getStatus()).thenReturn(200); + Mockito.when(response.readEntity(String.class)).thenReturn("{\"test\":\"test\"}"); + Mockito.when(response.getHeaders()).thenReturn(map); - @Test - public void testPostAuthwithResponse() throws JSONException, HttpException { + Mockito + .when(DmaapClientUtil.postResponsewtCambriaAuth(DmaapClientUtil.getTarget(getClientConfig(), "/path"), "username", + "password", ("{\"test\":\"test\"}").getBytes(), "application/json")) + .thenReturn(response); - Response response = Mockito.mock(Response.class); - MultivaluedMap map = new StringKeyIgnoreCaseMultivaluedMap<>(); - map.add("transactionid", "transactionid"); + mrBaseClient.postAuthwithResponse("/path", ("{\"test\":\"test\"}").getBytes(), "application/json", + "username", "password", "username", "password", "HTTPAUTH"); + assertTrue(true); - Mockito.when(response.getStatus()).thenReturn(200); - Mockito.when(response.readEntity(String.class)).thenReturn("{\"test\":\"test\"}"); - Mockito.when(response.getHeaders()).thenReturn(map); + } - Mockito - .when(DmaapClientUtil.postResponsewtCambriaAuth(DmaapClientUtil.getTarget(getClientConfig(),"/path"), "username", - "password", new String("{\"test\":\"test\"}").getBytes(), "application/json")) - .thenReturn(response); + @Test(expected = HttpException.class) + public void testPostAuthwithResponse_error() throws JSONException, HttpException { - mrBaseClient.postAuthwithResponse("/path", new String("{\"test\":\"test\"}").getBytes(), "application/json", - "username", "password", "username", "password", "HTTPAUTH"); - assertTrue(true); + ResponseBuilder responseBuilder = Response.ok(); + Mockito + .when(DmaapClientUtil.postResponsewtCambriaAuth(DmaapClientUtil.getTarget(getClientConfig(), "/path"), "username", + "password", ("{\"test\":\"test\"}").getBytes(), "application/json")) + .thenReturn( + responseBuilder.header("transactionid", "transactionid").entity("{\"test\":\"test\"}").build()); - } + mrBaseClient.postAuthwithResponse("/path", ("{\"test\":\"test\"}").getBytes(), "application/json", + null, null, null, null, "HTTPAUTH"); - @Test(expected = HttpException.class) - public void testPostAuthwithResponse_error() throws JSONException, HttpException { + } - ResponseBuilder responseBuilder = Response.ok(); - Mockito - .when(DmaapClientUtil.postResponsewtCambriaAuth(DmaapClientUtil.getTarget(getClientConfig(),"/path"), "username", - "password", new String("{\"test\":\"test\"}").getBytes(), "application/json")) - .thenReturn( - responseBuilder.header("transactionid", "transactionid").entity("{\"test\":\"test\"}").build()); + @Test + public void testPostWithResponse() throws JSONException, HttpException { - mrBaseClient.postAuthwithResponse("/path", new String("{\"test\":\"test\"}").getBytes(), "application/json", - null, null, null, null, "HTTPAUTH"); - assertTrue(true); + Response response = Mockito.mock(Response.class); + MultivaluedMap map = new StringKeyIgnoreCaseMultivaluedMap<>(); + map.add("transactionid", "transactionid"); - } + Mockito.when(response.getStatus()).thenReturn(200); + Mockito.when(response.readEntity(String.class)).thenReturn("{\"test\":\"test\"}"); + Mockito.when(response.getHeaders()).thenReturn(map); - @Test - public void testPostWithResponse() throws JSONException, HttpException { + Mockito.when(DmaapClientUtil.postResponsewtBasicAuth(DmaapClientUtil.getTarget(getClientConfig(), "/path"), + Base64.encodeAsString("username:password"), ("{\"test\":\"test\"}").getBytes(), "application/json")).thenReturn(response); - Response response = Mockito.mock(Response.class); - MultivaluedMap map = new StringKeyIgnoreCaseMultivaluedMap<>(); - map.add("transactionid", "transactionid"); + mrBaseClient.postWithResponse("/path", ("{\"test\":\"test\"}").getBytes(), "application/json", + "username", "password", "HTTPAUTH"); + assertTrue(true); - Mockito.when(response.getStatus()).thenReturn(200); - Mockito.when(response.readEntity(String.class)).thenReturn("{\"test\":\"test\"}"); - Mockito.when(response.getHeaders()).thenReturn(map); + } - Mockito.when(DmaapClientUtil.postResponsewtBasicAuth(DmaapClientUtil.getTarget(getClientConfig(),"/path"), - Base64.encodeAsString("username:password"), new String("{\"test\":\"test\"}").getBytes(), "application/json")).thenReturn(response); + @Test(expected = HttpException.class) + public void testPostWithResponse_error() throws JSONException, HttpException { - mrBaseClient.postWithResponse("/path", new String("{\"test\":\"test\"}").getBytes(), "application/json", - "username", "password", "HTTPAUTH"); - assertTrue(true); + ResponseBuilder responseBuilder = Response.ok(); + Mockito + .when(DmaapClientUtil.getResponsewtBasicAuth(DmaapClientUtil.getTarget(getClientConfig(), "/path"), + Base64.encodeAsString("username:password"))) + .thenReturn( + responseBuilder.header("transactionid", "transactionid").entity("{\"test\":\"test\"}").build()); - } + mrBaseClient.postWithResponse("/path", ("{\"test\":\"test\"}").getBytes(), "application/json", null, + null, "HTTPAUTH"); - @Test(expected = HttpException.class) - public void testPostWithResponse_error() throws JSONException, HttpException { + } - ResponseBuilder responseBuilder = Response.ok(); - Mockito - .when(DmaapClientUtil.getResponsewtBasicAuth(DmaapClientUtil.getTarget(getClientConfig(),"/path"), - Base64.encodeAsString("username:password"))) - .thenReturn( - responseBuilder.header("transactionid", "transactionid").entity("{\"test\":\"test\"}").build()); + @Test + public void testGetAuth() throws JSONException, HttpException { - mrBaseClient.postWithResponse("/path", new String("{\"test\":\"test\"}").getBytes(), "application/json", null, - null, "HTTPAUTH"); + Response response = Mockito.mock(Response.class); + MultivaluedMap map = new StringKeyIgnoreCaseMultivaluedMap<>(); + map.add("transactionid", "transactionid"); - } + Mockito.when(response.getStatus()).thenReturn(200); + Mockito.when(response.readEntity(String.class)).thenReturn("{\"test\":\"test\"}"); + Mockito.when(response.getHeaders()).thenReturn(map); - @Test - public void testGetAuth() throws JSONException, HttpException { + Mockito.when( + DmaapClientUtil.getResponsewtCambriaAuth(DmaapClientUtil.getTarget(getClientConfig(), "/path"), "username", "password")) + .thenReturn(response); + mrBaseClient.getAuth("/path", "username", "password", "username", "password", "HTTPAUTH"); + assertTrue(true); - Response response = Mockito.mock(Response.class); - MultivaluedMap map = new StringKeyIgnoreCaseMultivaluedMap<>(); - map.add("transactionid", "transactionid"); + } - Mockito.when(response.getStatus()).thenReturn(200); - Mockito.when(response.readEntity(String.class)).thenReturn("{\"test\":\"test\"}"); - Mockito.when(response.getHeaders()).thenReturn(map); + @Test(expected = HttpException.class) + public void testGetAuth_error() throws JSONException, HttpException { - Mockito.when( - DmaapClientUtil.getResponsewtCambriaAuth(DmaapClientUtil.getTarget(getClientConfig(),"/path"), "username", "password")) - .thenReturn(response); - mrBaseClient.getAuth("/path", "username", "password", "username", "password", "HTTPAUTH"); - assertTrue(true); + ResponseBuilder responseBuilder = Response.ok(); + Mockito + .when(DmaapClientUtil.postResponsewtCambriaAuth(DmaapClientUtil.getTarget(getClientConfig(), "/path"), "username", + "password", ("{\"test\":\"test\"}").getBytes(), "application/json")) + .thenReturn( + responseBuilder.header("transactionid", "transactionid").entity("{\"test\":\"test\"}").build()); - } + mrBaseClient.getAuth("/path", null, null, null, null, "HTTPAUTH"); - @Test(expected = HttpException.class) - public void testGetAuth_error() throws JSONException, HttpException { + } - ResponseBuilder responseBuilder = Response.ok(); - Mockito - .when(DmaapClientUtil.postResponsewtCambriaAuth(DmaapClientUtil.getTarget(getClientConfig(),"/path"), "username", - "password", new String("{\"test\":\"test\"}").getBytes(), "application/json")) - .thenReturn( - responseBuilder.header("transactionid", "transactionid").entity("{\"test\":\"test\"}").build()); + @Test + public void testGetNoAuth() throws JSONException, HttpException { - mrBaseClient.getAuth("/path", null, null, null, null, "HTTPAUTH"); - assertTrue(true); + Response response = Mockito.mock(Response.class); + MultivaluedMap map = new StringKeyIgnoreCaseMultivaluedMap<>(); + map.add("transactionid", "transactionid"); - } + Mockito.when(response.getStatus()).thenReturn(200); + Mockito.when(response.readEntity(String.class)).thenReturn("{\"test\":\"test\"}"); + Mockito.when(response.getHeaders()).thenReturn(map); - @Test - public void testGetNoAuth() throws JSONException, HttpException { + Mockito.when(DmaapClientUtil.getResponsewtNoAuth(DmaapClientUtil.getTarget(getClientConfig(), "/path"))).thenReturn(response); + mrBaseClient.getNoAuth("/path"); + assertTrue(true); - Response response = Mockito.mock(Response.class); - MultivaluedMap map = new StringKeyIgnoreCaseMultivaluedMap<>(); - map.add("transactionid", "transactionid"); + } - Mockito.when(response.getStatus()).thenReturn(200); - Mockito.when(response.readEntity(String.class)).thenReturn("{\"test\":\"test\"}"); - Mockito.when(response.getHeaders()).thenReturn(map); - Mockito.when(DmaapClientUtil.getResponsewtNoAuth(DmaapClientUtil.getTarget(getClientConfig(),"/path"))).thenReturn(response); - mrBaseClient.getNoAuth("/path"); - assertTrue(true); + @Test + public void testGetHTTPErrorResponseMessage() { + assertEquals("testtest", mrBaseClient.getHTTPErrorResponseMessage("testtest")); - } + } + @Test + public void getGTTPErrorResponseCode() { + assertEquals("500", mrBaseClient.getHTTPErrorResponseCode("500")); + } - @Test - public void testGetHTTPErrorResponseMessage() { - assertEquals("testtest", mrBaseClient.getHTTPErrorResponseMessage("testtest")); - } + private ClientConfig getClientConfig() { + if (config == null) { + config = DmaapClientUtil.getClientConfig(null); + } + return config; - @Test - public void getGTTPErrorResponseCode() { - assertEquals("500", mrBaseClient.getHTTPErrorResponseCode("500")); - } - - - - private ClientConfig getClientConfig(){ - if(config==null){ - config=DmaapClientUtil.getClientConfig(null); - } - return config; - - } + } } diff --git a/src/test/java/org/onap/dmaap/mr/client/impl/MRBatchPublisherTest.java b/src/test/java/org/onap/dmaap/mr/client/impl/MRBatchPublisherTest.java index 3d1e3d0..4d8811f 100644 --- a/src/test/java/org/onap/dmaap/mr/client/impl/MRBatchPublisherTest.java +++ b/src/test/java/org/onap/dmaap/mr/client/impl/MRBatchPublisherTest.java @@ -4,11 +4,13 @@ * ================================================================================ * Copyright © 2017 AT&T Intellectual Property. All rights reserved. * ================================================================================ + * Modifications Copyright © 2021 Orange. + * ================================================================================ * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * http://www.apache.org/licenses/LICENSE-2.0 - * + * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. @@ -17,38 +19,39 @@ * ============LICENSE_END========================================================= * * ECOMP is a trademark and service mark of AT&T Intellectual Property. - * + * *******************************************************************************/ + package org.onap.dmaap.mr.client.impl; +import org.junit.Before; +import org.junit.Test; + import java.io.IOException; import java.util.Arrays; import java.util.Collection; import java.util.HashSet; -import org.junit.Before; -import org.junit.Test; - public class MRBatchPublisherTest { - - private Collection hosts=new HashSet<>(Arrays.asList("/test")); - private MRBatchPublisher mrBatchPublisher=new MRBatchPublisher(hosts, "topic", 2, 20, true); - - - @Before - public void setup(){ - - - } - - @Test(expected = Test.None.class /* no exception expected */) - public void testSend() throws IOException{ - mrBatchPublisher.send("testmessage"); - } - - @Test(expected = Test.None.class /* no exception expected */) - public void testClose() throws IOException{ - mrBatchPublisher.close(); - } + + private Collection hosts = new HashSet<>(Arrays.asList("/test")); + private MRBatchPublisher mrBatchPublisher = new MRBatchPublisher(hosts, "topic", 2, 20, true); + + + @Before + public void setup() { + + + } + + @Test(expected = Test.None.class /* no exception expected */) + public void testSend() throws IOException { + mrBatchPublisher.send("testmessage"); + } + + @Test(expected = Test.None.class /* no exception expected */) + public void testClose() throws IOException { + mrBatchPublisher.close(); + } } diff --git a/src/test/java/org/onap/dmaap/mr/client/impl/MRConstantsTest.java b/src/test/java/org/onap/dmaap/mr/client/impl/MRConstantsTest.java index d912f9d..09fc2a8 100644 --- a/src/test/java/org/onap/dmaap/mr/client/impl/MRConstantsTest.java +++ b/src/test/java/org/onap/dmaap/mr/client/impl/MRConstantsTest.java @@ -4,11 +4,13 @@ * ================================================================================ * Copyright © 2017 AT&T Intellectual Property. All rights reserved. * ================================================================================ + * Modifications Copyright © 2021 Orange. + * ================================================================================ * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * http://www.apache.org/licenses/LICENSE-2.0 - * + * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. @@ -17,125 +19,112 @@ * ============LICENSE_END========================================================= * * ECOMP is a trademark and service mark of AT&T Intellectual Property. - * + * *******************************************************************************/ + package org.onap.dmaap.mr.client.impl; +import junit.framework.TestCase; +import org.apache.http.HttpHost; +import org.junit.Test; + import java.io.IOException; import java.util.ArrayList; import java.util.Collection; import java.util.Iterator; -import junit.framework.TestCase; - -import org.apache.http.HttpHost; -import org.junit.Test; - -public class MRConstantsTest extends TestCase -{ - @Test - public void testPlainHost () throws IOException - { - final String rawTopic = "bar"; - final String result = MRConstants.makeUrl ( rawTopic ); - assertEquals ( "/events/" + "bar", result ); - } - - @Test - public void testHostWithProtocol () throws IOException - { - final String rawTopic = "bar"; - final String result = MRConstants.makeUrl ( rawTopic ); - assertEquals ( "/events/" + "bar", result ); - } - - @Test - public void testHostWithProtocolAndPort () throws IOException - { - final String rawTopic = "bar"; - final String result = MRConstants.makeUrl ( rawTopic ); - assertEquals ( "/events/" + "bar", result ); - } - - @Test - public void testHostWithPort () throws IOException - { - final String rawTopic = "bar"; - final String result = MRConstants.makeUrl ( rawTopic ); - assertEquals ( "/events/" + "bar", result ); - } - - @Test - public void testHostWithPortAndEscapedTopic () throws IOException - { - final String rawTopic = "bar?bell"; - final String result = MRConstants.makeUrl ( rawTopic ); - assertEquals ( "/events/" + "bar%3Fbell", result ); - } - - @Test - public void testConsumerPlainHost () throws IOException - { - final String rawTopic = "bar"; - final String rawGroup = "group"; - final String rawId = "id"; - final String result = MRConstants.makeConsumerUrl ( rawTopic, rawGroup, rawId ); - assertEquals ( "/events/" + "bar/group/id", result ); - } - - @Test - public void testCreateHostList () - { - final ArrayList in = new ArrayList (); - in.add ( "foo" ); - in.add ( "bar" ); - in.add ( "baz:80" ); - - final Collection hosts = MRConstants.createHostsList ( in ); - assertEquals ( 3, hosts.size () ); - - final Iterator it = hosts.iterator (); - final HttpHost first = it.next (); - assertEquals ( MRConstants.STD_MR_SERVICE_PORT, first.getPort () ); - assertEquals ( "foo", first.getHostName () ); - - final HttpHost second = it.next (); - assertEquals ( MRConstants.STD_MR_SERVICE_PORT, second.getPort () ); - assertEquals ( "bar", second.getHostName () ); - - final HttpHost third = it.next (); - assertEquals ( 80, third.getPort () ); - assertEquals ( "baz", third.getHostName () ); - } - - private static final String[][] hostTests = - { - { "host", "host", "" + MRConstants.STD_MR_SERVICE_PORT}, - { ":oops", null, "-1" }, - { "host:1.3", null, "-1" }, - { "host:13", "host", "13" }, - { "host:", "host", "" + MRConstants.STD_MR_SERVICE_PORT}, - }; - - @Test - public void testHostParse () - { - for ( String[] test : hostTests ) - { - final String hostIn = test[0]; - final String hostOut = test[1]; - final int portOut = Integer.parseInt ( test[2] ); - - try - { - final HttpHost hh = MRConstants.hostForString ( hostIn ); - assertEquals ( hostOut, hh.getHostName () ); - assertEquals ( portOut, hh.getPort () ); - } - catch ( IllegalArgumentException x ) - { - assertEquals ( -1, portOut ); - } - } - } +public class MRConstantsTest extends TestCase { + @Test + public void testPlainHost() throws IOException { + final String rawTopic = "bar"; + final String result = MRConstants.makeUrl(rawTopic); + assertEquals("/events/" + "bar", result); + } + + @Test + public void testHostWithProtocol() throws IOException { + final String rawTopic = "bar"; + final String result = MRConstants.makeUrl(rawTopic); + assertEquals("/events/" + "bar", result); + } + + @Test + public void testHostWithProtocolAndPort() throws IOException { + final String rawTopic = "bar"; + final String result = MRConstants.makeUrl(rawTopic); + assertEquals("/events/" + "bar", result); + } + + @Test + public void testHostWithPort() throws IOException { + final String rawTopic = "bar"; + final String result = MRConstants.makeUrl(rawTopic); + assertEquals("/events/" + "bar", result); + } + + @Test + public void testHostWithPortAndEscapedTopic() throws IOException { + final String rawTopic = "bar?bell"; + final String result = MRConstants.makeUrl(rawTopic); + assertEquals("/events/" + "bar%3Fbell", result); + } + + @Test + public void testConsumerPlainHost() throws IOException { + final String rawTopic = "bar"; + final String rawGroup = "group"; + final String rawId = "id"; + final String result = MRConstants.makeConsumerUrl(rawTopic, rawGroup, rawId); + assertEquals("/events/" + "bar/group/id", result); + } + + @Test + public void testCreateHostList() { + final ArrayList in = new ArrayList(); + in.add("foo"); + in.add("bar"); + in.add("baz:80"); + + final Collection hosts = MRConstants.createHostsList(in); + assertEquals(3, hosts.size()); + + final Iterator it = hosts.iterator(); + final HttpHost first = it.next(); + assertEquals(MRConstants.STD_MR_SERVICE_PORT, first.getPort()); + assertEquals("foo", first.getHostName()); + + final HttpHost second = it.next(); + assertEquals(MRConstants.STD_MR_SERVICE_PORT, second.getPort()); + assertEquals("bar", second.getHostName()); + + final HttpHost third = it.next(); + assertEquals(80, third.getPort()); + assertEquals("baz", third.getHostName()); + } + + private static final String[][] hostTests = + { + {"host", "host", "" + MRConstants.STD_MR_SERVICE_PORT}, + {":oops", null, "-1"}, + {"host:1.3", null, "-1"}, + {"host:13", "host", "13"}, + {"host:", "host", "" + MRConstants.STD_MR_SERVICE_PORT}, + }; + + @Test + public void testHostParse() { + for (String[] test : hostTests) { + final String hostIn = test[0]; + final String hostOut = test[1]; + final int portOut = Integer.parseInt(test[2]); + + try { + final HttpHost hh = MRConstants.hostForString(hostIn); + assertEquals(hostOut, hh.getHostName()); + assertEquals(portOut, hh.getPort()); + } catch (IllegalArgumentException x) { + assertEquals(-1, portOut); + } + } + } } diff --git a/src/test/java/org/onap/dmaap/mr/client/impl/MRConsumerImplTest.java b/src/test/java/org/onap/dmaap/mr/client/impl/MRConsumerImplTest.java index 52c7111..7b77a95 100644 --- a/src/test/java/org/onap/dmaap/mr/client/impl/MRConsumerImplTest.java +++ b/src/test/java/org/onap/dmaap/mr/client/impl/MRConsumerImplTest.java @@ -4,11 +4,13 @@ * ================================================================================ * Copyright © 2017 AT&T Intellectual Property. All rights reserved. * ================================================================================ + * Modifications Copyright © 2021 Orange. + * ================================================================================ * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * http://www.apache.org/licenses/LICENSE-2.0 - * + * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. @@ -17,182 +19,181 @@ * ============LICENSE_END========================================================= * * ECOMP is a trademark and service mark of AT&T Intellectual Property. - * + * *******************************************************************************/ package org.onap.dmaap.mr.client.impl; +import junit.framework.TestCase; +import org.junit.Test; +import org.onap.dmaap.mr.client.MRClientFactory; +import org.onap.dmaap.mr.client.ProtocolType; + import java.io.File; import java.io.FileOutputStream; import java.io.IOException; import java.util.LinkedList; import java.util.Properties; -import junit.framework.TestCase; - -import org.junit.Test; -import org.onap.dmaap.mr.client.MRClientFactory; -import org.onap.dmaap.mr.test.clients.ProtocolTypeConstants; - public class MRConsumerImplTest extends TestCase { - @Test - public void testNullFilter() throws IOException { - final LinkedList hosts = new LinkedList(); - hosts.add("localhost:8080"); + @Test + public void testNullFilter() throws IOException { + final LinkedList hosts = new LinkedList(); + hosts.add("localhost:8080"); final MRConsumerImpl c = new MRConsumerImpl.MRConsumerImplBuilder().setHostPart(hosts) .setTopic("topic").setConsumerGroup("cg").setConsumerId("cid").setTimeoutMs(-1) .setLimit(-1).setFilter(null).setApiKey_username(null).setApiSecret_password(null) .createMRConsumerImpl(); - final String url = c.createUrlPath(MRConstants.makeConsumerUrl("localhost:8080", "topic", "cg", "cid", "http"), - -1, -1); - assertEquals("http://localhost:8080/events/" + "topic/cg/cid", url); - } - - @Test - public void testFilterWithNoTimeoutOrLimit() throws IOException { - final LinkedList hosts = new LinkedList(); - hosts.add("localhost:8080"); + final String url = c.createUrlPath(MRConstants.makeConsumerUrl("localhost:8080", "topic", "cg", "cid", "http"), + -1, -1); + assertEquals("http://localhost:8080/events/" + "topic/cg/cid", url); + } + + @Test + public void testFilterWithNoTimeoutOrLimit() throws IOException { + final LinkedList hosts = new LinkedList(); + hosts.add("localhost:8080"); final MRConsumerImpl c = new MRConsumerImpl.MRConsumerImplBuilder().setHostPart(hosts) .setTopic("topic").setConsumerGroup("cg").setConsumerId("cid").setTimeoutMs(-1) .setLimit(-1).setFilter("filter").setApiKey_username(null) .setApiSecret_password(null).createMRConsumerImpl(); - final String url = c.createUrlPath(MRConstants.makeConsumerUrl("localhost:8080", "topic", "cg", "cid", "http"), - -1, -1); - assertEquals("http://localhost:8080/events/" + "topic/cg/cid?filter=filter", url); - } - - @Test - public void testTimeoutNoLimitNoFilter() throws IOException { - final LinkedList hosts = new LinkedList(); - hosts.add("localhost:8080"); + final String url = c.createUrlPath(MRConstants.makeConsumerUrl("localhost:8080", "topic", "cg", "cid", "http"), + -1, -1); + assertEquals("http://localhost:8080/events/" + "topic/cg/cid?filter=filter", url); + } + + @Test + public void testTimeoutNoLimitNoFilter() throws IOException { + final LinkedList hosts = new LinkedList(); + hosts.add("localhost:8080"); final MRConsumerImpl c = new MRConsumerImpl.MRConsumerImplBuilder().setHostPart(hosts) .setTopic("topic").setConsumerGroup("cg").setConsumerId("cid").setTimeoutMs(30000) .setLimit(-1).setFilter(null).setApiKey_username(null).setApiSecret_password(null) .createMRConsumerImpl(); - final String url = c.createUrlPath(MRConstants.makeConsumerUrl("localhost:8080", "topic", "cg", "cid", "http"), - 30000, -1); - assertEquals("http://localhost:8080/events/" + "topic/cg/cid?timeout=30000", url); - } - - @Test - public void testNoTimeoutWithLimitNoFilter() throws IOException { - final LinkedList hosts = new LinkedList(); - hosts.add("localhost:8080"); + final String url = c.createUrlPath(MRConstants.makeConsumerUrl("localhost:8080", "topic", "cg", "cid", "http"), + 30000, -1); + assertEquals("http://localhost:8080/events/" + "topic/cg/cid?timeout=30000", url); + } + + @Test + public void testNoTimeoutWithLimitNoFilter() throws IOException { + final LinkedList hosts = new LinkedList(); + hosts.add("localhost:8080"); final MRConsumerImpl c = new MRConsumerImpl.MRConsumerImplBuilder().setHostPart(hosts) .setTopic("topic").setConsumerGroup("cg").setConsumerId("cid").setTimeoutMs(-1) .setLimit(100).setFilter(null).setApiKey_username(null).setApiSecret_password(null) .createMRConsumerImpl(); - final String url = c.createUrlPath(MRConstants.makeConsumerUrl("localhost:8080", "topic", "cg", "cid", "http"), - -1, 100); - assertEquals("http://localhost:8080/events/" + "topic/cg/cid?limit=100", url); - } - - @Test - public void testWithTimeoutWithLimitWithFilter() throws IOException { - final LinkedList hosts = new LinkedList(); - hosts.add("localhost:8080"); + final String url = c.createUrlPath(MRConstants.makeConsumerUrl("localhost:8080", "topic", "cg", "cid", "http"), + -1, 100); + assertEquals("http://localhost:8080/events/" + "topic/cg/cid?limit=100", url); + } + + @Test + public void testWithTimeoutWithLimitWithFilter() throws IOException { + final LinkedList hosts = new LinkedList(); + hosts.add("localhost:8080"); final MRConsumerImpl c = new MRConsumerImpl.MRConsumerImplBuilder().setHostPart(hosts) .setTopic("topic").setConsumerGroup("cg").setConsumerId("cid").setTimeoutMs(1000) .setLimit(400).setFilter("f").setApiKey_username(null).setApiSecret_password(null) .createMRConsumerImpl(); - final String url = c.createUrlPath(MRConstants.makeConsumerUrl("localhost:8080", "topic", "cg", "cid", "http"), - 1000, 400); - assertEquals("http://localhost:8080/events/" + "topic/cg/cid?timeout=1000&limit=400&filter=f", url); - } - - @Test - public void testFilterEncoding() throws IOException { - final LinkedList hosts = new LinkedList(); - hosts.add("localhost:8080"); + final String url = c.createUrlPath(MRConstants.makeConsumerUrl("localhost:8080", "topic", "cg", "cid", "http"), + 1000, 400); + assertEquals("http://localhost:8080/events/" + "topic/cg/cid?timeout=1000&limit=400&filter=f", url); + } + + @Test + public void testFilterEncoding() throws IOException { + final LinkedList hosts = new LinkedList(); + hosts.add("localhost:8080"); final MRConsumerImpl c = new MRConsumerImpl.MRConsumerImplBuilder().setHostPart(hosts) .setTopic("topic").setConsumerGroup("cg").setConsumerId("cid").setTimeoutMs(-1) .setLimit(-1).setFilter("{ \"foo\"=\"bar\"bar\" }").setApiKey_username(null) .setApiSecret_password(null).createMRConsumerImpl(); - final String url = c.createUrlPath(MRConstants.makeConsumerUrl("localhost:8080", "topic", "cg", "cid", "http"), - -1, -1); - assertEquals("http://localhost:8080/events/" + "topic/cg/cid?filter=%7B+%22foo%22%3D%22bar%22bar%22+%7D", url); - } - - @Test - public void testFetchWithReturnConsumerResponse() throws IOException { - final LinkedList hosts = new LinkedList(); - hosts.add("localhost:8080"); - Properties properties = new Properties(); - properties.load( - MRSimplerBatchPublisherTest.class.getClassLoader().getResourceAsStream("dme2/consumer.properties")); - - String routeFilePath = "dme2/preferredRoute.txt"; - - File file = new File(MRSimplerBatchPublisherTest.class.getClassLoader().getResource(routeFilePath).getFile()); - properties.put("routeFilePath", - MRSimplerBatchPublisherTest.class.getClassLoader().getResource(routeFilePath).getFile()); - - File outFile = new File(file.getParent() + "/consumer_tmp.properties"); - properties.store(new FileOutputStream(outFile), ""); - - MRClientFactory.prop=properties; + final String url = c.createUrlPath(MRConstants.makeConsumerUrl("localhost:8080", "topic", "cg", "cid", "http"), + -1, -1); + assertEquals("http://localhost:8080/events/" + "topic/cg/cid?filter=%7B+%22foo%22%3D%22bar%22bar%22+%7D", url); + } + + @Test + public void testFetchWithReturnConsumerResponse() throws IOException { + final LinkedList hosts = new LinkedList(); + hosts.add("localhost:8080"); + Properties properties = new Properties(); + properties.load( + MRSimplerBatchPublisherTest.class.getClassLoader().getResourceAsStream("dme2/consumer.properties")); + + String routeFilePath = "dme2/preferredRoute.txt"; + + File file = new File(MRSimplerBatchPublisherTest.class.getClassLoader().getResource(routeFilePath).getFile()); + properties.put("routeFilePath", + MRSimplerBatchPublisherTest.class.getClassLoader().getResource(routeFilePath).getFile()); + + File outFile = new File(file.getParent() + "/consumer_tmp.properties"); + properties.store(new FileOutputStream(outFile), ""); + + MRClientFactory.prop = properties; final MRConsumerImpl c = new MRConsumerImpl.MRConsumerImplBuilder().setHostPart(hosts) .setTopic("topic").setConsumerGroup("cg").setConsumerId("cid").setTimeoutMs(-1) .setLimit(-1).setFilter("{ \"foo\"=\"bar\"bar\" }").setApiKey_username(null) .setApiSecret_password(null).createMRConsumerImpl(); - c.setProps(properties); - assertNotNull(c.fetchWithReturnConsumerResponse()); - c.setProtocolFlag(ProtocolTypeConstants.AAF_AUTH.getValue()); - assertNotNull(c.fetchWithReturnConsumerResponse()); - c.setProtocolFlag(ProtocolTypeConstants.HTTPNOAUTH.getValue()); - assertNotNull(c.fetchWithReturnConsumerResponse()); - c.setProtocolFlag(ProtocolTypeConstants.AUTH_KEY.getValue()); - assertNotNull(c.fetchWithReturnConsumerResponse()); - assertTrue(true); - } - - @Test - public void testFetch() throws Exception { - final LinkedList hosts = new LinkedList(); - hosts.add("localhost:8080"); - - - Properties properties = new Properties(); - properties.load( - MRSimplerBatchPublisherTest.class.getClassLoader().getResourceAsStream("dme2/consumer.properties")); - - String routeFilePath = "dme2/preferredRoute.txt"; - - File file = new File(MRSimplerBatchPublisherTest.class.getClassLoader().getResource(routeFilePath).getFile()); - properties.put("routeFilePath", - MRSimplerBatchPublisherTest.class.getClassLoader().getResource(routeFilePath).getFile()); - - File outFile = new File(file.getParent() + "/consumer_tmp.properties"); - properties.store(new FileOutputStream(outFile), ""); - - MRClientFactory.prop=properties; + c.setProps(properties); + assertNotNull(c.fetchWithReturnConsumerResponse()); + c.setProtocolFlag(ProtocolType.AAF_AUTH.getValue()); + assertNotNull(c.fetchWithReturnConsumerResponse()); + c.setProtocolFlag(ProtocolType.HTTPNOAUTH.getValue()); + assertNotNull(c.fetchWithReturnConsumerResponse()); + c.setProtocolFlag(ProtocolType.AUTH_KEY.getValue()); + assertNotNull(c.fetchWithReturnConsumerResponse()); + assertTrue(true); + } + + @Test + public void testFetch() throws Exception { + final LinkedList hosts = new LinkedList(); + hosts.add("localhost:8080"); + + + Properties properties = new Properties(); + properties.load( + MRSimplerBatchPublisherTest.class.getClassLoader().getResourceAsStream("dme2/consumer.properties")); + + String routeFilePath = "dme2/preferredRoute.txt"; + + File file = new File(MRSimplerBatchPublisherTest.class.getClassLoader().getResource(routeFilePath).getFile()); + properties.put("routeFilePath", + MRSimplerBatchPublisherTest.class.getClassLoader().getResource(routeFilePath).getFile()); + + File outFile = new File(file.getParent() + "/consumer_tmp.properties"); + properties.store(new FileOutputStream(outFile), ""); + + MRClientFactory.prop = properties; final MRConsumerImpl c = new MRConsumerImpl.MRConsumerImplBuilder().setHostPart(hosts) .setTopic("topic").setConsumerGroup("cg").setConsumerId("cid").setTimeoutMs(-1) .setLimit(-1).setFilter("{ \"foo\"=\"bar\"bar\" }").setApiKey_username(null) .setApiSecret_password(null).createMRConsumerImpl(); - c.setProps(properties); - try { - c.fetch(); - } catch (Exception e) { - assertTrue(true); - } - c.setProtocolFlag(ProtocolTypeConstants.AAF_AUTH.getValue()); - try { - c.fetch(); - } catch (Exception e) { - assertTrue(true); - } - c.setProtocolFlag(ProtocolTypeConstants.HTTPNOAUTH.getValue()); - try { - c.fetch(); - } catch (Exception e) { - assertTrue(true); - } - c.setProtocolFlag(ProtocolTypeConstants.AUTH_KEY.getValue()); - try { - c.fetch(); - } catch (Exception e) { - assertTrue(true); - } - } + c.setProps(properties); + try { + c.fetch(); + } catch (Exception e) { + assertTrue(true); + } + c.setProtocolFlag(ProtocolType.AAF_AUTH.getValue()); + try { + c.fetch(); + } catch (Exception e) { + assertTrue(true); + } + c.setProtocolFlag(ProtocolType.HTTPNOAUTH.getValue()); + try { + c.fetch(); + } catch (Exception e) { + assertTrue(true); + } + c.setProtocolFlag(ProtocolType.AUTH_KEY.getValue()); + try { + c.fetch(); + } catch (Exception e) { + assertTrue(true); + } + } } diff --git a/src/test/java/org/onap/dmaap/mr/client/impl/MRMetaClientTest.java b/src/test/java/org/onap/dmaap/mr/client/impl/MRMetaClientTest.java index ea9cab4..00f1278 100644 --- a/src/test/java/org/onap/dmaap/mr/client/impl/MRMetaClientTest.java +++ b/src/test/java/org/onap/dmaap/mr/client/impl/MRMetaClientTest.java @@ -4,11 +4,13 @@ * ================================================================================ * Copyright © 2017 AT&T Intellectual Property. All rights reserved. * ================================================================================ + * Modifications Copyright © 2021 Orange. + * ================================================================================ * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * http://www.apache.org/licenses/LICENSE-2.0 - * + * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. @@ -17,110 +19,98 @@ * ============LICENSE_END========================================================= * * ECOMP is a trademark and service mark of AT&T Intellectual Property. - * + * *******************************************************************************/ + package org.onap.dmaap.mr.client.impl; +import com.att.nsa.apiClient.http.HttpException; +import com.att.nsa.apiClient.http.HttpObjectNotFoundException; +import org.junit.Test; +import org.onap.dmaap.mr.client.MRTopicManager.TopicInfo; + import java.io.IOException; import java.util.Collection; import java.util.LinkedList; import java.util.Set; -import org.junit.Before; -import org.junit.Test; import static org.junit.Assert.assertNotNull; import static org.junit.Assert.assertTrue; -import com.att.nsa.apiClient.http.HttpException; -import com.att.nsa.apiClient.http.HttpObjectNotFoundException; -import org.onap.dmaap.mr.client.MRTopicManager.TopicInfo; public class MRMetaClientTest { - - //@Rule public WireMockRule wireMock = new WireMockRule(); - - @Before - public void setUp(){/* - wireMock.stubFor(get(urlEqualTo("/topics")) - .willReturn(aResponse().withBody("{\"topics\":[\"topic1\",\"topic2\"]}").withHeader("Content-Type", "application/json"))); - wireMock.stubFor(get(urlEqualTo("/topics/topic1")) - .willReturn(aResponse().withBody("{\"topics\":[\"topic1\",\"topic2\"]}").withHeader("Content-Type", "application/json"))); - wireMock.stubFor(post(urlEqualTo("/topics/create")) - .willReturn(aResponse().withStatus(200))); - */} - - @Test - public void getTopicsTest() - { - final Collection hosts = new LinkedList (); - hosts.add ( "localhost:" +3904 ); - - MRMetaClient c; - try { - c = new MRMetaClient(hosts); - Set setString=c.getTopics(); - } catch (IOException e) { - e.printStackTrace(); - } - assertNotNull(hosts); - - - // assertEquals ("http://localhost:8080/events/" + "topic/cg/cid", url ); - - } - - @Test - public void getTopicMetadataTest() { - final Collection hosts = new LinkedList (); - hosts.add ( "localhost:" + 3904 ); - - final String topic ="topic1"; - - MRMetaClient c; - try { - c = new MRMetaClient(hosts); - TopicInfo topicInfo=c.getTopicMetadata(topic); - } catch (IOException | HttpObjectNotFoundException e) { - e.printStackTrace(); - } - assertNotNull(topic); - - } - - @Test - public void testcreateTopic(){ - final Collection hosts = new LinkedList (); - hosts.add ( "localhost:" + 3904 ); - - MRMetaClient c; - try { - c = new MRMetaClient(hosts); - c.createTopic("topic1", "testTopic", 1, 1); - } catch (IOException | HttpException e) { - e.printStackTrace(); - } - assertNotNull(hosts); - } - @Test - public void testupdateApiKey(){ - final Collection hosts = new LinkedList (); - hosts.add ( "localhost:" + 3904 ); - - MRMetaClient c; - try { - c = new MRMetaClient(hosts); - c.updateCurrentApiKey("test@onap.com", "test email"); - }catch (HttpException e) { - - } catch (IOException e) { - // TODO Auto-generated catch block - e.printStackTrace(); - } - catch (NullPointerException e) { - assertTrue(true); - } - - } - - + + @Test + public void getTopicsTest() { + final Collection hosts = new LinkedList(); + hosts.add("localhost:" + 3904); + + MRMetaClient c; + try { + c = new MRMetaClient(hosts); + Set setString = c.getTopics(); + } catch (IOException e) { + e.printStackTrace(); + } + assertNotNull(hosts); + + + //assertEquals ("http://localhost:8080/events/" + "topic/cg/cid", url ); + + } + + @Test + public void getTopicMetadataTest() { + final Collection hosts = new LinkedList(); + hosts.add("localhost:" + 3904); + + final String topic = "topic1"; + + MRMetaClient c; + try { + c = new MRMetaClient(hosts); + TopicInfo topicInfo = c.getTopicMetadata(topic); + } catch (IOException | HttpObjectNotFoundException e) { + e.printStackTrace(); + } + assertNotNull(topic); + + } + + @Test + public void testcreateTopic() { + final Collection hosts = new LinkedList(); + hosts.add("localhost:" + 3904); + + MRMetaClient c; + try { + c = new MRMetaClient(hosts); + c.createTopic("topic1", "testTopic", 1, 1); + } catch (IOException | HttpException e) { + e.printStackTrace(); + } + assertNotNull(hosts); + } + + @Test + public void testupdateApiKey() { + final Collection hosts = new LinkedList(); + hosts.add("localhost:" + 3904); + + MRMetaClient c; + try { + c = new MRMetaClient(hosts); + c.updateCurrentApiKey("test@onap.com", "test email"); + } catch (HttpException e) { + + } catch (IOException e) { + // TODO Auto-generated catch block + e.printStackTrace(); + } catch (NullPointerException e) { + assertTrue(true); + } + + } + + } diff --git a/src/test/java/org/onap/dmaap/mr/client/impl/MRSimplerBatchConsumerTest.java b/src/test/java/org/onap/dmaap/mr/client/impl/MRSimplerBatchConsumerTest.java index af5ccd2..26fee9e 100644 --- a/src/test/java/org/onap/dmaap/mr/client/impl/MRSimplerBatchConsumerTest.java +++ b/src/test/java/org/onap/dmaap/mr/client/impl/MRSimplerBatchConsumerTest.java @@ -4,11 +4,13 @@ * ================================================================================ * Copyright © 2017 AT&T Intellectual Property. All rights reserved. * ================================================================================ + * Modifications Copyright © 2021 Orange. + * ================================================================================ * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * http://www.apache.org/licenses/LICENSE-2.0 - * + * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. @@ -17,54 +19,56 @@ * ============LICENSE_END========================================================= * * ECOMP is a trademark and service mark of AT&T Intellectual Property. - * + * *******************************************************************************/ package org.onap.dmaap.mr.client.impl; +import org.junit.Before; +import org.junit.Test; +import org.onap.dmaap.mr.client.MRClientFactory; +import org.onap.dmaap.mr.client.MRConsumer; + import java.io.File; import java.io.FileOutputStream; import java.io.IOException; import java.util.Properties; -import org.junit.Before; -import org.junit.Test; -import org.onap.dmaap.mr.client.MRClientFactory; -import org.onap.dmaap.mr.client.MRConsumer; import static org.junit.Assert.assertNotNull; public class MRSimplerBatchConsumerTest { - - File outFile; - @Before - public void setUp() throws Exception { - Properties properties = new Properties(); - properties.load(MRSimplerBatchConsumerTest.class.getClassLoader().getResourceAsStream("dme2/consumer.properties")); - - String routeFilePath="dme2/preferredRoute.txt"; - - File file = new File(MRSimplerBatchConsumerTest.class.getClassLoader().getResource(routeFilePath).getFile()); - properties.put("DME2preferredRouterFilePath", MRSimplerBatchConsumerTest.class.getClassLoader().getResource(routeFilePath).getFile()); - - outFile = new File(file.getParent() + "/consumer_tmp.properties"); - properties.store(new FileOutputStream(outFile), ""); - } - - @Test - public void testSend() throws IOException, InterruptedException { - - final MRConsumer cc = MRClientFactory.createConsumer(outFile.getPath()); - - try { - for(String msg : cc.fetch()){ - System.out.println(msg); - } - } catch (Exception e) { - System.err.println ( e.getClass().getName () + ": " + e.getMessage () ); - } - assertNotNull(cc); - - } - + + File outFile; + + @Before + public void setUp() throws Exception { + Properties properties = new Properties(); + properties.load(MRSimplerBatchConsumerTest.class.getClassLoader().getResourceAsStream("dme2/consumer.properties")); + + String routeFilePath = "dme2/preferredRoute.txt"; + + File file = new File(MRSimplerBatchConsumerTest.class.getClassLoader().getResource(routeFilePath).getFile()); + properties.put("DME2preferredRouterFilePath", MRSimplerBatchConsumerTest.class.getClassLoader().getResource(routeFilePath).getFile()); + + outFile = new File(file.getParent() + "/consumer_tmp.properties"); + properties.store(new FileOutputStream(outFile), ""); + } + + @Test + public void testSend() throws IOException, InterruptedException { + + final MRConsumer cc = MRClientFactory.createConsumer(outFile.getPath()); + + try { + for (String msg : cc.fetch()) { + System.out.println(msg); + } + } catch (Exception e) { + System.err.println(e.getClass().getName() + ": " + e.getMessage()); + } + assertNotNull(cc); + + } + } diff --git a/src/test/java/org/onap/dmaap/mr/client/impl/MRSimplerBatchPublisherTest.java b/src/test/java/org/onap/dmaap/mr/client/impl/MRSimplerBatchPublisherTest.java index b2f8817..1ac22ef 100644 --- a/src/test/java/org/onap/dmaap/mr/client/impl/MRSimplerBatchPublisherTest.java +++ b/src/test/java/org/onap/dmaap/mr/client/impl/MRSimplerBatchPublisherTest.java @@ -4,11 +4,13 @@ * ================================================================================ * Copyright © 2017 AT&T Intellectual Property. All rights reserved. * ================================================================================ + * Modifications Copyright © 2021 Orange. + * ================================================================================ * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * http://www.apache.org/licenses/LICENSE-2.0 - * + * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. @@ -17,302 +19,298 @@ * ============LICENSE_END========================================================= * * ECOMP is a trademark and service mark of AT&T Intellectual Property. - * + * *******************************************************************************/ package org.onap.dmaap.mr.client.impl; -import static org.junit.Assert.assertEquals; +import org.json.JSONObject; +import org.junit.Assert; +import org.junit.Test; +import org.onap.dmaap.mr.client.MRClientFactory; +import org.onap.dmaap.mr.client.MRPublisher.Message; +import org.onap.dmaap.mr.client.ProtocolType; +import org.onap.dmaap.mr.client.response.MRPublisherResponse; import java.io.File; -import java.io.FileNotFoundException; import java.io.FileOutputStream; -import java.io.IOException; import java.util.List; import java.util.Properties; import java.util.concurrent.TimeUnit; -import org.json.JSONObject; -import org.junit.Assert; -import org.junit.Before; -import org.junit.Test; - -import org.onap.dmaap.mr.client.MRClientFactory; -import org.onap.dmaap.mr.client.MRPublisher.message; -import org.onap.dmaap.mr.client.response.MRPublisherResponse; -import org.onap.dmaap.mr.test.clients.ProtocolTypeConstants; +import static org.junit.Assert.assertEquals; public class MRSimplerBatchPublisherTest { - File outFile; + File outFile; + + public void setUp(String contentType) throws Exception { + Properties properties = new Properties(); + properties.load( + MRSimplerBatchPublisherTest.class.getClassLoader().getResourceAsStream("dme2/producer.properties")); + + String routeFilePath = "dme2/preferredRoute.txt"; + + File file = new File(MRSimplerBatchPublisherTest.class.getClassLoader().getResource(routeFilePath).getFile()); + properties.put("DME2preferredRouterFilePath", + MRSimplerBatchPublisherTest.class.getClassLoader().getResource(routeFilePath).getFile()); + if (contentType != null) { + properties.put("contenttype", contentType); + } + outFile = new File(file.getParent() + "/producer_tmp.properties"); + properties.store(new FileOutputStream(outFile), ""); + } + + @Test + public void testSend() throws Exception { + + setUp(null); + + final MRSimplerBatchPublisher pub = (MRSimplerBatchPublisher) MRClientFactory + .createBatchingPublisher(outFile.getPath()); + + // publish some messages + final JSONObject msg1 = new JSONObject(); + pub.send("MyPartitionKey", msg1.toString()); + + final List stuck = pub.close(1, TimeUnit.SECONDS); + Assert.assertEquals(1, stuck.size()); + + } + + @Test + public void testSendBatchWithResponse() throws Exception { + + setUp(null); + + final MRSimplerBatchPublisher pub = (MRSimplerBatchPublisher) MRClientFactory + .createBatchingPublisher(outFile.getPath(), true); + + // publish some messages + final JSONObject msg1 = new JSONObject(); + pub.send("MyPartitionKey", msg1.toString()); + MRPublisherResponse pubResponse = new MRPublisherResponse(); + pub.setPubResponse(pubResponse); + + MRPublisherResponse mrPublisherResponse = pub.sendBatchWithResponse(); + Assert.assertEquals(1, mrPublisherResponse.getPendingMsgs()); + + } + + @Test + public void testSendBatchWithResponseConText() throws Exception { + + setUp("text/plain"); + + final MRSimplerBatchPublisher pub = (MRSimplerBatchPublisher) MRClientFactory + .createBatchingPublisher(outFile.getPath()); + + // publish some messages + final JSONObject msg1 = new JSONObject(); + pub.send("MyPartitionKey", msg1.toString()); + + final List stuck = pub.close(1, TimeUnit.SECONDS); + Assert.assertEquals(1, stuck.size()); + + } + + @Test + public void testSendBatchWithResponseContCambria() throws Exception { - public void setUp(String contentType) throws Exception { - Properties properties = new Properties(); - properties.load( - MRSimplerBatchPublisherTest.class.getClassLoader().getResourceAsStream("dme2/producer.properties")); + setUp("application/cambria-zip"); - String routeFilePath = "dme2/preferredRoute.txt"; + final MRSimplerBatchPublisher pub = (MRSimplerBatchPublisher) MRClientFactory + .createBatchingPublisher(outFile.getPath()); - File file = new File(MRSimplerBatchPublisherTest.class.getClassLoader().getResource(routeFilePath).getFile()); - properties.put("DME2preferredRouterFilePath", - MRSimplerBatchPublisherTest.class.getClassLoader().getResource(routeFilePath).getFile()); - if (contentType != null) { - properties.put("contenttype", contentType); - } - outFile = new File(file.getParent() + "/producer_tmp.properties"); - properties.store(new FileOutputStream(outFile), ""); - } + // publish some messages + final JSONObject msg1 = new JSONObject(); + pub.send("MyPartitionKey", msg1.toString()); - @Test - public void testSend() throws Exception { + final List stuck = pub.close(1, TimeUnit.SECONDS); + Assert.assertEquals(1, stuck.size()); - setUp(null); + } - final MRSimplerBatchPublisher pub = (MRSimplerBatchPublisher) MRClientFactory - .createBatchingPublisher(outFile.getPath()); + @Test + public void testSendBatchWithResponseProtKey() throws Exception { - // publish some messages - final JSONObject msg1 = new JSONObject(); - pub.send("MyPartitionKey", msg1.toString()); + setUp(null); - final List stuck = pub.close(1, TimeUnit.SECONDS); - Assert.assertEquals(1, stuck.size()); + final MRSimplerBatchPublisher pub = (MRSimplerBatchPublisher) MRClientFactory + .createBatchingPublisher(outFile.getPath()); + pub.setProtocolFlag(ProtocolType.AUTH_KEY.getValue()); + // publish some messages + final JSONObject msg1 = new JSONObject(); + pub.send("MyPartitionKey", msg1.toString()); - } + final List stuck = pub.close(1, TimeUnit.SECONDS); + Assert.assertEquals(1, stuck.size()); - @Test - public void testSendBatchWithResponse() throws Exception { + } - setUp(null); + @Test + public void testSendBatchWithResponseProtAaf() throws Exception { - final MRSimplerBatchPublisher pub = (MRSimplerBatchPublisher) MRClientFactory - .createBatchingPublisher(outFile.getPath(), true); + setUp(null); - // publish some messages - final JSONObject msg1 = new JSONObject(); - pub.send("MyPartitionKey", msg1.toString()); - MRPublisherResponse pubResponse = new MRPublisherResponse(); - pub.setPubResponse(pubResponse); + final MRSimplerBatchPublisher pub = (MRSimplerBatchPublisher) MRClientFactory + .createBatchingPublisher(outFile.getPath()); + pub.setProtocolFlag(ProtocolType.AAF_AUTH.getValue()); + // publish some messages + final JSONObject msg1 = new JSONObject(); + pub.send("MyPartitionKey", msg1.toString()); - MRPublisherResponse mrPublisherResponse = pub.sendBatchWithResponse(); - Assert.assertEquals(1, mrPublisherResponse.getPendingMsgs()); + final List stuck = pub.close(1, TimeUnit.SECONDS); + Assert.assertEquals(1, stuck.size()); - } + } - @Test - public void testSendBatchWithResponseConText() throws Exception { + @Test + public void testSendBatchWithResponseProtNoAuth() throws Exception { - setUp("text/plain"); + setUp(null); - final MRSimplerBatchPublisher pub = (MRSimplerBatchPublisher) MRClientFactory - .createBatchingPublisher(outFile.getPath()); + final MRSimplerBatchPublisher pub = (MRSimplerBatchPublisher) MRClientFactory + .createBatchingPublisher(outFile.getPath()); + pub.setProtocolFlag(ProtocolType.HTTPNOAUTH.getValue()); + // publish some messages + final JSONObject msg1 = new JSONObject(); + pub.send("MyPartitionKey", msg1.toString()); - // publish some messages - final JSONObject msg1 = new JSONObject(); - pub.send("MyPartitionKey", msg1.toString()); + final List stuck = pub.close(1, TimeUnit.SECONDS); + Assert.assertEquals(1, stuck.size()); - final List stuck = pub.close(1, TimeUnit.SECONDS); - Assert.assertEquals(1, stuck.size()); + } - } + @Test + public void testSendBatchWithResponsecontypeText() throws Exception { - @Test - public void testSendBatchWithResponseContCambria() throws Exception { + setUp("text/plain"); - setUp("application/cambria-zip"); + final MRSimplerBatchPublisher pub = (MRSimplerBatchPublisher) MRClientFactory + .createBatchingPublisher(outFile.getPath(), true); - final MRSimplerBatchPublisher pub = (MRSimplerBatchPublisher) MRClientFactory - .createBatchingPublisher(outFile.getPath()); + // publish some messages + final JSONObject msg1 = new JSONObject(); + pub.send("MyPartitionKey", "payload"); + MRPublisherResponse pubResponse = new MRPublisherResponse(); + pub.setPubResponse(pubResponse); - // publish some messages - final JSONObject msg1 = new JSONObject(); - pub.send("MyPartitionKey", msg1.toString()); + MRPublisherResponse mrPublisherResponse = pub.sendBatchWithResponse(); + Assert.assertEquals(1, mrPublisherResponse.getPendingMsgs()); - final List stuck = pub.close(1, TimeUnit.SECONDS); - Assert.assertEquals(1, stuck.size()); + } - } + @Test + public void testSendBatchWithResponsecontypeCambria() throws Exception { - @Test - public void testSendBatchWithResponseProtKey() throws Exception { + setUp("application/cambria-zip"); - setUp(null); + final MRSimplerBatchPublisher pub = (MRSimplerBatchPublisher) MRClientFactory + .createBatchingPublisher(outFile.getPath(), true); - final MRSimplerBatchPublisher pub = (MRSimplerBatchPublisher) MRClientFactory - .createBatchingPublisher(outFile.getPath()); - pub.setProtocolFlag(ProtocolTypeConstants.AUTH_KEY.getValue()); - // publish some messages - final JSONObject msg1 = new JSONObject(); - pub.send("MyPartitionKey", msg1.toString()); + // publish some messages + final JSONObject msg1 = new JSONObject(); + pub.send("MyPartitionKey", "payload"); + MRPublisherResponse pubResponse = new MRPublisherResponse(); + pub.setPubResponse(pubResponse); - final List stuck = pub.close(1, TimeUnit.SECONDS); - Assert.assertEquals(1, stuck.size()); + MRPublisherResponse mrPublisherResponse = pub.sendBatchWithResponse(); + Assert.assertEquals(1, mrPublisherResponse.getPendingMsgs()); - } + } - @Test - public void testSendBatchWithResponseProtAaf() throws Exception { + @Test + public void testSendBatchWithResponsePrAuthKey() throws Exception { - setUp(null); + setUp(null); - final MRSimplerBatchPublisher pub = (MRSimplerBatchPublisher) MRClientFactory - .createBatchingPublisher(outFile.getPath()); - pub.setProtocolFlag(ProtocolTypeConstants.AAF_AUTH.getValue()); - // publish some messages - final JSONObject msg1 = new JSONObject(); - pub.send("MyPartitionKey", msg1.toString()); + final MRSimplerBatchPublisher pub = (MRSimplerBatchPublisher) MRClientFactory + .createBatchingPublisher(outFile.getPath(), true); + pub.setProtocolFlag(ProtocolType.AUTH_KEY.getValue()); - final List stuck = pub.close(1, TimeUnit.SECONDS); - Assert.assertEquals(1, stuck.size()); + // publish some messages + final JSONObject msg1 = new JSONObject(); + pub.send("MyPartitionKey", msg1.toString()); + MRPublisherResponse pubResponse = new MRPublisherResponse(); + pub.setPubResponse(pubResponse); - } + MRPublisherResponse mrPublisherResponse = pub.sendBatchWithResponse(); + Assert.assertEquals(1, mrPublisherResponse.getPendingMsgs()); - @Test - public void testSendBatchWithResponseProtNoAuth() throws Exception { + } - setUp(null); + @Test + public void testSendBatchWithResponsePrAaf() throws Exception { - final MRSimplerBatchPublisher pub = (MRSimplerBatchPublisher) MRClientFactory - .createBatchingPublisher(outFile.getPath()); - pub.setProtocolFlag(ProtocolTypeConstants.HTTPNOAUTH.getValue()); - // publish some messages - final JSONObject msg1 = new JSONObject(); - pub.send("MyPartitionKey", msg1.toString()); + setUp(null); - final List stuck = pub.close(1, TimeUnit.SECONDS); - Assert.assertEquals(1, stuck.size()); + final MRSimplerBatchPublisher pub = (MRSimplerBatchPublisher) MRClientFactory + .createBatchingPublisher(outFile.getPath(), true); + pub.setProtocolFlag(ProtocolType.AAF_AUTH.getValue()); - } + // publish some messages + final JSONObject msg1 = new JSONObject(); + pub.send("MyPartitionKey", msg1.toString()); + MRPublisherResponse pubResponse = new MRPublisherResponse(); + pub.setPubResponse(pubResponse); - @Test - public void testSendBatchWithResponsecontypeText() throws Exception { + MRPublisherResponse mrPublisherResponse = pub.sendBatchWithResponse(); + Assert.assertEquals(1, mrPublisherResponse.getPendingMsgs()); - setUp("text/plain"); + } - final MRSimplerBatchPublisher pub = (MRSimplerBatchPublisher) MRClientFactory - .createBatchingPublisher(outFile.getPath(), true); + @Test + public void testSendBatchWithResponsePrNoauth() throws Exception { - // publish some messages - final JSONObject msg1 = new JSONObject(); - pub.send("MyPartitionKey", "payload"); - MRPublisherResponse pubResponse = new MRPublisherResponse(); - pub.setPubResponse(pubResponse); + setUp(null); - MRPublisherResponse mrPublisherResponse = pub.sendBatchWithResponse(); - Assert.assertEquals(1, mrPublisherResponse.getPendingMsgs()); + final MRSimplerBatchPublisher pub = (MRSimplerBatchPublisher) MRClientFactory + .createBatchingPublisher(outFile.getPath(), true); + pub.setProtocolFlag(ProtocolType.HTTPNOAUTH.getValue()); - } + // publish some messages + final JSONObject msg1 = new JSONObject(); + pub.send("MyPartitionKey", msg1.toString()); + MRPublisherResponse pubResponse = new MRPublisherResponse(); + pub.setPubResponse(pubResponse); - @Test - public void testSendBatchWithResponsecontypeCambria() throws Exception { + MRPublisherResponse mrPublisherResponse = pub.sendBatchWithResponse(); + Assert.assertEquals(1, mrPublisherResponse.getPendingMsgs()); - setUp("application/cambria-zip"); + } - final MRSimplerBatchPublisher pub = (MRSimplerBatchPublisher) MRClientFactory - .createBatchingPublisher(outFile.getPath(), true); + @Test + public void createPublisherResponse() throws Exception { + setUp(null); + MRSimplerBatchPublisher pub = (MRSimplerBatchPublisher) MRClientFactory + .createBatchingPublisher(outFile.getPath(), true); - // publish some messages - final JSONObject msg1 = new JSONObject(); - pub.send("MyPartitionKey", "payload"); - MRPublisherResponse pubResponse = new MRPublisherResponse(); - pub.setPubResponse(pubResponse); + MRPublisherResponse response = pub.createMRPublisherResponse("{\"message\": \"published the message\", \"status\": \"200\"}", new MRPublisherResponse()); + assertEquals("200", response.getResponseCode()); - MRPublisherResponse mrPublisherResponse = pub.sendBatchWithResponse(); - Assert.assertEquals(1, mrPublisherResponse.getPendingMsgs()); + } - } + @Test + public void createPublisherResponseSucc() throws Exception { + setUp(null); + MRSimplerBatchPublisher pub = (MRSimplerBatchPublisher) MRClientFactory + .createBatchingPublisher(outFile.getPath(), true); - @Test - public void testSendBatchWithResponsePrAuthKey() throws Exception { + MRPublisherResponse response = pub.createMRPublisherResponse("{\"fakemessage\": \"published the message\", \"fakestatus\": \"200\"}", new MRPublisherResponse()); + assertEquals("200", response.getResponseCode()); - setUp(null); + } - final MRSimplerBatchPublisher pub = (MRSimplerBatchPublisher) MRClientFactory - .createBatchingPublisher(outFile.getPath(), true); - pub.setProtocolFlag(ProtocolTypeConstants.AUTH_KEY.getValue()); + @Test + public void createPublisherResponseError() throws Exception { + setUp(null); + MRSimplerBatchPublisher pub = (MRSimplerBatchPublisher) MRClientFactory + .createBatchingPublisher(outFile.getPath(), true); - // publish some messages - final JSONObject msg1 = new JSONObject(); - pub.send("MyPartitionKey", msg1.toString()); - MRPublisherResponse pubResponse = new MRPublisherResponse(); - pub.setPubResponse(pubResponse); - - MRPublisherResponse mrPublisherResponse = pub.sendBatchWithResponse(); - Assert.assertEquals(1, mrPublisherResponse.getPendingMsgs()); - - } - - @Test - public void testSendBatchWithResponsePrAaf() throws Exception { + MRPublisherResponse response = pub.createMRPublisherResponse("", new MRPublisherResponse()); + assertEquals("400", response.getResponseCode()); - setUp(null); - - final MRSimplerBatchPublisher pub = (MRSimplerBatchPublisher) MRClientFactory - .createBatchingPublisher(outFile.getPath(), true); - pub.setProtocolFlag(ProtocolTypeConstants.AAF_AUTH.getValue()); - - // publish some messages - final JSONObject msg1 = new JSONObject(); - pub.send("MyPartitionKey", msg1.toString()); - MRPublisherResponse pubResponse = new MRPublisherResponse(); - pub.setPubResponse(pubResponse); - - MRPublisherResponse mrPublisherResponse = pub.sendBatchWithResponse(); - Assert.assertEquals(1, mrPublisherResponse.getPendingMsgs()); - - } - - @Test - public void testSendBatchWithResponsePrNoauth() throws Exception { - - setUp(null); - - final MRSimplerBatchPublisher pub = (MRSimplerBatchPublisher) MRClientFactory - .createBatchingPublisher(outFile.getPath(), true); - pub.setProtocolFlag(ProtocolTypeConstants.HTTPNOAUTH.getValue()); - - // publish some messages - final JSONObject msg1 = new JSONObject(); - pub.send("MyPartitionKey", msg1.toString()); - MRPublisherResponse pubResponse = new MRPublisherResponse(); - pub.setPubResponse(pubResponse); - - MRPublisherResponse mrPublisherResponse = pub.sendBatchWithResponse(); - Assert.assertEquals(1, mrPublisherResponse.getPendingMsgs()); - - } - - @Test - public void createPublisherResponse() throws Exception{ - setUp(null); - MRSimplerBatchPublisher pub = (MRSimplerBatchPublisher) MRClientFactory - .createBatchingPublisher(outFile.getPath(), true); - - MRPublisherResponse response=pub.createMRPublisherResponse("{\"message\": \"published the message\", \"status\": \"200\"}", new MRPublisherResponse()); - assertEquals("200", response.getResponseCode()); - - } - - @Test - public void createPublisherResponseSucc() throws Exception{ - setUp(null); - MRSimplerBatchPublisher pub = (MRSimplerBatchPublisher) MRClientFactory - .createBatchingPublisher(outFile.getPath(), true); - - MRPublisherResponse response=pub.createMRPublisherResponse("{\"fakemessage\": \"published the message\", \"fakestatus\": \"200\"}", new MRPublisherResponse()); - assertEquals("200", response.getResponseCode()); - - } - - @Test - public void createPublisherResponseError() throws Exception{ - setUp(null); - MRSimplerBatchPublisher pub = (MRSimplerBatchPublisher) MRClientFactory - .createBatchingPublisher(outFile.getPath(), true); - - MRPublisherResponse response=pub.createMRPublisherResponse("", new MRPublisherResponse()); - assertEquals("400", response.getResponseCode()); - - } + } } diff --git a/src/test/java/org/onap/dmaap/mr/client/response/JUnitTestSuite.java b/src/test/java/org/onap/dmaap/mr/client/response/JUnitTestSuite.java index 362da00..0302edd 100644 --- a/src/test/java/org/onap/dmaap/mr/client/response/JUnitTestSuite.java +++ b/src/test/java/org/onap/dmaap/mr/client/response/JUnitTestSuite.java @@ -4,12 +4,14 @@ * ================================================================================ * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. * ================================================================================ + * Modifications Copyright © 2021 Orange. + * ================================================================================ * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at - * + * * http://www.apache.org/licenses/LICENSE-2.0 - * + * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. @@ -21,7 +23,6 @@ package org.onap.dmaap.mr.client.response; import junit.framework.TestSuite; - import org.junit.runner.RunWith; import org.junit.runners.Suite; import org.junit.runners.Suite.SuiteClasses; @@ -29,17 +30,17 @@ import org.slf4j.Logger; import org.slf4j.LoggerFactory; @RunWith(Suite.class) -@SuiteClasses({ MRConsumerResponseTest.class, MRPublisherResponseTest.class,}) +@SuiteClasses({MRConsumerResponseTest.class, MRPublisherResponseTest.class,}) public class JUnitTestSuite { - private static final Logger LOGGER = LoggerFactory.getLogger(JUnitTestSuite.class); + private static final Logger logger = LoggerFactory.getLogger(JUnitTestSuite.class); + + public static void main(String[] args) { + logger.info("Running the test suite"); - public static void main(String[] args) { - LOGGER.info("Running the test suite"); - - TestSuite tstSuite = new TestSuite(); - LOGGER.info("Total Test Counts " + tstSuite.countTestCases()); - } + TestSuite tstSuite = new TestSuite(); + logger.info("Total Test Counts " + tstSuite.countTestCases()); + } } diff --git a/src/test/java/org/onap/dmaap/mr/client/response/MRConsumerResponseTest.java b/src/test/java/org/onap/dmaap/mr/client/response/MRConsumerResponseTest.java index 0676fd7..2a89dae 100644 --- a/src/test/java/org/onap/dmaap/mr/client/response/MRConsumerResponseTest.java +++ b/src/test/java/org/onap/dmaap/mr/client/response/MRConsumerResponseTest.java @@ -4,12 +4,14 @@ * ================================================================================ * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. * ================================================================================ + * Modifications Copyright © 2021 Orange. + * ================================================================================ * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at - * + * * http://www.apache.org/licenses/LICENSE-2.0 - * + * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. @@ -20,70 +22,71 @@ package org.onap.dmaap.mr.client.response; -import static org.junit.Assert.assertTrue; import org.junit.After; import org.junit.Before; import org.junit.Test; +import static org.junit.Assert.assertTrue; + public class MRConsumerResponseTest { - private MRConsumerResponse test = null; + private MRConsumerResponse test = null; - @Before - public void setUp() throws Exception { - test = new MRConsumerResponse(); + @Before + public void setUp() throws Exception { + test = new MRConsumerResponse(); - } + } - @After - public void tearDown() throws Exception { + @After + public void tearDown() throws Exception { - } + } - @Test - public void testGetResponseCode() { + @Test + public void testGetResponseCode() { - test.getResponseCode(); - assertTrue(true); + test.getResponseCode(); + assertTrue(true); - } + } - @Test - public void testSetResponseCode() { + @Test + public void testSetResponseCode() { - test.setResponseCode("200"); - assertTrue(true); + test.setResponseCode("200"); + assertTrue(true); - } + } - @Test - public void testGetResponseMessage() { + @Test + public void testGetResponseMessage() { - test.getResponseMessage(); - assertTrue(true); + test.getResponseMessage(); + assertTrue(true); - } + } - @Test - public void testSetResponseMessage() { + @Test + public void testSetResponseMessage() { - test.setResponseMessage("responseMessage"); - assertTrue(true); + test.setResponseMessage("responseMessage"); + assertTrue(true); - } + } - @Test - public void testGetActualMessages() { + @Test + public void testGetActualMessages() { - test.getActualMessages(); - assertTrue(true); + test.getActualMessages(); + assertTrue(true); - } + } - @Test - public void testSetActualMessages() { + @Test + public void testSetActualMessages() { - test.setActualMessages(null); - assertTrue(true); + test.setActualMessages(null); + assertTrue(true); - } + } } diff --git a/src/test/java/org/onap/dmaap/mr/client/response/MRPublisherResponseTest.java b/src/test/java/org/onap/dmaap/mr/client/response/MRPublisherResponseTest.java index 19c829a..07b4ba3 100644 --- a/src/test/java/org/onap/dmaap/mr/client/response/MRPublisherResponseTest.java +++ b/src/test/java/org/onap/dmaap/mr/client/response/MRPublisherResponseTest.java @@ -4,12 +4,14 @@ * ================================================================================ * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. * ================================================================================ + * Modifications Copyright © 2021 Orange. + * ================================================================================ * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at - * + * * http://www.apache.org/licenses/LICENSE-2.0 - * + * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. @@ -20,80 +22,81 @@ package org.onap.dmaap.mr.client.response; -import static org.junit.Assert.assertTrue; import org.junit.After; import org.junit.Before; import org.junit.Test; +import static org.junit.Assert.assertTrue; + public class MRPublisherResponseTest { - private MRPublisherResponse response = null; + private MRPublisherResponse response = null; + + @Before + public void setUp() throws Exception { + response = new MRPublisherResponse(); + + } + + @After + public void tearDown() throws Exception { + + } - @Before - public void setUp() throws Exception { - response = new MRPublisherResponse(); + @Test + public void testGetResponseCode() { - } + response.getResponseCode(); + assertTrue(true); - @After - public void tearDown() throws Exception { + } - } + @Test + public void testSetResponseCode() { - @Test - public void testGetResponseCode() { + response.setResponseCode("200"); + assertTrue(true); - response.getResponseCode(); - assertTrue(true); + } - } - - @Test - public void testSetResponseCode() { + @Test + public void testGetResponseMessage() { - response.setResponseCode("200"); - assertTrue(true); + response.getResponseMessage(); + assertTrue(true); - } - - @Test - public void testGetResponseMessage() { + } - response.getResponseMessage(); - assertTrue(true); + @Test + public void testSetResponseMessage() { - } + response.setResponseMessage("responseMessage"); + assertTrue(true); - @Test - public void testSetResponseMessage() { + } - response.setResponseMessage("responseMessage"); - assertTrue(true); + @Test + public void testGetPendingMsgs() { - } + response.getPendingMsgs(); + assertTrue(true); - @Test - public void testGetPendingMsgs() { + } - response.getPendingMsgs(); - assertTrue(true); + @Test + public void testSetPendingMsgs() { - } + response.setPendingMsgs(5); + assertTrue(true); - @Test - public void testSetPendingMsgs() { + } - response.setPendingMsgs(5); - assertTrue(true); + @Test + public void testToString() { - } - - @Test - public void testToString() { + response.toString(); + assertTrue(true); - response.toString(); - assertTrue(true); + } - } - } diff --git a/src/test/java/org/onap/dmaap/mr/client/response/TestRunner.java b/src/test/java/org/onap/dmaap/mr/client/response/TestRunner.java index a5f43d4..c301551 100644 --- a/src/test/java/org/onap/dmaap/mr/client/response/TestRunner.java +++ b/src/test/java/org/onap/dmaap/mr/client/response/TestRunner.java @@ -4,12 +4,14 @@ * ================================================================================ * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. * ================================================================================ + * Modifications Copyright © 2021 Orange. + * ================================================================================ * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at - * + * * http://www.apache.org/licenses/LICENSE-2.0 - * + * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. @@ -27,16 +29,16 @@ import org.slf4j.Logger; import org.slf4j.LoggerFactory; public class TestRunner { - private static final Logger LOGGER = LoggerFactory.getLogger(TestRunner.class); + private static final Logger logger = LoggerFactory.getLogger(TestRunner.class); + + public static void main(String[] args) { + // TODO Auto-generated method stub + Result result = JUnitCore.runClasses(JUnitTestSuite.class); + for (Failure failure : result.getFailures()) { + logger.info(failure.toString()); - public static void main(String[] args) { - // TODO Auto-generated method stub - Result result = JUnitCore.runClasses(JUnitTestSuite.class); - for (Failure failure : result.getFailures()) { - LOGGER.info(failure.toString()); - - } - LOGGER.info(String.valueOf(result.wasSuccessful())); - } + } + logger.info(String.valueOf(result.wasSuccessful())); + } } diff --git a/src/test/java/org/onap/dmaap/mr/dme/client/DefaultLoggingFailoverFaultHandlerTest.java b/src/test/java/org/onap/dmaap/mr/dme/client/DefaultLoggingFailoverFaultHandlerTest.java deleted file mode 100644 index 5fa72dd..0000000 --- a/src/test/java/org/onap/dmaap/mr/dme/client/DefaultLoggingFailoverFaultHandlerTest.java +++ /dev/null @@ -1,59 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * ONAP Policy Engine - * ================================================================================ - * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. - * ================================================================================ - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * ============LICENSE_END========================================================= - */ - -package org.onap.dmaap.mr.dme.client; - -import org.junit.After; -import org.junit.Before; -import org.junit.Test; - -import static org.junit.Assert.assertTrue; - -public class DefaultLoggingFailoverFaultHandlerTest { - private DefaultLoggingFailoverFaultHandler handler = null; - - @Before - public void setUp() throws Exception { - handler = new DefaultLoggingFailoverFaultHandler(); - - } - - @After - public void tearDown() throws Exception { - - } - - @Test - public void testHandleEndpointFailover() { - -// handler.handleEndpointFailover(null); - assertTrue(true); - - } - /* - @Test - public void testHandleRouteOfferFailover() { - - handler.handleRouteOfferFailover(null); - assertTrue(true); - - } -*/ -} diff --git a/src/test/java/org/onap/dmaap/mr/dme/client/HeaderReplyHandlerTest.java b/src/test/java/org/onap/dmaap/mr/dme/client/HeaderReplyHandlerTest.java index c3a0bb1..0cc824d 100644 --- a/src/test/java/org/onap/dmaap/mr/dme/client/HeaderReplyHandlerTest.java +++ b/src/test/java/org/onap/dmaap/mr/dme/client/HeaderReplyHandlerTest.java @@ -4,12 +4,14 @@ * ================================================================================ * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. * ================================================================================ + * Modifications Copyright © 2021 Orange. + * ================================================================================ * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at - * + * * http://www.apache.org/licenses/LICENSE-2.0 - * + * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. @@ -20,60 +22,58 @@ package org.onap.dmaap.mr.dme.client; -import static org.junit.Assert.assertTrue; - -import java.util.HashMap; -import java.util.Map; - +import com.att.aft.dme2.api.util.DME2ExchangeResponseContext; import org.junit.After; import org.junit.Before; import org.junit.Test; -import com.att.aft.dme2.api.util.DME2ExchangeResponseContext; +import java.util.HashMap; +import java.util.Map; + +import static org.junit.Assert.assertTrue; public class HeaderReplyHandlerTest { - private HeaderReplyHandler handler = null; + private HeaderReplyHandler handler = null; + + @Before + public void setUp() throws Exception { + handler = new HeaderReplyHandler(); + + } + + @After + public void tearDown() throws Exception { + + } - @Before - public void setUp() throws Exception { - handler = new HeaderReplyHandler(); + @Test + public void testHandleFault() { - } + handler.handleFault(null); + assertTrue(true); - @After - public void tearDown() throws Exception { + } - } + @Test + public void testHandleEndpointFault() { - @Test - public void testHandleFault() { + handler.handleEndpointFault(null); + assertTrue(true); - handler.handleFault(null); - assertTrue(true); + } - } - - @Test - public void testHandleEndpointFault() { + @Test + public void testHandleReply() { - handler.handleEndpointFault(null); - assertTrue(true); + Map responseHeaders = new HashMap(); + responseHeaders.put("transactionId", "1234"); - } - - @Test - public void testHandleReply() { - - Map responseHeaders = new HashMap(); - responseHeaders.put("transactionId", "1234"); + DME2ExchangeResponseContext responseData = new DME2ExchangeResponseContext("service", + 200, new HashMap(), responseHeaders, "routeOffer", "1.0.0", "http://"); + handler.handleReply(responseData); + assertTrue(true); - DME2ExchangeResponseContext responseData = new DME2ExchangeResponseContext ("service", - 200, new HashMap (), responseHeaders, "routeOffer", "1.0.0", "http://"); - handler.handleReply(responseData); - assertTrue(true); + } - } - - } diff --git a/src/test/java/org/onap/dmaap/mr/dme/client/JUnitTestSuite.java b/src/test/java/org/onap/dmaap/mr/dme/client/JUnitTestSuite.java index e1f8431..cc13578 100644 --- a/src/test/java/org/onap/dmaap/mr/dme/client/JUnitTestSuite.java +++ b/src/test/java/org/onap/dmaap/mr/dme/client/JUnitTestSuite.java @@ -4,12 +4,14 @@ * ================================================================================ * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. * ================================================================================ + * Modifications Copyright © 2021 Orange. + * ================================================================================ * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at - * + * * http://www.apache.org/licenses/LICENSE-2.0 - * + * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. @@ -21,7 +23,6 @@ package org.onap.dmaap.mr.dme.client; import junit.framework.TestSuite; - import org.junit.runner.RunWith; import org.junit.runners.Suite; import org.junit.runners.Suite.SuiteClasses; @@ -29,18 +30,17 @@ import org.slf4j.Logger; import org.slf4j.LoggerFactory; @RunWith(Suite.class) -@SuiteClasses({ DefaultLoggingFailoverFaultHandlerTest.class, HeaderReplyHandlerTest.class,PreferredRouteReplyHandlerTest.class, - PreferredRouteRequestHandlerTest.class,SimpleExamplePublisherTest.class }) - +@SuiteClasses({HeaderReplyHandlerTest.class, PreferredRouteReplyHandlerTest.class, + PreferredRouteRequestHandlerTest.class, SimpleExamplePublisherTest.class}) public class JUnitTestSuite { - private static final Logger LOGGER = LoggerFactory.getLogger(JUnitTestSuite.class); + private static final Logger logger = LoggerFactory.getLogger(JUnitTestSuite.class); + + public static void main(String[] args) { + logger.info("Running the test suite"); - public static void main(String[] args) { - LOGGER.info("Running the test suite"); - - TestSuite tstSuite = new TestSuite(); - LOGGER.info("Total Test Counts " + tstSuite.countTestCases()); - } + TestSuite tstSuite = new TestSuite(); + logger.info("Total Test Counts " + tstSuite.countTestCases()); + } } diff --git a/src/test/java/org/onap/dmaap/mr/dme/client/PreferredRouteReplyHandlerTest.java b/src/test/java/org/onap/dmaap/mr/dme/client/PreferredRouteReplyHandlerTest.java index acfea5a..fb3b8d0 100644 --- a/src/test/java/org/onap/dmaap/mr/dme/client/PreferredRouteReplyHandlerTest.java +++ b/src/test/java/org/onap/dmaap/mr/dme/client/PreferredRouteReplyHandlerTest.java @@ -4,12 +4,14 @@ * ================================================================================ * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. * ================================================================================ + * Modifications Copyright © 2021 Orange. + * ================================================================================ * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at - * + * * http://www.apache.org/licenses/LICENSE-2.0 - * + * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. @@ -20,70 +22,64 @@ package org.onap.dmaap.mr.dme.client; -import java.util.HashMap; -import java.util.Map; - +import com.att.aft.dme2.api.util.DME2ExchangeResponseContext; import org.junit.After; import org.junit.Before; import org.junit.Test; -import com.att.aft.dme2.api.util.DME2ExchangeResponseContext; +import java.util.HashMap; +import java.util.Map; + import static org.junit.Assert.assertNotNull; public class PreferredRouteReplyHandlerTest { - private PreferredRouteReplyHandler handler = null; - - @Before - public void setUp() throws Exception { - handler = new PreferredRouteReplyHandler(); - - } - - @After - public void tearDown() throws Exception { + private PreferredRouteReplyHandler handler = null; - } + @Before + public void setUp() throws Exception { + handler = new PreferredRouteReplyHandler(); - @Test - public void testHandleReply() { - - Map responseHeaders = new HashMap (); - responseHeaders.put("transactionId", "1234"); + } - DME2ExchangeResponseContext responseData = new DME2ExchangeResponseContext ("service", - 200, new HashMap(), responseHeaders, "routeOffer", "1.0.0", "http://"); + @After + public void tearDown() throws Exception { - handler.handleReply(responseData); - assert(true); - assertNotNull(responseHeaders); + } - } -/* - @Test - public void testHandleFault() { - - handler.handleFault(null); - assertTrue(true); + @Test + public void testHandleReply() { - } - - @Test - public void testHandleEndpointFault() { + Map responseHeaders = new HashMap(); + responseHeaders.put("transactionId", "1234"); - handler.handleEndpointFault(null); - assertTrue(true); + DME2ExchangeResponseContext responseData = new DME2ExchangeResponseContext("service", + 200, new HashMap(), responseHeaders, "routeOffer", "1.0.0", "http://"); - } - - @Test - public void testRouteWriter() { + handler.handleReply(responseData); + assert (true); + assertNotNull(responseHeaders); - handler.routeWriter("routeKey", "routeValue"); - assertTrue(true); + } +/* + @Test + public void testHandleFault() { + handler.handleFault(null); + assertTrue(true); + } + + @Test + public void testHandleEndpointFault() { + handler.handleEndpointFault(null); + assertTrue(true); + } + + @Test + public void testRouteWriter() { + handler.routeWriter("routeKey", "routeValue"); + assertTrue(true); + } - } - */ - + } diff --git a/src/test/java/org/onap/dmaap/mr/dme/client/PreferredRouteRequestHandlerTest.java b/src/test/java/org/onap/dmaap/mr/dme/client/PreferredRouteRequestHandlerTest.java index 167f3ff..01e6c69 100644 --- a/src/test/java/org/onap/dmaap/mr/dme/client/PreferredRouteRequestHandlerTest.java +++ b/src/test/java/org/onap/dmaap/mr/dme/client/PreferredRouteRequestHandlerTest.java @@ -4,12 +4,14 @@ * ================================================================================ * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. * ================================================================================ + * Modifications Copyright © 2021 Orange. + * ================================================================================ * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at - * + * * http://www.apache.org/licenses/LICENSE-2.0 - * + * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. @@ -24,39 +26,43 @@ import org.junit.After; import org.junit.Before; import org.junit.Test; -public class PreferredRouteRequestHandlerTest { - private PreferredRouteRequestHandler handler = null; +import static org.junit.Assert.assertTrue; - @Before - public void setUp() throws Exception { - handler = new PreferredRouteRequestHandler(); +public class PreferredRouteRequestHandlerTest { + private PreferredRouteRequestHandler handler = null; - } + @Before + public void setUp() throws Exception { + handler = new PreferredRouteRequestHandler(); - @After - public void tearDown() throws Exception { + } - } + @After + public void tearDown() throws Exception { - @Test - public void testHandleRequest() { + } - /* handler.handleRequest(null); - assertTrue(true);*/ + @Test + public void testHandleRequest() { - } + assertTrue(true); + /* + handler.handleRequest(null); + assertTrue(true);*/ - @Test - public void testReadRoute() { + } -// try { -// handler.readRoute("routeKey"); -// } catch (NullPointerException e) { -// assertTrue(true); -// } + @Test + public void testReadRoute() { + assertTrue(true); +// try { +// handler.readRoute("routeKey"); +// } catch (NullPointerException e) { +// assertTrue(true); +// } // -// assertTrue(true); +// assertTrue(true); - } + } } diff --git a/src/test/java/org/onap/dmaap/mr/dme/client/SimpleExampleConsumer.java b/src/test/java/org/onap/dmaap/mr/dme/client/SimpleExampleConsumer.java new file mode 100644 index 0000000..ab49cb3 --- /dev/null +++ b/src/test/java/org/onap/dmaap/mr/dme/client/SimpleExampleConsumer.java @@ -0,0 +1,87 @@ +/******************************************************************************* + * ============LICENSE_START======================================================= + * org.onap.dmaap + * ================================================================================ + * Copyright © 2017 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Modifications Copyright © 2021 Orange. + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============LICENSE_END========================================================= + * + * ECOMP is a trademark and service mark of AT&T Intellectual Property. + * + *******************************************************************************/ + +package org.onap.dmaap.mr.dme.client; + +import org.onap.dmaap.mr.client.MRClientFactory; +import org.onap.dmaap.mr.client.MRConsumer; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +import javax.ws.rs.core.MultivaluedMap; +import java.util.List; +import java.util.Map; + +public class SimpleExampleConsumer { + + private static final Logger logger = LoggerFactory.getLogger(SimpleExampleConsumer.class); + + private SimpleExampleConsumer() { + } + + public static void main(String[] args) { + + long count = 0; + long nextReport = 5000; + String key; + + final long startMs = System.currentTimeMillis(); + + try { + + final MRConsumer cc = MRClientFactory.createConsumer("D:\\SG\\consumer.properties"); + while (true) { + for (String msg : cc.fetch()) { + logger.debug("Message Received: " + msg); + } + // Header for DME2 Call. + MultivaluedMap headersMap = MRClientFactory.getHTTPHeadersMap(); + for (Map.Entry> entry : headersMap.entrySet()) { + key = entry.getKey(); + logger.debug("Header Key " + key); + logger.debug("Header Value " + headersMap.get(key)); + } + // Header for HTTP Call. + + Map dme2headersMap = MRClientFactory.DME2HeadersMap; + for (Map.Entry entry : dme2headersMap.entrySet()) { + key = entry.getKey(); + logger.debug("Header Key " + key); + logger.debug("Header Value " + dme2headersMap.get(key)); + } + + if (count > nextReport) { + nextReport += 5000; + + final long endMs = System.currentTimeMillis(); + final long elapsedMs = endMs - startMs; + final double elapsedSec = elapsedMs / 1000.0; + final double eps = count / elapsedSec; + } + } + } catch (Exception x) { + logger.error("Exception in SimpleExampleConsumer", x); + } + } +} diff --git a/src/test/java/org/onap/dmaap/mr/dme/client/SimpleExamplePublisher.java b/src/test/java/org/onap/dmaap/mr/dme/client/SimpleExamplePublisher.java new file mode 100644 index 0000000..6a67774 --- /dev/null +++ b/src/test/java/org/onap/dmaap/mr/dme/client/SimpleExamplePublisher.java @@ -0,0 +1,123 @@ +/******************************************************************************* + * ============LICENSE_START======================================================= + * org.onap.dmaap + * ================================================================================ + * Copyright © 2017 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Modifications Copyright © 2021 Orange. + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============LICENSE_END========================================================= + * + * ECOMP is a trademark and service mark of AT&T Intellectual Property. + * + *******************************************************************************/ + +package org.onap.dmaap.mr.dme.client; + + +import org.json.JSONObject; +import org.onap.dmaap.mr.client.MRBatchingPublisher; +import org.onap.dmaap.mr.client.MRClientFactory; + +import javax.ws.rs.core.MultivaluedMap; +import java.io.IOException; +import java.util.Map; + +/** + * An example of how to use the Java publisher. + * + * @author author + */ +public class SimpleExamplePublisher { + static String content = null; + static String messageSize = null; + static String transport = null; + static String messageCount = null; + + public void publishMessage(String producerFilePath) throws IOException, InterruptedException { + + // create our publisher + // publish some messages + + StringBuilder sb = new StringBuilder(); + final MRBatchingPublisher pub = MRClientFactory.createBatchingPublisher(producerFilePath); + + if (content.equalsIgnoreCase("text/plain")) { + for (int i = 0; i < Integer.parseInt(messageCount); i++) { + for (int j = 0; j < Integer.parseInt(messageSize); j++) { + sb.append("T"); + } + + pub.send(sb.toString()); + } + } else if (content.equalsIgnoreCase("application/cambria")) { + for (int i = 0; i < Integer.parseInt(messageCount); i++) { + for (int j = 0; j < Integer.parseInt(messageSize); j++) { + sb.append("C"); + } + pub.send("Key", sb.toString()); + } + } else if (content.equalsIgnoreCase("application/json")) { + for (int i = 0; i < Integer.parseInt(messageCount); i++) { + + final JSONObject msg12 = new JSONObject(); + msg12.put("Name", "DMaaP Reference Client to Test jason Message"); + + pub.send(msg12.toString()); + + } + } + + // close the publisher to make sure everything's sent before exiting. + // The batching + // publisher interface allows the app to get the set of unsent messages. + // It could + // write them to disk, for example, to try to send them later. + /* final List stuck = pub.close(20, TimeUnit.SECONDS); + if (stuck.size() > 0) { + System.err.println(stuck.size() + " messages unsent"); + } else { + System.out.println("Clean exit; all messages sent."); + }*/ + + if (transport.equalsIgnoreCase("HTTP")) { + MultivaluedMap headersMap = MRClientFactory.getHTTPHeadersMap(); + for (String key : headersMap.keySet()) { + System.out.println("Header Key " + key); + System.out.println("Header Value " + headersMap.get(key)); + } + } else { + Map dme2headersMap = MRClientFactory.DME2HeadersMap; + for (String key : dme2headersMap.keySet()) { + System.out.println("Header Key " + key); + System.out.println("Header Value " + dme2headersMap.get(key)); + } + } + + } + + public static void main(String[] args) throws InterruptedException, Exception { + + String producerFilePath = args[0]; + content = args[1]; + messageSize = args[2]; + transport = args[3]; + messageCount = args[4]; + + + SimpleExamplePublisher publisher = new SimpleExamplePublisher(); + + publisher.publishMessage("D:\\SG\\producer.properties"); + } + +} diff --git a/src/test/java/org/onap/dmaap/mr/dme/client/SimpleExamplePublisherTest.java b/src/test/java/org/onap/dmaap/mr/dme/client/SimpleExamplePublisherTest.java index 477e92c..f787d88 100644 --- a/src/test/java/org/onap/dmaap/mr/dme/client/SimpleExamplePublisherTest.java +++ b/src/test/java/org/onap/dmaap/mr/dme/client/SimpleExamplePublisherTest.java @@ -4,12 +4,14 @@ * ================================================================================ * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. * ================================================================================ + * Modifications Copyright © 2021 Orange. + * ================================================================================ * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at - * + * * http://www.apache.org/licenses/LICENSE-2.0 - * + * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. @@ -20,39 +22,38 @@ package org.onap.dmaap.mr.dme.client; -import static org.junit.Assert.assertTrue; - import org.junit.After; import org.junit.Before; import org.junit.Test; +import static org.junit.Assert.assertTrue; + public class SimpleExamplePublisherTest { - private SimpleExamplePublisher pub = null; + private SimpleExamplePublisher pub = null; - @Before - public void setUp() throws Exception { - pub = new SimpleExamplePublisher(); + @Before + public void setUp() throws Exception { + pub = new SimpleExamplePublisher(); - } + } - @After - public void tearDown() throws Exception { + @After + public void tearDown() throws Exception { - } + } - @Test - public void testPublishMessage() { + @Test + public void testPublishMessage() { - try { - pub.publishMessage("/producer"); - } catch (Exception e) { - // TODO Auto-generated catch block - e.printStackTrace(); - } - assertTrue(true); + try { + pub.publishMessage("/producer"); + } catch (Exception e) { + // TODO Auto-generated catch block + e.printStackTrace(); + } + assertTrue(true); - } + } - } diff --git a/src/test/java/org/onap/dmaap/mr/dme/client/TestRunner.java b/src/test/java/org/onap/dmaap/mr/dme/client/TestRunner.java index 59fc7f0..8b31b77 100644 --- a/src/test/java/org/onap/dmaap/mr/dme/client/TestRunner.java +++ b/src/test/java/org/onap/dmaap/mr/dme/client/TestRunner.java @@ -4,12 +4,14 @@ * ================================================================================ * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. * ================================================================================ + * Modifications Copyright © 2021 Orange. + * ================================================================================ * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at - * + * * http://www.apache.org/licenses/LICENSE-2.0 - * + * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. @@ -27,16 +29,16 @@ import org.slf4j.Logger; import org.slf4j.LoggerFactory; public class TestRunner { - private static final Logger LOGGER = LoggerFactory.getLogger(TestRunner.class); + private static final Logger logger = LoggerFactory.getLogger(TestRunner.class); + + public static void main(String[] args) { + // TODO Auto-generated method stub + Result result = JUnitCore.runClasses(JUnitTestSuite.class); + for (Failure failure : result.getFailures()) { + logger.info(failure.toString()); - public static void main(String[] args) { - // TODO Auto-generated method stub - Result result = JUnitCore.runClasses(JUnitTestSuite.class); - for (Failure failure : result.getFailures()) { - LOGGER.info(failure.toString()); - - } - LOGGER.info(String.valueOf(result.wasSuccessful())); - } + } + logger.info(String.valueOf(result.wasSuccessful())); + } } diff --git a/src/test/java/org/onap/dmaap/mr/test/clients/ConsolePublisher.java b/src/test/java/org/onap/dmaap/mr/test/clients/ConsolePublisher.java new file mode 100644 index 0000000..503af01 --- /dev/null +++ b/src/test/java/org/onap/dmaap/mr/test/clients/ConsolePublisher.java @@ -0,0 +1,90 @@ +/******************************************************************************* + * ============LICENSE_START======================================================= + * org.onap.dmaap + * ================================================================================ + * Copyright © 2017 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Modifications Copyright © 2021 Orange. + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============LICENSE_END========================================================= + * + * ECOMP is a trademark and service mark of AT&T Intellectual Property. + * + *******************************************************************************/ + +package org.onap.dmaap.mr.test.clients; + +import org.onap.dmaap.mr.client.MRBatchingPublisher; +import org.onap.dmaap.mr.client.MRClientFactory; +import org.onap.dmaap.mr.client.MRPublisher.Message; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +import java.io.BufferedReader; +import java.io.IOException; +import java.io.InputStreamReader; +import java.util.List; +import java.util.UUID; +import java.util.concurrent.TimeUnit; + +/** + * A simple publisher that reads from std in, sending each line as a message. + * + * @author author + */ +public class ConsolePublisher { + + private static final Logger logger = LoggerFactory.getLogger(ConsolePublisher.class); + + private ConsolePublisher() { + } + + public static void main(String[] args) throws IOException //throws IOException, InterruptedException + { + // read the hosts(s) from the command line + final String hosts = args.length > 0 ? args[0] : "mr1.onap.com,mr2.onap.com,mr3.onap.com"; + + // read the topic name from the command line + final String topic = args.length > 1 ? args[1] : "TEST-TOPIC"; + + // read the topic name from the command line + final String partition = args.length > 2 ? args[2] : UUID.randomUUID().toString(); + + // set up some batch limits and the compression flag + final int maxBatchSize = 100; + final long maxAgeMs = 250; + final boolean withGzip = false; + + // create our publisher + final MRBatchingPublisher pub = MRClientFactory.createBatchingPublisher(hosts, topic, maxBatchSize, maxAgeMs, withGzip); + + final BufferedReader cin = new BufferedReader(new InputStreamReader(System.in)); + try { + String line = null; + while ((line = cin.readLine()) != null) { + pub.send(partition, line); + } + } finally { + List leftovers = null; + try { + leftovers = pub.close(10, TimeUnit.SECONDS); + } catch (InterruptedException e) { + logger.error("Send on close interrupted."); + Thread.currentThread().interrupt(); + } + for (Message m : leftovers) { + logger.error("Unsent message: " + m.fMsg); + } + } + } +} diff --git a/src/test/java/org/onap/dmaap/mr/test/clients/ConsolePublisherTest.java b/src/test/java/org/onap/dmaap/mr/test/clients/ConsolePublisherTest.java index be0574a..41039d8 100644 --- a/src/test/java/org/onap/dmaap/mr/test/clients/ConsolePublisherTest.java +++ b/src/test/java/org/onap/dmaap/mr/test/clients/ConsolePublisherTest.java @@ -4,12 +4,14 @@ * ================================================================================ * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. * ================================================================================ + * Modifications Copyright © 2021 Orange. + * ================================================================================ * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at - * + * * http://www.apache.org/licenses/LICENSE-2.0 - * + * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. @@ -20,35 +22,35 @@ package org.onap.dmaap.mr.test.clients; -import static org.junit.Assert.assertTrue; - import org.junit.After; import org.junit.Before; import org.junit.Test; +import static org.junit.Assert.assertTrue; + public class ConsolePublisherTest { - @Before - public void setUp() throws Exception { + @Before + public void setUp() throws Exception { - } + } - @After - public void tearDown() throws Exception { + @After + public void tearDown() throws Exception { - } + } - @Test - public void testMain() { + @Test + public void testMain() { - try { - ConsolePublisher.main(null); - } catch (Exception e) { - // TODO Auto-generated catch block - e.printStackTrace(); - } - assertTrue(true); + try { + ConsolePublisher.main(null); + } catch (Exception e) { + // TODO Auto-generated catch block + e.printStackTrace(); + } + assertTrue(true); - } + } } diff --git a/src/test/java/org/onap/dmaap/mr/test/clients/JUnitTestSuite.java b/src/test/java/org/onap/dmaap/mr/test/clients/JUnitTestSuite.java index a0c81a8..8152972 100644 --- a/src/test/java/org/onap/dmaap/mr/test/clients/JUnitTestSuite.java +++ b/src/test/java/org/onap/dmaap/mr/test/clients/JUnitTestSuite.java @@ -4,12 +4,14 @@ * ================================================================================ * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. * ================================================================================ + * Modifications Copyright © 2021 Orange. + * ================================================================================ * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at - * + * * http://www.apache.org/licenses/LICENSE-2.0 - * + * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. @@ -21,7 +23,6 @@ package org.onap.dmaap.mr.test.clients; import junit.framework.TestSuite; - import org.junit.runner.RunWith; import org.junit.runners.Suite; import org.junit.runners.Suite.SuiteClasses; @@ -29,19 +30,19 @@ import org.slf4j.Logger; import org.slf4j.LoggerFactory; @RunWith(Suite.class) -@SuiteClasses({ SimpleExamplePublisherTest.class, ProtocolTypeConstantsTest.class, - SampleConsumerTest.class, SamplePublisherTest.class, SimpleExampleConsumerTest.class, ConsolePublisherTest.class, - SimpleExamplePublisherWithResponseTest.class, SimpleExampleConsumerWithReturnResponseTest.class,}) +@SuiteClasses({SimpleExamplePublisherTest.class, ProtocolTypeConstantsTest.class, + SampleConsumerTest.class, SamplePublisherTest.class, SimpleExampleConsumerTest.class, ConsolePublisherTest.class, + SimpleExamplePublisherWithResponseTest.class, SimpleExampleConsumerWithReturnResponseTest.class,}) public class JUnitTestSuite { - private static final Logger LOGGER = LoggerFactory.getLogger(JUnitTestSuite.class); + private static final Logger logger = LoggerFactory.getLogger(JUnitTestSuite.class); + + public static void main(String[] args) { + logger.info("Running the test suite"); - public static void main(String[] args) { - LOGGER.info("Running the test suite"); - - TestSuite tstSuite = new TestSuite(); - LOGGER.info("Total Test Counts " + tstSuite.countTestCases()); - } + TestSuite tstSuite = new TestSuite(); + logger.info("Total Test Counts " + tstSuite.countTestCases()); + } } diff --git a/src/test/java/org/onap/dmaap/mr/test/clients/ProtocolTypeConstantsTest.java b/src/test/java/org/onap/dmaap/mr/test/clients/ProtocolTypeConstantsTest.java index 573be98..1dd8381 100644 --- a/src/test/java/org/onap/dmaap/mr/test/clients/ProtocolTypeConstantsTest.java +++ b/src/test/java/org/onap/dmaap/mr/test/clients/ProtocolTypeConstantsTest.java @@ -4,12 +4,14 @@ * ================================================================================ * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. * ================================================================================ + * Modifications Copyright © 2021 Orange. + * ================================================================================ * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at - * + * * http://www.apache.org/licenses/LICENSE-2.0 - * + * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. @@ -20,38 +22,39 @@ package org.onap.dmaap.mr.test.clients; -import static org.junit.Assert.assertTrue; - import org.junit.After; import org.junit.Before; import org.junit.Test; +import org.onap.dmaap.mr.client.ProtocolType; + +import static org.junit.Assert.assertTrue; public class ProtocolTypeConstantsTest { - private ProtocolTypeConstants constants = null; + private ProtocolType constants = null; + + @Before + public void setUp() throws Exception { + // constants = new ProtocolTypeConstants(); - @Before - public void setUp() throws Exception { - // constants = new ProtocolTypeConstants(); + } - } + @After + public void tearDown() throws Exception { - @After - public void tearDown() throws Exception { + } - } + @Test + public void testGetValue() { - @Test - public void testGetValue() { + try { + constants.getValue(); + } catch (Exception e) { + // TODO Auto-generated catch block + e.printStackTrace(); + } + assertTrue(true); - try { - constants.getValue(); - } catch (Exception e) { - // TODO Auto-generated catch block - e.printStackTrace(); - } - assertTrue(true); + } - } - } diff --git a/src/test/java/org/onap/dmaap/mr/test/clients/SampleConsumer.java b/src/test/java/org/onap/dmaap/mr/test/clients/SampleConsumer.java new file mode 100644 index 0000000..215ddda --- /dev/null +++ b/src/test/java/org/onap/dmaap/mr/test/clients/SampleConsumer.java @@ -0,0 +1,81 @@ +/******************************************************************************* + * ============LICENSE_START======================================================= + * org.onap.dmaap + * ================================================================================ + * Copyright © 2017 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Modifications Copyright © 2021 Orange. + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============LICENSE_END========================================================= + * + * ECOMP is a trademark and service mark of AT&T Intellectual Property. + * + *******************************************************************************/ +package org.onap.dmaap.mr.test.clients; + +import org.onap.dmaap.mr.client.MRClientFactory; +import org.onap.dmaap.mr.client.MRConsumer; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +import java.util.LinkedList; + +public class SampleConsumer { + private SampleConsumer() { + } + + public static void main(String[] args) { + final Logger logger = LoggerFactory.getLogger(SampleConsumer.class); + + + logger.info("Sample Consumer Class executing"); + final String topic = "org.onap.dmaap.mr.testingTopic"; + final String url = (args.length > 1 ? args[1] : "localhost:8181"); + final String group = (args.length > 2 ? args[2] : "grp"); + + final String id = (args.length > 3 ? args[3] : "1"); + + long count = 0; + long nextReport = 5000; + + final long startMs = System.currentTimeMillis(); + + final LinkedList urlList = new LinkedList<>(); + for (String u : url.split(",")) { + urlList.add(u); + } + + final MRConsumer cc = MRClientFactory.createConsumer(urlList, topic, group, id, 10 * 1000, 1000, null, "CG0TXc2Aa3v8LfBk", "pj2rhxJWKP23pgy8ahMnjH88"); + try { + while (true) { + for (String msg : cc.fetch()) { + logger.info("" + (++count) + ": " + msg); + } + + if (count > nextReport) { + nextReport += 5000; + + final long endMs = System.currentTimeMillis(); + final long elapsedMs = endMs - startMs; + final double elapsedSec = elapsedMs / 1000.0; + final double eps = count / elapsedSec; + logger.info("Consumed " + count + " in " + elapsedSec + "; " + eps + " eps"); + } + logger.info("" + (++count) + ": consumed message"); + } + } catch (Exception x) { + logger.error(x.getClass().getName() + ": " + x.getMessage()); + throw new IllegalArgumentException(x); + } + } +} diff --git a/src/test/java/org/onap/dmaap/mr/test/clients/SampleConsumerTest.java b/src/test/java/org/onap/dmaap/mr/test/clients/SampleConsumerTest.java index 8d359f4..1c95f1d 100644 --- a/src/test/java/org/onap/dmaap/mr/test/clients/SampleConsumerTest.java +++ b/src/test/java/org/onap/dmaap/mr/test/clients/SampleConsumerTest.java @@ -4,12 +4,14 @@ * ================================================================================ * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. * ================================================================================ + * Modifications Copyright © 2021 Orange. + * ================================================================================ * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at - * + * * http://www.apache.org/licenses/LICENSE-2.0 - * + * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. @@ -20,34 +22,34 @@ package org.onap.dmaap.mr.test.clients; -import static org.junit.Assert.assertTrue; - import org.junit.After; import org.junit.Before; import org.junit.Test; +import static org.junit.Assert.assertTrue; + public class SampleConsumerTest { - @Before - public void setUp() throws Exception { + @Before + public void setUp() throws Exception { - } + } - @After - public void tearDown() throws Exception { + @After + public void tearDown() throws Exception { - } + } - @Test - public void testMain() { + @Test + public void testMain() { - try { - SampleConsumer.main( new String[0]); - } catch (Exception e) { - assertTrue(true); - } - assertTrue(true); + try { + SampleConsumer.main(new String[0]); + } catch (Exception e) { + assertTrue(true); + } + assertTrue(true); - } + } } diff --git a/src/test/java/org/onap/dmaap/mr/test/clients/SamplePublisher.java b/src/test/java/org/onap/dmaap/mr/test/clients/SamplePublisher.java new file mode 100644 index 0000000..0c80194 --- /dev/null +++ b/src/test/java/org/onap/dmaap/mr/test/clients/SamplePublisher.java @@ -0,0 +1,82 @@ +/******************************************************************************* + * ============LICENSE_START======================================================= + * org.onap.dmaap + * ================================================================================ + * Copyright © 2017 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Modifications Copyright © 2021 Orange. + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============LICENSE_END========================================================= + * + * ECOMP is a trademark and service mark of AT&T Intellectual Property. + * + *******************************************************************************/ + +package org.onap.dmaap.mr.test.clients; + +import org.json.JSONObject; +import org.onap.dmaap.mr.client.MRBatchingPublisher; +import org.onap.dmaap.mr.client.MRClientBuilders.PublisherBuilder; +import org.onap.dmaap.mr.client.MRPublisher.Message; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +import java.io.IOException; +import java.util.List; +import java.util.concurrent.TimeUnit; + +public class SamplePublisher { + public static void main(String[] args) throws IOException, InterruptedException { + final Logger logger = LoggerFactory.getLogger(SampleConsumer.class); + // read the hosts(s) from the command line + final String hosts = (args.length > 0 ? args[0] : "localhost:8181"); + + // read the topic name from the command line + + final String topic = (args.length > 1 ? args[1] : "org.onap.dmaap.mr.testingTopic"); + + // set up some batch limits and the compression flag + final int maxBatchSize = 100; + final int maxAgeMs = 250; + final boolean withGzip = false; + + // create our publisher + + final MRBatchingPublisher pub = new PublisherBuilder(). + usingHosts(hosts). + onTopic(topic).limitBatch(maxBatchSize, maxAgeMs). + authenticatedBy("CG0TXc2Aa3v8LfBk", "pj2rhxJWKP23pgy8ahMnjH88"). + build(); + // publish some messages + final JSONObject msg1 = new JSONObject(); + msg1.put("name", "tttttttttttttttt"); + msg1.put("greeting", "ooooooooooooooooo"); + pub.send("MyPartitionKey", msg1.toString()); + + final JSONObject msg2 = new JSONObject(); + msg2.put("now", System.currentTimeMillis()); + pub.send("MyOtherPartitionKey", msg2.toString()); + + // ... + + // close the publisher to make sure everything's sent before exiting. The batching + // publisher interface allows the app to get the set of unsent messages. It could + // write them to disk, for example, to try to send them later. + final List stuck = pub.close(20, TimeUnit.SECONDS); + if (!stuck.isEmpty()) { + logger.warn(stuck.size() + " messages unsent"); + } else { + logger.info("Clean exit; all messages sent."); + } + } +} diff --git a/src/test/java/org/onap/dmaap/mr/test/clients/SamplePublisherTest.java b/src/test/java/org/onap/dmaap/mr/test/clients/SamplePublisherTest.java index 33f80e5..7c74a05 100644 --- a/src/test/java/org/onap/dmaap/mr/test/clients/SamplePublisherTest.java +++ b/src/test/java/org/onap/dmaap/mr/test/clients/SamplePublisherTest.java @@ -4,12 +4,14 @@ * ================================================================================ * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. * ================================================================================ + * Modifications Copyright © 2021 Orange. + * ================================================================================ * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at - * + * * http://www.apache.org/licenses/LICENSE-2.0 - * + * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. @@ -20,35 +22,35 @@ package org.onap.dmaap.mr.test.clients; -import static org.junit.Assert.assertTrue; - import org.junit.After; import org.junit.Before; import org.junit.Test; +import static org.junit.Assert.assertTrue; + public class SamplePublisherTest { - @Before - public void setUp() throws Exception { + @Before + public void setUp() throws Exception { - } + } - @After - public void tearDown() throws Exception { + @After + public void tearDown() throws Exception { - } + } - @Test - public void testMain() { + @Test + public void testMain() { - try { - SamplePublisher.main( new String[0]); - } catch (Exception e) { - // TODO Auto-generated catch block - assertTrue(true); - } - assertTrue(true); + try { + SamplePublisher.main(new String[0]); + } catch (Exception e) { + // TODO Auto-generated catch block + assertTrue(true); + } + assertTrue(true); - } + } } diff --git a/src/test/java/org/onap/dmaap/mr/test/clients/SimpleExampleConsumer.java b/src/test/java/org/onap/dmaap/mr/test/clients/SimpleExampleConsumer.java new file mode 100644 index 0000000..feb825d --- /dev/null +++ b/src/test/java/org/onap/dmaap/mr/test/clients/SimpleExampleConsumer.java @@ -0,0 +1,89 @@ +/******************************************************************************* + * ============LICENSE_START======================================================= + * org.onap.dmaap + * ================================================================================ + * Copyright © 2017 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Modifications Copyright © 2021 Orange. + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============LICENSE_END========================================================= + * + * ECOMP is a trademark and service mark of AT&T Intellectual Property. + * + *******************************************************************************/ + +package org.onap.dmaap.mr.test.clients; + +import org.onap.dmaap.mr.client.MRClientFactory; +import org.onap.dmaap.mr.client.MRConsumer; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +import java.io.File; +import java.io.FileReader; +import java.io.FileWriter; +import java.util.Properties; + +public class SimpleExampleConsumer { + + static FileWriter routeWriter = null; + static Properties props = null; + static FileReader routeReader = null; + + public static void main(String[] args) { + final Logger logger = LoggerFactory.getLogger(SimpleExampleConsumer.class); + + long count = 0; + long nextReport = 5000; + + final long startMs = System.currentTimeMillis(); + + try { + String routeFilePath = "/src/main/resources/dme2/preferredRoute.txt"; + + File fo = new File(routeFilePath); + if (!fo.exists()) { + routeWriter = new FileWriter(new File(routeFilePath)); + } + routeReader = new FileReader(new File(routeFilePath)); + props = new Properties(); + final MRConsumer cc = MRClientFactory.createConsumer("/src/main/resources/dme2/consumer.properties"); + int i = 0; + while (i < 10) { + Thread.sleep(2); + i++; + for (String msg : cc.fetch()) { + + System.out.println(msg); + } + + if (count > nextReport) { + nextReport += 5000; + + final long endMs = System.currentTimeMillis(); + final long elapsedMs = endMs - startMs; + final double elapsedSec = elapsedMs / 1000.0; + final double eps = count / elapsedSec; + System.out.println("Consumed " + count + " in " + elapsedSec + "; " + eps + " eps"); + } + } + } catch (InterruptedException e) { + logger.error("Interrupted!", e); + // Restore interrupted state... + Thread.currentThread().interrupt(); + } catch (Exception x) { + System.err.println(x.getClass().getName() + ": " + x.getMessage()); + logger.error("exception: ", x); + } + } +} diff --git a/src/test/java/org/onap/dmaap/mr/test/clients/SimpleExampleConsumerTest.java b/src/test/java/org/onap/dmaap/mr/test/clients/SimpleExampleConsumerTest.java index 1ccc839..532e040 100644 --- a/src/test/java/org/onap/dmaap/mr/test/clients/SimpleExampleConsumerTest.java +++ b/src/test/java/org/onap/dmaap/mr/test/clients/SimpleExampleConsumerTest.java @@ -4,12 +4,14 @@ * ================================================================================ * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. * ================================================================================ + * Modifications Copyright © 2021 Orange. + * ================================================================================ * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at - * + * * http://www.apache.org/licenses/LICENSE-2.0 - * + * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. @@ -20,35 +22,35 @@ package org.onap.dmaap.mr.test.clients; -import static org.junit.Assert.assertTrue; - import org.junit.After; import org.junit.Before; import org.junit.Test; +import static org.junit.Assert.assertTrue; + public class SimpleExampleConsumerTest { - @Before - public void setUp() throws Exception { + @Before + public void setUp() throws Exception { - } + } - @After - public void tearDown() throws Exception { + @After + public void tearDown() throws Exception { - } + } - @Test - public void testMain() { + @Test + public void testMain() { - try { - SimpleExampleConsumer.main(null); - } catch (Exception e) { - // TODO Auto-generated catch block - e.printStackTrace(); - } - assertTrue(true); + try { + SimpleExampleConsumer.main(null); + } catch (Exception e) { + // TODO Auto-generated catch block + e.printStackTrace(); + } + assertTrue(true); - } + } } diff --git a/src/test/java/org/onap/dmaap/mr/test/clients/SimpleExampleConsumerWithReturnResponse.java b/src/test/java/org/onap/dmaap/mr/test/clients/SimpleExampleConsumerWithReturnResponse.java new file mode 100644 index 0000000..6374ab5 --- /dev/null +++ b/src/test/java/org/onap/dmaap/mr/test/clients/SimpleExampleConsumerWithReturnResponse.java @@ -0,0 +1,91 @@ +/******************************************************************************* + * ============LICENSE_START======================================================= + * org.onap.dmaap + * ================================================================================ + * Copyright © 2017 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Modifications Copyright © 2021 Orange. + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============LICENSE_END========================================================= + * + * ECOMP is a trademark and service mark of AT&T Intellectual Property. + * + *******************************************************************************/ + +package org.onap.dmaap.mr.test.clients; + +import org.onap.dmaap.mr.client.MRClientFactory; +import org.onap.dmaap.mr.client.MRConsumer; +import org.onap.dmaap.mr.client.response.MRConsumerResponse; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +import java.io.File; +import java.io.FileReader; +import java.io.FileWriter; +import java.util.Properties; + +public class SimpleExampleConsumerWithReturnResponse { + + private static final Logger logger = LoggerFactory.getLogger(SimpleExampleConsumerWithReturnResponse.class); + + static FileWriter routeWriter = null; + static Properties props = null; + static FileReader routeReader = null; + + public static void main(String[] args) { + + long count = 0; + long nextReport = 5000; + // remove while true and limite execution time in seconds + int timeMax = 86400; // one day + long endDate = System.currentTimeMillis() + timeMax * 1000; + + final long startMs = System.currentTimeMillis(); + + try { + String routeFilePath = "src/main/resources/dme2/preferredRoute.txt"; + + + File fo = new File(routeFilePath); + if (!fo.exists()) { + routeWriter = new FileWriter(new File(routeFilePath)); + } + routeReader = new FileReader(new File(routeFilePath)); + props = new Properties(); + final MRConsumer cc = MRClientFactory.createConsumer("src/main/resources/dme2/consumer.properties"); + while (System.currentTimeMillis() < endDate) { + MRConsumerResponse mrConsumerResponse = cc.fetchWithReturnConsumerResponse(); + System.out.println("mrConsumerResponse code :" + mrConsumerResponse.getResponseCode()); + + System.out.println("mrConsumerResponse Message :" + mrConsumerResponse.getResponseMessage()); + + System.out.println("mrConsumerResponse ActualMessage :" + mrConsumerResponse.getActualMessages()); + + if (count > nextReport) { + nextReport += 5000; + + final long endMs = System.currentTimeMillis(); + final long elapsedMs = endMs - startMs; + final double elapsedSec = elapsedMs / 1000.0; + final double eps = count / elapsedSec; + System.out.println("Consumed " + count + " in " + elapsedSec + "; " + eps + " eps"); + } + } + } catch (Exception x) { + System.err.println(x.getClass().getName() + ": " + x.getMessage()); + logger.error("exception: ", x); + } + } + +} diff --git a/src/test/java/org/onap/dmaap/mr/test/clients/SimpleExampleConsumerWithReturnResponseTest.java b/src/test/java/org/onap/dmaap/mr/test/clients/SimpleExampleConsumerWithReturnResponseTest.java index d814125..0dc04ea 100644 --- a/src/test/java/org/onap/dmaap/mr/test/clients/SimpleExampleConsumerWithReturnResponseTest.java +++ b/src/test/java/org/onap/dmaap/mr/test/clients/SimpleExampleConsumerWithReturnResponseTest.java @@ -4,12 +4,14 @@ * ================================================================================ * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. * ================================================================================ + * Modifications Copyright © 2021 Orange. + * ================================================================================ * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at - * + * * http://www.apache.org/licenses/LICENSE-2.0 - * + * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. @@ -20,34 +22,34 @@ package org.onap.dmaap.mr.test.clients; -import static org.junit.Assert.assertTrue; - import org.junit.After; import org.junit.Before; import org.junit.Test; +import static org.junit.Assert.assertTrue; + public class SimpleExampleConsumerWithReturnResponseTest { - @Before - public void setUp() throws Exception { + @Before + public void setUp() throws Exception { - } + } - @After - public void tearDown() throws Exception { + @After + public void tearDown() throws Exception { - } + } - @Test - public void testMain() { + @Test + public void testMain() { - try { - SimpleExampleConsumerWithReturnResponse.main(null); - } catch (Exception e) { - // TODO Auto-generated catch block e.printStackTrace(); - } - assertTrue(true); + try { + SimpleExampleConsumerWithReturnResponse.main(null); + } catch (Exception e) { + // TODO Auto-generated catch block e.printStackTrace(); + } + assertTrue(true); - } + } } diff --git a/src/test/java/org/onap/dmaap/mr/test/clients/SimpleExamplePublisher.java b/src/test/java/org/onap/dmaap/mr/test/clients/SimpleExamplePublisher.java new file mode 100644 index 0000000..a30d45d --- /dev/null +++ b/src/test/java/org/onap/dmaap/mr/test/clients/SimpleExamplePublisher.java @@ -0,0 +1,94 @@ +/******************************************************************************* + * ============LICENSE_START======================================================= + * org.onap.dmaap + * ================================================================================ + * Copyright © 2017 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Modifications Copyright © 2021 Orange. + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============LICENSE_END========================================================= + * + * ECOMP is a trademark and service mark of AT&T Intellectual Property. + * + *******************************************************************************/ + +package org.onap.dmaap.mr.test.clients; + +import org.json.JSONObject; +import org.onap.dmaap.mr.client.MRBatchingPublisher; +import org.onap.dmaap.mr.client.MRClientFactory; +import org.onap.dmaap.mr.client.MRPublisher.Message; + +import java.io.File; +import java.io.FileReader; +import java.io.FileWriter; +import java.io.IOException; +import java.util.List; +import java.util.Properties; +import java.util.concurrent.TimeUnit; + +/** + * An example of how to use the Java publisher. + * + * @author author + */ +public class SimpleExamplePublisher { + static FileWriter routeWriter = null; + static Properties props = null; + static FileReader routeReader = null; + + public void publishMessage(String producerFilePath) throws IOException, InterruptedException, Exception { + + // create our publisher + final MRBatchingPublisher pub = MRClientFactory.createBatchingPublisher(producerFilePath); + // publish some messages + final JSONObject msg1 = new JSONObject(); + msg1.put("Name", "Sprint"); + + pub.send("First cambria messge"); + pub.send("MyPartitionKey", msg1.toString()); + + final JSONObject msg2 = new JSONObject(); + + + // ... + + // close the publisher to make sure everything's sent before exiting. The batching + // publisher interface allows the app to get the set of unsent messages. It could + // write them to disk, for example, to try to send them later. + final List stuck = pub.close(20, TimeUnit.SECONDS); + if (stuck.isEmpty()) { + System.err.println(stuck.size() + " messages unsent"); + } else { + System.out.println("Clean exit; all messages sent."); + } + } + + public static void main(String[] args) throws InterruptedException, Exception { + + String routeFilePath = "/src/main/resources/dme2/preferredRoute.txt"; + + SimpleExamplePublisher publisher = new SimpleExamplePublisher(); + + + File fo = new File(routeFilePath); + if (!fo.exists()) { + routeWriter = new FileWriter(new File(routeFilePath)); + } + routeReader = new FileReader(new File(routeFilePath)); + props = new Properties(); + publisher.publishMessage("/src/main/resources/dme2/producer.properties"); + } + +} + diff --git a/src/test/java/org/onap/dmaap/mr/test/clients/SimpleExamplePublisherTest.java b/src/test/java/org/onap/dmaap/mr/test/clients/SimpleExamplePublisherTest.java index 43faf5e..5449400 100644 --- a/src/test/java/org/onap/dmaap/mr/test/clients/SimpleExamplePublisherTest.java +++ b/src/test/java/org/onap/dmaap/mr/test/clients/SimpleExamplePublisherTest.java @@ -4,12 +4,14 @@ * ================================================================================ * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. * ================================================================================ + * Modifications Copyright © 2021 Orange. + * ================================================================================ * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at - * + * * http://www.apache.org/licenses/LICENSE-2.0 - * + * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. @@ -20,61 +22,61 @@ package org.onap.dmaap.mr.test.clients; -import static org.junit.Assert.assertTrue; - -import java.io.IOException; import org.junit.After; import org.junit.Before; import org.junit.Test; +import java.io.IOException; + +import static org.junit.Assert.assertTrue; + public class SimpleExamplePublisherTest { - private SimpleExamplePublisher pub = null; - - @Before - public void setUp() throws Exception { - pub = new SimpleExamplePublisher(); - - } - - @After - public void tearDown() throws Exception { - - } - - @Test - public void testPublishMessage() { - try { - pub.publishMessage("/producer"); - } catch (NullPointerException e) { - assertTrue(true); - } catch (IOException e) { - // TODO Auto-generated catch block - e.printStackTrace(); - } catch (InterruptedException e) { - // TODO Auto-generated catch block - e.printStackTrace(); - } catch (Exception e) { - // TODO Auto-generated catch block - e.printStackTrace(); - } - - assertTrue(true); - - } - - @Test - public void testMain() { - - try { - SimpleExamplePublisher.main(null); - } catch (Exception e) { - // TODO Auto-generated catch block - e.printStackTrace(); - } - assertTrue(true); - - } - - + private SimpleExamplePublisher pub = null; + + @Before + public void setUp() throws Exception { + pub = new SimpleExamplePublisher(); + + } + + @After + public void tearDown() throws Exception { + + } + + @Test + public void testPublishMessage() { + try { + pub.publishMessage("/producer"); + } catch (NullPointerException e) { + assertTrue(true); + } catch (IOException e) { + // TODO Auto-generated catch block + e.printStackTrace(); + } catch (InterruptedException e) { + // TODO Auto-generated catch block + e.printStackTrace(); + } catch (Exception e) { + // TODO Auto-generated catch block + e.printStackTrace(); + } + + assertTrue(true); + + } + + @Test + public void testMain() { + + try { + SimpleExamplePublisher.main(null); + } catch (Exception e) { + // TODO Auto-generated catch block + e.printStackTrace(); + } + assertTrue(true); + + } + } diff --git a/src/test/java/org/onap/dmaap/mr/test/clients/SimpleExamplePublisherWithResponse.java b/src/test/java/org/onap/dmaap/mr/test/clients/SimpleExamplePublisherWithResponse.java new file mode 100644 index 0000000..08bc778 --- /dev/null +++ b/src/test/java/org/onap/dmaap/mr/test/clients/SimpleExamplePublisherWithResponse.java @@ -0,0 +1,85 @@ +/******************************************************************************* + * ============LICENSE_START======================================================= + * org.onap.dmaap + * ================================================================================ + * Copyright © 2017 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Modifications Copyright © 2021 Orange. + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============LICENSE_END========================================================= + * + * ECOMP is a trademark and service mark of AT&T Intellectual Property. + * + *******************************************************************************/ + +package org.onap.dmaap.mr.test.clients; + +import org.json.JSONObject; +import org.onap.dmaap.mr.client.MRBatchingPublisher; +import org.onap.dmaap.mr.client.MRClientFactory; +import org.onap.dmaap.mr.client.response.MRPublisherResponse; + +import java.io.File; +import java.io.FileReader; +import java.io.FileWriter; +import java.io.IOException; +import java.util.Properties; + +/** + * An example of how to use the Java publisher. + * + * @author author + */ +public class SimpleExamplePublisherWithResponse { + static FileWriter routeWriter = null; + static Properties props = null; + static FileReader routeReader = null; + + public static void main(String[] args) throws InterruptedException, Exception { + + String routeFilePath = "src/main/resources/dme2/preferredRoute.txt"; + String msgCount = args[0]; + SimpleExamplePublisherWithResponse publisher = new SimpleExamplePublisherWithResponse(); + File fo = new File(routeFilePath); + if (!fo.exists()) { + routeWriter = new FileWriter(new File(routeFilePath)); + } + routeReader = new FileReader(new File(routeFilePath)); + props = new Properties(); + int i = 0; + while (i < Integer.valueOf(msgCount)) { + publisher.publishMessage("src/main/resources/dme2/producer.properties", Integer.valueOf(msgCount)); + i++; + } + } + + public void publishMessage(String producerFilePath, int count) throws IOException, InterruptedException { + // create our publisher + final MRBatchingPublisher pub = MRClientFactory.createBatchingPublisher(producerFilePath, true); + // publish some messages + final JSONObject msg1 = new JSONObject(); + + msg1.put("Partition:1", "Message:" + count); + msg1.put("greeting", "Hello .."); + + + pub.send("1", msg1.toString()); + pub.send("1", msg1.toString()); + + MRPublisherResponse res = pub.sendBatchWithResponse(); + + System.out.println("Pub response->" + res.toString()); + } + + +} diff --git a/src/test/java/org/onap/dmaap/mr/test/clients/SimpleExamplePublisherWithResponseTest.java b/src/test/java/org/onap/dmaap/mr/test/clients/SimpleExamplePublisherWithResponseTest.java index 08dec2b..0b6e182 100644 --- a/src/test/java/org/onap/dmaap/mr/test/clients/SimpleExamplePublisherWithResponseTest.java +++ b/src/test/java/org/onap/dmaap/mr/test/clients/SimpleExamplePublisherWithResponseTest.java @@ -4,12 +4,14 @@ * ================================================================================ * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. * ================================================================================ + * Modifications Copyright © 2021 Orange. + * ================================================================================ * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at - * + * * http://www.apache.org/licenses/LICENSE-2.0 - * + * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. @@ -20,48 +22,43 @@ package org.onap.dmaap.mr.test.clients; -import static org.junit.Assert.assertTrue; - import org.junit.After; import org.junit.Before; import org.junit.Test; +import java.io.FileNotFoundException; +import java.io.IOException; + +import static org.junit.Assert.assertTrue; + public class SimpleExamplePublisherWithResponseTest { - - private SimpleExamplePublisherWithResponse pub = null; - - @Before - public void setUp() throws Exception { - pub = new SimpleExamplePublisherWithResponse(); - } - @After - public void tearDown() throws Exception { + private SimpleExamplePublisherWithResponse pub = null; + + @Before + public void setUp() throws Exception { + pub = new SimpleExamplePublisherWithResponse(); + } - } + @After + public void tearDown() throws Exception { - @Test - public void testMain() { + } - try { - SimpleExamplePublisherWithResponse.main( new String[0]); - } catch (Exception e) { - assertTrue(true); - } - assertTrue(true); + @Test + public void testMain() { - } - - @Test - public void testPublishMessage() { + try { + SimpleExamplePublisherWithResponse.main(new String[0]); + } catch (Exception e) { + assertTrue(true); + } + assertTrue(true); - try { - pub.publishMessage("/producer", 100); - } catch (Exception e) { - // TODO Auto-generated catch block - e.printStackTrace(); - } - assertTrue(true); + } - } + @Test(expected = FileNotFoundException.class) + public void testPublishMessage() throws IOException, InterruptedException { + pub.publishMessage("/producer", 100); + } } diff --git a/src/test/java/org/onap/dmaap/mr/test/clients/TestRunner.java b/src/test/java/org/onap/dmaap/mr/test/clients/TestRunner.java index 6db09f8..0b4a74b 100644 --- a/src/test/java/org/onap/dmaap/mr/test/clients/TestRunner.java +++ b/src/test/java/org/onap/dmaap/mr/test/clients/TestRunner.java @@ -4,12 +4,14 @@ * ================================================================================ * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. * ================================================================================ + * Modifications Copyright © 2021 Orange. + * ================================================================================ * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at - * + * * http://www.apache.org/licenses/LICENSE-2.0 - * + * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. @@ -27,16 +29,16 @@ import org.slf4j.Logger; import org.slf4j.LoggerFactory; public class TestRunner { - private static final Logger LOGGER = LoggerFactory.getLogger(TestRunner.class); + private static final Logger logger = LoggerFactory.getLogger(TestRunner.class); + + public static void main(String[] args) { + // TODO Auto-generated method stub + Result result = JUnitCore.runClasses(JUnitTestSuite.class); + for (Failure failure : result.getFailures()) { + logger.info(failure.toString()); - public static void main(String[] args) { - // TODO Auto-generated method stub - Result result = JUnitCore.runClasses(JUnitTestSuite.class); - for (Failure failure : result.getFailures()) { - LOGGER.info(failure.toString()); - - } - LOGGER.info(String.valueOf(result.wasSuccessful())); - } + } + logger.info(String.valueOf(result.wasSuccessful())); + } } diff --git a/src/test/java/org/onap/dmaap/mr/test/support/JUnitTestSuite.java b/src/test/java/org/onap/dmaap/mr/test/support/JUnitTestSuite.java index 3c3b4c8..d244f34 100644 --- a/src/test/java/org/onap/dmaap/mr/test/support/JUnitTestSuite.java +++ b/src/test/java/org/onap/dmaap/mr/test/support/JUnitTestSuite.java @@ -4,12 +4,14 @@ * ================================================================================ * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. * ================================================================================ + * Modifications Copyright © 2021 Orange. + * ================================================================================ * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at - * + * * http://www.apache.org/licenses/LICENSE-2.0 - * + * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. @@ -21,7 +23,6 @@ package org.onap.dmaap.mr.test.support; import junit.framework.TestSuite; - import org.junit.runner.RunWith; import org.junit.runners.Suite; import org.junit.runners.Suite.SuiteClasses; @@ -29,17 +30,17 @@ import org.slf4j.Logger; import org.slf4j.LoggerFactory; @RunWith(Suite.class) -@SuiteClasses({ MRBatchingPublisherMockTest.class, MRConsumerMockTest.class,}) +@SuiteClasses({MRBatchingPublisherMockTest.class, MRConsumerMockTest.class,}) public class JUnitTestSuite { - private static final Logger LOGGER = LoggerFactory.getLogger(JUnitTestSuite.class); + private static final Logger logger = LoggerFactory.getLogger(JUnitTestSuite.class); + + public static void main(String[] args) { + logger.info("Running the test suite"); - public static void main(String[] args) { - LOGGER.info("Running the test suite"); - - TestSuite tstSuite = new TestSuite(); - LOGGER.info("Total Test Counts " + tstSuite.countTestCases()); - } + TestSuite tstSuite = new TestSuite(); + logger.info("Total Test Counts " + tstSuite.countTestCases()); + } } diff --git a/src/test/java/org/onap/dmaap/mr/test/support/MRBatchingPublisherMock.java b/src/test/java/org/onap/dmaap/mr/test/support/MRBatchingPublisherMock.java new file mode 100644 index 0000000..beaf9e9 --- /dev/null +++ b/src/test/java/org/onap/dmaap/mr/test/support/MRBatchingPublisherMock.java @@ -0,0 +1,167 @@ +/******************************************************************************* + * ============LICENSE_START======================================================= + * org.onap.dmaap + * ================================================================================ + * Copyright © 2017 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Modifications Copyright © 2021 Orange. + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============LICENSE_END========================================================= + * + * ECOMP is a trademark and service mark of AT&T Intellectual Property. + * + *******************************************************************************/ + +package org.onap.dmaap.mr.test.support; + +import org.onap.dmaap.mr.client.MRBatchingPublisher; +import org.onap.dmaap.mr.client.response.MRPublisherResponse; +import org.slf4j.Logger; + +import java.util.Collection; +import java.util.LinkedList; +import java.util.List; +import java.util.concurrent.TimeUnit; + +/** + * A helper for unit testing systems that use a MRPublisher. When setting + * up your test, inject an instance into MRClientFactory to have it return + * the mock client. + * + * @author author + */ +public class MRBatchingPublisherMock implements MRBatchingPublisher { + public class Entry { + public Entry(String partition, String msg) { + fPartition = partition; + fMessage = msg; + } + + @Override + public String toString() { + return fMessage; + } + + public final String fPartition; + public final String fMessage; + } + + public MRBatchingPublisherMock() { + fCaptures = new LinkedList<>(); + } + + public interface Listener { + void onMessage(Entry e); + } + + public void addListener(Listener listener) { + fListeners.add(listener); + } + + public List getCaptures() { + return getCaptures(new MessageFilter() { + @Override + public boolean match(String msg) { + return true; + } + }); + } + + public interface MessageFilter { + boolean match(String msg); + } + + public List getCaptures(MessageFilter filter) { + final LinkedList result = new LinkedList<>(); + for (Entry capture : fCaptures) { + if (filter.match(capture.fMessage)) { + result.add(capture); + } + } + return result; + } + + public int received() { + return fCaptures.size(); + } + + public void reset() { + fCaptures.clear(); + } + + @Override + public int send(String partition, String msg) { + final Entry e = new Entry(partition, msg); + + fCaptures.add(e); + for (Listener l : fListeners) { + l.onMessage(e); + } + return 1; + } + + @Override + public int send(Message msg) { + return send(msg.fPartition, msg.fMsg); + } + + @Override + public int send(String msg) { + return 1; + + } + + @Override + public int send(Collection msgs) { + int sum = 0; + for (Message m : msgs) { + sum += send(m); + } + return sum; + } + + @Override + public int getPendingMessageCount() { + return 0; + } + + @Override + public List close(long timeout, TimeUnit timeoutUnits) { + return new LinkedList<>(); + } + + @Override + public void close() { + } + + @Override + public void setApiCredentials(String apiKey, String apiSecret) { + } + + @Override + public void clearApiCredentials() { + } + + @Override + public void logTo(Logger log) { + } + + private final LinkedList fCaptures; + private LinkedList fListeners = new LinkedList<>(); + + @Override + public MRPublisherResponse sendBatchWithResponse() { + // TODO Auto-generated method stub + return null; + } +} diff --git a/src/test/java/org/onap/dmaap/mr/test/support/MRBatchingPublisherMockTest.java b/src/test/java/org/onap/dmaap/mr/test/support/MRBatchingPublisherMockTest.java index af76c52..1de5bcb 100644 --- a/src/test/java/org/onap/dmaap/mr/test/support/MRBatchingPublisherMockTest.java +++ b/src/test/java/org/onap/dmaap/mr/test/support/MRBatchingPublisherMockTest.java @@ -4,12 +4,14 @@ * ================================================================================ * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. * ================================================================================ + * Modifications Copyright © 2021 Orange. + * ================================================================================ * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at - * + * * http://www.apache.org/licenses/LICENSE-2.0 - * + * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. @@ -20,166 +22,165 @@ package org.onap.dmaap.mr.test.support; -import static org.junit.Assert.assertTrue; - -import java.util.ArrayList; - import org.junit.After; import org.junit.Before; import org.junit.Test; +import org.onap.dmaap.mr.client.MRPublisher.Message; -import org.onap.dmaap.mr.client.MRPublisher.message; +import java.util.ArrayList; + +import static org.junit.Assert.assertTrue; public class MRBatchingPublisherMockTest { - private MRBatchingPublisherMock pub = null; + private MRBatchingPublisherMock pub = null; + + private MRBatchingPublisherMock.Entry entry = null; + + @Before + public void setUp() throws Exception { + pub = new MRBatchingPublisherMock(); + entry = pub.new Entry("partition", "msg"); + + } + + @After + public void tearDown() throws Exception { + + } + + @Test + public void testToString() { + + entry.toString(); + assertTrue(true); + + } + + @Test + public void testAddListener() { + + pub.addListener(null); + assertTrue(true); + + } + + @Test + public void testGetCaptures() { + + pub.getCaptures(); + assertTrue(true); + + } - private MRBatchingPublisherMock.Entry entry = null; + @Test + public void testGetCaptures2() { - @Before - public void setUp() throws Exception { - pub = new MRBatchingPublisherMock(); - entry = pub.new Entry("partition", "msg"); + pub.getCaptures(null); + assertTrue(true); - } + } - @After - public void tearDown() throws Exception { + @Test + public void testReceived() { - } + pub.received(); + assertTrue(true); - @Test - public void testToString() { + } - entry.toString(); - assertTrue(true); + @Test + public void testResend() { - } + pub.reset(); + assertTrue(true); - @Test - public void testAddListener() { + } - pub.addListener(null); - assertTrue(true); + @Test + public void testSend() { - } + pub.send("partition", "msg"); + assertTrue(true); - @Test - public void testGetCaptures() { + } - pub.getCaptures(); - assertTrue(true); + @Test + public void testSend2() { - } + pub.send("msg"); + assertTrue(true); - @Test - public void testGetCaptures2() { + } - pub.getCaptures(null); - assertTrue(true); + @Test + public void testSend3() { + //sending message m obj + pub.send(new ArrayList()); + assertTrue(true); - } + } - @Test - public void testReceived() { + @Test + public void testSend4() { + //sending collection of message m objects + pub.send(new Message("partition", "msg")); + assertTrue(true); - pub.received(); - assertTrue(true); + } - } - - @Test - public void testResend() { + @Test + public void testSendBatchWithResponse() { - pub.reset(); - assertTrue(true); + pub.sendBatchWithResponse(); + assertTrue(true); - } - - @Test - public void testSend() { + } - pub.send("partition", "msg"); - assertTrue(true); + @Test + public void testLogTo() { - } - - @Test - public void testSend2() { + pub.logTo(null); + assertTrue(true); - pub.send("msg"); - assertTrue(true); + } - } - - @Test - public void testSend3() { - //sending message m obj - pub.send(new ArrayList()); - assertTrue(true); + @Test + public void testClearApiCredentials() { - } - - @Test - public void testSend4() { - //sending collection of message m objects - pub.send(new message("partition", "msg")); - assertTrue(true); + pub.clearApiCredentials(); + assertTrue(true); - } - - @Test - public void testSendBatchWithResponse() { + } - pub.sendBatchWithResponse(); - assertTrue(true); + @Test + public void testSetApiCredentials() { - } - - @Test - public void testLogTo() { + pub.setApiCredentials("apikey", "apisecret"); + assertTrue(true); - pub.logTo(null); - assertTrue(true); + } - } - - @Test - public void testClearApiCredentials() { + @Test + public void testClose() { - pub.clearApiCredentials(); - assertTrue(true); + pub.close(); + assertTrue(true); - } - - @Test - public void testSetApiCredentials() { + } - pub.setApiCredentials("apikey", "apisecret"); - assertTrue(true); + @Test + public void testClose2() { - } - - @Test - public void testClose() { + pub.close(100, null); + assertTrue(true); - pub.close(); - assertTrue(true); + } - } - - @Test - public void testClose2() { + @Test + public void testGetPendingMessageCount() { - pub.close(100, null); - assertTrue(true); + pub.getPendingMessageCount(); + assertTrue(true); - } - - @Test - public void testGetPendingMessageCount() { - - pub.getPendingMessageCount(); - assertTrue(true); - - } + } } diff --git a/src/test/java/org/onap/dmaap/mr/test/support/MRConsumerMock.java b/src/test/java/org/onap/dmaap/mr/test/support/MRConsumerMock.java new file mode 100644 index 0000000..55cd245 --- /dev/null +++ b/src/test/java/org/onap/dmaap/mr/test/support/MRConsumerMock.java @@ -0,0 +1,148 @@ +/******************************************************************************* + * ============LICENSE_START======================================================= + * org.onap.dmaap + * ================================================================================ + * Copyright © 2017 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Modifications Copyright © 2021 Orange. + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============LICENSE_END========================================================= + * + * ECOMP is a trademark and service mark of AT&T Intellectual Property. + * + *******************************************************************************/ + +package org.onap.dmaap.mr.test.support; + +import org.onap.dmaap.mr.client.MRConsumer; +import org.onap.dmaap.mr.client.response.MRConsumerResponse; +import org.slf4j.Logger; + +import java.io.IOException; +import java.util.LinkedList; +import java.util.List; + +/** + * A helper for unit testing systems that use a MRConsumer. When setting + * up your test, inject an instance into MRClientFactory to have it return + * the mock client. + * + * @author author + */ +public class MRConsumerMock implements MRConsumer { + public class Entry { + public Entry(long waitMs, int statusCode, List msgs) { + fWaitMs = waitMs; + fStatusCode = statusCode; + fStatusMsg = null; + fMsgs = new LinkedList<>(msgs); + } + + public Entry(long waitMs, int statusCode, String statusMsg) { + fWaitMs = waitMs; + fStatusCode = statusCode; + fStatusMsg = statusMsg; + fMsgs = null; + } + + public LinkedList run() throws IOException { + try { + Thread.sleep(fWaitMs); + if (fStatusCode >= 200 && fStatusCode <= 299) { + return fMsgs; + } + throw new IOException("" + fStatusCode + " " + fStatusMsg); + } catch (InterruptedException e) { + Thread.currentThread().interrupt(); + throw new IOException(e); + } + } + + private final long fWaitMs; + private final int fStatusCode; + private final String fStatusMsg; + private final LinkedList fMsgs; + } + + public MRConsumerMock() { + fReplies = new LinkedList<>(); + } + + @Override + public void close() { + } + + @Override + public void setApiCredentials(String apiKey, String apiSecret) { + } + + @Override + public void clearApiCredentials() { + } + + public synchronized void add(Entry e) { + fReplies.add(e); + } + + public void addImmediateMsg(String msg) { + addDelayedMsg(0, msg); + } + + public void addDelayedMsg(long delay, String msg) { + final LinkedList list = new LinkedList<>(); + list.add(msg); + add(new Entry(delay, 200, list)); + } + + public void addImmediateMsgGroup(List msgs) { + addDelayedMsgGroup(0, msgs); + } + + public void addDelayedMsgGroup(long delay, List msgs) { + final LinkedList list = new LinkedList<>(msgs); + add(new Entry(delay, 200, list)); + } + + public void addImmediateError(int statusCode, String statusText) { + add(new Entry(0, statusCode, statusText)); + } + + @Override + public Iterable fetch() throws IOException { + return fetch(-1, -1); + } + + @Override + public Iterable fetch(int timeoutMs, int limit) throws IOException { + return fReplies.size() > 0 ? fReplies.removeFirst().run() : new LinkedList(); + } + + @Override + public void logTo(Logger log) { + } + + private final LinkedList fReplies; + + @Override + public MRConsumerResponse fetchWithReturnConsumerResponse() { + // TODO Auto-generated method stub + return null; + } + + @Override + public MRConsumerResponse fetchWithReturnConsumerResponse(int timeoutMs, + int limit) { + // TODO Auto-generated method stub + return null; + } +} diff --git a/src/test/java/org/onap/dmaap/mr/test/support/MRConsumerMockTest.java b/src/test/java/org/onap/dmaap/mr/test/support/MRConsumerMockTest.java index b3c4174..de5420a 100644 --- a/src/test/java/org/onap/dmaap/mr/test/support/MRConsumerMockTest.java +++ b/src/test/java/org/onap/dmaap/mr/test/support/MRConsumerMockTest.java @@ -4,12 +4,14 @@ * ================================================================================ * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. * ================================================================================ + * Modifications Copyright © 2021 Orange. + * ================================================================================ * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at - * + * * http://www.apache.org/licenses/LICENSE-2.0 - * + * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. @@ -20,150 +22,150 @@ package org.onap.dmaap.mr.test.support; -import static org.junit.Assert.assertTrue; +import org.junit.After; +import org.junit.Before; +import org.junit.Test; import java.io.IOException; import java.util.ArrayList; -import org.junit.After; -import org.junit.Before; -import org.junit.Test; +import static org.junit.Assert.assertTrue; public class MRConsumerMockTest { - private MRConsumerMock cons = null; - private MRConsumerMock.Entry entry = null; - - @Before - public void setUp() throws Exception { - cons = new MRConsumerMock(); - entry = cons.new Entry(100, 200, "statusMsg"); - - } - - @After - public void tearDown() throws Exception { - - } - - @Test - public void testClose() { - - cons.close(); - assertTrue(true); - - } - - @Test - public void testRun() { - try { - entry.run(); - } catch (IOException e) { - // TODO Auto-generated catch block - e.printStackTrace(); - } - - assertTrue(true); - - } - - @Test - public void testSetApiCredentials() { - cons.setApiCredentials("apikey", "apisecret"); - assertTrue(true); - - } - - @Test - public void testClearApiCredentials() { - cons.clearApiCredentials(); - assertTrue(true); - - } - - @Test - public void testAdd() { - cons.add(entry); - assertTrue(true); - - } - - @Test - public void testAddImmediateMsg() { - cons.addImmediateMsg("ImmediateMsg"); - assertTrue(true); - - } - - @Test - public void testAddDelayedMsg() { - cons.addDelayedMsg(100, "msg"); - assertTrue(true); - - } - - @Test - public void testAddImmediateMsgGroup() { - cons.addImmediateMsgGroup(new ArrayList()); - assertTrue(true); - - } - - @Test - public void testAddDelayedMsgGroup() { - cons.addDelayedMsgGroup(100,new ArrayList()); - assertTrue(true); - - } - - @Test - public void testAddImmediateError() { - cons.addImmediateError(200, "OK"); - assertTrue(true); - - } - - @Test - public void testFetch() { - try { - cons.fetch(); - } catch (IOException e) { - // TODO Auto-generated catch block - e.printStackTrace(); - } - assertTrue(true); - - } - - @Test - public void testFetch2() { - try { - cons.fetch(100, 200); - } catch (IOException e) { - // TODO Auto-generated catch block - e.printStackTrace(); - } - assertTrue(true); - - } - - @Test - public void testLogTo() { - cons.logTo(null); - assertTrue(true); - - } - - @Test - public void testFetchWithReturnConsumerResponse() { - cons.fetchWithReturnConsumerResponse(); - assertTrue(true); - - } - - @Test - public void testGetchWithReturnConsumerResponse() { - cons.fetchWithReturnConsumerResponse(100,200); - assertTrue(true); - - } + private MRConsumerMock cons = null; + private MRConsumerMock.Entry entry = null; + + @Before + public void setUp() throws Exception { + cons = new MRConsumerMock(); + entry = cons.new Entry(100, 200, "statusMsg"); + + } + + @After + public void tearDown() throws Exception { + + } + + @Test + public void testClose() { + + cons.close(); + assertTrue(true); + + } + + @Test + public void testRun() { + try { + entry.run(); + } catch (IOException e) { + // TODO Auto-generated catch block + e.printStackTrace(); + } + + assertTrue(true); + + } + + @Test + public void testSetApiCredentials() { + cons.setApiCredentials("apikey", "apisecret"); + assertTrue(true); + + } + + @Test + public void testClearApiCredentials() { + cons.clearApiCredentials(); + assertTrue(true); + + } + + @Test + public void testAdd() { + cons.add(entry); + assertTrue(true); + + } + + @Test + public void testAddImmediateMsg() { + cons.addImmediateMsg("ImmediateMsg"); + assertTrue(true); + + } + + @Test + public void testAddDelayedMsg() { + cons.addDelayedMsg(100, "msg"); + assertTrue(true); + + } + + @Test + public void testAddImmediateMsgGroup() { + cons.addImmediateMsgGroup(new ArrayList()); + assertTrue(true); + + } + + @Test + public void testAddDelayedMsgGroup() { + cons.addDelayedMsgGroup(100, new ArrayList()); + assertTrue(true); + + } + + @Test + public void testAddImmediateError() { + cons.addImmediateError(200, "OK"); + assertTrue(true); + + } + + @Test + public void testFetch() { + try { + cons.fetch(); + } catch (IOException e) { + // TODO Auto-generated catch block + e.printStackTrace(); + } + assertTrue(true); + + } + + @Test + public void testFetch2() { + try { + cons.fetch(100, 200); + } catch (IOException e) { + // TODO Auto-generated catch block + e.printStackTrace(); + } + assertTrue(true); + + } + + @Test + public void testLogTo() { + cons.logTo(null); + assertTrue(true); + + } + + @Test + public void testFetchWithReturnConsumerResponse() { + cons.fetchWithReturnConsumerResponse(); + assertTrue(true); + + } + + @Test + public void testGetchWithReturnConsumerResponse() { + cons.fetchWithReturnConsumerResponse(100, 200); + assertTrue(true); + + } } diff --git a/src/test/java/org/onap/dmaap/mr/test/support/TestRunner.java b/src/test/java/org/onap/dmaap/mr/test/support/TestRunner.java index 69f499f..f10ac2b 100644 --- a/src/test/java/org/onap/dmaap/mr/test/support/TestRunner.java +++ b/src/test/java/org/onap/dmaap/mr/test/support/TestRunner.java @@ -4,12 +4,14 @@ * ================================================================================ * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. * ================================================================================ + * Modifications Copyright © 2021 Orange. + * ================================================================================ * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at - * + * * http://www.apache.org/licenses/LICENSE-2.0 - * + * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. @@ -27,16 +29,16 @@ import org.slf4j.Logger; import org.slf4j.LoggerFactory; public class TestRunner { - private static final Logger LOGGER = LoggerFactory.getLogger(TestRunner.class); + private static final Logger logger = LoggerFactory.getLogger(TestRunner.class); + + public static void main(String[] args) { + // TODO Auto-generated method stub + Result result = JUnitCore.runClasses(JUnitTestSuite.class); + for (Failure failure : result.getFailures()) { + logger.info(failure.toString()); - public static void main(String[] args) { - // TODO Auto-generated method stub - Result result = JUnitCore.runClasses(JUnitTestSuite.class); - for (Failure failure : result.getFailures()) { - LOGGER.info(failure.toString()); - - } - LOGGER.info(String.valueOf(result.wasSuccessful())); - } + } + logger.info(String.valueOf(result.wasSuccessful())); + } } diff --git a/src/test/java/org/onap/dmaap/mr/tools/ApiKeyCommandTest.java b/src/test/java/org/onap/dmaap/mr/tools/ApiKeyCommandTest.java index f86d4f2..cd801c3 100644 --- a/src/test/java/org/onap/dmaap/mr/tools/ApiKeyCommandTest.java +++ b/src/test/java/org/onap/dmaap/mr/tools/ApiKeyCommandTest.java @@ -4,12 +4,14 @@ * ================================================================================ * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. * ================================================================================ + * Modifications Copyright © 2021 Orange. + * ================================================================================ * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at - * + * * http://www.apache.org/licenses/LICENSE-2.0 - * + * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. @@ -20,14 +22,10 @@ package org.onap.dmaap.mr.tools; -import static org.junit.Assert.assertTrue; - -import java.io.IOException; -import java.io.PrintStream; -import java.util.Arrays; -import java.util.Iterator; -import java.util.List; - +import com.att.nsa.apiClient.credentials.ApiCredential; +import com.att.nsa.apiClient.http.HttpException; +import com.att.nsa.apiClient.http.HttpObjectNotFoundException; +import com.att.nsa.cmdtool.CommandNotReadyException; import org.junit.After; import org.junit.Before; import org.junit.Test; @@ -35,185 +33,188 @@ import org.junit.runner.RunWith; import org.mockito.InjectMocks; import org.mockito.Mock; import org.mockito.MockitoAnnotations; +import org.onap.dmaap.mr.client.MRClient.MRApiException; +import org.onap.dmaap.mr.client.MRClientFactory; +import org.onap.dmaap.mr.client.MRIdentityManager; +import org.onap.dmaap.mr.client.MRIdentityManager.ApiKey; import org.powermock.api.mockito.PowerMockito; import org.powermock.core.classloader.annotations.PowerMockIgnore; import org.powermock.core.classloader.annotations.PrepareForTest; import org.powermock.modules.junit4.PowerMockRunner; -import com.att.nsa.apiClient.credentials.ApiCredential; -import com.att.nsa.apiClient.http.HttpException; -import com.att.nsa.apiClient.http.HttpObjectNotFoundException; -import com.att.nsa.cmdtool.CommandNotReadyException; -import org.onap.dmaap.mr.client.MRClient.MRApiException; -import org.onap.dmaap.mr.client.MRClientFactory; -import org.onap.dmaap.mr.client.MRIdentityManager; -import org.onap.dmaap.mr.client.MRIdentityManager.ApiKey; +import java.io.IOException; +import java.io.PrintStream; +import java.util.Arrays; +import java.util.Iterator; +import java.util.List; + +import static org.junit.Assert.assertTrue; @RunWith(PowerMockRunner.class) @PowerMockIgnore("jdk.internal.reflect.*") -@PrepareForTest({ MRClientFactory.class }) +@PrepareForTest({MRClientFactory.class}) public class ApiKeyCommandTest { - @InjectMocks - private ApiKeyCommand command; - @Mock - private MRIdentityManager tm; - @Mock - private ApiKey ti; - @Mock - private ApiKey key; - @Mock - private ApiCredential ac; - @Mock - private PrintStream printStream; - - @Before - public void setUp() throws Exception { - MockitoAnnotations.initMocks(this); - PowerMockito.mockStatic(MRClientFactory.class); - PowerMockito.when(MRClientFactory.createIdentityManager(Arrays.asList("localhost"), null, null)).thenReturn(tm); - PowerMockito.when(tm.getApiKey("testtopic")).thenReturn(key); - PowerMockito.when(tm.createApiKey("testtopic", "1")).thenReturn(ac); - - } - - @After - public void tearDown() throws Exception { - - } - - @Test - public void testGetMatches() { - - command.getMatches(); - assertTrue(true); - - } - - @Test - public void testCheckReady() { - - try { - command.checkReady(new MRCommandContext()); - } catch (CommandNotReadyException e) { - // TODO Auto-generated catch block - e.printStackTrace(); - } - assertTrue(true); - - } - - @Test - public void testExecute() { - - String[] parts1 = { "create", "testtopic", "1" }; - String[] parts2 = { "list", "testtopic", "1" }; - String[] parts3 = { "revoke", "write", "read" }; - List parts = Arrays.asList(parts1, parts2, parts3); - for (Iterator iterator = parts.iterator(); iterator.hasNext();) { - String[] part = (String[]) iterator.next(); - - try { - command.execute(part, new MRCommandContext(), printStream); - } catch (CommandNotReadyException e) { - // TODO Auto-generated catch block - e.printStackTrace(); - } - assertTrue(true); - - } - } - - @Test - public void testExecute_error1() throws HttpObjectNotFoundException, HttpException, MRApiException, IOException { - PowerMockito.when(tm.getApiKey("testtopic")).thenThrow(new IOException("error")); - String[] parts1 = { "create", "testtopic", "1" }; - String[] parts2 = { "list", "testtopic", "1" }; - String[] parts3 = { "revoke", "write", "read" }; - List parts = Arrays.asList(parts1, parts2, parts3); - for (Iterator iterator = parts.iterator(); iterator.hasNext();) { - String[] part = (String[]) iterator.next(); - - try { - command.execute(part, new MRCommandContext(), printStream); - } catch (CommandNotReadyException e) { - // TODO Auto-generated catch block - e.printStackTrace(); - } - assertTrue(true); - } - - } - - @Test - public void testExecute_error2() throws HttpObjectNotFoundException, HttpException, MRApiException, IOException { - PowerMockito.when(tm.getApiKey("testtopic")).thenThrow(new MRApiException("error")); - String[] parts1 = { "create", "testtopic", "1" }; - String[] parts2 = { "list", "testtopic", "1" }; - String[] parts3 = { "revoke", "write", "read" }; - List parts = Arrays.asList(parts1, parts2, parts3); - for (Iterator iterator = parts.iterator(); iterator.hasNext();) { - String[] part = (String[]) iterator.next(); - - try { - command.execute(part, new MRCommandContext(),printStream); - } catch (CommandNotReadyException e) { - // TODO Auto-generated catch block - e.printStackTrace(); - } - assertTrue(true); - - } - } - - @Test - public void testExecute_error3() throws HttpObjectNotFoundException, HttpException, MRApiException, IOException { - PowerMockito.when(tm.getApiKey("testtopic")).thenThrow(new HttpException(500, "error")); - String[] parts1 = { "create", "testtopic", "1" }; - String[] parts2 = { "list", "testtopic", "1" }; - String[] parts3 = { "revoke", "write", "read" }; - List parts = Arrays.asList(parts1, parts2, parts3); - for (Iterator iterator = parts.iterator(); iterator.hasNext();) { - String[] part = (String[]) iterator.next(); - - try { - command.execute(part, new MRCommandContext(), printStream); - } catch (CommandNotReadyException e) { - // TODO Auto-generated catch block - e.printStackTrace(); - } - assertTrue(true); - } - - } - - @Test - public void testExecute_error4() throws HttpObjectNotFoundException, HttpException, MRApiException, IOException { - PowerMockito.when(tm.getApiKey("testtopic")).thenThrow(new HttpObjectNotFoundException("error")); - String[] parts1 = { "create", "testtopic", "1" }; - String[] parts2 = { "list", "testtopic", "1" }; - String[] parts3 = { "revoke", "write", "read" }; - List parts = Arrays.asList(parts1, parts2, parts3); - for (Iterator iterator = parts.iterator(); iterator.hasNext();) { - String[] part = (String[]) iterator.next(); - - try { - command.execute(part, new MRCommandContext(), printStream); - } catch (CommandNotReadyException e) { - // TODO Auto-generated catch block - e.printStackTrace(); - } - assertTrue(true); - - } - } - - @Test - public void testDisplayHelp() { - - command.displayHelp(printStream); - assertTrue(true); - - } + @InjectMocks + private ApiKeyCommand command; + @Mock + private MRIdentityManager tm; + @Mock + private ApiKey ti; + @Mock + private ApiKey key; + @Mock + private ApiCredential ac; + @Mock + private PrintStream printStream; + + @Before + public void setUp() throws Exception { + MockitoAnnotations.initMocks(this); + PowerMockito.mockStatic(MRClientFactory.class); + PowerMockito.when(MRClientFactory.createIdentityManager(Arrays.asList("localhost"), null, null)).thenReturn(tm); + PowerMockito.when(tm.getApiKey("testtopic")).thenReturn(key); + PowerMockito.when(tm.createApiKey("testtopic", "1")).thenReturn(ac); + + } + + @After + public void tearDown() throws Exception { + + } + + @Test + public void testGetMatches() { + + command.getMatches(); + assertTrue(true); + + } + + @Test + public void testCheckReady() { + + try { + command.checkReady(new MRCommandContext()); + } catch (CommandNotReadyException e) { + // TODO Auto-generated catch block + e.printStackTrace(); + } + assertTrue(true); + + } + + @Test + public void testExecute() { + + String[] parts1 = {"create", "testtopic", "1"}; + String[] parts2 = {"list", "testtopic", "1"}; + String[] parts3 = {"revoke", "write", "read"}; + List parts = Arrays.asList(parts1, parts2, parts3); + for (Iterator iterator = parts.iterator(); iterator.hasNext(); ) { + String[] part = (String[]) iterator.next(); + + try { + command.execute(part, new MRCommandContext(), printStream); + } catch (CommandNotReadyException e) { + // TODO Auto-generated catch block + e.printStackTrace(); + } + assertTrue(true); + + } + } + + @Test + public void testExecute_error1() throws HttpObjectNotFoundException, HttpException, MRApiException, IOException { + PowerMockito.when(tm.getApiKey("testtopic")).thenThrow(new IOException("error")); + String[] parts1 = {"create", "testtopic", "1"}; + String[] parts2 = {"list", "testtopic", "1"}; + String[] parts3 = {"revoke", "write", "read"}; + List parts = Arrays.asList(parts1, parts2, parts3); + for (Iterator iterator = parts.iterator(); iterator.hasNext(); ) { + String[] part = (String[]) iterator.next(); + + try { + command.execute(part, new MRCommandContext(), printStream); + } catch (CommandNotReadyException e) { + // TODO Auto-generated catch block + e.printStackTrace(); + } + assertTrue(true); + } + + } + + @Test + public void testExecute_error2() throws HttpObjectNotFoundException, HttpException, MRApiException, IOException { + PowerMockito.when(tm.getApiKey("testtopic")).thenThrow(new MRApiException("error")); + String[] parts1 = {"create", "testtopic", "1"}; + String[] parts2 = {"list", "testtopic", "1"}; + String[] parts3 = {"revoke", "write", "read"}; + List parts = Arrays.asList(parts1, parts2, parts3); + for (Iterator iterator = parts.iterator(); iterator.hasNext(); ) { + String[] part = (String[]) iterator.next(); + + try { + command.execute(part, new MRCommandContext(), printStream); + } catch (CommandNotReadyException e) { + // TODO Auto-generated catch block + e.printStackTrace(); + } + assertTrue(true); + + } + } + + @Test + public void testExecute_error3() throws HttpObjectNotFoundException, HttpException, MRApiException, IOException { + PowerMockito.when(tm.getApiKey("testtopic")).thenThrow(new HttpException(500, "error")); + String[] parts1 = {"create", "testtopic", "1"}; + String[] parts2 = {"list", "testtopic", "1"}; + String[] parts3 = {"revoke", "write", "read"}; + List parts = Arrays.asList(parts1, parts2, parts3); + for (Iterator iterator = parts.iterator(); iterator.hasNext(); ) { + String[] part = (String[]) iterator.next(); + + try { + command.execute(part, new MRCommandContext(), printStream); + } catch (CommandNotReadyException e) { + // TODO Auto-generated catch block + e.printStackTrace(); + } + assertTrue(true); + } + + } + + @Test + public void testExecute_error4() throws HttpObjectNotFoundException, HttpException, MRApiException, IOException { + PowerMockito.when(tm.getApiKey("testtopic")).thenThrow(new HttpObjectNotFoundException("error")); + String[] parts1 = {"create", "testtopic", "1"}; + String[] parts2 = {"list", "testtopic", "1"}; + String[] parts3 = {"revoke", "write", "read"}; + List parts = Arrays.asList(parts1, parts2, parts3); + for (Iterator iterator = parts.iterator(); iterator.hasNext(); ) { + String[] part = (String[]) iterator.next(); + + try { + command.execute(part, new MRCommandContext(), printStream); + } catch (CommandNotReadyException e) { + // TODO Auto-generated catch block + e.printStackTrace(); + } + assertTrue(true); + + } + } + + @Test + public void testDisplayHelp() { + + command.displayHelp(printStream); + assertTrue(true); + + } } diff --git a/src/test/java/org/onap/dmaap/mr/tools/AuthCommandTest.java b/src/test/java/org/onap/dmaap/mr/tools/AuthCommandTest.java index e312d9b..4966f30 100644 --- a/src/test/java/org/onap/dmaap/mr/tools/AuthCommandTest.java +++ b/src/test/java/org/onap/dmaap/mr/tools/AuthCommandTest.java @@ -4,12 +4,14 @@ * ================================================================================ * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. * ================================================================================ + * Modifications Copyright © 2021 Orange. + * ================================================================================ * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at - * + * * http://www.apache.org/licenses/LICENSE-2.0 - * + * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. @@ -20,10 +22,7 @@ package org.onap.dmaap.mr.tools; -import static org.junit.Assert.assertTrue; - -import java.io.PrintStream; - +import com.att.nsa.cmdtool.CommandNotReadyException; import org.junit.After; import org.junit.Before; import org.junit.Test; @@ -34,82 +33,84 @@ import org.mockito.MockitoAnnotations; import org.powermock.core.classloader.annotations.PowerMockIgnore; import org.powermock.modules.junit4.PowerMockRunner; -import com.att.nsa.cmdtool.CommandNotReadyException; +import java.io.PrintStream; + +import static org.junit.Assert.assertTrue; @RunWith(PowerMockRunner.class) @PowerMockIgnore("jdk.internal.reflect.*") public class AuthCommandTest { - @InjectMocks - private AuthCommand command = null; - @Mock - private PrintStream printStream; + @InjectMocks + private AuthCommand command = null; + @Mock + private PrintStream printStream; - @Before - public void setUp() throws Exception { - MockitoAnnotations.initMocks(this); + @Before + public void setUp() throws Exception { + MockitoAnnotations.initMocks(this); - } + } - @After - public void tearDown() throws Exception { + @After + public void tearDown() throws Exception { - } + } - @Test - public void testGetMatches() { + @Test + public void testGetMatches() { - command.getMatches(); - assertTrue(true); + command.getMatches(); + assertTrue(true); - } + } - @Test - public void testCheckReady() { + @Test + public void testCheckReady() { - try { - command.checkReady(new MRCommandContext()); - } catch (CommandNotReadyException e) { - // TODO Auto-generated catch block - e.printStackTrace(); - } - assertTrue(true); + try { + command.checkReady(new MRCommandContext()); + } catch (CommandNotReadyException e) { + // TODO Auto-generated catch block + e.printStackTrace(); + } + assertTrue(true); - } + } - @Test - public void testExecute() { + @Test + public void testExecute() { - try { - String[] parts = new String[5]; - command.execute(parts, new MRCommandContext(), printStream); - } catch (CommandNotReadyException e) { - // TODO Auto-generated catch block - e.printStackTrace(); - } - assertTrue(true); + try { + String[] parts = new String[5]; + command.execute(parts, new MRCommandContext(), printStream); + } catch (CommandNotReadyException e) { + // TODO Auto-generated catch block + e.printStackTrace(); + } + assertTrue(true); - } + } - @Test - public void testExecute1() { + @Test + public void testExecute1() { - try { - String[] parts = { "userName", "password" }; - command.execute(parts, new MRCommandContext(), printStream); - } catch (CommandNotReadyException e) { - // TODO Auto-generated catch block - e.printStackTrace(); - } - assertTrue(true); + try { + String[] parts = {"userName", "password"}; + command.execute(parts, new MRCommandContext(), printStream); + } catch (CommandNotReadyException e) { + // TODO Auto-generated catch block + e.printStackTrace(); + } + assertTrue(true); - } + } - @Test - public void testDisplayHelp() { + @Test + public void testDisplayHelp() { - command.displayHelp(printStream); - assertTrue(true); + command.displayHelp(printStream); + assertTrue(true); - } + } } diff --git a/src/test/java/org/onap/dmaap/mr/tools/ClusterCommandTest.java b/src/test/java/org/onap/dmaap/mr/tools/ClusterCommandTest.java index 5d78488..e503e21 100644 --- a/src/test/java/org/onap/dmaap/mr/tools/ClusterCommandTest.java +++ b/src/test/java/org/onap/dmaap/mr/tools/ClusterCommandTest.java @@ -4,12 +4,14 @@ * ================================================================================ * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. * ================================================================================ + * Modifications Copyright © 2021 Orange. + * ================================================================================ * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at - * + * * http://www.apache.org/licenses/LICENSE-2.0 - * + * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. @@ -20,12 +22,7 @@ package org.onap.dmaap.mr.tools; -import static org.junit.Assert.assertTrue; - -import java.io.FileNotFoundException; -import java.io.PrintStream; -import java.util.Arrays; - +import com.att.nsa.cmdtool.CommandNotReadyException; import org.junit.After; import org.junit.Before; import org.junit.Test; @@ -37,72 +34,76 @@ import org.powermock.api.mockito.PowerMockito; import org.powermock.core.classloader.annotations.PowerMockIgnore; import org.powermock.modules.junit4.PowerMockRunner; -import com.att.nsa.cmdtool.CommandNotReadyException; +import java.io.FileNotFoundException; +import java.io.PrintStream; +import java.util.Arrays; + +import static org.junit.Assert.assertTrue; @RunWith(PowerMockRunner.class) @PowerMockIgnore("jdk.internal.reflect.*") public class ClusterCommandTest { - @InjectMocks - private ClusterCommand command; - @Mock - private MRCommandContext context; - @Mock - private PrintStream printStream; + @InjectMocks + private ClusterCommand command; + @Mock + private MRCommandContext context; + @Mock + private PrintStream printStream; - @Before - public void setUp() throws Exception { - MockitoAnnotations.initMocks(this); - PowerMockito.when(context.getCluster()).thenReturn(Arrays.asList("localhost")); - } + @Before + public void setUp() throws Exception { + MockitoAnnotations.initMocks(this); + PowerMockito.when(context.getCluster()).thenReturn(Arrays.asList("localhost")); + } - @After - public void tearDown() throws Exception { + @After + public void tearDown() throws Exception { - } + } - @Test - public void testGetMatches() { + @Test + public void testGetMatches() { - command.getMatches(); - assertTrue(true); + command.getMatches(); + assertTrue(true); - } + } - @Test - public void testCheckReady() { + @Test + public void testCheckReady() { - try { - command.checkReady(context); - } catch (CommandNotReadyException e) { - // TODO Auto-generated catch block - e.printStackTrace(); - } - assertTrue(true); + try { + command.checkReady(context); + } catch (CommandNotReadyException e) { + // TODO Auto-generated catch block + e.printStackTrace(); + } + assertTrue(true); - } + } - @Test - public void testExecute() throws FileNotFoundException, CommandNotReadyException { - String[] parts = { "create", "testtopic", "1", "1" }; - command.execute(parts, context, printStream); - assertTrue(true); + @Test + public void testExecute() throws FileNotFoundException, CommandNotReadyException { + String[] parts = {"create", "testtopic", "1", "1"}; + command.execute(parts, context, printStream); + assertTrue(true); - } + } - @Test - public void testExecute1() throws FileNotFoundException, CommandNotReadyException { - String[] parts = {}; - command.execute(parts, context, printStream); - assertTrue(true); + @Test + public void testExecute1() throws FileNotFoundException, CommandNotReadyException { + String[] parts = {}; + command.execute(parts, context, printStream); + assertTrue(true); - } + } - @Test - public void testDisplayHelp() { + @Test + public void testDisplayHelp() { - command.displayHelp(printStream); - assertTrue(true); + command.displayHelp(printStream); + assertTrue(true); - } + } } diff --git a/src/test/java/org/onap/dmaap/mr/tools/JUnitTestSuite.java b/src/test/java/org/onap/dmaap/mr/tools/JUnitTestSuite.java index 782dbb0..a0642ff 100644 --- a/src/test/java/org/onap/dmaap/mr/tools/JUnitTestSuite.java +++ b/src/test/java/org/onap/dmaap/mr/tools/JUnitTestSuite.java @@ -4,12 +4,14 @@ * ================================================================================ * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. * ================================================================================ + * Modifications Copyright © 2021 Orange. + * ================================================================================ * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at - * + * * http://www.apache.org/licenses/LICENSE-2.0 - * + * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. @@ -21,7 +23,6 @@ package org.onap.dmaap.mr.tools; import junit.framework.TestSuite; - import org.junit.runner.RunWith; import org.junit.runners.Suite; import org.junit.runners.Suite.SuiteClasses; @@ -29,18 +30,18 @@ import org.slf4j.Logger; import org.slf4j.LoggerFactory; @RunWith(Suite.class) -@SuiteClasses({ ApiKeyCommandTest.class, AuthCommandTest.class, ClusterCommandTest.class, - MessageCommandTest.class, MRCommandContextTest.class, TopicCommandTest.class, TraceCommandTest.class,}) +@SuiteClasses({ApiKeyCommandTest.class, AuthCommandTest.class, ClusterCommandTest.class, + MessageCommandTest.class, MRCommandContextTest.class, TopicCommandTest.class, TraceCommandTest.class,}) public class JUnitTestSuite { - private static final Logger LOGGER = LoggerFactory.getLogger(JUnitTestSuite.class); + private static final Logger logger = LoggerFactory.getLogger(JUnitTestSuite.class); + + public static void main(String[] args) { + logger.info("Running the test suite"); - public static void main(String[] args) { - LOGGER.info("Running the test suite"); - - TestSuite tstSuite = new TestSuite(); - LOGGER.info("Total Test Counts " + tstSuite.countTestCases()); - } + TestSuite tstSuite = new TestSuite(); + logger.info("Total Test Counts " + tstSuite.countTestCases()); + } } diff --git a/src/test/java/org/onap/dmaap/mr/tools/MRCommandContextTest.java b/src/test/java/org/onap/dmaap/mr/tools/MRCommandContextTest.java index 8e778d4..806f302 100644 --- a/src/test/java/org/onap/dmaap/mr/tools/MRCommandContextTest.java +++ b/src/test/java/org/onap/dmaap/mr/tools/MRCommandContextTest.java @@ -4,12 +4,14 @@ * ================================================================================ * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. * ================================================================================ + * Modifications Copyright © 2021 Orange. + * ================================================================================ * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at - * + * * http://www.apache.org/licenses/LICENSE-2.0 - * + * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. @@ -20,135 +22,134 @@ package org.onap.dmaap.mr.tools; -import static org.junit.Assert.assertTrue; - - import org.junit.After; import org.junit.Before; import org.junit.Test; +import static org.junit.Assert.assertTrue; + public class MRCommandContextTest { - private MRCommandContext command = null; - private String[] parts = new String[5]; + private MRCommandContext command = null; + private String[] parts = new String[5]; - @Before - public void setUp() throws Exception { - command = new MRCommandContext(); + @Before + public void setUp() throws Exception { + command = new MRCommandContext(); - for (int i = 0; i < parts.length; i++) { - parts[i] = "String" + (i + 1); - } + for (int i = 0; i < parts.length; i++) { + parts[i] = "String" + (i + 1); + } - } + } - @After - public void tearDown() throws Exception { + @After + public void tearDown() throws Exception { - } + } - @Test - public void testRequestShutdown() { + @Test + public void testRequestShutdown() { - command.requestShutdown(); - assertTrue(true); + command.requestShutdown(); + assertTrue(true); - } + } - @Test - public void testShouldContinue() { + @Test + public void testShouldContinue() { - command.shouldContinue(); - assertTrue(true); + command.shouldContinue(); + assertTrue(true); - } + } - @Test - public void testSetAuth() { + @Test + public void testSetAuth() { - command.setAuth("key", "pwd"); - assertTrue(true); + command.setAuth("key", "pwd"); + assertTrue(true); - } + } - @Test - public void testClearAuth() { + @Test + public void testClearAuth() { - command.clearAuth(); - assertTrue(true); + command.clearAuth(); + assertTrue(true); - } + } - @Test - public void testCheckClusterReady() { + @Test + public void testCheckClusterReady() { - command.checkClusterReady(); - assertTrue(true); + command.checkClusterReady(); + assertTrue(true); - } + } - @Test - public void testGetCluster() { + @Test + public void testGetCluster() { - command.getCluster(); - assertTrue(true); + command.getCluster(); + assertTrue(true); - } + } - @Test - public void testClearCluster() { + @Test + public void testClearCluster() { - command.clearCluster(); - assertTrue(true); + command.clearCluster(); + assertTrue(true); - } + } - @Test - public void testAddClusterHost() { + @Test + public void testAddClusterHost() { - command.addClusterHost("host"); - assertTrue(true); + command.addClusterHost("host"); + assertTrue(true); - } + } - @Test - public void testGetApiKey() { + @Test + public void testGetApiKey() { - command.getApiKey(); - assertTrue(true); + command.getApiKey(); + assertTrue(true); - } + } - @Test - public void testGetApiPwd() { + @Test + public void testGetApiPwd() { - command.getApiPwd(); - assertTrue(true); + command.getApiPwd(); + assertTrue(true); - } + } - @Test - public void testUseTracer() { + @Test + public void testUseTracer() { - command.useTracer(null); - assertTrue(true); + command.useTracer(null); + assertTrue(true); - } + } - @Test - public void testNoTracer() { + @Test + public void testNoTracer() { - command.noTracer(); - assertTrue(true); + command.noTracer(); + assertTrue(true); - } + } - @Test - public void testApplyTracer() { + @Test + public void testApplyTracer() { - command.applyTracer(null); - assertTrue(true); + command.applyTracer(null); + assertTrue(true); - } + } } diff --git a/src/test/java/org/onap/dmaap/mr/tools/MRTool.java b/src/test/java/org/onap/dmaap/mr/tools/MRTool.java new file mode 100644 index 0000000..022f2ee --- /dev/null +++ b/src/test/java/org/onap/dmaap/mr/tools/MRTool.java @@ -0,0 +1,49 @@ +/******************************************************************************* + * ============LICENSE_START======================================================= + * org.onap.dmaap + * ================================================================================ + * Copyright © 2017 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Modifications Copyright © 2021 Orange. + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============LICENSE_END========================================================= + * + * ECOMP is a trademark and service mark of AT&T Intellectual Property. + * + *******************************************************************************/ + +package org.onap.dmaap.mr.tools; + +import com.att.nsa.cmdtool.CommandLineTool; +import org.onap.dmaap.mr.client.impl.MRClientVersionInfo; + +import java.io.IOException; + +public class MRTool extends CommandLineTool { + protected MRTool() { + super("MR Tool (" + MRClientVersionInfo.getVersion() + ")", "MR> "); + + registerCommand(new ApiKeyCommand()); + registerCommand(new AuthCommand()); + registerCommand(new ClusterCommand()); + registerCommand(new MessageCommand()); + registerCommand(new TopicCommand()); + registerCommand(new TraceCommand()); + } + + public static void main(String[] args) throws IOException { + final MRTool ct = new MRTool(); + final MRCommandContext ccc = new MRCommandContext(); + ct.runFromMain(args, ccc); + } +} diff --git a/src/test/java/org/onap/dmaap/mr/tools/MessageCommandTest.java b/src/test/java/org/onap/dmaap/mr/tools/MessageCommandTest.java index 933ee48..c6c9af4 100644 --- a/src/test/java/org/onap/dmaap/mr/tools/MessageCommandTest.java +++ b/src/test/java/org/onap/dmaap/mr/tools/MessageCommandTest.java @@ -4,12 +4,14 @@ * ================================================================================ * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. * ================================================================================ + * Modifications Copyright © 2021 Orange. + * ================================================================================ * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at - * + * * http://www.apache.org/licenses/LICENSE-2.0 - * + * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. @@ -20,15 +22,7 @@ package org.onap.dmaap.mr.tools; -import static org.junit.Assert.assertTrue; - -import java.io.IOException; -import java.io.PrintStream; -import java.util.Arrays; -import java.util.Iterator; -import java.util.List; -import java.util.concurrent.TimeUnit; - +import com.att.nsa.cmdtool.CommandNotReadyException; import org.junit.After; import org.junit.Before; import org.junit.Test; @@ -36,181 +30,188 @@ import org.junit.runner.RunWith; import org.mockito.InjectMocks; import org.mockito.Mock; import org.mockito.MockitoAnnotations; +import org.onap.dmaap.mr.client.MRBatchingPublisher; +import org.onap.dmaap.mr.client.MRClientFactory; +import org.onap.dmaap.mr.client.MRConsumer; +import org.onap.dmaap.mr.client.MRTopicManager.TopicInfo; import org.powermock.api.mockito.PowerMockito; import org.powermock.core.classloader.annotations.PowerMockIgnore; import org.powermock.core.classloader.annotations.PrepareForTest; import org.powermock.modules.junit4.PowerMockRunner; -import com.att.nsa.cmdtool.CommandNotReadyException; -import org.onap.dmaap.mr.client.MRBatchingPublisher; -import org.onap.dmaap.mr.client.MRClientFactory; -import org.onap.dmaap.mr.client.MRConsumer; -import org.onap.dmaap.mr.client.MRTopicManager.TopicInfo; +import java.io.IOException; +import java.io.PrintStream; +import java.util.Arrays; +import java.util.Iterator; +import java.util.List; +import java.util.concurrent.TimeUnit; + +import static org.junit.Assert.assertTrue; @RunWith(PowerMockRunner.class) @PowerMockIgnore("jdk.internal.reflect.*") -@PrepareForTest({ MRClientFactory.class, ToolsUtil.class }) +@PrepareForTest({MRClientFactory.class, ToolsUtil.class}) public class MessageCommandTest { - @InjectMocks - private MessageCommand command; - @Mock - private MRConsumer tm; - @Mock - private TopicInfo ti; - @Mock - private MRBatchingPublisher pub; - @Mock - private MRConsumer cc; - @Mock - private PrintStream printStream; - - @Before - public void setUp() throws Exception { - MockitoAnnotations.initMocks(this); - PowerMockito.mockStatic(MRClientFactory.class); - PowerMockito.mockStatic(ToolsUtil.class); - PowerMockito.when(MRClientFactory.createConsumer(Arrays.asList("localhost"), "testtopic", "2", "3", -1, -1, - null, null, null)).thenReturn(cc); - - } - - @After - public void tearDown() throws Exception { - - } - - @Test - public void testGetMatches() { - - command.getMatches(); - assertTrue(true); - - } - - @Test - public void testCheckReady() { - - try { - command.checkReady(new MRCommandContext()); - } catch (CommandNotReadyException e) { - // TODO Auto-generated catch block - e.printStackTrace(); - } - assertTrue(true); - - } - - @Test - public void testExecute() { - - String[] parts1 = { "read", "testtopic", "2", "3" }; - String[] parts2 = { "write", "testtopic", "2", "3" }; - List parts = Arrays.asList(parts1, parts2); - for (Iterator iterator = parts.iterator(); iterator.hasNext();) { - String[] part = (String[]) iterator.next(); - - MRCommandContext context = new MRCommandContext(); - PowerMockito.when(ToolsUtil.createBatchPublisher(context, "testtopic")).thenReturn(pub); - try { - command.execute(part, context, printStream); - } catch (CommandNotReadyException e) { - assertTrue(true); - } - } - assertTrue(true); - - } - - @Test - public void testExecute_error1() { - try { - PowerMockito.doThrow(new Exception()).when(cc).fetch(); - } catch (IOException e) { - // TODO Auto-generated catch block - e.printStackTrace(); - } catch (Exception e) { - // TODO Auto-generated catch block - e.printStackTrace(); - } - String[] parts1 = { "read", "testtopic", "2", "3" }; - String[] parts2 = { "write", "testtopic", "2", "3" }; - List parts = Arrays.asList(parts1, parts2); - for (Iterator iterator = parts.iterator(); iterator.hasNext();) { - String[] part = (String[]) iterator.next(); - - MRCommandContext context = new MRCommandContext(); - PowerMockito.when(ToolsUtil.createBatchPublisher(context, "testtopic")).thenReturn(pub); - try { - command.execute(part, context, printStream); - } catch (CommandNotReadyException e) { - // TODO Auto-generated catch block - e.printStackTrace(); - } - } - assertTrue(true); - - } - - @Test - public void testExecute_error2() { - try { - PowerMockito.doThrow(new IOException()).when(pub).close(500, TimeUnit.MILLISECONDS); - PowerMockito.doThrow(new IOException()).when(pub).send("2", "3"); - - } catch (IOException e) { - // TODO Auto-generated catch block - e.printStackTrace(); - } catch (InterruptedException e) { - // TODO Auto-generated catch block - e.printStackTrace(); - } - String[] parts1 = { "read", "testtopic", "2", "3" }; - String[] parts2 = { "write", "testtopic", "2", "3" }; - List parts = Arrays.asList(parts1, parts2); - for (Iterator iterator = parts.iterator(); iterator.hasNext();) { - String[] part = (String[]) iterator.next(); - - MRCommandContext context = new MRCommandContext(); - PowerMockito.when(ToolsUtil.createBatchPublisher(context, "testtopic")).thenReturn(pub); - try { - command.execute(part, context, printStream); - } catch (CommandNotReadyException e) { - // TODO Auto-generated catch block - e.printStackTrace(); - } - } - assertTrue(true); - - } - - /* - * @Test public void testExecute_error3() { - * - * try { PowerMockito.doThrow(new IOException()).when(pub).send("2", "3"); - * PowerMockito.doThrow(new InterruptedException()).when(pub).close(500, - * TimeUnit.MILLISECONDS); } catch (IOException e) { // TODO Auto-generated - * catch block e.printStackTrace(); } catch (InterruptedException e) { // - * TODO Auto-generated catch block e.printStackTrace(); } String[] parts1 = - * { "read", "testtopic", "2", "3" }; String[] parts2 = { "write", - * "testtopic", "2", "3" }; List parts = Arrays.asList(parts1, - * parts2); for (Iterator iterator = parts.iterator(); iterator.hasNext();) - * { String[] part = (String[]) iterator.next(); PrintStream printStream = - * new PrintStream(System.out); - * - * MRCommandContext context = new MRCommandContext(); - * PowerMockito.when(ToolsUtil.createBatchPublisher(context, - * "testtopic")).thenReturn(pub); try { command.execute(part, context, - * printStream); } catch (CommandNotReadyException e) { // TODO - * Auto-generated catch block e.printStackTrace(); } } assertTrue(true); - * - * } - */ - - @Test - public void testDisplayHelp() { - - command.displayHelp(printStream); - - } + @InjectMocks + private MessageCommand command; + @Mock + private MRConsumer tm; + @Mock + private TopicInfo ti; + @Mock + private MRBatchingPublisher pub; + @Mock + private MRConsumer cc; + @Mock + private PrintStream printStream; + + @Before + public void setUp() throws Exception { + MockitoAnnotations.initMocks(this); + PowerMockito.mockStatic(MRClientFactory.class); + PowerMockito.mockStatic(ToolsUtil.class); + PowerMockito.when(MRClientFactory.createConsumer(Arrays.asList("localhost"), "testtopic", "2", "3", -1, -1, + null, null, null)).thenReturn(cc); + + } + + @After + public void tearDown() throws Exception { + + } + + @Test + public void testGetMatches() { + + command.getMatches(); + assertTrue(true); + + } + + @Test + public void testCheckReady() { + + try { + command.checkReady(new MRCommandContext()); + } catch (CommandNotReadyException e) { + // TODO Auto-generated catch block + e.printStackTrace(); + } + assertTrue(true); + + } + + @Test + public void testExecute() { + + String[] parts1 = {"read", "testtopic", "2", "3"}; + String[] parts2 = {"write", "testtopic", "2", "3"}; + List parts = Arrays.asList(parts1, parts2); + for (Iterator iterator = parts.iterator(); iterator.hasNext(); ) { + String[] part = (String[]) iterator.next(); + + MRCommandContext context = new MRCommandContext(); + PowerMockito.when(ToolsUtil.createBatchPublisher(context, "testtopic")).thenReturn(pub); + try { + command.execute(part, context, printStream); + } catch (CommandNotReadyException e) { + assertTrue(true); + } + } + assertTrue(true); + + } + + @Test + public void testExecute_error1() { + try { + PowerMockito.doThrow(new Exception()).when(cc).fetch(); + } catch (IOException e) { + // TODO Auto-generated catch block + e.printStackTrace(); + } catch (Exception e) { + // TODO Auto-generated catch block + e.printStackTrace(); + } + String[] parts1 = {"read", "testtopic", "2", "3"}; + String[] parts2 = {"write", "testtopic", "2", "3"}; + List parts = Arrays.asList(parts1, parts2); + for (Iterator iterator = parts.iterator(); iterator.hasNext(); ) { + String[] part = (String[]) iterator.next(); + + MRCommandContext context = new MRCommandContext(); + PowerMockito.when(ToolsUtil.createBatchPublisher(context, "testtopic")).thenReturn(pub); + try { + command.execute(part, context, printStream); + } catch (CommandNotReadyException e) { + // TODO Auto-generated catch block + e.printStackTrace(); + } + } + assertTrue(true); + + } + + @Test + public void testExecute_error2() { + try { + PowerMockito.doThrow(new IOException()).when(pub).close(500, TimeUnit.MILLISECONDS); + PowerMockito.doThrow(new IOException()).when(pub).send("2", "3"); + + } catch (IOException e) { + // TODO Auto-generated catch block + e.printStackTrace(); + } catch (InterruptedException e) { + // TODO Auto-generated catch block + e.printStackTrace(); + } + String[] parts1 = {"read", "testtopic", "2", "3"}; + String[] parts2 = {"write", "testtopic", "2", "3"}; + List parts = Arrays.asList(parts1, parts2); + for (Iterator iterator = parts.iterator(); iterator.hasNext(); ) { + String[] part = (String[]) iterator.next(); + + MRCommandContext context = new MRCommandContext(); + PowerMockito.when(ToolsUtil.createBatchPublisher(context, "testtopic")).thenReturn(pub); + try { + command.execute(part, context, printStream); + } catch (CommandNotReadyException e) { + // TODO Auto-generated catch block + e.printStackTrace(); + } + } + assertTrue(true); + + } + + /* + * @Test public void testExecute_error3() { + * + * try { PowerMockito.doThrow(new IOException()).when(pub).send("2", "3"); + * PowerMockito.doThrow(new InterruptedException()).when(pub).close(500, + * TimeUnit.MILLISECONDS); } catch (IOException e) { // TODO Auto-generated + * catch block e.printStackTrace(); } catch (InterruptedException e) { // + * TODO Auto-generated catch block e.printStackTrace(); } String[] parts1 = + * { "read", "testtopic", "2", "3" }; String[] parts2 = { "write", + * "testtopic", "2", "3" }; List parts = Arrays.asList(parts1, + * parts2); for (Iterator iterator = parts.iterator(); iterator.hasNext();) + * { String[] part = (String[]) iterator.next(); PrintStream printStream = + * new PrintStream(System.out); + * + * MRCommandContext context = new MRCommandContext(); + * PowerMockito.when(ToolsUtil.createBatchPublisher(context, + * "testtopic")).thenReturn(pub); try { command.execute(part, context, + * printStream); } catch (CommandNotReadyException e) { // TODO + * Auto-generated catch block e.printStackTrace(); } } assertTrue(true); + * + * } + */ + + @Test + public void testDisplayHelp() { + + command.displayHelp(printStream); + assertTrue(true); + } } diff --git a/src/test/java/org/onap/dmaap/mr/tools/TestRunner.java b/src/test/java/org/onap/dmaap/mr/tools/TestRunner.java index 2fd831b..3e2380f 100644 --- a/src/test/java/org/onap/dmaap/mr/tools/TestRunner.java +++ b/src/test/java/org/onap/dmaap/mr/tools/TestRunner.java @@ -4,12 +4,14 @@ * ================================================================================ * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. * ================================================================================ + * Modifications Copyright © 2021 Orange. + * ================================================================================ * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at - * + * * http://www.apache.org/licenses/LICENSE-2.0 - * + * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. @@ -28,17 +30,17 @@ import org.slf4j.Logger; import org.slf4j.LoggerFactory; public class TestRunner { - private static final Logger LOGGER = LoggerFactory.getLogger(TestRunner.class); + private static final Logger logger = LoggerFactory.getLogger(TestRunner.class); + + public static void main(String[] args) { + // TODO Auto-generated method stub + Result result = JUnitCore.runClasses(JUnitTestSuite.class); + for (Failure failure : result.getFailures()) { + logger.info(failure.toString()); - public static void main(String[] args) { - // TODO Auto-generated method stub - Result result = JUnitCore.runClasses(JUnitTestSuite.class); - for (Failure failure : result.getFailures()) { - LOGGER.info(failure.toString()); - - } - LOGGER.info(String.valueOf(result.wasSuccessful())); - } + } + logger.info(String.valueOf(result.wasSuccessful())); + } } diff --git a/src/test/java/org/onap/dmaap/mr/tools/ToolsUtilTest.java b/src/test/java/org/onap/dmaap/mr/tools/ToolsUtilTest.java index 080d6d5..115e007 100644 --- a/src/test/java/org/onap/dmaap/mr/tools/ToolsUtilTest.java +++ b/src/test/java/org/onap/dmaap/mr/tools/ToolsUtilTest.java @@ -4,6 +4,8 @@ * ================================================================================ * Copyright (C) 2018 Nokia * ================================================================================ + * Modifications Copyright © 2021 Orange. + * ================================================================================ * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at @@ -23,12 +25,13 @@ */ package org.onap.dmaap.mr.tools; -import org.onap.dmaap.mr.client.MRBatchingPublisher; -import java.util.Arrays; -import java.util.List; import org.junit.Assert; import org.junit.Test; import org.mockito.Mockito; +import org.onap.dmaap.mr.client.MRBatchingPublisher; + +import java.util.Arrays; +import java.util.List; public class ToolsUtilTest { diff --git a/src/test/java/org/onap/dmaap/mr/tools/TopicCommandTest.java b/src/test/java/org/onap/dmaap/mr/tools/TopicCommandTest.java index 4abd1e4..bcb95cd 100644 --- a/src/test/java/org/onap/dmaap/mr/tools/TopicCommandTest.java +++ b/src/test/java/org/onap/dmaap/mr/tools/TopicCommandTest.java @@ -4,12 +4,14 @@ * ================================================================================ * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. * ================================================================================ + * Modifications Copyright © 2021 Orange. + * ================================================================================ * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at - * + * * http://www.apache.org/licenses/LICENSE-2.0 - * + * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. @@ -20,14 +22,9 @@ package org.onap.dmaap.mr.tools; -import static org.junit.Assert.assertTrue; - -import java.io.IOException; -import java.io.PrintStream; -import java.util.Arrays; -import java.util.Iterator; -import java.util.List; - +import com.att.nsa.apiClient.http.HttpException; +import com.att.nsa.apiClient.http.HttpObjectNotFoundException; +import com.att.nsa.cmdtool.CommandNotReadyException; import org.junit.After; import org.junit.Before; import org.junit.Test; @@ -35,192 +32,196 @@ import org.junit.runner.RunWith; import org.mockito.InjectMocks; import org.mockito.Mock; import org.mockito.MockitoAnnotations; +import org.onap.dmaap.mr.client.MRClientFactory; +import org.onap.dmaap.mr.client.MRTopicManager; +import org.onap.dmaap.mr.client.MRTopicManager.TopicInfo; import org.powermock.api.mockito.PowerMockito; import org.powermock.core.classloader.annotations.PowerMockIgnore; import org.powermock.core.classloader.annotations.PrepareForTest; import org.powermock.modules.junit4.PowerMockRunner; -import com.att.nsa.apiClient.http.HttpException; -import com.att.nsa.apiClient.http.HttpObjectNotFoundException; -import com.att.nsa.cmdtool.CommandNotReadyException; -import org.onap.dmaap.mr.client.MRClientFactory; -import org.onap.dmaap.mr.client.MRTopicManager.TopicInfo; -import org.onap.dmaap.mr.client.MRTopicManager; +import java.io.IOException; +import java.io.PrintStream; +import java.util.Arrays; +import java.util.Iterator; +import java.util.List; + +import static org.junit.Assert.assertTrue; @RunWith(PowerMockRunner.class) @PowerMockIgnore("jdk.internal.reflect.*") -@PrepareForTest({ MRClientFactory.class }) +@PrepareForTest({MRClientFactory.class}) public class TopicCommandTest { - @InjectMocks - private TopicCommand command; - @Mock - private MRTopicManager tm; - @Mock - private TopicInfo ti; - @Mock - private PrintStream printStream; - - @Before - public void setUp() throws Exception { - - MockitoAnnotations.initMocks(this); - PowerMockito.mockStatic(MRClientFactory.class); - PowerMockito.when(MRClientFactory.createTopicManager(Arrays.asList("localhost"), null, null)).thenReturn(tm); - PowerMockito.when(tm.getTopicMetadata("testtopic")).thenReturn(ti); - - } - - @After - public void tearDown() throws Exception { - - } - - @Test - public void testGetMatches() { - - command.getMatches(); - assertTrue(true); - - } - - @Test - public void testCheckReady() { - - try { - command.checkReady(new MRCommandContext()); - } catch (CommandNotReadyException e) { - // TODO Auto-generated catch block - e.printStackTrace(); - } - assertTrue(true); - - } - - @Test - public void testExecute() { - - String[] parts1 = { "create", "testtopic", "1", "1" }; - String[] parts2 = { "grant", "write", "read", "1" }; - String[] parts3 = { "revoke", "write", "read", "1" }; - String[] parts4 = { "list", "testtopic", "1", "1" }; - List parts = Arrays.asList(parts1, parts2, parts3, parts4); - for (Iterator iterator = parts.iterator(); iterator.hasNext();) { - String[] part = (String[]) iterator.next(); - - try { - command.execute(part, new MRCommandContext(), printStream); - } catch (CommandNotReadyException e) { - // TODO Auto-generated catch block - e.printStackTrace(); - } - assertTrue(true); - - } - - } - - @Test - public void testExecute_error() { - - String[] parts1 = { "create", "testtopic", "1", "1" }; - String[] parts2 = { "grant", "write", "read", "1" }; - String[] parts3 = { "revoke", "write", "read", "1" }; - String[] parts4 = { "list", "testtopic", "1", "1" }; - List parts = Arrays.asList(parts1, parts2, parts3, parts4); - for (Iterator iterator = parts.iterator(); iterator.hasNext();) { - String[] part = (String[]) iterator.next(); - - try { - command.execute(part, new MRCommandContext(), printStream); - } catch (CommandNotReadyException e) { - // TODO Auto-generated catch block - e.printStackTrace(); - } - assertTrue(true); - - } - - } - - @Test - public void testExecute_error_1() throws com.att.nsa.apiClient.http.HttpException, IOException { - PowerMockito.when(tm.getTopicMetadata("testtopic")).thenThrow(new IOException("error")); - PowerMockito.doThrow(new IOException()).when(tm).createTopic("testtopic", "", 1, 1); - PowerMockito.doThrow(new IOException()).when(tm).revokeProducer("read", "1"); - String[] parts1 = { "create", "testtopic", "1", "1" }; - String[] parts2 = { "grant", "read", "read", "1" }; - String[] parts3 = { "revoke", "write", "read", "1" }; - String[] parts4 = { "list", "testtopic", "1", "1" }; - List parts = Arrays.asList(parts1, parts2, parts3, parts4); - for (Iterator iterator = parts.iterator(); iterator.hasNext();) { - String[] part = (String[]) iterator.next(); - - try { - command.execute(part, new MRCommandContext(), printStream); - } catch (CommandNotReadyException e) { - // TODO Auto-generated catch block - e.printStackTrace(); - } - assertTrue(true); - - } - - } - - @Test - public void testExecute_error_2() throws com.att.nsa.apiClient.http.HttpException, IOException { - PowerMockito.when(tm.getTopicMetadata("testtopic")).thenThrow(new HttpObjectNotFoundException("error")); - PowerMockito.doThrow(new HttpException(500, "error")).when(tm).createTopic("testtopic", "", 1, 1); - PowerMockito.doThrow(new HttpException(500, "error")).when(tm).revokeConsumer("read", "1"); - PowerMockito.doThrow(new HttpException(500, "error")).when(tm).allowConsumer("read", "1"); - String[] parts1 = { "create", "testtopic", "1", "1" }; - String[] parts2 = { "grant", "write", "write", "1" }; - String[] parts3 = { "revoke", "read", "read", "1" }; - String[] parts4 = { "list", "testtopic", "1", "1" }; - List parts = Arrays.asList(parts1, parts2, parts3, parts4); - for (Iterator iterator = parts.iterator(); iterator.hasNext();) { - String[] part = (String[]) iterator.next(); - - try { - command.execute(part, new MRCommandContext(), printStream); - } catch (CommandNotReadyException e) { - // TODO Auto-generated catch block - e.printStackTrace(); - } - assertTrue(true); - - } - - } - - @Test - public void testExecute_error_3() throws com.att.nsa.apiClient.http.HttpException, IOException { - PowerMockito.doThrow(new HttpException(500, "error")).when(tm).createTopic("testtopic", "", 1, 1); - PowerMockito.doThrow(new HttpException(500, "error")).when(tm).allowProducer("read", "1"); - String[] parts1 = { "create", "testtopic", "1a", "1a" }; - String[] parts2 = { "grant", "write", "read", "1" }; - List parts = Arrays.asList(parts1, parts2); - for (Iterator iterator = parts.iterator(); iterator.hasNext();) { - String[] part = (String[]) iterator.next(); - - try { - command.execute(part, new MRCommandContext(), printStream); - } catch (CommandNotReadyException e) { - // TODO Auto-generated catch block - e.printStackTrace(); - } - assertTrue(true); - - } - - } - - @Test - public void testDisplayHelp() { - - command.displayHelp(printStream); - assertTrue(true); - - } + @InjectMocks + private TopicCommand command; + @Mock + private MRTopicManager tm; + @Mock + private TopicInfo ti; + @Mock + private PrintStream printStream; + + @Before + public void setUp() throws Exception { + + MockitoAnnotations.initMocks(this); + PowerMockito.mockStatic(MRClientFactory.class); + PowerMockito.when(MRClientFactory.createTopicManager(Arrays.asList("localhost"), null, null)).thenReturn(tm); + PowerMockito.when(tm.getTopicMetadata("testtopic")).thenReturn(ti); + + } + + @After + public void tearDown() throws Exception { + + } + + @Test + public void testGetMatches() { + + command.getMatches(); + assertTrue(true); + + } + + @Test + public void testCheckReady() { + + try { + command.checkReady(new MRCommandContext()); + } catch (CommandNotReadyException e) { + // TODO Auto-generated catch block + e.printStackTrace(); + } + assertTrue(true); + + } + + @Test + public void testExecute() { + + String[] parts1 = {"create", "testtopic", "1", "1"}; + String[] parts2 = {"grant", "write", "read", "1"}; + String[] parts3 = {"revoke", "write", "read", "1"}; + String[] parts4 = {"list", "testtopic", "1", "1"}; + List parts = Arrays.asList(parts1, parts2, parts3, parts4); + for (Iterator iterator = parts.iterator(); iterator.hasNext(); ) { + String[] part = (String[]) iterator.next(); + + try { + command.execute(part, new MRCommandContext(), printStream); + } catch (CommandNotReadyException e) { + // TODO Auto-generated catch block + e.printStackTrace(); + } + assertTrue(true); + + } + + } + + @Test + public void testExecute_error() { + + String[] parts1 = {"create", "testtopic", "1", "1"}; + String[] parts2 = {"grant", "write", "read", "1"}; + String[] parts3 = {"revoke", "write", "read", "1"}; + String[] parts4 = {"list", "testtopic", "1", "1"}; + List parts = Arrays.asList(parts1, parts2, parts3, parts4); + for (Iterator iterator = parts.iterator(); iterator.hasNext(); ) { + String[] part = (String[]) iterator.next(); + + try { + command.execute(part, new MRCommandContext(), printStream); + } catch (CommandNotReadyException e) { + // TODO Auto-generated catch block + e.printStackTrace(); + } + assertTrue(true); + + } + + } + + @Test + public void testExecute_error_1() throws com.att.nsa.apiClient.http.HttpException, IOException { + PowerMockito.when(tm.getTopicMetadata("testtopic")).thenThrow(new IOException("error")); + PowerMockito.doThrow(new IOException()).when(tm).createTopic("testtopic", "", 1, 1); + PowerMockito.doThrow(new IOException()).when(tm).revokeProducer("read", "1"); + String[] parts1 = {"create", "testtopic", "1", "1"}; + String[] parts2 = {"grant", "read", "read", "1"}; + String[] parts3 = {"revoke", "write", "read", "1"}; + String[] parts4 = {"list", "testtopic", "1", "1"}; + List parts = Arrays.asList(parts1, parts2, parts3, parts4); + for (Iterator iterator = parts.iterator(); iterator.hasNext(); ) { + String[] part = (String[]) iterator.next(); + + try { + command.execute(part, new MRCommandContext(), printStream); + } catch (CommandNotReadyException e) { + // TODO Auto-generated catch block + e.printStackTrace(); + } + assertTrue(true); + + } + + } + + @Test + public void testExecute_error_2() throws com.att.nsa.apiClient.http.HttpException, IOException { + PowerMockito.when(tm.getTopicMetadata("testtopic")).thenThrow(new HttpObjectNotFoundException("error")); + PowerMockito.doThrow(new HttpException(500, "error")).when(tm).createTopic("testtopic", "", 1, 1); + PowerMockito.doThrow(new HttpException(500, "error")).when(tm).revokeConsumer("read", "1"); + PowerMockito.doThrow(new HttpException(500, "error")).when(tm).allowConsumer("read", "1"); + String[] parts1 = {"create", "testtopic", "1", "1"}; + String[] parts2 = {"grant", "write", "write", "1"}; + String[] parts3 = {"revoke", "read", "read", "1"}; + String[] parts4 = {"list", "testtopic", "1", "1"}; + List parts = Arrays.asList(parts1, parts2, parts3, parts4); + for (Iterator iterator = parts.iterator(); iterator.hasNext(); ) { + String[] part = (String[]) iterator.next(); + + try { + command.execute(part, new MRCommandContext(), printStream); + } catch (CommandNotReadyException e) { + // TODO Auto-generated catch block + e.printStackTrace(); + } + assertTrue(true); + + } + + } + + @Test + public void testExecute_error_3() throws com.att.nsa.apiClient.http.HttpException, IOException { + PowerMockito.doThrow(new HttpException(500, "error")).when(tm).createTopic("testtopic", "", 1, 1); + PowerMockito.doThrow(new HttpException(500, "error")).when(tm).allowProducer("read", "1"); + String[] parts1 = {"create", "testtopic", "1a", "1a"}; + String[] parts2 = {"grant", "write", "read", "1"}; + List parts = Arrays.asList(parts1, parts2); + for (Iterator iterator = parts.iterator(); iterator.hasNext(); ) { + String[] part = (String[]) iterator.next(); + + try { + command.execute(part, new MRCommandContext(), printStream); + } catch (CommandNotReadyException e) { + // TODO Auto-generated catch block + e.printStackTrace(); + } + assertTrue(true); + + } + + } + + @Test + public void testDisplayHelp() { + + command.displayHelp(printStream); + assertTrue(true); + + } } diff --git a/src/test/java/org/onap/dmaap/mr/tools/TraceCommandTest.java b/src/test/java/org/onap/dmaap/mr/tools/TraceCommandTest.java index ab4d670..ae97c1e 100644 --- a/src/test/java/org/onap/dmaap/mr/tools/TraceCommandTest.java +++ b/src/test/java/org/onap/dmaap/mr/tools/TraceCommandTest.java @@ -4,12 +4,14 @@ * ================================================================================ * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. * ================================================================================ + * Modifications Copyright © 2021 Orange. + * ================================================================================ * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at - * + * * http://www.apache.org/licenses/LICENSE-2.0 - * + * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. @@ -20,10 +22,7 @@ package org.onap.dmaap.mr.tools; -import static org.junit.Assert.assertTrue; - -import java.io.PrintStream; - +import com.att.nsa.cmdtool.CommandNotReadyException; import org.junit.After; import org.junit.Before; import org.junit.Test; @@ -34,71 +33,73 @@ import org.mockito.MockitoAnnotations; import org.powermock.core.classloader.annotations.PowerMockIgnore; import org.powermock.modules.junit4.PowerMockRunner; -import com.att.nsa.cmdtool.CommandNotReadyException; +import java.io.PrintStream; + +import static org.junit.Assert.assertTrue; @RunWith(PowerMockRunner.class) @PowerMockIgnore("jdk.internal.reflect.*") public class TraceCommandTest { - @InjectMocks - private TraceCommand command; - private String[] parts = new String[5]; - @Mock - private PrintStream printStream; + @InjectMocks + private TraceCommand command; + private String[] parts = new String[5]; + @Mock + private PrintStream printStream; - @Before - public void setUp() throws Exception { - MockitoAnnotations.initMocks(this); - for (int i = 0; i < parts.length; i++) { - parts[i] = "String" + (i + 1); - } + @Before + public void setUp() throws Exception { + MockitoAnnotations.initMocks(this); + for (int i = 0; i < parts.length; i++) { + parts[i] = "String" + (i + 1); + } - } + } - @After - public void tearDown() throws Exception { + @After + public void tearDown() throws Exception { - } + } - @Test - public void testGetMatches() { + @Test + public void testGetMatches() { - command.getMatches(); - assertTrue(true); + command.getMatches(); + assertTrue(true); - } + } - @Test - public void testCheckReady() { + @Test + public void testCheckReady() { - try { - command.checkReady(new MRCommandContext()); - } catch (CommandNotReadyException e) { - // TODO Auto-generated catch block - e.printStackTrace(); - } - assertTrue(true); + try { + command.checkReady(new MRCommandContext()); + } catch (CommandNotReadyException e) { + // TODO Auto-generated catch block + e.printStackTrace(); + } + assertTrue(true); - } + } - @Test - public void testExecute() { + @Test + public void testExecute() { - try { - command.execute(parts, new MRCommandContext(), printStream); - } catch (CommandNotReadyException e) { - // TODO Auto-generated catch block - e.printStackTrace(); - } - assertTrue(true); + try { + command.execute(parts, new MRCommandContext(), printStream); + } catch (CommandNotReadyException e) { + // TODO Auto-generated catch block + e.printStackTrace(); + } + assertTrue(true); - } + } - @Test - public void testDisplayHelp() { + @Test + public void testDisplayHelp() { - command.displayHelp(printStream); - assertTrue(true); + command.displayHelp(printStream); + assertTrue(true); - } + } } diff --git a/src/test/java/org/onap/dmaap/mr/tools/ValidatorUtilTest.java b/src/test/java/org/onap/dmaap/mr/tools/ValidatorUtilTest.java index baa5440..198f828 100644 --- a/src/test/java/org/onap/dmaap/mr/tools/ValidatorUtilTest.java +++ b/src/test/java/org/onap/dmaap/mr/tools/ValidatorUtilTest.java @@ -4,11 +4,13 @@ * ================================================================================ * Copyright © 2018 IBM Intellectual Property. All rights reserved. * ================================================================================ + * Modifications Copyright © 2021 Orange. + * ================================================================================ * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * http://www.apache.org/licenses/LICENSE-2.0 - * + * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. @@ -17,192 +19,244 @@ * ============LICENSE_END========================================================= * * ECOMP is a trademark and service mark of AT&T Intellectual Property. - * + * *******************************************************************************/ package org.onap.dmaap.mr.tools; -import static org.junit.Assert.assertEquals; +import org.junit.Test; +import org.onap.dmaap.mr.client.ProtocolType; import java.util.Properties; -import org.junit.Test; - -import org.onap.dmaap.mr.test.clients.ProtocolTypeConstants; +import static org.junit.Assert.*; public class ValidatorUtilTest { @Test public void testValidateForDME2WithNullServiceName() { Properties props = new Properties(); - props.setProperty("TransportType", ProtocolTypeConstants.DME2.getValue()); - try{ + props.setProperty("TransportType", ProtocolType.DME2.getValue()); + try { ValidatorUtil.validatePublisher(props); - } catch(IllegalArgumentException e) { - assertEquals(e.getMessage(), "Servicename is needed"); + fail(); + } catch (IllegalArgumentException e) { + assertEquals("ServiceName is needed", e.getMessage()); } } - + @Test public void testValidateForDME2WithNullTopic() { Properties props = new Properties(); - props.setProperty("TransportType", ProtocolTypeConstants.DME2.getValue()); + props.setProperty("TransportType", ProtocolType.DME2.getValue()); props.setProperty("ServiceName", "ServiceName"); - try{ + try { ValidatorUtil.validatePublisher(props); - } catch(IllegalArgumentException e) { - assertEquals(e.getMessage(), "topic is needed"); + fail(); + } catch (IllegalArgumentException e) { + assertEquals("topic is needed", e.getMessage()); } - + } - + @Test public void testValidateForDME2WithNullUserName() { Properties props = new Properties(); - props.setProperty("TransportType", ProtocolTypeConstants.DME2.getValue()); + props.setProperty("TransportType", ProtocolType.DME2.getValue()); props.setProperty("ServiceName", "ServiceName"); props.setProperty("topic", "topic"); - try{ + try { ValidatorUtil.validatePublisher(props); - } catch(IllegalArgumentException e) { - assertEquals(e.getMessage(), "username is needed"); + fail(); + } catch (IllegalArgumentException e) { + assertEquals("username is needed", e.getMessage()); } - + } - + @Test public void testValidateForDME2WithNullPassword() { Properties props = new Properties(); - props.setProperty("TransportType", ProtocolTypeConstants.DME2.getValue()); + props.setProperty("TransportType", ProtocolType.DME2.getValue()); props.setProperty("ServiceName", "ServiceName"); props.setProperty("topic", "topic"); props.setProperty("username", "username"); - - try{ + + try { ValidatorUtil.validatePublisher(props); - } catch(IllegalArgumentException e) { - assertEquals(e.getMessage(), "password is needed"); + fail(); + } catch (IllegalArgumentException e) { + assertEquals("password is needed", e.getMessage()); } - + } - - - - + + @Test public void testValidateForNonDME2WithNullServiceName() { Properties props = new Properties(); - props.setProperty("TransportType", ProtocolTypeConstants.AUTH_KEY.getValue()); - try{ + props.setProperty("TransportType", ProtocolType.AUTH_KEY.getValue()); + try { ValidatorUtil.validatePublisher(props); - } catch(IllegalArgumentException e) { - assertEquals(e.getMessage(), "Servicename is needed"); + fail(); + } catch (IllegalArgumentException e) { + assertEquals("host is needed", e.getMessage()); } - + } - + @Test public void testValidateForNonDME2WithNullTopic() { Properties props = new Properties(); - props.setProperty("TransportType", ProtocolTypeConstants.AUTH_KEY.getValue()); + props.setProperty("TransportType", ProtocolType.AUTH_KEY.getValue()); props.setProperty("host", "ServiceName"); - try{ + try { ValidatorUtil.validatePublisher(props); - } catch(IllegalArgumentException e) { - assertEquals(e.getMessage(), "topic is needed"); + fail(); + } catch (IllegalArgumentException e) { + assertEquals("topic is needed", e.getMessage()); } - + } - + @Test public void testValidateForNonDME2WithNullContenttype() { Properties props = new Properties(); - props.setProperty("TransportType", ProtocolTypeConstants.AUTH_KEY.getValue()); + props.setProperty("TransportType", ProtocolType.AUTH_KEY.getValue()); props.setProperty("host", "ServiceName"); props.setProperty("topic", "topic"); - try{ + try { ValidatorUtil.validatePublisher(props); - } catch(IllegalArgumentException e) { - assertEquals(e.getMessage(), "contenttype is needed"); + fail(); + } catch (IllegalArgumentException e) { + assertEquals("contenttype is needed", e.getMessage()); } - + } - + @Test public void testValidateForNonDME2WithNullUserName() { Properties props = new Properties(); - props.setProperty("TransportType", ProtocolTypeConstants.AUTH_KEY.getValue()); + props.setProperty("TransportType", ProtocolType.AUTH_KEY.getValue()); props.setProperty("host", "ServiceName"); props.setProperty("topic", "topic"); props.setProperty("contenttype", "contenttype"); - try{ + try { ValidatorUtil.validatePublisher(props); - } catch(IllegalArgumentException e) { - assertEquals(e.getMessage(), "username is needed"); + fail(); + } catch (IllegalArgumentException e) { + assertEquals("username is needed", e.getMessage()); } - + } - + @Test public void testValidateForNonDME2WithNullPassword() { Properties props = new Properties(); - props.setProperty("TransportType", ProtocolTypeConstants.AUTH_KEY.getValue()); + props.setProperty("TransportType", ProtocolType.AUTH_KEY.getValue()); props.setProperty("host", "ServiceName"); props.setProperty("topic", "topic"); props.setProperty("username", "username"); props.setProperty("contenttype", "contenttype"); - - try{ + + try { ValidatorUtil.validatePublisher(props); - } catch(IllegalArgumentException e) { - assertEquals(e.getMessage(), "password is needed"); + fail(); + } catch (IllegalArgumentException e) { + assertEquals("password is needed", e.getMessage()); } - + } - + @Test public void testValidateForNonDME2WithAuthKey() { Properties props = new Properties(); - props.setProperty("TransportType", ProtocolTypeConstants.AUTH_KEY.getValue()); + props.setProperty("TransportType", ProtocolType.AUTH_KEY.getValue()); props.setProperty("host", "ServiceName"); props.setProperty("topic", "topic"); props.setProperty("username", "username"); props.setProperty("contenttype", "contenttype"); props.setProperty("password", "password"); - - try{ + + try { ValidatorUtil.validatePublisher(props); - } catch(IllegalArgumentException e) { - assertEquals(e.getMessage(), "authKey is needed"); + fail(); + } catch (IllegalArgumentException e) { + assertEquals("authKey is needed", e.getMessage()); } - + } - + @Test public void testValidateForNonDME2WithOutAuthDate() { Properties props = new Properties(); - props.setProperty("TransportType", ProtocolTypeConstants.AUTH_KEY.getValue()); + props.setProperty("TransportType", ProtocolType.AUTH_KEY.getValue()); props.setProperty("host", "ServiceName"); props.setProperty("topic", "topic"); props.setProperty("username", "username"); props.setProperty("contenttype", "contenttype"); props.setProperty("password", "password"); props.setProperty("authKey", "authKey"); - - - try{ + + + try { ValidatorUtil.validatePublisher(props); - } catch(IllegalArgumentException e) { - assertEquals(e.getMessage(), "authDate is needed"); + fail(); + } catch (IllegalArgumentException e) { + assertEquals("authDate is needed", e.getMessage()); } } - + @Test public void testValidateForNonDME2WithAuthDate() { Properties props = new Properties(); - props.setProperty("TransportType", ProtocolTypeConstants.AUTH_KEY.getValue()); + props.setProperty("TransportType", ProtocolType.AUTH_KEY.getValue()); + props.setProperty("host", "ServiceName"); + props.setProperty("topic", "topic"); + props.setProperty("username", "username"); + props.setProperty("contenttype", "contenttype"); + props.setProperty("password", "password"); + props.setProperty("authKey", "authKey"); + props.setProperty("authDate", "authDate"); + + try { + ValidatorUtil.validatePublisher(props); + fail(); + } catch (IllegalArgumentException e) { + assertEquals("maxBatchSize is needed", e.getMessage()); + } + } + + + @Test + public void testValidateForNonDME2WithMaxAgeMs() { + Properties props = new Properties(); + props.setProperty("TransportType", ProtocolType.AUTH_KEY.getValue()); + props.setProperty("host", "ServiceName"); + props.setProperty("topic", "topic"); + props.setProperty("username", "username"); + props.setProperty("contenttype", "contenttype"); + props.setProperty("password", "password"); + props.setProperty("authKey", "authKey"); + props.setProperty("authDate", "authDate"); + props.setProperty("maxBatchSize", "maxBatchSize"); + + try { + ValidatorUtil.validatePublisher(props); + fail(); + } catch (IllegalArgumentException e) { + assertEquals("maxAgeMs is needed", e.getMessage()); + } + + + } + + @Test + public void testValidateForNonDME2WithMessageSentThreadOccurrence() { + Properties props = new Properties(); + props.setProperty("TransportType", ProtocolType.AUTH_KEY.getValue()); props.setProperty("host", "ServiceName"); props.setProperty("topic", "topic"); props.setProperty("username", "username"); @@ -210,106 +264,95 @@ public class ValidatorUtilTest { props.setProperty("password", "password"); props.setProperty("authKey", "authKey"); props.setProperty("authDate", "authDate"); - - try{ + props.setProperty("maxBatchSize", "maxBatchSize"); + props.setProperty("maxAgeMs", "maxAgeMs"); + + try { ValidatorUtil.validatePublisher(props); - } catch(IllegalArgumentException e) { - assertEquals(e.getMessage(), "maxBatchSize is needed"); + fail(); + } catch (IllegalArgumentException e) { + assertEquals("MessageSentThreadOccurrence is needed", e.getMessage()); } + } - - - @Test - public void testValidateForNonDME2WithMaxAgeMs() { - Properties props = new Properties(); - props.setProperty("TransportType", ProtocolTypeConstants.AUTH_KEY.getValue()); - props.setProperty("host", "ServiceName"); - props.setProperty("topic", "topic"); - props.setProperty("username", "username"); - props.setProperty("contenttype", "contenttype"); - props.setProperty("password", "password"); - props.setProperty("authKey", "authKey"); - props.setProperty("authDate", "authDate"); - props.setProperty("maxBatchSize", "maxBatchSize"); - - try{ - ValidatorUtil.validatePublisher(props); - } catch(IllegalArgumentException e) { - assertEquals(e.getMessage(), "maxAgeMs is needed"); - } - - - + + + @Test + public void testValidateSubscriberWithoutGroup() { + Properties props = new Properties(); + props.setProperty("TransportType", ProtocolType.AUTH_KEY.getValue()); + props.setProperty("host", "ServiceName"); + props.setProperty("topic", "topic"); + props.setProperty("username", "username"); + props.setProperty("contenttype", "contenttype"); + props.setProperty("password", "password"); + props.setProperty("authKey", "authKey"); + props.setProperty("authDate", "authDate"); + props.setProperty("maxBatchSize", "maxBatchSize"); + props.setProperty("maxAgeMs", "maxAgeMs"); + + try { + ValidatorUtil.validateSubscriber(props); + fail(); + } catch (IllegalArgumentException e) { + assertEquals("group is needed", e.getMessage()); + } } - - @Test - public void testValidateForNonDME2WithMessageSentThreadOccurance() { - Properties props = new Properties(); - props.setProperty("TransportType", ProtocolTypeConstants.AUTH_KEY.getValue()); - props.setProperty("host", "ServiceName"); - props.setProperty("topic", "topic"); - props.setProperty("username", "username"); - props.setProperty("contenttype", "contenttype"); - props.setProperty("password", "password"); - props.setProperty("authKey", "authKey"); - props.setProperty("authDate", "authDate"); - props.setProperty("maxBatchSize", "maxBatchSize"); - props.setProperty("maxAgeMs", "maxAgeMs"); - - try{ - ValidatorUtil.validatePublisher(props); - } catch(IllegalArgumentException e) { - assertEquals(e.getMessage(), "MessageSentThreadOccurance is needed"); - } - + + @Test + public void testValidateSubscriberWithoutCustomer() { + Properties props = new Properties(); + props.setProperty("TransportType", ProtocolType.AUTH_KEY.getValue()); + props.setProperty("host", "ServiceName"); + props.setProperty("topic", "topic"); + props.setProperty("username", "username"); + props.setProperty("contenttype", "contenttype"); + props.setProperty("password", "password"); + props.setProperty("authKey", "authKey"); + props.setProperty("authDate", "authDate"); + props.setProperty("maxBatchSize", "maxBatchSize"); + props.setProperty("maxAgeMs", "maxAgeMs"); + props.setProperty("group", "group"); + + try { + ValidatorUtil.validateSubscriber(props); + fail(); + } catch (IllegalArgumentException e) { + assertEquals("Consumer (id) is needed", e.getMessage()); } - - - @Test - public void testValidateSubscriberWithoutGroup() { - Properties props = new Properties(); - props.setProperty("TransportType", ProtocolTypeConstants.AUTH_KEY.getValue()); - props.setProperty("host", "ServiceName"); - props.setProperty("topic", "topic"); - props.setProperty("username", "username"); - props.setProperty("contenttype", "contenttype"); - props.setProperty("password", "password"); - props.setProperty("authKey", "authKey"); - props.setProperty("authDate", "authDate"); - props.setProperty("maxBatchSize", "maxBatchSize"); - props.setProperty("maxAgeMs", "maxAgeMs"); - - try{ - ValidatorUtil.validateSubscriber(props); - } catch(IllegalArgumentException e) { - assertEquals(e.getMessage(), "group is needed"); - } - } - - @Test - public void testValidateSubscriberWithoutCustomer() { - Properties props = new Properties(); - props.setProperty("TransportType", ProtocolTypeConstants.AUTH_KEY.getValue()); - props.setProperty("host", "ServiceName"); - props.setProperty("topic", "topic"); - props.setProperty("username", "username"); - props.setProperty("contenttype", "contenttype"); - props.setProperty("password", "password"); - props.setProperty("authKey", "authKey"); - props.setProperty("authDate", "authDate"); - props.setProperty("maxBatchSize", "maxBatchSize"); - props.setProperty("maxAgeMs", "maxAgeMs"); - props.setProperty("group", "group"); - - try{ - ValidatorUtil.validateSubscriber(props); - } catch(IllegalArgumentException e) { - assertEquals(e.getMessage(), "Consumer (Id) is needed"); - } - } - - - - - + } + + @Test + public void testValidatePublisher() { + Properties props = new Properties(); + props.setProperty("TransportType", ProtocolType.AUTH_KEY.getValue()); + props.setProperty("host", "ServiceName"); + props.setProperty("topic", "topic"); + props.setProperty("username", "username"); + props.setProperty("contenttype", "contenttype"); + props.setProperty("password", "password"); + props.setProperty("authKey", "authKey"); + props.setProperty("authDate", "authDate"); + props.setProperty("maxBatchSize", "maxBatchSize"); + props.setProperty("maxAgeMs", "maxAgeMs"); + props.setProperty("MessageSentThreadOccurrence", "10"); + + try { + ValidatorUtil.validatePublisher(props); + } catch (IllegalArgumentException e) { + fail(); + return; + } + + props.remove("MessageSentThreadOccurrence"); + props.setProperty("MessageSentThreadOccurance", "10"); + try { + ValidatorUtil.validatePublisher(props); + } catch (IllegalArgumentException e) { + fail(); + } + } + + + } diff --git a/src/test/resources/dme2/consumer.properties b/src/test/resources/dme2/consumer.properties index 34b87fe..08a5908 100644 --- a/src/test/resources/dme2/consumer.properties +++ b/src/test/resources/dme2/consumer.properties @@ -2,7 +2,7 @@ # ============LICENSE_START======================================================= # org.onap.dmaap # ================================================================================ -# Copyright © 2017 AT&T Intellectual Property. All rights reserved. +# Copyright © 2017 AT&T Intellectual Property. All rights reserved. # ================================================================================ # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. diff --git a/src/test/resources/dme2/producer.properties b/src/test/resources/dme2/producer.properties index 5ea5cfe..d293d43 100644 --- a/src/test/resources/dme2/producer.properties +++ b/src/test/resources/dme2/producer.properties @@ -2,7 +2,9 @@ # ============LICENSE_START======================================================= # org.onap.dmaap # ================================================================================ -# Copyright © 2017 AT&T Intellectual Property. All rights reserved. +# Copyright © 2017 AT&T Intellectual Property. All rights reserved. +# ================================================================================ +# Modifications Copyright © 2021 Orange. # ================================================================================ # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. @@ -49,4 +51,4 @@ AFT_DME2_ROUNDTRIP_TIMEOUT_MS=240000 AFT_DME2_EP_READ_TIMEOUT_MS=50000 sessionstickinessrequired=NO #DME2preferredRouterFilePath=C:/Users/rn509j/ONAP/dmaapclient/target/classes/dme2/preferredRoute.txt -MessageSentThreadOccurance=50 +MessageSentThreadOccurrence=50 -- cgit 1.2.3-korg