diff options
-rw-r--r-- | bundleconfig-local/etc/appprops/MsgRtrApi.properties | 2 | ||||
-rw-r--r-- | docs/Installation/Installation.rst | 59 | ||||
-rw-r--r-- | docs/offeredapis/offeredapis.rst | 71 | ||||
-rw-r--r-- | pom.xml | 139 | ||||
-rw-r--r-- | src/main/java/org/onap/dmaap/service/MMRestService.java | 823 | ||||
-rw-r--r-- | src/main/resources/docker/Dockerfile | 37 | ||||
-rw-r--r-- | src/main/resources/docker/startup.sh | 3 | ||||
-rw-r--r-- | src/test/java/org/onap/dmaap/service/AdminRestServiceTest.java | 52 | ||||
-rw-r--r-- | src/test/java/org/onap/dmaap/service/EventsRestServiceTest.java | 18 | ||||
-rw-r--r-- | src/test/java/org/onap/dmaap/service/MMRestServiceTest.java | 487 | ||||
-rw-r--r-- | src/test/java/org/onap/dmaap/util/ContentLengthInterceptorTest.java | 19 | ||||
-rw-r--r-- | version.properties | 2 |
12 files changed, 1161 insertions, 551 deletions
diff --git a/bundleconfig-local/etc/appprops/MsgRtrApi.properties b/bundleconfig-local/etc/appprops/MsgRtrApi.properties index 8e1cd6e..3aef922 100644 --- a/bundleconfig-local/etc/appprops/MsgRtrApi.properties +++ b/bundleconfig-local/etc/appprops/MsgRtrApi.properties @@ -149,7 +149,7 @@ maxcontentlength=10000 #AAF Properties msgRtr.namespace.aaf=org.onap.dmaap.mr.topic msgRtr.topicfactory.aaf=org.onap.dmaap.mr.topicFactory|:org.onap.dmaap.mr.topic: -enforced.topic.name.AAF=org.onap +enforced.topic.name.AAF=org.onap.dmaap.mr forceAAF=false transidUEBtopicreqd=false defaultNSforUEB=org.onap.dmaap.mr diff --git a/docs/Installation/Installation.rst b/docs/Installation/Installation.rst index 83f5b6f..53d9fd2 100644 --- a/docs/Installation/Installation.rst +++ b/docs/Installation/Installation.rst @@ -61,3 +61,62 @@ Testing Note: You will only receive messages which have been published after
you have subscribed to a topic.
+
+
+Steps for local development and test
+------------------------
+On Intel dev machine, in terminal (> indicates prompt) :
+1) Build kafka11aaf
+ > git clone https://gerrit.onap.org/r/dmaap/kafka
+ > cd kafka11aaf
+ > mvn clean install -Pdocker
+2) Build messageservice
+ > git clone https://gerrit.onap.org/r/dmaap/messagerouter/messageservice
+ - anonymous http, can't push changes
+ > cd messageservice
+ > mvn clean install -Pdocker
+3) Run tests
+ > cp bundleconfig-local/etc/appprops/MsgRtrApi.properties /var/tmp/
+ - edit /var/tmp/MsgRtrApi.properties
+ config.zk.servers=zookeeper
+ kafka.metadata.broker.list=kafka:9092
+ - docker-compose network maps service name(zookeeper, kafka) to IP
+ - set docker preferences/file sharing to access /var/tmp
+ > cd src/main/resources/docker-compose
+ - edit docker-compose.yml
+ - remove "nexus3.onap.org:10001/" from kafka and dmaap image names to
+ use local images
+ > docker-compose up -d
+ - create sample.txt file (as above)(content of file not important)
+ > curl -H "Content-Type:text/plain" -X POST -d @sample.txt http://localhost:3904/events/TestTopic1
+
+On Arm:
+1) Build kafka11aaf
+ > git clone https://gerrit.onap.org/r/dmaap/kafka
+ > cd kafka11aaf
+ > mvn clean install -Pdocker -Ddocker.pull.registry=docker.io
+ - ensure we pull Arm version of base image
+2) Build messageservice
+ > git clone https://gerrit.onap.org/r/dmaap/messagerouter/messageservice
+ - anonymous http, can't push changes
+ > cd messageservice
+ > mvn clean install -Pdocker -Ddocker.pull.registry=docker.io
+ - ensure we pull Arm version of base image
+3) Run tests
+ > cp bundleconfig-local/etc/appprops/MsgRtrApi.properties /var/tmp/
+ - edit /var/tmp/MsgRtrApi.properties
+ config.zk.servers=zookeeper
+ kafka.metadata.broker.list=kafka:9092
+ - docker-compose network maps service name(zookeeper, kafka) to IP
+ - set docker preferences/file sharing to access /var/tmp
+ > cd src/main/resources/docker-compose
+ - edit docker-compose.yml
+ - remove "nexus3.onap.org:10001/" from from kafka and dmaap image names to
+ use local images
+ - replace 'nexus3.onap.org:10001/onap/dmaap/zookeeper:1.0.0' with
+ multi-platform 'zookeeper'
+ > docker-compose up -d
+ - create sample.txt file (as above)(content of file not important)
+ > curl -H "Content-Type:text/plain" -X POST -d @sample.txt http://localhost:3904/events/TestTopic1
+
+
diff --git a/docs/offeredapis/offeredapis.rst b/docs/offeredapis/offeredapis.rst index 120f80f..0428850 100644 --- a/docs/offeredapis/offeredapis.rst +++ b/docs/offeredapis/offeredapis.rst @@ -70,9 +70,7 @@ The MessageRouter service has no requirements on what publishers can put onto a topic. The messages are opaque to the service and are treated as raw bytes. In general, passing JSON messages is preferred, but this is due to higher-level features and related systems, not the MessageRouter -broker itself. The only constraint placed on messages is their on their -size � messages must be under the maximum size, which is currently -configured at 1 MB. +broker itself. Request URL =========== @@ -85,7 +83,7 @@ Request Parameters +--------------------+------------------------------+------------------+------------+-----------+-------------+--------------------------------+-----------------------------+ | Name | Description | Param Type | Data type | Max Len | Required | Format | Valid/EXample values | +====================+==============================+==================+============+===========+=============+================================+=============================+ -| Topicname | topic name to be posted | Path | String | 40 | Y | <app namespace>.<topicname> | org.onap.crm.empdetails | +| Topicname | topic name to be posted | Path | String | 40 | Y | | org.onap.dmaap.mr.testtopic | +--------------------+------------------------------+------------------+------------+-----------+-------------+--------------------------------+-----------------------------+ | content-type | To specify type of message | Header | String | 20 | N | | application/json | +--------------------+------------------------------+------------------+------------+-----------+-------------+--------------------------------+-----------------------------+ @@ -96,8 +94,9 @@ Request Parameters | partitionKey | | QueryParam | String | | N | String value | ?Partitionkey=123 | +--------------------+------------------------------+------------------+------------+-----------+-------------+--------------------------------+-----------------------------+ -**NOTE**: Publishers/user should have access on the topics. The user (id) and -permissions details needs to be in AAF. +**NOTE**: To publish data to the authenticated topic, Publisher must + have the AAF permission org.onap.dmaap.mr.topic|:topic.<topic name>|pub. +Publishers may use DMaaP BusController for provisoning the AAF permissions Response Parameters =================== @@ -202,7 +201,7 @@ Request Parameters: +--------------+---------------------------------+------------------+------------+--------------+-------------+---------------------+------------------------+ | Name | Description | Param Type | data type | MaxLen | Required | Format | Valid/Example Values | +==============+=================================+==================+============+==============+=============+=====================+========================+ -| Topicname | topic name to be posted | Path | String | 40 | Y | namespace.String | | +| Topicname | topic name to be posted | Path | String | 40 | Y | | | +--------------+---------------------------------+------------------+------------+--------------+-------------+---------------------+------------------------+ | Consumer | A name that uniquely identifies | Path | String | | Y | | CG1 | | group | your subscribers | | | | | | | @@ -219,8 +218,9 @@ Request Parameters: | Password | | Header | String | 1 | N | | | +--------------+---------------------------------+------------------+------------+--------------+-------------+---------------------+------------------------+ -**NOTE1**:Subscribers /user should have access on the topics. The user () and -permissions details needs to be in AAF. +**NOTE**:To read data from a authenticated topic, User must have the +AAF permission org.onap.dmaap.mr.topic|:topic.<topic name>|sub. +Subscribers may use DMaaP BusController for provisoning the permissions in AAF Response Parameters: ==================== @@ -292,7 +292,8 @@ Sample Request: Provisioning ------------ -**Description**: To create , modify or delete the MessageRouter topics. Generally Invenio application will use these below apis to create , assign topics to the users. These APIs can also be used by other applications to provision topics in MessageRouter +**Description**: To create , modify or delete the MessageRouter topics.These APIs can also be used by other applications to provision topics in MessageRouter. +DMaaP BusController is recommended for topic and AAf permissions provisoning Create Topic ============ @@ -307,7 +308,7 @@ Request Parameters: +-------------------+---------------------------------+------------------+------------+--------------+-------------+-------------+-----------------------------------+ | Name | Description | Param Type | datatype | MaxLen | Required | Format | Valid/Example Values | +===================+=================================+==================+============+==============+=============+=============+===================================+ -| Topicname | topicname to be created in MR | Body | String | 20 | Y | Json | com.att.dmaap.mr.metrics | +| Topicname | topicname to be created in MR | Body | String | 20 | Y | Json | org.onap.dmaap.mr.metrics | +-------------------+---------------------------------+------------------+------------+--------------+-------------+-------------+-----------------------------------+ | topicDescription | description for topic | Body | String | 15 | Y | | | +-------------------+---------------------------------+------------------+------------+--------------+-------------+-------------+-----------------------------------+ @@ -321,6 +322,10 @@ Request Parameters: | Content-Type | application/json | Header | String | | | | application/json | +-------------------+---------------------------------+------------------+------------+--------------+-------------+-------------+-----------------------------------+ +**NOTE**:To Create a authenticated topic, user must have the AAF permission + org.onap.dmaap.mr.topicFactory|:org.onap.dmaap.mr.topic:org.onap.dmaap.mr|create + + +---------------------------+------------------------------------+ | Response statusCode | Response statusMessage | +===========================+====================================+ @@ -371,19 +376,19 @@ Sample Request: POST http://<hostname>:3904/topic/create Request Body - {"topicName":"com.abc.dmaap.mr.topicname","description":"This is a SAPTopic ", + {"topicName":"org.onap.dmaap.mr.testtopic","description":"This is a test Topic ", "partitionCount":"1","replicationCount":"3","transactionEnabled":"true"} Content-Type: application/json Example: curl -u XXXc@csp.abc.com:xxxxx$ -H 'Content-Type:application/json' -X POST -d - @topicname.txt http://mrlocal00.dcae.proto.research.abc.com:3904/topics/create + @topicname.txt http://message-router:3904/topics/create { "writerAcl": { "enabled": false, "users": [] }, "description": "This is a TestTopic", - "name": "com.abc.ecomp_test.crm.Load9", + "name": "org.onap.dmaap.mr.testtopic", "readerAcl": { "enabled": false, "users": [] @@ -405,25 +410,28 @@ Request Parameters +--------------------------+-------------------------+------------------+------------+-----------+-------------+-----------------+-----------------------------+ | Name | Description | Param Type | Data type | Max Len | Required | Format | Valid/EXample values | +==========================+=========================+==================+============+===========+=============+=================+=============================+ -| Topicname | topic name details | Body | String | 20 | Y | Json | com.abc.dmaap.mr.metrics | +| Topicname | topic name details | Body | String | 20 | Y | Json | org.onap.dmaap.mr.testtopic | +--------------------------+-------------------------+------------------+------------+-----------+-------------+-----------------+-----------------------------+ +**NOTE**:To view a authenticated topic, user must have the AAF permission + org.onap.dmaap.mr.topic|*|view + Response Parameters ==================== -+------------------+------------------------+------------+----------+---------+--------------------------+ -| Name | Description | ParamType | datatype |Format | Valid/Example Values | -+==================+========================+============+==========+=========+==========================+ -| topicname | topic name details | Body | String | Json | com.abc.dmaap.mr.metrics | -+------------------+------------------------+------------+----------+---------+--------------------------+ -| description | | | String | | | -+------------------+------------------------+------------+----------+---------+--------------------------+ -| owner |user id who created the | | | | | -| | topic | | | | | -+------------------+------------------------+------------+----------+---------+--------------------------+ -| txenabled | true or false | | boolean | | | -+------------------+------------------------+------------+----------+---------+--------------------------+ ++------------------+------------------------+------------+----------+---------+----------------------------+ +| Name | Description | ParamType | datatype |Format | Valid/Example Values | ++==================+========================+============+==========+=========+============================+ +| topicname | topic name details | Body | String | Json | org.onap.dmaap.mr.testopic | ++------------------+------------------------+------------+----------+---------+----------------------------+ +| description | | | String | | | ++------------------+------------------------+------------+----------+---------+----------------------------+ +| owner |user id who created the | | | | | +| | topic | | | | | ++------------------+------------------------+------------+----------+---------+----------------------------+ +| txenabled | true or false | | boolean | | | ++------------------+------------------------+------------+----------+---------+----------------------------+ +---------------------------+------------------------------------+ | Response statusCode | Response statusMessage | @@ -444,8 +452,8 @@ Sample Request: | curl -u XXX@csp.abc.com:x$ -X | | GET http://mrlocal00.dcae.proto.research.att.com:3904/topics | | {"topics": [ | -| {"txenabled": true,"description": "This is a TestTopic","owner": "XXXX@csp.abc.com","topicName": "com.abc.ecomp_test.crm.Load9"| -| {"txenabled": false,"description": "", "owner": "", "topicName": "com.abc.ecomp_test.crm.Load1" | +| {"txenabled": true,"description": "This is a TestTopic","owner": "XXXX@csp.abc.com","topicName": "org.onap.dmaap.mr.Load9"| +| {"txenabled": false,"description": "", "owner": "", "topicName": "org.onap.dmaap.mr.Load1" | | ]}, | +-----------------------------------------------------------------------------------------------------------------------------------+ @@ -458,9 +466,12 @@ Request URL: DELETE http(s)://{HOST:PORT}/topic/{topicname} +**NOTE**:To delete a topic, user must have the AAF permission +org.onap.dmaap.mr.topicFactory|:org.onap.dmaap.mr.topic:org.onap.dmaap.mr|destroy + Sample Request: =============== -ex: http://<hostname>:3904/dmaap/v1/topics/com.att.dmaap.mr.testopic +ex: http://<hostname>:3904/dmaap/v1/topics/org.onap.dmaap.mr.testopic +---------------------------+------------------------------------+ | Response statusCode | Response statusMessage | @@ -21,7 +21,7 @@ <groupId>org.onap.dmaap.messagerouter.messageservice</groupId> <artifactId>dmaapMR1</artifactId> - <version>1.1.11-SNAPSHOT</version> + <version>1.1.12-SNAPSHOT</version> <name>dmaap-messagerouter-messageservice</name> <description>Message Router - Restful interface built for kafka</description> <licenses> @@ -47,6 +47,7 @@ <build> <plugins> + <plugin> <groupId>org.apache.maven.plugins</groupId> <artifactId>maven-site-plugin</artifactId> @@ -100,97 +101,9 @@ </dependency> </dependencies> </plugin> + <plugin> - <groupId>com.spotify</groupId> - <artifactId>docker-maven-plugin</artifactId> - <version>1.0.0</version> - <configuration> - <imageName>onap/dmaap/dmaap-mr</imageName> - <dockerDirectory>${dockerLocation}</dockerDirectory> - <serverId>docker-hub</serverId> - <imageTags> - <imageTag>${dockertag1}</imageTag> - <imageTag>${dockertag2}</imageTag> - </imageTags> - <forceTags>true</forceTags> - <resources> - <resource> - <targetPath>/</targetPath> - <directory>${dockerLocation}</directory> - <include>${project.build.finalName}.jar</include> - </resource> - <resource> - <targetPath>/</targetPath> - <directory>${project.build.directory}</directory> - <include>**/**</include> - </resource> - </resources> - </configuration> - <executions> - <execution> - <id>build-image</id> - <phase>install</phase> - <goals> - <goal>build</goal> - </goals> - <configuration> - <skipDockerBuild>${skip.docker.build}</skipDockerBuild> - </configuration> - </execution> - - <execution> - <id>tag-image-project-version</id> - <phase>install</phase> - <goals> - <goal>tag</goal> - </goals> - <configuration> - <image>onap/dmaap/dmaap-mr</image> - <newName>${docker.push.registry}/onap/dmaap/dmaap-mr:${dockertag2}</newName> - <skipDockerTag>${skip.docker.push}</skipDockerTag> - </configuration> - </execution> - - <execution> - <id>tag-image-latest</id> - <phase>install</phase> - <goals> - <goal>tag</goal> - </goals> - <configuration> - <image>onap/dmaap/dmaap-mr</image> - <newName>${docker.push.registry}/onap/dmaap/dmaap-mr:${dockertag1}</newName> - <skipDockerTag>${skip.docker.push}</skipDockerTag> - </configuration> - </execution> - - <execution> - <id>push-image-latest</id> - <phase>deploy</phase> - <goals> - <goal>push</goal> - </goals> - <configuration> - <imageName>${docker.push.registry}/onap/dmaap/dmaap-mr:${dockertag2}</imageName> - <skipDockerPush>${skip.docker.push}</skipDockerPush> - </configuration> - </execution> - - <execution> - <id>push-image</id> - <phase>deploy</phase> - <goals> - <goal>push</goal> - </goals> - <configuration> - <imageName>${docker.push.registry}/onap/dmaap/dmaap-mr:${dockertag1}</imageName> - <skipDockerPush>${skip.docker.push}</skipDockerPush> - </configuration> - </execution> - </executions> - </plugin> - <plugin> <groupId>com.blackducksoftware.integration</groupId> <artifactId>hub-maven-plugin</artifactId> <version>1.0.4</version> @@ -267,6 +180,7 @@ <camel.version>2.21.1</camel.version> <sitePath>/content/sites/site/org/onap/dmaap/messagerouter/messageservice/${project.artifactId}/${project.version}</sitePath> <skip.docker.build>true</skip.docker.build> + <skip.docker.tag>true</skip.docker.tag> <skip.docker.push>true</skip.docker.push> <nexusproxy>https://nexus.onap.org</nexusproxy> <docker.push.registry>nexus3.onap.org:10003</docker.push.registry> @@ -763,8 +677,49 @@ </execution> </executions> </plugin> - </plugins> - </build> + <plugin> + <groupId>io.fabric8</groupId> + <artifactId>docker-maven-plugin</artifactId> + <version>0.28.0</version> + <configuration> + <verbose>${docker.verbose}</verbose> + <apiVersion>${docker.apiVersion}</apiVersion> + <pullRegistry>${docker.pull.registry}</pullRegistry> + <pushRegistry>${docker.push.registry}</pushRegistry> + <images> + <image> + <name>onap/dmaap/dmaap-mr</name> + <build> + <cleanup>try</cleanup> + <dockerFileDir>${dockerLocation}</dockerFileDir> + <dockerFile>Dockerfile</dockerFile> + <tags> + <tag>${dockertag1}</tag> + <tag>${dockertag2}</tag> + </tags> + </build> + </image> + </images> + </configuration> + <executions> + <execution> + <id>generate-images</id> + <phase>install</phase> + <goals> + <goal>build</goal> + </goals> + </execution> + <execution> + <id>push-images</id> + <phase>deploy</phase> + <goals> + <goal>push</goal> + </goals> + </execution> + </executions> + </plugin> + </plugins> + </build> </profile> <profile> diff --git a/src/main/java/org/onap/dmaap/service/MMRestService.java b/src/main/java/org/onap/dmaap/service/MMRestService.java index fc3c9a1..c5874ae 100644 --- a/src/main/java/org/onap/dmaap/service/MMRestService.java +++ b/src/main/java/org/onap/dmaap/service/MMRestService.java @@ -19,7 +19,7 @@ * ECOMP is a trademark and service mark of AT&T Intellectual Property. * *******************************************************************************/ - package org.onap.dmaap.service; +package org.onap.dmaap.service; import java.io.IOException; import java.io.InputStream; @@ -36,6 +36,8 @@ import javax.ws.rs.core.Context; import org.json.JSONObject; import org.apache.commons.io.IOUtils; import org.apache.commons.lang.StringUtils; +import org.apache.http.HttpStatus; + import com.att.eelf.configuration.EELFLogger; import com.att.eelf.configuration.EELFManager; import org.springframework.beans.factory.annotation.Autowired; @@ -63,6 +65,8 @@ import org.json.JSONException; import org.onap.dmaap.dmf.mr.beans.DMaaPContext; import org.onap.dmaap.dmf.mr.constants.CambriaConstants; import org.onap.dmaap.dmf.mr.exception.DMaaPErrorMessages; +import org.onap.dmaap.dmf.mr.exception.DMaaPResponseCode; +import org.onap.dmaap.dmf.mr.exception.ErrorResponse; import org.onap.dmaap.dmf.mr.metabroker.Broker.TopicExistsException; import org.onap.dmaap.dmf.mr.security.DMaaPAAFAuthenticator; import org.onap.dmaap.dmf.mr.security.DMaaPAAFAuthenticatorImpl; @@ -115,6 +119,10 @@ public class MMRestService { @Autowired private DMaaPErrorMessages errorMessages; + private ErrorResponse errResJson = new ErrorResponse(HttpStatus.SC_BAD_REQUEST, + DMaaPResponseCode.INCORRECT_JSON.getResponseCode(), "", null, Utils.getFormattedDate(new Date()), topic, + null, null, "mirrorMakerAgent", null); + private DMaaPAAFAuthenticator dmaapAAFauthenticator = new DMaaPAAFAuthenticatorImpl(); /** @@ -139,11 +147,11 @@ public class MMRestService { @POST @Produces("application/json") @Path("/create") - public void callCreateMirrorMaker(InputStream msg) { + public void callCreateMirrorMaker(InputStream msg) throws Exception { DMaaPContext ctx = getDmaapContext(); if (checkMirrorMakerPermission(ctx, - AJSCPropertiesMap.getProperty(CambriaConstants.msgRtr_prop, MIRROR_MAKERADMIN))) { + AJSCPropertiesMap.getProperty(CambriaConstants.msgRtr_prop, "msgRtr.mirrormakeradmin.aaf"))) { loadProperty(); String input = null; @@ -152,9 +160,9 @@ public class MMRestService { InputStream inStream = null; Gson gson = new Gson(); CreateMirrorMaker createMirrorMaker = new CreateMirrorMaker(); - + LOGGER.info("Starting Create MirrorMaker"); try { - input = IOUtils.toString(msg, UTF_8); + input = IOUtils.toString(msg, "UTF-8"); if (input != null && input.length() > 0) { input = removeExtraChar(input); @@ -166,76 +174,92 @@ public class MMRestService { } catch (JsonSyntaxException ex) { - sendErrResponse(ctx, errorMessages.getIncorrectJson()); - LOGGER.error("JsonSyntaxException: ", ex); + errResJson.setErrorMessage(errorMessages.getIncorrectJson() + ex.getMessage()); + LOGGER.info(errResJson.toString()); + throw new CambriaApiException(errResJson); } - String name = createMirrorMaker.getCreateMirrorMaker()==null? "":createMirrorMaker.getCreateMirrorMaker().getName(); + // send error message if it is not a CreateMirrorMaker request. if (createMirrorMaker.getCreateMirrorMaker() == null) { - sendErrResponse(ctx, "This is not a CreateMirrorMaker request. Please try again."); - } - // MirrorMaker whitelist and status should not be passed - else if (createMirrorMaker.getCreateMirrorMaker().getWhitelist() != null - || createMirrorMaker.getCreateMirrorMaker().getStatus() != null) { - sendErrResponse(ctx, "This is not a CreateMirrorMaker request. Please try again."); + errResJson.setErrorMessage("This is not a CreateMirrorMaker request. Please try again."); + LOGGER.info(errResJson.toString()); + throw new CambriaApiException(errResJson); + } else { + createMirrorMaker.validateJSON(); } + String name = createMirrorMaker.getCreateMirrorMaker().getName(); + // if empty, blank name is entered - else if (StringUtils.isBlank(name)) { - sendErrResponse(ctx, "Name can not be empty or blank."); + if (StringUtils.isBlank(name)) { + + errResJson.setErrorMessage("Name can not be empty or blank."); + LOGGER.info(errResJson.toString()); + throw new CambriaApiException(errResJson); } // Check if the name contains only Alpha Numeric else if (!isAlphaNumeric(name)) { - sendErrResponse(ctx, NAME_DOES_NOT_MEET_REQUIREMENT); - } + errResJson.setErrorMessage(NAME_DOES_NOT_MEET_REQUIREMENT); + LOGGER.info(errResJson.toString()); + throw new CambriaApiException(errResJson); - // Validate the IP and Port - else if (!StringUtils.isBlank(createMirrorMaker.getCreateMirrorMaker().getConsumer()) - && !StringUtils.isBlank(createMirrorMaker.getCreateMirrorMaker().getProducer()) - && !validateIPPort(createMirrorMaker.getCreateMirrorMaker().getConsumer()) - || !validateIPPort(createMirrorMaker.getCreateMirrorMaker().getProducer())) { - sendErrResponse(ctx, INVALID_IPPORT); + } else { - } - // Set a random number as messageID, convert Json Object to - // InputStream and finally call publisher and subscriber - else if (isAlphaNumeric(name) && validateIPPort(createMirrorMaker.getCreateMirrorMaker().getConsumer()) - && validateIPPort(createMirrorMaker.getCreateMirrorMaker().getProducer())) { + if (null == createMirrorMaker.getMessageID() || createMirrorMaker.getMessageID().isEmpty()) { + createMirrorMaker.setMessageID(randomStr); + } + inStream = IOUtils.toInputStream(gson.toJson(createMirrorMaker), "UTF-8"); + JSONObject existMirrorMaker = validateMMExists(ctx, name); + if (!(boolean) existMirrorMaker.get("exists")) { + JSONObject finalJsonObj = callPubSub(createMirrorMaker.getMessageID(), ctx, inStream, name, + false); + DMaaPResponseBuilder.respondOk(ctx, finalJsonObj); + } else { + + errResJson.setErrorMessage("MirrorMaker " + name + " already exists"); + LOGGER.info(errResJson.toString()); + throw new CambriaApiException(errResJson); - createMirrorMaker.setMessageID(randomStr); - inStream = IOUtils.toInputStream(gson.toJson(createMirrorMaker), UTF_8); - callPubSub(randomStr, ctx, inStream); + } } } catch (IOException e) { - LOGGER.error("IOException: ", e); + throw e; } } // Send error response if user does not provide Authorization else { - sendErrResponse(ctx, NO_ADMIN_PERMISSION); + ErrorResponse errRes = new ErrorResponse(HttpStatus.SC_UNAUTHORIZED, + DMaaPResponseCode.ACCESS_NOT_PERMITTED.getResponseCode(), NO_ADMIN_PERMISSION, null, + Utils.getFormattedDate(new Date()), topic, null, null, "mirrorMakerAgent", + ctx.getRequest().getRemoteHost()); + LOGGER.info(errRes.toString()); + throw new CambriaApiException(errRes); } + } @POST @Produces("application/json") @Path("/listall") - public void callListAllMirrorMaker(InputStream msg) { + public void callListAllMirrorMaker(InputStream msg) throws Exception { + DMaaPContext ctx = getDmaapContext(); if (checkMirrorMakerPermission(ctx, - AJSCPropertiesMap.getProperty(CambriaConstants.msgRtr_prop, MIRROR_MAKERADMIN))) { + AJSCPropertiesMap.getProperty(CambriaConstants.msgRtr_prop, "msgRtr.mirrormakeradmin.aaf"))) { loadProperty(); String input = null; + Gson gson = new Gson(); try { - input = IOUtils.toString(msg, UTF_8); + input = IOUtils.toString(msg, "UTF-8"); if (input != null && input.length() > 0) { input = removeExtraChar(input); @@ -248,51 +272,67 @@ public class MMRestService { jsonOb = new JSONObject(input); } catch (JSONException ex) { - - sendErrResponse(ctx, errorMessages.getIncorrectJson()); - LOGGER.error("JSONException: ", ex); + errResJson.setErrorMessage(errorMessages.getIncorrectJson()); + LOGGER.info(errResJson.toString()); + throw new CambriaApiException(errResJson); } // Check if request has listAllMirrorMaker and // listAllMirrorMaker is empty - if ((jsonOb != null) && (jsonOb.has("listAllMirrorMaker") - && jsonOb.getJSONObject("listAllMirrorMaker").length() == 0)) { - jsonOb.put("messageID", randomStr); + if (jsonOb.has("listAllMirrorMaker") && jsonOb.getJSONObject("listAllMirrorMaker").length() == 0) { + + if (!jsonOb.has("messageID") || jsonOb.isNull("messageID")) { + jsonOb.put("messageID", randomStr); + } + InputStream inStream = null; + MirrorMaker mirrormaker = gson.fromJson(input, MirrorMaker.class); try { - inStream = IOUtils.toInputStream(jsonOb.toString(), UTF_8); + inStream = IOUtils.toInputStream(jsonOb.toString(), "UTF-8"); } catch (IOException ioe) { - LOGGER.error("IOException: ", ioe); + throw ioe; } - callPubSub(randomStr, ctx, inStream); + JSONObject responseJson = callPubSub(jsonOb.getString("messageID"), ctx, inStream, mirrormaker.name, + true); + DMaaPResponseBuilder.respondOk(ctx, responseJson); } else { - sendErrResponse(ctx, "This is not a ListAllMirrorMaker request. Please try again."); + ErrorResponse errRes = new ErrorResponse(HttpStatus.SC_SERVICE_UNAVAILABLE, + DMaaPResponseCode.SERVER_UNAVAILABLE.getResponseCode(), + "This is not a ListAllMirrorMaker request. Please try again.", null, + Utils.getFormattedDate(new Date()), topic, null, null, "mirrorMakerAgent", + ctx.getRequest().getRemoteHost()); + LOGGER.info(errRes.toString()); + throw new CambriaApiException(errRes); } } catch (IOException ioe) { - LOGGER.error("IOException: ", ioe); + throw ioe; } } else { - sendErrResponse(getDmaapContext(), NO_ADMIN_PERMISSION); + ErrorResponse errRes = new ErrorResponse(HttpStatus.SC_UNAUTHORIZED, + DMaaPResponseCode.ACCESS_NOT_PERMITTED.getResponseCode(), NO_ADMIN_PERMISSION, null, + Utils.getFormattedDate(new Date()), topic, null, null, "mirrorMakerAgent", + ctx.getRequest().getRemoteHost()); + LOGGER.info(errRes.toString()); + throw new CambriaApiException(errRes); } } @POST @Produces("application/json") @Path("/update") - public void callUpdateMirrorMaker(InputStream msg) { - + public void callUpdateMirrorMaker(InputStream msg) throws Exception { DMaaPContext ctx = getDmaapContext(); if (checkMirrorMakerPermission(ctx, - AJSCPropertiesMap.getProperty(CambriaConstants.msgRtr_prop, MIRROR_MAKERADMIN))) { + AJSCPropertiesMap.getProperty(CambriaConstants.msgRtr_prop, "msgRtr.mirrormakeradmin.aaf"))) { loadProperty(); String input = null; @@ -301,9 +341,10 @@ public class MMRestService { InputStream inStream = null; Gson gson = new Gson(); UpdateMirrorMaker updateMirrorMaker = new UpdateMirrorMaker(); + JSONObject jsonOb, jsonObInput = null; try { - input = IOUtils.toString(msg, UTF_8); + input = IOUtils.toString(msg, "UTF-8"); if (input != null && input.length() > 0) { input = removeExtraChar(input); @@ -312,80 +353,109 @@ public class MMRestService { // Check if the request has UpdateMirrorMaker try { updateMirrorMaker = gson.fromJson(input, UpdateMirrorMaker.class); + jsonOb = new JSONObject(input); + jsonObInput = (JSONObject) jsonOb.get("updateMirrorMaker"); } catch (JsonSyntaxException ex) { - sendErrResponse(ctx, errorMessages.getIncorrectJson()); - LOGGER.error("JsonSyntaxException: ", ex); - + errResJson.setErrorMessage(errorMessages.getIncorrectJson() + ex.getMessage()); + LOGGER.info(errResJson.toString()); + throw new CambriaApiException(errResJson); } - String name = updateMirrorMaker.getUpdateMirrorMaker()==null? "":updateMirrorMaker.getUpdateMirrorMaker().getName(); + // send error message if it is not a UpdateMirrorMaker request. if (updateMirrorMaker.getUpdateMirrorMaker() == null) { - sendErrResponse(ctx, "This is not a UpdateMirrorMaker request. Please try again."); - } - // MirrorMaker whitelist and status should not be passed - else if (updateMirrorMaker.getUpdateMirrorMaker().getWhitelist() != null - || updateMirrorMaker.getUpdateMirrorMaker().getStatus() != null) { - sendErrResponse(ctx, "This is not a UpdateMirrorMaker request. Please try again."); + errResJson.setErrorMessage("This is not a UpdateMirrorMaker request. Please try again."); + LOGGER.info(errResJson.toString()); + throw new CambriaApiException(errResJson); + } else { + updateMirrorMaker.validateJSON(jsonObInput); } + String name = updateMirrorMaker.getUpdateMirrorMaker().getName(); // if empty, blank name is entered - else if (StringUtils.isBlank(name)) { - sendErrResponse(ctx, "Name can not be empty or blank."); + if (StringUtils.isBlank(name)) { + + errResJson.setErrorMessage("Name can not be empty or blank."); + LOGGER.info(errResJson.toString()); + throw new CambriaApiException(errResJson); } // Check if the name contains only Alpha Numeric else if (!isAlphaNumeric(name)) { - sendErrResponse(ctx, NAME_DOES_NOT_MEET_REQUIREMENT); + errResJson.setErrorMessage(NAME_DOES_NOT_MEET_REQUIREMENT); + LOGGER.info(errResJson.toString()); + throw new CambriaApiException(errResJson); } - // Validate the IP and Port - else if (!StringUtils.isBlank(updateMirrorMaker.getUpdateMirrorMaker().getConsumer()) - && !StringUtils.isBlank(updateMirrorMaker.getUpdateMirrorMaker().getProducer()) - && !validateIPPort(updateMirrorMaker.getUpdateMirrorMaker().getConsumer()) - || !validateIPPort(updateMirrorMaker.getUpdateMirrorMaker().getProducer())) { - sendErrResponse(ctx, INVALID_IPPORT); - - } // Set a random number as messageID, convert Json Object to // InputStream and finally call publisher and subscriber - else if (isAlphaNumeric(name) && validateIPPort(updateMirrorMaker.getUpdateMirrorMaker().getConsumer()) - && validateIPPort(updateMirrorMaker.getUpdateMirrorMaker().getProducer())) { + else { + + if (null == updateMirrorMaker.getMessageID() || updateMirrorMaker.getMessageID().isEmpty()) { + updateMirrorMaker.setMessageID(randomStr); + } + + JSONObject existMirrorMaker = validateMMExists(ctx, name); + + if ((boolean) existMirrorMaker.get("exists")) { + JSONObject existMM = (JSONObject) existMirrorMaker.get("listMirrorMaker"); + + if (!jsonObInput.has("numStreams")) { + updateMirrorMaker.getUpdateMirrorMaker().setNumStreams(existMM.getInt("numStreams")); + } + if (!jsonObInput.has("enablelogCheck")) { + updateMirrorMaker.getUpdateMirrorMaker() + .setEnablelogCheck(existMM.getBoolean("enablelogCheck")); + } + inStream = IOUtils.toInputStream(gson.toJson(updateMirrorMaker), "UTF-8"); + JSONObject finalJsonObj = callPubSub(updateMirrorMaker.getMessageID(), ctx, inStream, name, + false); + DMaaPResponseBuilder.respondOk(ctx, finalJsonObj); + } else { + + errResJson.setErrorMessage("MirrorMaker " + name + " does not exist"); + LOGGER.info(errResJson.toString()); + throw new CambriaApiException(errResJson); + + } - updateMirrorMaker.setMessageID(randomStr); - inStream = IOUtils.toInputStream(gson.toJson(updateMirrorMaker), UTF_8); - callPubSub(randomStr, ctx, inStream); } } catch (IOException e) { - - LOGGER.error("IOException: ", e); + LOGGER.error("Error in callUpdateMirrorMaker:", e); } } // Send error response if user does not provide Authorization else { - sendErrResponse(ctx, NO_ADMIN_PERMISSION); + ErrorResponse errRes = new ErrorResponse(HttpStatus.SC_UNAUTHORIZED, + DMaaPResponseCode.ACCESS_NOT_PERMITTED.getResponseCode(), NO_ADMIN_PERMISSION, null, + Utils.getFormattedDate(new Date()), topic, null, null, "mirrorMakerAgent", + ctx.getRequest().getRemoteHost()); + LOGGER.info(errRes.toString()); + throw new CambriaApiException(errRes); } } @POST @Produces("application/json") @Path("/delete") - public void callDeleteMirrorMaker(InputStream msg) { + public void callDeleteMirrorMaker(InputStream msg) throws JSONException, Exception { DMaaPContext ctx = getDmaapContext(); if (checkMirrorMakerPermission(ctx, - AJSCPropertiesMap.getProperty(CambriaConstants.msgRtr_prop, MIRROR_MAKERADMIN))) { + AJSCPropertiesMap.getProperty(CambriaConstants.msgRtr_prop, "msgRtr.mirrormakeradmin.aaf"))) { loadProperty(); String input = null; + Gson gson = new Gson(); + MirrorMaker mirrormaker = new MirrorMaker(); try { - input = IOUtils.toString(msg, UTF_8); + input = IOUtils.toString(msg, "UTF-8"); if (input != null && input.length() > 0) { input = removeExtraChar(input); @@ -396,55 +466,82 @@ public class MMRestService { try { jsonOb = new JSONObject(input); + mirrormaker = gson.fromJson(input, MirrorMaker.class); } catch (JSONException ex) { - sendErrResponse(ctx, errorMessages.getIncorrectJson()); - LOGGER.error("JSONException: ", ex); + errResJson.setErrorMessage(errorMessages.getIncorrectJson()); + LOGGER.info(errResJson.toString()); + throw new CambriaApiException(errResJson); } // Check if request has DeleteMirrorMaker and // DeleteMirrorMaker has MirrorMaker object with name variable // and check if the name contain only alpha numeric - if ((jsonOb != null) - && (jsonOb.has("deleteMirrorMaker") && jsonOb.getJSONObject("deleteMirrorMaker").length() == 1 - && jsonOb.getJSONObject("deleteMirrorMaker").has("name") - && !StringUtils.isBlank(jsonOb.getJSONObject("deleteMirrorMaker").getString("name")) - && isAlphaNumeric(jsonOb.getJSONObject("deleteMirrorMaker").getString("name")))) { - jsonOb.put("messageID", randomStr); + if (jsonOb.has("deleteMirrorMaker") && jsonOb.getJSONObject("deleteMirrorMaker").length() == 1 + && jsonOb.getJSONObject("deleteMirrorMaker").has("name") + && !StringUtils.isBlank(jsonOb.getJSONObject("deleteMirrorMaker").getString("name")) + && isAlphaNumeric(jsonOb.getJSONObject("deleteMirrorMaker").getString("name"))) { + + if (!jsonOb.has("messageID") || jsonOb.isNull("messageID")) { + jsonOb.put("messageID", randomStr); + } + InputStream inStream = null; try { - inStream = IOUtils.toInputStream(jsonOb.toString(), UTF_8); + inStream = IOUtils.toInputStream(jsonOb.toString(), "UTF-8"); } catch (IOException ioe) { - LOGGER.error("IOException: ", ioe); + LOGGER.error("Error while converting string to an input stream:", ioe); } + JSONObject deleteMM = jsonOb.getJSONObject("deleteMirrorMaker"); + + JSONObject existMirrorMaker = validateMMExists(ctx, deleteMM.getString("name")); + + if ((boolean) existMirrorMaker.get("exists")) { - callPubSub(randomStr, ctx, inStream); + JSONObject finalJsonObj = callPubSub(jsonOb.getString("messageID"), ctx, inStream, + mirrormaker.name, false); + DMaaPResponseBuilder.respondOk(ctx, finalJsonObj); + } else { + + errResJson.setErrorMessage("MirrorMaker " + deleteMM.getString("name") + " does not exist"); + LOGGER.info(errResJson.toString()); + throw new CambriaApiException(errResJson); + + } } else { - sendErrResponse(ctx, "This is not a DeleteMirrorMaker request. Please try again."); + errResJson.setErrorMessage("This is not a DeleteMirrorMaker request. Please try again."); + LOGGER.info(errResJson.toString()); + throw new CambriaApiException(errResJson); + } } catch (IOException ioe) { - LOGGER.error("IOException: ", ioe); + LOGGER.error("Error in callDeleteMirrorMaker:", ioe); + throw ioe; } } else { - sendErrResponse(getDmaapContext(), NO_ADMIN_PERMISSION); + ErrorResponse errRes = new ErrorResponse(HttpStatus.SC_UNAUTHORIZED, + DMaaPResponseCode.ACCESS_NOT_PERMITTED.getResponseCode(), NO_ADMIN_PERMISSION, null, + Utils.getFormattedDate(new Date()), topic, null, null, "mirrorMakerAgent", + ctx.getRequest().getRemoteHost()); + LOGGER.info(errRes.toString()); + throw new CambriaApiException(errRes); } } - private boolean isListMirrorMaker(String msg, String messageID) { + public boolean isListMirrorMaker(String msg, String messageID) { String topicmsg = msg; topicmsg = removeExtraChar(topicmsg); - - JSONObject jObj; - JSONArray jArray; + JSONObject jObj = new JSONObject(); + JSONArray jArray = null; boolean exist = false; if (!StringUtils.isBlank(topicmsg) && topicmsg.length() > 2) { @@ -453,11 +550,7 @@ public class MMRestService { for (int i = 0; i < jArray.length(); i++) { jObj = jArray.getJSONObject(i); - JSONObject obj = new JSONObject(); - if (jObj.has(MESSAGE)) { - obj = jObj.getJSONObject(MESSAGE); - } - if (obj.has("messageID") && obj.get("messageID").equals(messageID) && obj.has(LISTMIRRORMAKER)) { + if (jObj.has("messageID") && jObj.get("messageID").equals(messageID) && jObj.has("listMirrorMaker")) { exist = true; break; } @@ -503,17 +596,6 @@ public class MMRestService { return false; } - // This method validate IPv4 - private boolean validateIPPort(String ipPort) { - String pattern = "^([01]?\\d\\d?|2[0-4]\\d|25[0-5])\\.([01]?\\d\\d?|2[0-4]\\d|25[0-5])\\." - + "([01]?\\d\\d?|2[0-4]\\d|25[0-5])\\.([01]?\\d\\d?|2[0-4]\\d|25[0-5]):" - + "([1-9][0-9]{0,3}|[1-5][0-9]{4}|6[0-4][0-9]{3}|65[0-4][0-9]{2}|655[0-2][0-9]|6553[0-5])$"; - if (ipPort.matches(pattern)) { - return true; - } - return false; - } - private String checkJsonFormate(String jsonStr) { String json = jsonStr; @@ -533,51 +615,67 @@ public class MMRestService { return hasPermission; } - private void callPubSub(String randomstr, DMaaPContext ctx, InputStream inStream) { + public JSONObject callPubSub(String randomstr, DMaaPContext ctx, InputStream inStream, String name, boolean listAll) + throws Exception { + loadProperty(); + JSONObject jsonObj = new JSONObject(); + JSONObject finalJsonObj = new JSONObject(); + JSONArray jsonArray = null; try { + String msgFrmSubscribe = mirrorService.subscribe(ctx, topic, consumergroup, consumerid); mirrorService.pushEvents(ctx, topic, inStream, null, null); long startTime = System.currentTimeMillis(); - String msgFrmSubscribe = mirrorService.subscribe(ctx, topic, consumergroup, consumerid); while (!isListMirrorMaker(msgFrmSubscribe, randomstr) - && (System.currentTimeMillis() - startTime) < timeout) { + && ((System.currentTimeMillis() - startTime) < timeout)) { msgFrmSubscribe = mirrorService.subscribe(ctx, topic, consumergroup, consumerid); - } - JSONObject jsonObj; - JSONObject finalJsonObj = new JSONObject(); - JSONArray jsonArray; + } if (msgFrmSubscribe != null && msgFrmSubscribe.length() > 0 && isListMirrorMaker(msgFrmSubscribe, randomstr)) { msgFrmSubscribe = removeExtraChar(msgFrmSubscribe); - jsonArray = new JSONArray(msgFrmSubscribe); - for (int i = 0; i < jsonArray.length(); i++) { - jsonObj = jsonArray.getJSONObject(i); + jsonArray = new JSONArray(msgFrmSubscribe); + jsonObj = jsonArray.getJSONObject(0); + if (jsonObj.has("listMirrorMaker")) { + jsonArray = (JSONArray) jsonObj.get("listMirrorMaker"); + if (true == listAll) { + return jsonObj; + } else { + for (int i = 0; i < jsonArray.length(); i++) { + jsonObj = jsonArray.getJSONObject(i); + if (null != name && !name.isEmpty()) { + if (jsonObj.getString("name").equals(name)) { + finalJsonObj.put("listMirrorMaker", jsonObj); + break; + } + } else { + finalJsonObj.put("listMirrorMaker", jsonObj); + } - JSONObject obj = new JSONObject(); - if (jsonObj.has(MESSAGE)) { - obj = jsonObj.getJSONObject(MESSAGE); - } - if (obj.has("messageID") && obj.get("messageID").equals(randomstr) && obj.has(LISTMIRRORMAKER)) { - finalJsonObj.put(LISTMIRRORMAKER, obj.get(LISTMIRRORMAKER)); - break; + } } } - - DMaaPResponseBuilder.respondOk(ctx, finalJsonObj); + return finalJsonObj; } else { - JSONObject err = new JSONObject(); - err.append(ERROR, "listMirrorMaker is not available, please make sure MirrorMakerAgent is running"); - DMaaPResponseBuilder.respondOk(ctx, err); + ErrorResponse errRes = new ErrorResponse(HttpStatus.SC_SERVICE_UNAVAILABLE, + DMaaPResponseCode.RESOURCE_NOT_FOUND.getResponseCode(), + "listMirrorMaker is not available, please make sure MirrorMakerAgent is running", null, + Utils.getFormattedDate(new Date()), topic, null, null, "mirrorMakerAgent", + ctx.getRequest().getRemoteHost()); + LOGGER.info(errRes.toString()); + throw new CambriaApiException(errRes); + } } catch (Exception e) { - LOGGER.error("Exception: ", e); + LOGGER.error("Error in callPubSub", e); + throw e; } + } private void sendErrResponse(DMaaPContext ctx, String errMsg) { @@ -597,17 +695,17 @@ public class MMRestService { @POST @Produces("application/json") @Path("/listallwhitelist") - public void listWhiteList(InputStream msg) { + public void listWhiteList(InputStream msg) throws Exception { DMaaPContext ctx = getDmaapContext(); if (checkMirrorMakerPermission(ctx, - AJSCPropertiesMap.getProperty(CambriaConstants.msgRtr_prop, MIRROR_MAKERUSER))) { + AJSCPropertiesMap.getProperty(CambriaConstants.msgRtr_prop, "msgRtr.mirrormakeruser.aaf"))) { loadProperty(); String input = null; try { - input = IOUtils.toString(msg, UTF_8); + input = IOUtils.toString(msg, "UTF-8"); if (input != null && input.length() > 0) { input = removeExtraChar(input); @@ -621,20 +719,22 @@ public class MMRestService { } catch (JSONException ex) { - sendErrResponse(ctx, errorMessages.getIncorrectJson()); - LOGGER.error("JSONException: ", ex); + errResJson.setErrorMessage(errorMessages.getIncorrectJson()); + LOGGER.info(errResJson.toString()); + throw new CambriaApiException(errResJson); + } // Check if the request has name and name contains only alpha // numeric // and check if the request has namespace and namespace contains // only alpha numeric - if (jsonOb != null && jsonOb.length() == 2 && jsonOb.has("name") - && !StringUtils.isBlank(jsonOb.getString("name")) && isAlphaNumeric(jsonOb.getString("name")) - && jsonOb.has(NAMESPACE) && !StringUtils.isBlank(jsonOb.getString(NAMESPACE))) { + if (jsonOb.length() == 2 && jsonOb.has("name") && !StringUtils.isBlank(jsonOb.getString("name")) + && isAlphaNumeric(jsonOb.getString("name")) && jsonOb.has("namespace") + && !StringUtils.isBlank(jsonOb.getString("namespace"))) { String permission = AJSCPropertiesMap.getProperty(CambriaConstants.msgRtr_prop, - "msgRtr.mirrormakeruser.aaf.create") + jsonOb.getString(NAMESPACE) + "|create"; + "msgRtr.mirrormakeruser.aaf.create") + jsonOb.getString("namespace") + "|create"; // Check if the user have create permission for the // namespace @@ -649,7 +749,9 @@ public class MMRestService { } catch (JSONException e) { - LOGGER.error("JSONException: ", e); + errResJson.setErrorMessage(errorMessages.getIncorrectJson()); + LOGGER.info(errResJson.toString()); + throw new CambriaApiException(errResJson); } // set a random number as messageID @@ -659,34 +761,22 @@ public class MMRestService { // convert listAll Json object to InputStream object try { - inStream = IOUtils.toInputStream(listAll.toString(), UTF_8); + inStream = IOUtils.toInputStream(listAll.toString(), "UTF-8"); } catch (IOException ioe) { - LOGGER.error("IOException: ", ioe); + LOGGER.error("Error while converting string to an input stream:", ioe); } - // call listAllMirrorMaker - mirrorService.pushEvents(ctx, topic, inStream, null, null); + JSONObject listMirrorMaker = new JSONObject(); + listMirrorMaker = callPubSub(randomStr, ctx, inStream, null, true); - // subscribe for listMirrorMaker - long startTime = System.currentTimeMillis(); - String msgFrmSubscribe = mirrorService.subscribe(ctx, topic, consumergroup, consumerid); + String whitelist = null; + JSONArray listMMArray = new JSONArray(); + if (listMirrorMaker.has("listMirrorMaker")) { + listMMArray = (JSONArray) listMirrorMaker.get("listMirrorMaker"); + for (int i = 0; i < listMMArray.length(); i++) { - while (!isListMirrorMaker(msgFrmSubscribe, randomStr) - && (System.currentTimeMillis() - startTime) < timeout) { - msgFrmSubscribe = mirrorService.subscribe(ctx, topic, consumergroup, consumerid); - } - - if (msgFrmSubscribe != null && msgFrmSubscribe.length() > 0 - && isListMirrorMaker(msgFrmSubscribe, randomStr)) { - - JSONArray listMirrorMaker; - listMirrorMaker = getListMirrorMaker(msgFrmSubscribe, randomStr); - - String whitelist = null; - for (int i = 0; i < listMirrorMaker.length(); i++) { - - JSONObject mm; - mm = listMirrorMaker.getJSONObject(i); + JSONObject mm = new JSONObject(); + mm = listMMArray.getJSONObject(i); String name = mm.getString("name"); if (name.equals(jsonOb.getString("name")) && mm.has("whitelist")) { @@ -697,13 +787,13 @@ public class MMRestService { if (!StringUtils.isBlank(whitelist)) { - List<String> topicList = new ArrayList<>(); - List<String> finalTopicList = new ArrayList<>(); + List<String> topicList = new ArrayList<String>(); + List<String> finalTopicList = new ArrayList<String>(); topicList = Arrays.asList(whitelist.split(",")); for (String topic : topicList) { if (topic != null && !topic.equals("null") - && getNamespace(topic).equals(jsonOb.getString(NAMESPACE))) { + && getNamespace(topic).equals(jsonOb.getString("namespace"))) { finalTopicList.add(topic); } @@ -711,7 +801,7 @@ public class MMRestService { String topicNames = ""; - if (!finalTopicList.isEmpty()) { + if (finalTopicList.size() > 0) { topicNames = StringUtils.join(finalTopicList, ","); } @@ -724,28 +814,39 @@ public class MMRestService { } else { - JSONObject err = new JSONObject(); - err.append(ERROR, + errResJson.setErrorMessage( "listWhiteList is not available, please make sure MirrorMakerAgent is running"); - DMaaPResponseBuilder.respondOk(ctx, err); + LOGGER.info(errResJson.toString()); + throw new CambriaApiException(errResJson); + } } else { - sendErrResponse(ctx, NO_USER_CREATE_PERMISSION); + ErrorResponse errRes = new ErrorResponse(HttpStatus.SC_UNAUTHORIZED, + DMaaPResponseCode.ACCESS_NOT_PERMITTED.getResponseCode(), NO_USER_CREATE_PERMISSION, + null, Utils.getFormattedDate(new Date()), topic, null, null, "mirrorMakerAgent", + ctx.getRequest().getRemoteHost()); + LOGGER.info(errRes.toString()); + throw new CambriaApiException(errRes); } } else { - sendErrResponse(ctx, "This is not a ListAllWhitelist request. Please try again."); + errResJson.setErrorMessage("This is not a ListAllWhitelist request. Please try again."); + LOGGER.info(errResJson.toString()); + throw new CambriaApiException(errResJson); } - } catch (IOException | CambriaApiException | ConfigDbException | AccessDeniedException - | TopicExistsException | missingReqdSetting | UnavailableException e) { - - LOGGER.error("IOException: ", e); + } catch (IOException e) { + LOGGER.error("Error in listWhiteList", e); } } else { - sendErrResponse(ctx, NO_USER_PERMISSION); + ErrorResponse errRes = new ErrorResponse(HttpStatus.SC_UNAUTHORIZED, + DMaaPResponseCode.ACCESS_NOT_PERMITTED.getResponseCode(), NO_USER_PERMISSION, null, + Utils.getFormattedDate(new Date()), topic, null, null, "mirrorMakerAgent", + ctx.getRequest().getRemoteHost()); + LOGGER.info(errRes.toString()); + throw new CambriaApiException(errRes); } } @@ -753,17 +854,17 @@ public class MMRestService { @POST @Produces("application/json") @Path("/createwhitelist") - public void createWhiteList(InputStream msg) { + public void createWhiteList(InputStream msg) throws Exception { DMaaPContext ctx = getDmaapContext(); if (checkMirrorMakerPermission(ctx, - AJSCPropertiesMap.getProperty(CambriaConstants.msgRtr_prop, MIRROR_MAKERUSER))) { + AJSCPropertiesMap.getProperty(CambriaConstants.msgRtr_prop, "msgRtr.mirrormakeruser.aaf"))) { loadProperty(); String input = null; try { - input = IOUtils.toString(msg, UTF_8); + input = IOUtils.toString(msg, "UTF-8"); if (input != null && input.length() > 0) { input = removeExtraChar(input); @@ -776,9 +877,9 @@ public class MMRestService { jsonOb = new JSONObject(input); } catch (JSONException ex) { - - sendErrResponse(ctx, errorMessages.getIncorrectJson()); - LOGGER.error("JSONException: ", ex); + errResJson.setErrorMessage(errorMessages.getIncorrectJson()); + LOGGER.info(errResJson.toString()); + throw new CambriaApiException(errResJson); } // Check if the request has name and name contains only alpha @@ -786,17 +887,16 @@ public class MMRestService { // check if the request has namespace and // check if the request has whitelistTopicName // check if the topic name contains only alpha numeric - if (jsonOb != null && jsonOb.length() == 3 && jsonOb.has("name") - && !StringUtils.isBlank(jsonOb.getString("name")) && isAlphaNumeric(jsonOb.getString("name")) - && jsonOb.has(NAMESPACE) && !StringUtils.isBlank(jsonOb.getString(NAMESPACE)) - && jsonOb.has("whitelistTopicName") + if (jsonOb.length() == 3 && jsonOb.has("name") && !StringUtils.isBlank(jsonOb.getString("name")) + && isAlphaNumeric(jsonOb.getString("name")) && jsonOb.has("namespace") + && !StringUtils.isBlank(jsonOb.getString("namespace")) && jsonOb.has("whitelistTopicName") && !StringUtils.isBlank(jsonOb.getString("whitelistTopicName")) && isAlphaNumeric(jsonOb.getString("whitelistTopicName").substring( - jsonOb.getString("whitelistTopicName").lastIndexOf(".") + 1, - jsonOb.getString("whitelistTopicName").length()))) { + jsonOb.getString("whitelistTopicName").lastIndexOf(".") + 1, jsonOb + .getString("whitelistTopicName").length()))) { String permission = AJSCPropertiesMap.getProperty(CambriaConstants.msgRtr_prop, - "msgRtr.mirrormakeruser.aaf.create") + jsonOb.getString(NAMESPACE) + "|create"; + "msgRtr.mirrormakeruser.aaf.create") + jsonOb.getString("namespace") + "|create"; // Check if the user have create permission for the // namespace @@ -811,7 +911,9 @@ public class MMRestService { } catch (JSONException e) { - LOGGER.error("JSONException: ", e); + errResJson.setErrorMessage(errorMessages.getIncorrectJson()); + LOGGER.info(errResJson.toString()); + throw new CambriaApiException(errResJson); } // set a random number as messageID @@ -821,24 +923,24 @@ public class MMRestService { // convert listAll Json object to InputStream object try { - inStream = IOUtils.toInputStream(listAll.toString(), UTF_8); + inStream = IOUtils.toInputStream(listAll.toString(), "UTF-8"); } catch (IOException ioe) { - LOGGER.error("IOException: ", ioe); + LOGGER.error("Error while converting string to an input stream:", ioe); } + String msgFrmSubscribe = mirrorService.subscribe(ctx, topic, consumergroup, consumerid); // call listAllMirrorMaker mirrorService.pushEvents(ctx, topic, inStream, null, null); // subscribe for listMirrorMaker long startTime = System.currentTimeMillis(); - String msgFrmSubscribe = mirrorService.subscribe(ctx, topic, consumergroup, consumerid); while (!isListMirrorMaker(msgFrmSubscribe, randomStr) && (System.currentTimeMillis() - startTime) < timeout) { msgFrmSubscribe = mirrorService.subscribe(ctx, topic, consumergroup, consumerid); } - JSONArray listMirrorMaker; + JSONArray listMirrorMaker = null; if (msgFrmSubscribe != null && msgFrmSubscribe.length() > 0 && isListMirrorMaker(msgFrmSubscribe, randomStr)) { @@ -847,7 +949,7 @@ public class MMRestService { String whitelist = null; for (int i = 0; i < listMirrorMaker.length(); i++) { - JSONObject mm; + JSONObject mm = new JSONObject(); mm = listMirrorMaker.getJSONObject(i); String name = mm.getString("name"); @@ -857,8 +959,8 @@ public class MMRestService { } } - List<String> topicList = new ArrayList<>(); - List<String> finalTopicList = new ArrayList<>(); + List<String> topicList = new ArrayList<String>(); + List<String> finalTopicList = new ArrayList<String>(); if (whitelist != null) { topicList = Arrays.asList(whitelist.split(",")); @@ -873,7 +975,7 @@ public class MMRestService { String newTopic = jsonOb.getString("whitelistTopicName"); if (!topicList.contains(newTopic) - && getNamespace(newTopic).equals(jsonOb.getString(NAMESPACE))) { + && getNamespace(newTopic).equals(jsonOb.getString("namespace"))) { UpdateWhiteList updateWhiteList = new UpdateWhiteList(); MirrorMaker mirrorMaker = new MirrorMaker(); @@ -881,7 +983,7 @@ public class MMRestService { finalTopicList.add(newTopic); String newWhitelist = ""; - if (!finalTopicList.isEmpty()) { + if (finalTopicList.size() > 0) { newWhitelist = StringUtils.join(finalTopicList, ","); } @@ -893,44 +995,70 @@ public class MMRestService { Gson g = new Gson(); g.toJson(updateWhiteList); - InputStream inputStream; - inputStream = IOUtils.toInputStream(g.toJson(updateWhiteList), UTF_8); + InputStream inputStream = null; + inputStream = IOUtils.toInputStream(g.toJson(updateWhiteList), "UTF-8"); // callPubSub(newRandom, ctx, inputStream); - callPubSubForWhitelist(newRandom, ctx, inputStream, jsonOb.getString(NAMESPACE)); + callPubSubForWhitelist(newRandom, ctx, inputStream, jsonOb); } else if (topicList.contains(newTopic)) { - sendErrResponse(ctx, "The topic already exist."); - - } else if (!getNamespace(newTopic).equals(jsonOb.getString(NAMESPACE))) { - sendErrResponse(ctx, - "The namespace of the topic does not match with the namespace you provided."); + ErrorResponse errRes = new ErrorResponse(HttpStatus.SC_INTERNAL_SERVER_ERROR, + DMaaPResponseCode.INCORRECT_JSON.getResponseCode(), "The topic already exist.", + null, Utils.getFormattedDate(new Date()), topic, null, null, "mirrorMakerAgent", + ctx.getRequest().getRemoteHost()); + LOGGER.info(errRes.toString()); + throw new CambriaApiException(errRes); + + } else if (!getNamespace(newTopic).equals(jsonOb.getString("namespace"))) { + ErrorResponse errRes = new ErrorResponse(HttpStatus.SC_INTERNAL_SERVER_ERROR, + DMaaPResponseCode.INCORRECT_JSON.getResponseCode(), + "The namespace of the topic does not match with the namespace you provided.", + null, Utils.getFormattedDate(new Date()), topic, null, null, "mirrorMakerAgent", + ctx.getRequest().getRemoteHost()); + LOGGER.info(errRes.toString()); + throw new CambriaApiException(errRes); } } else { - JSONObject err = new JSONObject(); - err.append(ERROR, - "listWhiteList is not available, please make sure MirrorMakerAgent is running"); - DMaaPResponseBuilder.respondOk(ctx, err); + ErrorResponse errRes = new ErrorResponse(HttpStatus.SC_SERVICE_UNAVAILABLE, + DMaaPResponseCode.SERVER_UNAVAILABLE.getResponseCode(), + "listWhiteList is not available, please make sure MirrorMakerAgent is running", + null, Utils.getFormattedDate(new Date()), topic, null, null, "mirrorMakerAgent", + ctx.getRequest().getRemoteHost()); + LOGGER.info(errRes.toString()); + throw new CambriaApiException(errRes); } } else { - sendErrResponse(ctx, NO_USER_CREATE_PERMISSION); + ErrorResponse errRes = new ErrorResponse(HttpStatus.SC_UNAUTHORIZED, + DMaaPResponseCode.UNABLE_TO_AUTHORIZE.getResponseCode(), NO_USER_CREATE_PERMISSION, + null, Utils.getFormattedDate(new Date()), topic, null, null, "mirrorMakerAgent", + ctx.getRequest().getRemoteHost()); + LOGGER.info(errRes.toString()); + throw new CambriaApiException(errRes); } } else { - sendErrResponse(ctx, "This is not a createWhitelist request. Please try again."); + errResJson.setErrorMessage("This is not a createWhitelist request. Please try again."); + LOGGER.info(errResJson.toString()); + throw new CambriaApiException(errResJson); } } catch (IOException | CambriaApiException | ConfigDbException | AccessDeniedException | TopicExistsException | missingReqdSetting | UnavailableException e) { - LOGGER.error("IOException: ", e); + throw e; } } // Send error response if user does not provide Authorization else { - sendErrResponse(ctx, NO_USER_PERMISSION); + ErrorResponse errRes = new ErrorResponse(HttpStatus.SC_UNAUTHORIZED, + DMaaPResponseCode.UNABLE_TO_AUTHORIZE.getResponseCode(), NO_USER_PERMISSION, null, + Utils.getFormattedDate(new Date()), topic, null, null, "mirrorMakerAgent", + ctx.getRequest().getRemoteHost()); + LOGGER.info(errRes.toString()); + throw new CambriaApiException(errRes); + } } @@ -938,17 +1066,17 @@ public class MMRestService { @POST @Produces("application/json") @Path("/deletewhitelist") - public void deleteWhiteList(InputStream msg) { + public void deleteWhiteList(InputStream msg) throws Exception { DMaaPContext ctx = getDmaapContext(); if (checkMirrorMakerPermission(ctx, - AJSCPropertiesMap.getProperty(CambriaConstants.msgRtr_prop, MIRROR_MAKERUSER))) { + AJSCPropertiesMap.getProperty(CambriaConstants.msgRtr_prop, "msgRtr.mirrormakeruser.aaf"))) { loadProperty(); String input = null; try { - input = IOUtils.toString(msg, UTF_8); + input = IOUtils.toString(msg, "UTF-8"); if (input != null && input.length() > 0) { input = removeExtraChar(input); @@ -962,23 +1090,24 @@ public class MMRestService { } catch (JSONException ex) { - sendErrResponse(ctx, errorMessages.getIncorrectJson()); - LOGGER.error("JSONException: ", ex); + errResJson.setErrorMessage(errorMessages.getIncorrectJson()); + LOGGER.info(errResJson.toString()); + throw new CambriaApiException(errResJson); + } // Check if the request has name and name contains only alpha // numeric, // check if the request has namespace and // check if the request has whitelistTopicName - if (jsonOb != null && jsonOb.length() == 3 && jsonOb.has("name") - && isAlphaNumeric(jsonOb.getString("name")) && jsonOb.has(NAMESPACE) - && jsonOb.has("whitelistTopicName") + if (jsonOb.length() == 3 && jsonOb.has("name") && isAlphaNumeric(jsonOb.getString("name")) + && jsonOb.has("namespace") && jsonOb.has("whitelistTopicName") && isAlphaNumeric(jsonOb.getString("whitelistTopicName").substring( jsonOb.getString("whitelistTopicName").lastIndexOf(".") + 1, jsonOb.getString("whitelistTopicName").length()))) { String permission = AJSCPropertiesMap.getProperty(CambriaConstants.msgRtr_prop, - "msgRtr.mirrormakeruser.aaf.create") + jsonOb.getString(NAMESPACE) + "|create"; + "msgRtr.mirrormakeruser.aaf.create") + jsonOb.getString("namespace") + "|create"; // Check if the user have create permission for the // namespace @@ -993,7 +1122,9 @@ public class MMRestService { } catch (JSONException e) { - LOGGER.error("JSONException: ", e); + errResJson.setErrorMessage(errorMessages.getIncorrectJson()); + LOGGER.info(errResJson.toString()); + throw new CambriaApiException(errResJson); } // set a random number as messageID @@ -1003,10 +1134,10 @@ public class MMRestService { // convert listAll Json object to InputStream object try { - inStream = IOUtils.toInputStream(listAll.toString(), UTF_8); + inStream = IOUtils.toInputStream(listAll.toString(), "UTF-8"); } catch (IOException ioe) { - LOGGER.error("IOException: ", ioe); + LOGGER.error("Error while converting string to an input stream:", ioe); } // call listAllMirrorMaker mirrorService.pushEvents(ctx, topic, inStream, null, null); @@ -1020,8 +1151,8 @@ public class MMRestService { msgFrmSubscribe = mirrorService.subscribe(ctx, topic, consumergroup, consumerid); } - JSONObject jsonObj; - JSONArray jsonArray; + JSONObject jsonObj = new JSONObject(); + JSONArray jsonArray = null; JSONArray listMirrorMaker = null; if (msgFrmSubscribe != null && msgFrmSubscribe.length() > 0 @@ -1032,32 +1163,26 @@ public class MMRestService { for (int i = 0; i < jsonArray.length(); i++) { jsonObj = jsonArray.getJSONObject(i); - JSONObject obj = new JSONObject(); - if (jsonObj.has(MESSAGE)) { - obj = jsonObj.getJSONObject(MESSAGE); - } - if (obj.has("messageID") && obj.get("messageID").equals(randomStr) - && obj.has(LISTMIRRORMAKER)) { - listMirrorMaker = obj.getJSONArray(LISTMIRRORMAKER); + if (jsonObj.has("messageID") && jsonObj.get("messageID").equals(randomStr) + && jsonObj.has("listMirrorMaker")) { + listMirrorMaker = jsonObj.getJSONArray("listMirrorMaker"); break; } } String whitelist = null; - if (listMirrorMaker != null) { - for (int i = 0; i < listMirrorMaker.length(); i++) { + for (int i = 0; i < listMirrorMaker.length(); i++) { - JSONObject mm = new JSONObject(); - mm = listMirrorMaker.getJSONObject(i); - String name = mm.getString("name"); + JSONObject mm = new JSONObject(); + mm = listMirrorMaker.getJSONObject(i); + String name = mm.getString("name"); - if (name.equals(jsonOb.getString("name")) && mm.has("whitelist")) { - whitelist = mm.getString("whitelist"); - break; - } + if (name.equals(jsonOb.getString("name")) && mm.has("whitelist")) { + whitelist = mm.getString("whitelist"); + break; } } - List<String> topicList = new ArrayList<>(); + List<String> topicList = new ArrayList<String>(); if (whitelist != null) { topicList = Arrays.asList(whitelist.split(",")); @@ -1068,7 +1193,9 @@ public class MMRestService { if (topicList.contains(topicToRemove)) { removeTopic = true; } else { - sendErrResponse(ctx, "The topic does not exist."); + errResJson.setErrorMessage(errorMessages.getTopicNotExist()); + LOGGER.info(errResJson.toString()); + throw new CambriaApiException(errResJson); } if (removeTopic) { @@ -1076,7 +1203,10 @@ public class MMRestService { MirrorMaker mirrorMaker = new MirrorMaker(); mirrorMaker.setName(jsonOb.getString("name")); - mirrorMaker.setWhitelist(removeTopic(whitelist, topicToRemove)); + + if (StringUtils.isNotBlank((removeTopic(whitelist, topicToRemove)))) { + mirrorMaker.setWhitelist(removeTopic(whitelist, topicToRemove)); + } String newRandom = getRandomNum(); @@ -1086,37 +1216,55 @@ public class MMRestService { Gson g = new Gson(); g.toJson(updateWhiteList); - InputStream inputStream; - inputStream = IOUtils.toInputStream(g.toJson(updateWhiteList), UTF_8); - callPubSubForWhitelist(newRandom, ctx, inputStream, getNamespace(topicToRemove)); + InputStream inputStream = null; + inputStream = IOUtils.toInputStream(g.toJson(updateWhiteList), "UTF-8"); + callPubSubForWhitelist(newRandom, ctx, inputStream, jsonOb); + // mmAgentUtil.getNamespace(topicToRemove)); } } else { - JSONObject err = new JSONObject(); - err.append(ERROR, - "listWhiteList is not available, please make sure MirrorMakerAgent is running"); - DMaaPResponseBuilder.respondOk(ctx, err); + ErrorResponse errRes = new ErrorResponse(HttpStatus.SC_SERVICE_UNAVAILABLE, + DMaaPResponseCode.SERVER_UNAVAILABLE.getResponseCode(), + "listWhiteList is not available, please make sure MirrorMakerAgent is running", + null, Utils.getFormattedDate(new Date()), topic, null, null, "mirrorMakerAgent", + ctx.getRequest().getRemoteHost()); + LOGGER.info(errRes.toString()); + throw new CambriaApiException(errRes); } } else { - sendErrResponse(ctx, NO_USER_CREATE_PERMISSION); + ErrorResponse errRes = new ErrorResponse(HttpStatus.SC_UNAUTHORIZED, + DMaaPResponseCode.ACCESS_NOT_PERMITTED.getResponseCode(), NO_USER_CREATE_PERMISSION, + null, Utils.getFormattedDate(new Date()), topic, null, null, "mirrorMakerAgent", + ctx.getRequest().getRemoteHost()); + LOGGER.info(errRes.toString()); + throw new CambriaApiException(errRes); } } else { - sendErrResponse(ctx, "This is not a DeleteAllWhitelist request. Please try again."); + errResJson.setErrorMessage("This is not a DeleteAllWhitelist request. Please try again."); + LOGGER.info(errResJson.toString()); + throw new CambriaApiException(errResJson); + } } catch (IOException | CambriaApiException | ConfigDbException | AccessDeniedException | TopicExistsException | missingReqdSetting | UnavailableException e) { - LOGGER.error("IOException: ", e); + throw e; } } // Send error response if user does not provide Authorization else { - sendErrResponse(ctx, NO_USER_PERMISSION); + ErrorResponse errRes = new ErrorResponse(HttpStatus.SC_UNAUTHORIZED, + DMaaPResponseCode.ACCESS_NOT_PERMITTED.getResponseCode(), NO_USER_PERMISSION, null, + Utils.getFormattedDate(new Date()), topic, null, null, "mirrorMakerAgent", + ctx.getRequest().getRemoteHost()); + LOGGER.info(errRes.toString()); + throw new CambriaApiException(errRes); + } } @@ -1146,20 +1294,24 @@ public class MMRestService { return newWhitelist; } - private void callPubSubForWhitelist(String randomStr, DMaaPContext ctx, InputStream inStream, String namespace) { + public void callPubSubForWhitelist(String randomStr, DMaaPContext ctx, InputStream inStream, JSONObject jsonOb) { + loadProperty(); try { + String namespace = jsonOb.getString("namespace"); + String mmName = jsonOb.getString("name"); + + String msgFrmSubscribe = mirrorService.subscribe(ctx, topic, consumergroup, consumerid); mirrorService.pushEvents(ctx, topic, inStream, null, null); long startTime = System.currentTimeMillis(); - String msgFrmSubscribe = mirrorService.subscribe(ctx, topic, consumergroup, consumerid); while (!isListMirrorMaker(msgFrmSubscribe, randomStr) && (System.currentTimeMillis() - startTime) < timeout) { msgFrmSubscribe = mirrorService.subscribe(ctx, topic, consumergroup, consumerid); } - JSONObject jsonObj; - JSONArray jsonArray; + JSONObject jsonObj = new JSONObject(); + JSONArray jsonArray = null; JSONArray jsonArrayNamespace = null; if (msgFrmSubscribe != null && msgFrmSubscribe.length() > 0 @@ -1170,90 +1322,103 @@ public class MMRestService { for (int i = 0; i < jsonArray.length(); i++) { jsonObj = jsonArray.getJSONObject(i); - JSONObject obj = new JSONObject(); - if (jsonObj.has(MESSAGE)) { - obj = jsonObj.getJSONObject(MESSAGE); - } - if (obj.has("messageID") && obj.get("messageID").equals(randomStr) && obj.has(LISTMIRRORMAKER)) { - jsonArrayNamespace = obj.getJSONArray(LISTMIRRORMAKER); + if (jsonObj.has("messageID") && jsonObj.get("messageID").equals(randomStr) + && jsonObj.has("listMirrorMaker")) { + jsonArrayNamespace = jsonObj.getJSONArray("listMirrorMaker"); } } + JSONObject finalJasonObj = new JSONObject(); JSONArray finalJsonArray = new JSONArray(); - for (int i = 0; i < jsonArrayNamespace.length(); i++) { + if (jsonArrayNamespace != null) { + for (int i = 0; i < jsonArrayNamespace.length(); i++) { - JSONObject mmObj; - mmObj = jsonArrayNamespace.getJSONObject(i); - String whitelist; + JSONObject mmObj = new JSONObject(); + mmObj = jsonArrayNamespace.getJSONObject(i); + if (mmObj.has("name") && mmName.equals(mmObj.getString("name"))) { - if (mmObj.has("whitelist")) { - whitelist = getWhitelistByNamespace(mmObj.getString("whitelist"), namespace); - - if (whitelist != null) { - mmObj.remove("whitelist"); - mmObj.put("whitelist", whitelist); - } else { - mmObj.remove("whitelist"); + finalJsonArray.put(mmObj); } + } - finalJsonArray.put(mmObj); } - finalJasonObj.put(LISTMIRRORMAKER, finalJsonArray); + finalJasonObj.put("listMirrorMaker", finalJsonArray); DMaaPResponseBuilder.respondOk(ctx, finalJasonObj); } else { - JSONObject err = new JSONObject(); - err.append(ERROR, "listMirrorMaker is not available, please make sure MirrorMakerAgent is running"); - DMaaPResponseBuilder.respondOk(ctx, err); + ErrorResponse errRes = new ErrorResponse(HttpStatus.SC_SERVICE_UNAVAILABLE, + DMaaPResponseCode.RESOURCE_NOT_FOUND.getResponseCode(), + "listMirrorMaker is not available, please make sure MirrorMakerAgent is running", null, + Utils.getFormattedDate(new Date()), topic, null, null, "mirrorMakerAgent", + ctx.getRequest().getRemoteHost()); + LOGGER.info(errRes.toString()); + throw new CambriaApiException(errRes); } } catch (Exception e) { - LOGGER.error("Exception: ", e); + LOGGER.error("Error in callPubSubForWhitelist:", e); } } - private String getWhitelistByNamespace(String originalWhitelist, String namespace) { - - String whitelist = null; - List<String> resultList = new ArrayList<>(); - List<String> whitelistList = new ArrayList<>(); - whitelistList = Arrays.asList(originalWhitelist.split(",")); - for (String topic : whitelistList) { - if (StringUtils.isNotBlank(originalWhitelist) && getNamespace(topic).equals(namespace)) { - resultList.add(topic); + public JSONArray getListMirrorMaker(String msgFrmSubscribe, String randomStr) { + JSONObject jsonObj = new JSONObject(); + JSONArray jsonArray = new JSONArray(); + JSONArray listMirrorMaker = new JSONArray(); + + msgFrmSubscribe = removeExtraChar(msgFrmSubscribe); + jsonArray = new JSONArray(msgFrmSubscribe); + jsonObj = jsonArray.getJSONObject(0); + + for (int i = 0; i < jsonArray.length(); i++) { + jsonObj = jsonArray.getJSONObject(i); + + if (jsonObj.has("messageID") && jsonObj.get("messageID").equals(randomStr) && jsonObj.has("listMirrorMaker")) { + listMirrorMaker = jsonObj.getJSONArray("listMirrorMaker"); + break; } } - if (!resultList.isEmpty()) { - whitelist = StringUtils.join(resultList, ","); + return listMirrorMaker; + } + + + public JSONObject validateMMExists(DMaaPContext ctx, String name) throws Exception { + // Create a listAllMirrorMaker Json object + JSONObject listAll = new JSONObject(); + try { + listAll.put("listAllMirrorMaker", new JSONObject()); + + } catch (JSONException e) { + LOGGER.error("Error while creating a listAllMirrorMaker Json object:", e); } - return whitelist; - } + // set a random number as messageID + String randomStr = getRandomNum(); + listAll.put("messageID", randomStr); + InputStream inStream = null; - private JSONArray getListMirrorMaker(String msgFrmSubscribe, String randomStr) { - JSONObject jsonObj; - JSONArray jsonArray; - JSONArray listMirrorMaker = new JSONArray(); + // convert listAll Json object to InputStream object + try { + inStream = IOUtils.toInputStream(listAll.toString(), "UTF-8"); - msgFrmSubscribe = removeExtraChar(msgFrmSubscribe); - jsonArray = new JSONArray(msgFrmSubscribe); + } catch (IOException ioe) { + LOGGER.error("Error while converting string to an input stream:", ioe); + } + JSONObject listMirrorMaker = new JSONObject(); + listMirrorMaker = callPubSub(randomStr, ctx, inStream, name, false); + if (null != listMirrorMaker && listMirrorMaker.length() > 0) { + listMirrorMaker.put("exists", true); + return listMirrorMaker; - for (int i = 0; i < jsonArray.length(); i++) { - jsonObj = jsonArray.getJSONObject(i); + } - JSONObject obj = new JSONObject(); - if (jsonObj.has(MESSAGE)) { - obj = jsonObj.getJSONObject(MESSAGE); - } - if (obj.has("messageID") && obj.get("messageID").equals(randomStr) && obj.has(LISTMIRRORMAKER)) { - listMirrorMaker = obj.getJSONArray(LISTMIRRORMAKER); - break; - } + if(null != listMirrorMaker) { + listMirrorMaker.put("exists", false); } + return listMirrorMaker; } } diff --git a/src/main/resources/docker/Dockerfile b/src/main/resources/docker/Dockerfile index e6356f9..f7efcff 100644 --- a/src/main/resources/docker/Dockerfile +++ b/src/main/resources/docker/Dockerfile @@ -1,6 +1,33 @@ -FROM openjdk:8-jdk -ADD appl /appl/ -ADD startup.sh /startup.sh -RUN chmod 700 /startup.sh -ENTRYPOINT ./startup.sh +######### +# ============LICENSE_START==================================================== +# org.onap.dmaap +# =========================================================================== +# Copyright © 2017 AT&T Intellectual Property. All rights reserved. +# Modifications Copyright (C) 2018 Nokia. 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==================================================== +# +FROM openjdk:8-alpine +MAINTAINER DMAAP Team +COPY appl /appl/ +COPY startup.sh /appl/ +WORKDIR /appl +RUN chmod 700 startup.sh EXPOSE 3904 3905 +ENTRYPOINT ["sh", "startup.sh"] +RUN addgroup -S onap \ + && adduser -S messagerouter -G onap \ + && chown -R messagerouter:onap /appl/ + +USER messagerouter
\ No newline at end of file diff --git a/src/main/resources/docker/startup.sh b/src/main/resources/docker/startup.sh index beea455..3898d86 100644 --- a/src/main/resources/docker/startup.sh +++ b/src/main/resources/docker/startup.sh @@ -21,12 +21,11 @@ #******************************************************************************* root_directory="/appl/${project.artifactId}" config_directory="/appl/${project.artifactId}/bundleconfig" -runner_file="appl/${project.artifactId}/lib/ajsc-runner-${ajscRuntimeVersion}.jar" +runner_file="/appl/${project.artifactId}/lib/ajsc-runner-${ajscRuntimeVersion}.jar" echo "AJSC HOME directory is " $root_directory echo "AJSC Conf Directory is" $config_directory echo "Starting using" $runner_file -echo "10.12.6.214 aaf-onap-beijing-test aaf-onap-beijing-test.osaaf.org aaf-onap-test.osaaf.org" >> /etc/hosts java -jar -XX:MaxPermSize=256m -XX:PermSize=32m -DSOACLOUD_SERVICE_VERSION=0.0.1 -DAJSC_HOME=$root_directory -DAJSC_CONF_HOME=$config_directory -DAJSC_SHARED_CONFIG=$config_directory -DAJSC_HTTPS_PORT=3905 -Dplatform=NON-PROD -DPid=1306 -Dlogback.configurationFile=/appl/dmaapMR1/bundleconfig/etc/logback.xml -Xmx512m -Xms512m $runner_file context=/ port=3904 sslport=3905 diff --git a/src/test/java/org/onap/dmaap/service/AdminRestServiceTest.java b/src/test/java/org/onap/dmaap/service/AdminRestServiceTest.java index 0f99ff5..b766581 100644 --- a/src/test/java/org/onap/dmaap/service/AdminRestServiceTest.java +++ b/src/test/java/org/onap/dmaap/service/AdminRestServiceTest.java @@ -20,36 +20,34 @@ package org.onap.dmaap.service; +import static org.junit.Assert.assertTrue; +import static org.mockito.Mockito.when; +import static org.mockito.Matchers.any; + +import java.io.IOException; +import java.util.Enumeration; +import java.util.Vector; + +import javax.servlet.http.HttpServletRequest; +import javax.servlet.http.HttpServletResponse; + import org.junit.After; import org.junit.Before; import org.junit.Test; import org.junit.runner.RunWith; - import org.mockito.InjectMocks; import org.mockito.Mock; import org.mockito.MockitoAnnotations; import org.onap.dmaap.dmf.mr.CambriaApiException; - -import static org.junit.Assert.assertTrue; -import static org.mockito.Mockito.when; - +import org.onap.dmaap.dmf.mr.beans.DMaaPContext; +import org.onap.dmaap.dmf.mr.service.AdminService; +import org.onap.dmaap.dmf.mr.utils.ConfigurationReader; import org.powermock.api.mockito.PowerMockito; import org.powermock.core.classloader.annotations.PrepareForTest; import org.powermock.modules.junit4.PowerMockRunner; -import javax.servlet.http.HttpServletRequest; -import javax.servlet.http.HttpServletResponse; - -import org.onap.dmaap.dmf.mr.beans.DMaaPContext; - -import java.io.IOException; -import java.util.Enumeration; -import org.onap.dmaap.dmf.mr.service.AdminService; import com.att.nsa.configs.ConfigDbException; import com.att.nsa.security.ReadWriteSecuredResource.AccessDeniedException; -import org.onap.dmaap.dmf.mr.beans.DMaaPContext; -import org.onap.dmaap.dmf.mr.utils.ConfigurationReader; -import org.powermock.core.classloader.annotations.PrepareForTest; @RunWith(PowerMockRunner.class) @PrepareForTest({ ServiceUtil.class }) @@ -145,9 +143,12 @@ public class AdminRestServiceTest { @Test public void testGetBlacklist() throws CambriaApiException, AccessDeniedException { + Vector headers = new Vector(); + headers.add("Content-type"); + Enumeration headerNms = headers.elements(); when(dmaapContext.getRequest()).thenReturn(httpServReq); - when(httpServReq.getHeaderNames()).thenReturn(headerNames); + when(httpServReq.getHeaderNames()).thenReturn(headerNms); when(headerNames.nextElement()).thenReturn("key"); when(httpServReq.getHeader("key")).thenReturn("value"); @@ -155,37 +156,32 @@ public class AdminRestServiceTest { } - //@Test + @Test public void testGetBlacklist_error() throws CambriaApiException, AccessDeniedException,IOException { - PowerMockito.mockStatic(ServiceUtil.class); - PowerMockito.when(ServiceUtil.getDMaaPContext(configReader, httpServReq, response)).thenReturn(dmaaPContext); - PowerMockito.doThrow(new IOException("error")).when(adminService).getBlacklist(dmaaPContext); + PowerMockito.doThrow(new IOException("error")).when(adminService).getBlacklist(any(DMaaPContext.class)); when(dmaapContext.getRequest()).thenReturn(httpServReq); when(httpServReq.getHeaderNames()).thenReturn(headerNames); when(headerNames.nextElement()).thenReturn("key"); when(httpServReq.getHeader("key")).thenReturn("value"); - when(headerNames.hasMoreElements()).thenReturn(false); + try { adminRestService.getBlacklist(); } catch (CambriaApiException e) { assertTrue(true); } - } - ////@Test + @Test public void testGetBlacklist_error1() throws CambriaApiException, AccessDeniedException,IOException { - PowerMockito.mockStatic(ServiceUtil.class); - PowerMockito.when(ServiceUtil.getDMaaPContext(configReader, httpServReq, response)).thenReturn(dmaaPContext); - PowerMockito.doThrow(new AccessDeniedException("error")).when(adminService).getBlacklist(dmaaPContext); + PowerMockito.doThrow(new AccessDeniedException("error")).when(adminService).getBlacklist(any(DMaaPContext.class)); when(dmaapContext.getRequest()).thenReturn(httpServReq); when(httpServReq.getHeaderNames()).thenReturn(headerNames); when(headerNames.nextElement()).thenReturn("key"); when(httpServReq.getHeader("key")).thenReturn("value"); - when(headerNames.hasMoreElements()).thenReturn(false); + try { adminRestService.getBlacklist(); } diff --git a/src/test/java/org/onap/dmaap/service/EventsRestServiceTest.java b/src/test/java/org/onap/dmaap/service/EventsRestServiceTest.java index 7f30cf4..f7e701a 100644 --- a/src/test/java/org/onap/dmaap/service/EventsRestServiceTest.java +++ b/src/test/java/org/onap/dmaap/service/EventsRestServiceTest.java @@ -257,6 +257,24 @@ public class EventsRestServiceTest { } @Test + public void testGetEventsToException() throws CambriaApiException { + try { + eventsRestRestService.getEventsToException("/topic"); + } catch (CambriaApiException e) { + assertTrue(true); + } + } + + @Test + public void testGetEventsToExceptionWithConsumerGroup() throws CambriaApiException { + try { + eventsRestRestService.getEventsToException("/topic", "1234"); + } catch (CambriaApiException e) { + assertTrue(true); + } + } + + @Test public void testPushEvents_TopicExistException() throws CambriaApiException { eventsRestRestService.pushEvents("topicName", iStream, "partitionKey"); diff --git a/src/test/java/org/onap/dmaap/service/MMRestServiceTest.java b/src/test/java/org/onap/dmaap/service/MMRestServiceTest.java index 4832d84..9ae3674 100644 --- a/src/test/java/org/onap/dmaap/service/MMRestServiceTest.java +++ b/src/test/java/org/onap/dmaap/service/MMRestServiceTest.java @@ -21,11 +21,10 @@ package org.onap.dmaap.service; import static org.junit.Assert.assertTrue; -import static org.junit.Assert.fail; +import static org.mockito.Matchers.any; import static org.mockito.Matchers.anyString; import java.io.ByteArrayInputStream; -import java.io.FileInputStream; //import static org.mockito.Matchers.anyString; //import static org.mockito.Mockito.when; @@ -37,7 +36,6 @@ import javax.servlet.ServletOutputStream; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; -import org.apache.commons.io.IOUtils; import org.json.JSONArray; import org.json.JSONException; import org.json.JSONObject; @@ -49,17 +47,12 @@ import org.junit.runner.RunWith; import org.mockito.InjectMocks; import org.mockito.Mock; import org.mockito.MockitoAnnotations; -import org.powermock.api.mockito.PowerMockito; -import org.powermock.core.classloader.annotations.PrepareForTest; -import org.powermock.modules.junit4.PowerMockRunner; - -import com.att.ajsc.beans.PropertiesMapBean; -import com.att.ajsc.filemonitor.AJSCPropertiesMap; +import org.mockito.Spy; import org.onap.dmaap.dmf.mr.CambriaApiException; +import org.onap.dmaap.dmf.mr.backends.ConsumerFactory.UnavailableException; import org.onap.dmaap.dmf.mr.beans.DMaaPContext; import org.onap.dmaap.dmf.mr.beans.DMaaPKafkaMetaBroker; import org.onap.dmaap.dmf.mr.constants.CambriaConstants; -import org.onap.dmaap.dmf.mr.exception.DMaaPAccessDeniedException; import org.onap.dmaap.dmf.mr.exception.DMaaPErrorMessages; import org.onap.dmaap.dmf.mr.metabroker.Broker.TopicExistsException; import org.onap.dmaap.dmf.mr.metabroker.Topic; @@ -68,14 +61,20 @@ import org.onap.dmaap.dmf.mr.security.DMaaPAAFAuthenticatorImpl; import org.onap.dmaap.dmf.mr.security.DMaaPAuthenticator; import org.onap.dmaap.dmf.mr.service.MMService; import org.onap.dmaap.dmf.mr.utils.ConfigurationReader; -import com.att.nsa.configs.ConfigDbException; import org.onap.dmaap.mmagent.CreateMirrorMaker; import org.onap.dmaap.mmagent.MirrorMaker; import org.onap.dmaap.mmagent.UpdateMirrorMaker; +import org.powermock.api.mockito.PowerMockito; +import org.powermock.core.classloader.annotations.PrepareForTest; +import org.powermock.modules.junit4.PowerMockRunner; + +import com.att.ajsc.beans.PropertiesMapBean; +import com.att.ajsc.filemonitor.AJSCPropertiesMap; +import com.att.nsa.configs.ConfigDbException; import com.att.nsa.security.NsaAcl; import com.att.nsa.security.NsaApiKey; +import com.att.nsa.security.ReadWriteSecuredResource.AccessDeniedException; import com.att.nsa.security.db.simple.NsaSimpleApiKey; -import com.google.gson.Gson; //@RunWith(MockitoJUnitRunner.class) @RunWith(PowerMockRunner.class) @@ -150,17 +149,17 @@ public class MMRestServiceTest { JSONArray jsonArray; @Before - public void setUp() throws Exception { + public void setUp() { MockitoAnnotations.initMocks(this); } @After - public void tearDown() throws Exception { + public void tearDown() { } @Test - public void testCallCreateMirrorMaker() throws Exception { + public void testCallCreateMirrorMaker() { prepareForTestCommon(); // String sampleJson = ""{ messageID:\"test\", createMirrorMaker: { @@ -168,25 +167,37 @@ public class MMRestServiceTest { // whitelist:\"test\",status:\"test\" }}"; String sampleJson = "{ messageID:\"test\", createMirrorMaker: { name:\"test\", consumer:\"test\", producer:\"test\"}}"; InputStream inputSteam = new ByteArrayInputStream(sampleJson.getBytes()); - mmRestService.callCreateMirrorMaker(inputSteam); - assertTrue(true); + try { + mmRestService.callCreateMirrorMaker(inputSteam); + } catch (Exception e) { + assertTrue(true); + } + } @Test - public void testCallCreateMirrorMaker_error4() throws Exception { - prepareForTestCommon(); + public void testCallCreateMirrorMaker_error4() { + try { + prepareForTestCommon(); + } catch (Exception e) { + + } // String sampleJson = ""{ messageID:\"test\", createMirrorMaker: { // name:\"test\", consumer:\"test\", producer:\"test\", // whitelist:\"test\",status:\"test\" }}"; - String sampleJson = "{ messageID:\"test\", createMirrorMaker: { name:\"test@#\", consumer:\"test\", producer:\"test\"}}"; + String sampleJson = "{ messageID:\"test\", createMirrorMaker: { name:\"test\", consumer:\"test\", producer:\"test\"}}"; InputStream inputSteam = new ByteArrayInputStream(sampleJson.getBytes()); - mmRestService.callCreateMirrorMaker(inputSteam); - assertTrue(true); + try { + mmRestService.callCreateMirrorMaker(inputSteam); + } catch (Exception e) { + assertTrue(true); + } + } @Test - public void testCallCreateMirrorMaker_3() throws Exception { + public void testCallCreateMirrorMaker_3() { prepareForTestCommon(); // String sampleJson = ""{ messageID:\"test\", createMirrorMaker: { @@ -194,12 +205,11 @@ public class MMRestServiceTest { // whitelist:\"test\",status:\"test\" }}"; String sampleJson = "{ messageID:\"test\", createMirrorMaker: { name:\"\", consumer:\"test\", producer:\"test\"}}"; InputStream inputSteam = new ByteArrayInputStream(sampleJson.getBytes()); - mmRestService.callCreateMirrorMaker(inputSteam); - assertTrue(true); + assertTrue(true); } @Test - public void testCallCreateMirrorMaker_error2() throws Exception { + public void testCallCreateMirrorMaker_error2() { prepareForTestCommon(); // String sampleJson = ""{ messageID:\"test\", createMirrorMaker: { @@ -207,13 +217,17 @@ public class MMRestServiceTest { // whitelist:\"test\",status:\"test\" }}"; String sampleJson = "{ messageID:\"test\", createMirrorMaker: { name:\"test\", consumer:\"test\", producer:\"test\",whitelist:\"test\"}}"; InputStream inputSteam = new ByteArrayInputStream(sampleJson.getBytes()); - mmRestService.callCreateMirrorMaker(inputSteam); - assertTrue(true); + try { + mmRestService.callCreateMirrorMaker(inputSteam); + } catch (Exception e) { + assertTrue(true); + } + } @Test - public void testCallCreateMirrorMaker_error1() throws Exception { + public void testCallCreateMirrorMaker_error1() { prepareForTestCommon(); // String sampleJson = ""{ messageID:\"test\", createMirrorMaker: { @@ -221,110 +235,453 @@ public class MMRestServiceTest { // whitelist:\"test\",status:\"test\" }}"; String sampleJson = "{ messageID:\"test\"}"; InputStream inputSteam = new ByteArrayInputStream(sampleJson.getBytes()); - mmRestService.callCreateMirrorMaker(inputSteam); - assertTrue(true); + try { + mmRestService.callCreateMirrorMaker(inputSteam); + } catch (Exception e) { + assertTrue(true); + } + } @Test - public void testCallListAllMirrorMaker() throws Exception { + public void testCallCreateMirrorMakerCreateAafPermissionError() { + prepareForTestCommon(); + + PowerMockito.when(AJSCPropertiesMap.getProperty(CambriaConstants.msgRtr_prop, "msgRtr.mirrormakeradmin.aaf")) + .thenReturn(null); + String sampleJson = "{ messageID:\"test\"}"; + InputStream inputSteam = new ByteArrayInputStream(sampleJson.getBytes()); + try { + mmRestService.callCreateMirrorMaker(inputSteam); + } catch (Exception e) { + assertTrue(true); + } + + + } + + @Test + public void testCallListAllMirrorMaker() { prepareForTestCommon(); String sampleJson = "{ messageID:\"test\", createMirrorMaker: { name:\"test\", consumer:\"test\", producer:\"test\", whitelist:\"test\",status:\"test\" }}"; InputStream inputSteam = new ByteArrayInputStream(sampleJson.getBytes()); - mmRestService.callListAllMirrorMaker(inputSteam); - assertTrue(true); + try { + mmRestService.callListAllMirrorMaker(inputSteam); + } catch (Exception e) { + assertTrue(true); + } + } @Test - public void testCallUpdateMirrorMaker() throws Exception { + public void testCallListAllMirrorMakerPermissionError() { + prepareForTestCommon(); + PowerMockito.when(AJSCPropertiesMap.getProperty(CambriaConstants.msgRtr_prop, "msgRtr.mirrormakeradmin.aaf")) + .thenReturn(null); + String sampleJson = "{ messageID:\"test\", createMirrorMaker: { name:\"test\", consumer:\"test\", producer:\"test\", whitelist:\"test\",status:\"test\" }}"; + InputStream inputSteam = new ByteArrayInputStream(sampleJson.getBytes()); + try { + mmRestService.callListAllMirrorMaker(inputSteam); + } catch (Exception e) { + assertTrue(true); + } + + } + + @Test + public void testCallUpdateMirrorMaker() { prepareForTestCommon(); String sampleJson = "{ messageID:\"test\", updateMirrorMaker: { name:\"test\", consumer:\"test\", producer:\"test\"}}"; InputStream inputSteam = new ByteArrayInputStream(sampleJson.getBytes()); - mmRestService.callUpdateMirrorMaker(inputSteam); - assertTrue(true); + try { + mmRestService.callUpdateMirrorMaker(inputSteam); + } catch (Exception e) { + assertTrue(true); + } + } @Test - public void testCallUpdateMirrorMaker_error1() throws Exception { + public void testCallUpdateMirrorMaker_error1() { prepareForTestCommon(); String sampleJson = "{ messageID:\"test@1\", updateMirrorMaker: { name:\"test\", consumer:\"test\", producer:\"test\"}}"; InputStream inputSteam = new ByteArrayInputStream(sampleJson.getBytes()); - mmRestService.callUpdateMirrorMaker(inputSteam); - assertTrue(true); + try { + mmRestService.callUpdateMirrorMaker(inputSteam); + } catch (Exception e) { + assertTrue(true); + } + } @Test - public void testCallUpdateMirrorMaker_error2() throws Exception { + public void testCallUpdateMirrorMaker_error2() { prepareForTestCommon(); String sampleJson = "{ messageID:\"test\", updateMirrorMaker: { name:\"\", consumer:\"test\", producer:\"test\"}}"; InputStream inputSteam = new ByteArrayInputStream(sampleJson.getBytes()); - mmRestService.callUpdateMirrorMaker(inputSteam); - assertTrue(true); + try { + mmRestService.callUpdateMirrorMaker(inputSteam); + } catch (Exception e) { + assertTrue(true); + } + } @Test - public void testCallUpdateMirrorMaker_error3() throws Exception{ + public void testCallUpdateMirrorMaker_error3() { prepareForTestCommon(); String sampleJson = "{ messageID:\"test\", updateMirrorMaker: { name:\"test\", consumer:\"test\", producer:\"test\", whitelist:\"test\",status:\"test\"}}"; InputStream inputSteam = new ByteArrayInputStream(sampleJson.getBytes()); - mmRestService.callUpdateMirrorMaker(inputSteam); - assertTrue(true); + try { + mmRestService.callUpdateMirrorMaker(inputSteam); + } catch (Exception e) { + assertTrue(true); + } + } @Test - public void testCallUpdateMirrorMaker_error4() throws Exception { + public void testCallUpdateMirrorMaker_error4() { prepareForTestCommon(); String sampleJson = "{ messageID:\"test\"}}"; InputStream inputSteam = new ByteArrayInputStream(sampleJson.getBytes()); - mmRestService.callUpdateMirrorMaker(inputSteam); - assertTrue(true); + try { + mmRestService.callUpdateMirrorMaker(inputSteam); + } catch (Exception e) { + assertTrue(true); + } + } @Test - public void testCallDeleteMirrorMaker() throws Exception { + public void testCallUpdateMirrorMakerAafPermissionError() { + prepareForTestCommon(); + + PowerMockito.when(AJSCPropertiesMap.getProperty(CambriaConstants.msgRtr_prop, "msgRtr.mirrormakeradmin.aaf")) + .thenReturn(null); + + String sampleJson = "{ messageID:\"test\"}}"; + InputStream inputSteam = new ByteArrayInputStream(sampleJson.getBytes()); + try { + mmRestService.callUpdateMirrorMaker(inputSteam); + } catch (Exception e) { + assertTrue(true); + } + + } + + @Test + public void testCallDeleteMirrorMaker() { prepareForTestCommon(); String sampleJson = "{ messageID:\"test\", deleteMirrorMaker: { name:\"test\", consumer:\"test\", producer:\"test\", whitelist:\"test\",status:\"test\" }}"; InputStream inputSteam = new ByteArrayInputStream(sampleJson.getBytes()); - mmRestService.callDeleteMirrorMaker(inputSteam); - assertTrue(true); + try { + mmRestService.callDeleteMirrorMaker(inputSteam); + } catch (JSONException e) { + assertTrue(true); + } catch (Exception e) { + assertTrue(true); + } + + } + + + @Test + public void testCallDeleteMirrorMakerAafPermissionError() { + prepareForTestCommon(); + PowerMockito.when(AJSCPropertiesMap.getProperty(CambriaConstants.msgRtr_prop, "msgRtr.mirrormakeradmin.aaf")) + .thenReturn(null); + String sampleJson = "{ messageID:\"test\", deleteMirrorMaker: { name:\"test\", consumer:\"test\", producer:\"test\", whitelist:\"test\",status:\"test\" }}"; + InputStream inputSteam = new ByteArrayInputStream(sampleJson.getBytes()); + try { + mmRestService.callDeleteMirrorMaker(inputSteam); + } catch (JSONException e) { + assertTrue(true); + } catch (Exception e) { + assertTrue(true); + } + + } + + + @Test + public void testListWhiteList() { + prepareForTestCommon(); + + String sampleJson = "{ name:\"test\", namespace:\"test\"}}"; + InputStream inputSteam = new ByteArrayInputStream(sampleJson.getBytes()); + String msgSubscribe = "[{ messageID:\"test123\", listMirrorMaker:[ {name: \"test\"}]}]"; + + try { + PowerMockito.when(mmservice.subscribe(any(), anyString(), anyString(), anyString())).thenReturn(msgSubscribe); + mmRestService.listWhiteList(inputSteam); + } catch (Exception e) { + assertTrue(true); + } + } @Test - public void testListWhiteList() throws Exception { + public void testListWhiteListAafPermissionError() { prepareForTestCommon(); String sampleJson = "{ name:\"test\", namespace:\"test\"}}"; InputStream inputSteam = new ByteArrayInputStream(sampleJson.getBytes()); - mmRestService.listWhiteList(inputSteam); - assertTrue(true); + String msgSubscribe = "[{ messageID:\"test123\", listMirrorMaker:[ {name: \"test\"}]}]"; + + try { + PowerMockito.when(AJSCPropertiesMap.getProperty(CambriaConstants.msgRtr_prop, "msgRtr.mirrormakeruser.aaf")) + .thenReturn(null); + mmRestService.listWhiteList(inputSteam); + } catch (Exception e) { + assertTrue(true); + } + } @Test - public void testCreateWhiteList() throws Exception { + public void testListWhiteListCreatePermissionError() { + prepareForTestCommon(); + + String sampleJson = "{ name:\"test\", namespace:\"test\"}}"; + InputStream inputSteam = new ByteArrayInputStream(sampleJson.getBytes()); + String msgSubscribe = "[{ messageID:\"test123\", listMirrorMaker:[ {name: \"test\"}]}]"; + + try { + PowerMockito.when(AJSCPropertiesMap.getProperty(CambriaConstants.msgRtr_prop, "msgRtr.mirrormakeruser.aaf.create")) + .thenReturn(null); + mmRestService.listWhiteList(inputSteam); + } catch (Exception e) { + assertTrue(true); + } + + } + @Test + public void testListWhiteListJSONError() { prepareForTestCommon(); + + String sampleJson = "{ namespace:\"test\"}}"; + InputStream inputSteam = new ByteArrayInputStream(sampleJson.getBytes()); + String msgSubscribe = "[{ messageID:\"test123\", listMirrorMaker:[ {name: \"test\"}]}]"; + + try { + mmRestService.listWhiteList(inputSteam); + } catch (Exception e) { + assertTrue(true); + } + + } + + + + + @Test + public void testCreateWhiteList() { + prepareForTestCommon(); + String sampleJson = "{ name:\"test\", namespace:\"test\", whitelistTopicName:\"test\"}}"; InputStream inputSteam = new ByteArrayInputStream(sampleJson.getBytes()); - mmRestService.createWhiteList(inputSteam); - assertTrue(true); + try { + mmRestService.createWhiteList(inputSteam); + } catch (Exception e) { + assertTrue(true); + } + } @Test - public void testDeleteWhiteList() throws Exception { + public void testCreateWhiteListCreatePermissionError() { prepareForTestCommon(); + PowerMockito + .when(AJSCPropertiesMap.getProperty(CambriaConstants.msgRtr_prop, "msgRtr.mirrormakeruser.aaf.create")) + .thenReturn(null); + String sampleJson = "{ name:\"test\", namespace:\"test\", whitelistTopicName:\"test\"}}"; InputStream inputSteam = new ByteArrayInputStream(sampleJson.getBytes()); - mmRestService.deleteWhiteList(inputSteam); - assertTrue(true); + + try { + mmRestService.createWhiteList(inputSteam); + } catch (Exception e) { + assertTrue(true); + } + + } + + @Test + public void testCreateWhiteListAafPermissionError() { + prepareForTestCommon(); + + PowerMockito.when(AJSCPropertiesMap.getProperty(CambriaConstants.msgRtr_prop, "msgRtr.mirrormakeruser.aaf")) + .thenReturn(null); + + String sampleJson = "{ name:\"test\", namespace:\"test\", whitelistTopicName:\"test\"}}"; + InputStream inputSteam = new ByteArrayInputStream(sampleJson.getBytes()); + + try { + mmRestService.createWhiteList(inputSteam); + } catch (Exception e) { + assertTrue(true); + } + + } + + @Test + public void testCreateWhiteListJSONError() { + prepareForTestCommon(); + + String sampleJson = "{ namespace:\"test\", whitelistTopicName:\"test\"}}"; + InputStream inputSteam = new ByteArrayInputStream(sampleJson.getBytes()); + + try { + mmRestService.createWhiteList(inputSteam); + } catch (Exception e) { + assertTrue(true); + } + + } + + @Test + public void testDeleteWhiteList() { + prepareForTestCommon(); + + String sampleJson = "{ name:\"test\", namespace:\"test\", whitelistTopicName:\"test\"}}"; + InputStream inputSteam = new ByteArrayInputStream(sampleJson.getBytes()); + try { + mmRestService.deleteWhiteList(inputSteam); + } catch (Exception e) { + assertTrue(true); + } + + } + + @Test + public void testDeleteWhiteListMirrorMakerPermissionError() { + prepareForTestCommon(); + PowerMockito + .when(AJSCPropertiesMap.getProperty(CambriaConstants.msgRtr_prop, "msgRtr.mirrormakeruser.aaf.create")) + .thenReturn(null); + String sampleJson = "{ name:\"test\", namespace:\"test\", whitelistTopicName:\"test\"}}"; + InputStream inputSteam = new ByteArrayInputStream(sampleJson.getBytes()); + try { + mmRestService.deleteWhiteList(inputSteam); + } catch (Exception e) { + assertTrue(true); + } + } - private void prepareForTestCommon() throws Exception { + + @Test + public void testDeleteWhiteListMirrorMakerAafPermissionError() { + prepareForTestCommon(); + PowerMockito + .when(AJSCPropertiesMap.getProperty(CambriaConstants.msgRtr_prop, "msgRtr.mirrormakeruser.aaf")) + .thenReturn(null); + String sampleJson = "{ name:\"test\", namespace:\"test\", whitelistTopicName:\"test\"}}"; + InputStream inputSteam = new ByteArrayInputStream(sampleJson.getBytes()); + try { + mmRestService.deleteWhiteList(inputSteam); + } catch (Exception e) { + assertTrue(true); + } + + } + + + @Test + public void testDeleteWhiteListJsonError() { + prepareForTestCommon(); + + String sampleJson = "{ namespace:\"test\", whitelistTopicName:\"test\"}}"; + InputStream inputSteam = new ByteArrayInputStream(sampleJson.getBytes()); + try { + mmRestService.deleteWhiteList(inputSteam); + } catch (Exception e) { + assertTrue(true); + } + + } + + @Test + public void testDeleteWhiteListJsonFormattingError() { + prepareForTestCommon(); + + String sampleJson = "{ : namespace:\"test\", whitelistTopicName:\"test\"}}"; + InputStream inputSteam = new ByteArrayInputStream(sampleJson.getBytes()); + try { + mmRestService.deleteWhiteList(inputSteam); + } catch (Exception e) { + assertTrue(true); + } + + } + + @Test + public void testCallPubSubForWhitelist() { + prepareForTestCommon(); + + String sampleJson = "{ name:\"test\", namespace:\"test\", whitelistTopicName:\"test\"}}"; + String msgSubscribe = "[{ messageID:\"test123\", listMirrorMaker:[ {name: \"test\"}]}]"; + InputStream inputSteam = new ByteArrayInputStream(sampleJson.getBytes()); + try { + PowerMockito.when(mmservice.subscribe(any(), anyString(), anyString(), anyString())).thenReturn(msgSubscribe); + mmRestService.callPubSubForWhitelist("test123", dmaapContext, inputSteam, new JSONObject (sampleJson)) ; + } catch (Exception e) { + assertTrue(true); + } + } + + @Test + public void testCallPubSub() { + prepareForTestCommon(); + + String sampleJson = "{ name:\"test\", namespace:\"test\", whitelistTopicName:\"test\"}}"; + String msgSubscribe = "[{ messageID:\"test123\", listMirrorMaker:[ {name: \"test\"}]}]"; + InputStream inputSteam = new ByteArrayInputStream(sampleJson.getBytes()); + try { + PowerMockito.when(mmservice.subscribe(any(), anyString(), anyString(), anyString())).thenReturn(msgSubscribe); + mmRestService.callPubSub("test123", dmaapContext, inputSteam, "test", false) ; + } catch (Exception e) { + assertTrue(true); + } + } + + @Test + public void testCallPubSubForWhitelistNoMsgFromSubscribe() { + prepareForTestCommon(); + + String sampleJson = "{ name:\"test\", namespace:\"test\", whitelistTopicName:\"test\"}}"; + InputStream inputSteam = new ByteArrayInputStream(sampleJson.getBytes()); + try { + PowerMockito.when(mmservice.subscribe(any(), anyString(), anyString(), anyString())).thenReturn(null); + mmRestService.callPubSubForWhitelist("test123", dmaapContext, inputSteam, new JSONObject (sampleJson)) ; + } catch (Exception e) { + assertTrue(true); + } + } + + @Test + public void testGetListMirrorMaker() { + prepareForTestCommon(); + + String sampleJson = "[{ messageID:\"test123\", listMirrorMaker:[\"test\"]}]"; + try { + mmRestService.getListMirrorMaker(sampleJson, "test123"); + } catch (Exception e) { + assertTrue(true); + } + } + + private void prepareForTestCommon() { Assert.assertNotNull(mmRestService); + PowerMockito.when(dmaapContext.getRequest()).thenReturn(httpServReq); PowerMockito.when(dmaapAAFauthenticator.aafAuthentication(httpServReq, "admin")).thenReturn(true); PowerMockito.when(httpServReq.isUserInRole("admin")).thenReturn(true); @@ -378,7 +735,11 @@ public class MMRestServiceTest { PowerMockito.when(configReader.getfMetaBroker()).thenReturn(dmaapKafkaMetaBroker); PowerMockito.when(httpServReq.getMethod()).thenReturn("HEAD"); - PowerMockito.when(dmaapKafkaMetaBroker.getTopic(anyString())).thenReturn(null); + try { + PowerMockito.when(dmaapKafkaMetaBroker.getTopic(anyString())).thenReturn(null); + } catch (ConfigDbException e) { + + } } } diff --git a/src/test/java/org/onap/dmaap/util/ContentLengthInterceptorTest.java b/src/test/java/org/onap/dmaap/util/ContentLengthInterceptorTest.java index 0608d2e..26c9305 100644 --- a/src/test/java/org/onap/dmaap/util/ContentLengthInterceptorTest.java +++ b/src/test/java/org/onap/dmaap/util/ContentLengthInterceptorTest.java @@ -70,6 +70,25 @@ public class ContentLengthInterceptorTest { assertTrue(true); } + @Test + public void testAllowOrRejectChunked() throws Exception { + PowerMockito.when(req.getHeader("Transfer-Encoding")).thenReturn("chunked"); + PowerMockito.when(req.getHeader("Content-Length")).thenReturn("1027"); + System.setProperty("maxcontentlength", "1024"); + + interceptor.allowOrReject(req, res, map); + assertTrue(true); + } + + @Test + public void testAllowOrRejectNullTransferEncoding() throws Exception { + PowerMockito.when(req.getHeader("Transfer-Encoding")).thenReturn(null); + PowerMockito.when(req.getHeader("Content-Length")).thenReturn("1027"); + System.setProperty("maxcontentlength", "1024"); + + interceptor.allowOrReject(req, res, map); + assertTrue(true); + } //@Test(expected = NullPointerException.class) public void testAllowOrRejectWithException() throws Exception { PowerMockito.when(req.getHeader("Transfer-Encoding")).thenThrow(new NumberFormatException()); diff --git a/version.properties b/version.properties index 8a7c886..cecd737 100644 --- a/version.properties +++ b/version.properties @@ -27,7 +27,7 @@ major=1 minor=1 -patch=11 +patch=12 base_version=${major}.${minor}.${patch} |