From d1d033f52cdcccf5dc098892d2fb6b2316b160b4 Mon Sep 17 00:00:00 2001 From: Surabhi Date: Mon, 18 Apr 2022 13:00:41 +0530 Subject: [PATCH 1/8] Build & deploy workflow --- .github/workflows/build.yml | 64 +++++++++++++++++++++++++ .github/workflows/docker-build-push.yml | 29 +++++++++++ Dockerfile | 38 +++++++++++++++ pom.xml | 4 +- settings.xml | 32 +++++++++++++ 5 files changed, 165 insertions(+), 2 deletions(-) create mode 100644 .github/workflows/build.yml create mode 100644 .github/workflows/docker-build-push.yml create mode 100644 Dockerfile create mode 100644 settings.xml diff --git a/.github/workflows/build.yml b/.github/workflows/build.yml new file mode 100644 index 0000000..d046ef8 --- /dev/null +++ b/.github/workflows/build.yml @@ -0,0 +1,64 @@ +name: Build on Push & Pull Request +on: [push, pull_request] + +jobs: + build: + name: Build + runs-on: ubuntu-latest + steps: + - uses: actions/checkout@v1 + with: + fetch-depth: 0 # Shallow clones should be disabled for a better relevancy of analysis + + - name: Set up JDK 11 + uses: actions/setup-java@v1 + with: + java-version: 11 + distribution: 'temurin' + + - name: Cache Maven packages + uses: actions/cache@v1 + with: + path: ~/.m2 + key: ${{ runner.os }}-m2-${{ hashFiles('**/pom.xml') }} + restore-keys: ${{ runner.os }}-m2 + + - name: maven-settings-xml-action + uses: whelk-io/maven-settings-xml-action@v20 + with: + servers: > + [ + { + "id": "github-message-rosa", + "username": "${env.GITHUB_USERNAME}", + "password": "${env.GITHUB_TOKEN}" + }, + { + "id": "github-adapter", + "username": "${env.GITHUB_USERNAME}", + "password": "${env.GITHUB_TOKEN}" + }, + { + "id": "github-utils", + "username": "${env.GITHUB_USERNAME}", + "password": "${env.GITHUB_TOKEN}" + }, + { + "id": "github-dao", + "username": "${env.GITHUB_USERNAME}", + "password": "${env.GITHUB_TOKEN}" + } + ] + output_file: $GITHUB_WORKSPACE/settings.xml + env: + GITHUB_USERNAME: ${{ secrets.USERNAME }} + GITHUB_TOKEN: ${{ secrets.TOKEN }} + + - name: Build and analyze + env: + GITHUB_USERNAME: ${{ secrets.USERNAME }} + GITHUB_TOKEN: ${{ secrets.TOKEN }} + run: | + cat $GITHUB_WORKSPACE/settings.xml + mvn -B verify -s $GITHUB_WORKSPACE/settings.xml -DskipTests + \ No newline at end of file diff --git a/.github/workflows/docker-build-push.yml b/.github/workflows/docker-build-push.yml new file mode 100644 index 0000000..5becbb7 --- /dev/null +++ b/.github/workflows/docker-build-push.yml @@ -0,0 +1,29 @@ +name: Docker Build & Push on Tag + +on: + push: + tags: + - 'v*.*.*' + +jobs: + docker-build-push: + runs-on: ubuntu-20.04 + timeout-minutes: 40 + steps: + - uses: actions/checkout@v1 + - name: Login to DockerHub Registry + run: echo ${{ secrets.DOCKER_HUB_ACCESS_TOKEN }} | docker login -u ${{ secrets.DOCKER_HUB_USERNAME }} --password-stdin + - name: Set output + id: vars + run: echo ::set-output name=tag::${GITHUB_REF#refs/*/} + - name: Build the tagged Docker image + env: + RELEASE_VERSION: ${{ steps.vars.outputs.tag }} + run: | + echo $RELEASE_VERSION + echo ${{ steps.vars.outputs.tag }} + docker build . --file Dockerfile --build-arg username=${{ secrets.USERNAME }} --build-arg token=${{ secrets.TOKEN }} --tag samagragovernance/orchestrator:$RELEASE_VERSION + - name: Push the tagged Docker image + env: + RELEASE_VERSION: ${{ steps.vars.outputs.tag }} + run: docker push samagragovernance/orchestrator:$RELEASE_VERSION diff --git a/Dockerfile b/Dockerfile new file mode 100644 index 0000000..a9e105c --- /dev/null +++ b/Dockerfile @@ -0,0 +1,38 @@ +# Build stage +FROM maven:3.6.0-jdk-11-slim AS build +ENV HOME=/home/app +RUN mkdir -p $HOME +WORKDIR $HOME +ADD pom.xml $HOME + +# Arguments +ARG username +ARG token + +# Print arguments value +RUN echo $username +RUN echo $token + +# copy settings file to home settings file +COPY /settings.xml $HOME/settings.xml + +# replace username & token in settings file +RUN sed -i "s/USERNAME/$username/g" $HOME/settings.xml +RUN sed -i "s/TOKEN/$token/g" $HOME/settings.xml +RUN cat $HOME/settings.xml + +# Maven package build +RUN mvn -s $HOME/settings.xml dependency:go-offline + +ADD /src $HOME/src +RUN mvn package -s $HOME/settings.xml -DskipTests=true + +# Package stage +FROM openjdk:12-alpine +ENV HOME=/home/app +ENV export $(cat .env | xargs) +WORKDIR $HOME +COPY --from=build $HOME/target/*.jar app.jar + +EXPOSE 8080 +ENTRYPOINT ["java","-jar","app.jar"] diff --git a/pom.xml b/pom.xml index 5f091cc..a52e57c 100644 --- a/pom.xml +++ b/pom.xml @@ -103,12 +103,12 @@ com.uci message-rosa - 0.0.1-SNAPSHOT + 0.0.1 com.uci utils - 0.0.1-SNAPSHOT + 0.0.3 org.springframework.boot diff --git a/settings.xml b/settings.xml new file mode 100644 index 0000000..f1b88bf --- /dev/null +++ b/settings.xml @@ -0,0 +1,32 @@ + + + + github + USERNAME + TOKEN + + + github-utils + USERNAME + TOKEN + + + github-message-rosa + USERNAME + TOKEN + + + github-dao + USERNAME + TOKEN + + + github-adapter + USERNAME + TOKEN + + + From f5c7f49774a6f3cfef09c255ebc9665b87c38289 Mon Sep 17 00:00:00 2001 From: Surabhi Date: Mon, 18 Apr 2022 13:03:15 +0530 Subject: [PATCH 2/8] fix --- pom.xml | 19 +++++++++++++++++++ 1 file changed, 19 insertions(+) diff --git a/pom.xml b/pom.xml index a52e57c..d810a5c 100644 --- a/pom.xml +++ b/pom.xml @@ -19,6 +19,25 @@ 11 + + + + github-utils + GitHub Packages + https://maven.pkg.github.com/samagra-comms/utils + + + github-dao + GitHub Packages + https://maven.pkg.github.com/samagra-comms/dao + + + github-message-rosa + GitHub Packages + https://maven.pkg.github.com/samagra-comms/message-rosa + + + org.springframework.boot From 79cbb24d200e34409bb76dcf20ff43d9a698949c Mon Sep 17 00:00:00 2001 From: Surabhi Date: Thu, 21 Apr 2022 15:32:17 +0530 Subject: [PATCH 3/8] dao version change --- pom.xml | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/pom.xml b/pom.xml index d810a5c..b05d195 100644 --- a/pom.xml +++ b/pom.xml @@ -109,7 +109,7 @@ com.uci dao - 1.0 + 0.0.1 org.springframework.boot From bfd2901034286d676257282f7fd3ca0c095450bb Mon Sep 17 00:00:00 2001 From: Surabhi Date: Tue, 26 Apr 2022 12:15:14 +0530 Subject: [PATCH 4/8] build changes- final --- .github/workflows/build.yml | 9 +++------ 1 file changed, 3 insertions(+), 6 deletions(-) diff --git a/.github/workflows/build.yml b/.github/workflows/build.yml index d046ef8..4bb346b 100644 --- a/.github/workflows/build.yml +++ b/.github/workflows/build.yml @@ -6,12 +6,9 @@ jobs: name: Build runs-on: ubuntu-latest steps: - - uses: actions/checkout@v1 - with: - fetch-depth: 0 # Shallow clones should be disabled for a better relevancy of analysis - + - uses: actions/checkout@v2 - name: Set up JDK 11 - uses: actions/setup-java@v1 + uses: actions/setup-java@v2 with: java-version: 11 distribution: 'temurin' @@ -60,5 +57,5 @@ jobs: GITHUB_TOKEN: ${{ secrets.TOKEN }} run: | cat $GITHUB_WORKSPACE/settings.xml - mvn -B verify -s $GITHUB_WORKSPACE/settings.xml -DskipTests + mvn -s $GITHUB_WORKSPACE/settings.xml clean install -DskipTests \ No newline at end of file From 47413398a1f6911482fa91a6ceaba0f4260a5237 Mon Sep 17 00:00:00 2001 From: Surabhi Date: Tue, 26 Apr 2022 12:16:49 +0530 Subject: [PATCH 5/8] build changes- final --- .github/workflows/build.yml | 4 +--- 1 file changed, 1 insertion(+), 3 deletions(-) diff --git a/.github/workflows/build.yml b/.github/workflows/build.yml index 4bb346b..67cfe66 100644 --- a/.github/workflows/build.yml +++ b/.github/workflows/build.yml @@ -55,7 +55,5 @@ jobs: env: GITHUB_USERNAME: ${{ secrets.USERNAME }} GITHUB_TOKEN: ${{ secrets.TOKEN }} - run: | - cat $GITHUB_WORKSPACE/settings.xml - mvn -s $GITHUB_WORKSPACE/settings.xml clean install -DskipTests + run: mvn -s $GITHUB_WORKSPACE/settings.xml clean install -DskipTests \ No newline at end of file From ae810936f4cb738f7bbb15b679fde19a8a8e182c Mon Sep 17 00:00:00 2001 From: Yashwant Date: Tue, 26 Apr 2022 12:45:51 +0530 Subject: [PATCH 6/8] minor changes --- pom.xml | 7 +- .../Consumer/ReactiveConsumerTest.java | 12 +++ .../Controllers/MessageRosaTest.java | 16 ++++ .../com/uci/orchestrator/User/TestConfig.java | 75 ++++++++++++++++++- 4 files changed, 106 insertions(+), 4 deletions(-) create mode 100644 src/test/java/com/uci/orchestrator/Consumer/ReactiveConsumerTest.java create mode 100644 src/test/java/com/uci/orchestrator/Controllers/MessageRosaTest.java diff --git a/pom.xml b/pom.xml index 5f091cc..c458a79 100644 --- a/pom.xml +++ b/pom.xml @@ -129,7 +129,12 @@ org.springframework.data spring-data-cassandra - + + io.projectreactor + reactor-test + test + + diff --git a/src/test/java/com/uci/orchestrator/Consumer/ReactiveConsumerTest.java b/src/test/java/com/uci/orchestrator/Consumer/ReactiveConsumerTest.java new file mode 100644 index 0000000..48a4ce3 --- /dev/null +++ b/src/test/java/com/uci/orchestrator/Consumer/ReactiveConsumerTest.java @@ -0,0 +1,12 @@ +package com.uci.orchestrator.Consumer; + +import org.junit.jupiter.api.Test; + +import static org.junit.jupiter.api.Assertions.*; + +class ReactiveConsumerTest { + + @Test + void onMessage() { + } +} \ No newline at end of file diff --git a/src/test/java/com/uci/orchestrator/Controllers/MessageRosaTest.java b/src/test/java/com/uci/orchestrator/Controllers/MessageRosaTest.java new file mode 100644 index 0000000..ec6a0a4 --- /dev/null +++ b/src/test/java/com/uci/orchestrator/Controllers/MessageRosaTest.java @@ -0,0 +1,16 @@ +package com.uci.orchestrator.Controllers; + +import org.junit.jupiter.api.Test; + +import static org.junit.jupiter.api.Assertions.*; + +class MessageRosaTest { + + @Test + void greeting() { + } + + @Test + void deleteLastMessage() { + } +} \ No newline at end of file diff --git a/src/test/java/com/uci/orchestrator/User/TestConfig.java b/src/test/java/com/uci/orchestrator/User/TestConfig.java index a7eab9c..da82030 100644 --- a/src/test/java/com/uci/orchestrator/User/TestConfig.java +++ b/src/test/java/com/uci/orchestrator/User/TestConfig.java @@ -1,13 +1,82 @@ package com.uci.orchestrator.User; +import com.fasterxml.jackson.core.JsonProcessingException; +import com.fasterxml.jackson.databind.JsonNode; +import com.fasterxml.jackson.databind.ObjectMapper; +import com.github.benmanes.caffeine.cache.Cache; +import com.uci.orchestrator.Consumer.CampaignConsumer; +import com.uci.utils.CampaignService; +import com.uci.utils.kafka.SimpleProducer; import io.fusionauth.client.FusionAuthClient; +import lombok.extern.slf4j.Slf4j; +import org.apache.kafka.clients.producer.Producer; +import org.apache.kafka.clients.producer.ProducerConfig; +import org.apache.logging.log4j.LogManager; +import org.apache.logging.log4j.Logger; +import org.mockito.Mock; +import org.mockito.Mockito; +import org.springframework.beans.factory.annotation.Autowired; import org.springframework.boot.test.context.TestConfiguration; import org.springframework.context.annotation.Bean; +import org.springframework.context.annotation.Configuration; +import org.springframework.kafka.core.DefaultKafkaProducerFactory; +import org.springframework.kafka.core.KafkaTemplate; +import org.springframework.kafka.core.ProducerFactory; +import org.springframework.web.reactive.function.client.WebClient; + +import java.util.HashMap; +import java.util.Map; + -@TestConfiguration public class TestConfig { - @Bean - public FusionAuthClient client() { + + @Autowired + SimpleProducer simpleProducer; + + @Bean + public Logger getLogger(){ + return LogManager.getLogger(); + } + + @Bean + public CampaignService getCampaignService() throws JsonProcessingException { + ObjectMapper objectMapper = new ObjectMapper(); + JsonNode botNode = objectMapper.readTree("{\"id\":\"api.bot.getByParam\",\"ver\":\"1.0\",\"ts\":\"2022-04-21T19:16:52.914Z\",\"params\":{\"resmsgid\":\"9a01a120-c1a7-11ec-afae-4f4769c7c758\",\"msgid\":\"9a00b6c0-c1a7-11ec-afae-4f4769c7c758\",\"status\":\"successful\",\"err\":null,\"errmsg\":null},\"responseCode\":\"OK\",\"result\":{\"data\":{\"id\":\"d655cf03-1f6f-4510-acf6-d3f51b488a5e\",\"name\":\"UCI Demo\",\"startingMessage\":\"Hi UCI\",\"users\":[],\"logicIDs\":[\"e96b0865-5a76-4566-8694-c09361b8ae32\"],\"owners\":null,\"created_at\":\"2021-07-08T18:48:37.740Z\",\"updated_at\":\"2022-02-11T14:09:53.570Z\",\"status\":\"enabled\",\"description\":\"For Internal Demo\",\"startDate\":\"2022-02-01T00:00:00.000Z\",\"endDate\":null,\"purpose\":\"For Internal Demo\",\"ownerOrgID\":\"ORG_001\",\"ownerID\":\"95e4942d-cbe8-477d-aebd-ad8e6de4bfc8\",\"logic\":[{\"id\":\"e96b0865-5a76-4566-8694-c09361b8ae32\",\"transformers\":[{\"id\":\"bbf56981-b8c9-40e9-8067-468c2c753659\",\"meta\":{\"form\":\"https://hosted.my.form.here.com\",\"formID\":\"UCI-demo-1\"}}],\"adapter\":\"44a9df72-3d7a-4ece-94c5-98cf26307324\",\"name\":\"UCI Demo\",\"created_at\":\"2021-07-08T18:47:44.925Z\",\"updated_at\":\"2022-02-03T12:29:32.959Z\",\"description\":null}]}}}\n"); + Cache cache = Mockito.mock(Cache.class); + Mockito.when(cache.getIfPresent("campaign-node-by-id:d655cf03-1f6f-4510-acf6-d3f51b488a5e")).thenReturn(botNode); + return new CampaignService(getWebClient(), getFusionAuthClient(), cache); + } + + @Bean + public CampaignConsumer getCampaignConsumer(){ + return new CampaignConsumer(); + } + + @Bean + public FusionAuthClient getFusionAuthClient() { return new FusionAuthClient("c0VY85LRCYnsk64xrjdXNVFFJ3ziTJ91r08Cm0Pcjbc", "http://134.209.150.161:9011"); } + + @Bean + public WebClient getWebClient(){ + return WebClient.builder().build(); + } + + @Bean + public Cache getCache(){ + return null; + } + + @Bean + public SimpleProducer getSimpleProducer(){ + Map configuration = new HashMap<>(); + configuration.put(ProducerConfig.BOOTSTRAP_SERVERS_CONFIG, "165.232.182.146:9094"); + configuration.put(ProducerConfig.CLIENT_ID_CONFIG, "sample-producer"); + configuration.put(ProducerConfig.ACKS_CONFIG, "all"); + configuration.put(ProducerConfig.KEY_SERIALIZER_CLASS_CONFIG, org.springframework.kafka.support.serializer.JsonSerializer.class); + configuration.put(ProducerConfig.VALUE_SERIALIZER_CLASS_CONFIG, org.springframework.kafka.support.serializer.JsonSerializer.class); + + ProducerFactory producerFactory = new DefaultKafkaProducerFactory(configuration); + return new SimpleProducer(new KafkaTemplate(producerFactory)); + } } \ No newline at end of file From aca56e434de977ea4ae41fe30ffcd32135ebaef4 Mon Sep 17 00:00:00 2001 From: Yashwant Date: Fri, 29 Apr 2022 17:31:14 +0530 Subject: [PATCH 7/8] temporary changes --- pom.xml | 5 + .../Application/AppConfigOrchestrator.java | 12 +- .../Consumer/ReactiveConsumer.java | 8 +- .../Health/ServiceStatusController.java | 2 - .../ApplicationConfiguration.java | 304 +++++++++++++++--- .../Consumer/CampaignConsumerTest.java | 125 +++---- .../Consumer/CampaignConsumerTest2.java | 88 ----- .../Consumer/ReactiveConsumerTest.java | 80 ++++- .../Controllers/MessageRosaTest.java | 16 - .../com/uci/orchestrator/IntegrationTest.java | 34 +- .../User/CampaignServiceTest.java | 25 -- .../com/uci/orchestrator/User/TestConfig.java | 82 ----- .../orchestrator/User/UserServiceTest.java | 31 -- src/test/resources/log4j2-testconfig.xml | 14 - 14 files changed, 425 insertions(+), 401 deletions(-) delete mode 100644 src/test/java/com/uci/orchestrator/Consumer/CampaignConsumerTest2.java delete mode 100644 src/test/java/com/uci/orchestrator/Controllers/MessageRosaTest.java delete mode 100644 src/test/java/com/uci/orchestrator/User/CampaignServiceTest.java delete mode 100644 src/test/java/com/uci/orchestrator/User/TestConfig.java delete mode 100644 src/test/java/com/uci/orchestrator/User/UserServiceTest.java delete mode 100644 src/test/resources/log4j2-testconfig.xml diff --git a/pom.xml b/pom.xml index a07e7c3..1373149 100644 --- a/pom.xml +++ b/pom.xml @@ -129,6 +129,11 @@ utils 0.0.3 + + org.mockito + mockito-junit-jupiter + 3.7.7 + org.springframework.boot spring-boot-starter-web diff --git a/src/main/java/com/uci/orchestrator/Application/AppConfigOrchestrator.java b/src/main/java/com/uci/orchestrator/Application/AppConfigOrchestrator.java index c461cdf..8c74d28 100644 --- a/src/main/java/com/uci/orchestrator/Application/AppConfigOrchestrator.java +++ b/src/main/java/com/uci/orchestrator/Application/AppConfigOrchestrator.java @@ -70,12 +70,12 @@ public CampaignService getCampaignService() { return new CampaignService(webClient, fusionAuthClient, cache); } - @Bean - public KieSession DroolSession() { - Resource resource = ResourceFactory.newClassPathResource("OrchestratorRules.xlsx", getClass()); - KieSession kSession = new DroolsBeanFactory().getKieSession(resource); - return kSession; - } +// @Bean +// public KieSession DroolSession() { +// Resource resource = ResourceFactory.newClassPathResource("OrchestratorRules.xlsx", getClass()); +// KieSession kSession = new DroolsBeanFactory().getKieSession(resource); +// return kSession; +// } @Bean Map kafkaConsumerConfiguration() { diff --git a/src/main/java/com/uci/orchestrator/Consumer/ReactiveConsumer.java b/src/main/java/com/uci/orchestrator/Consumer/ReactiveConsumer.java index d984c2e..c90a17b 100644 --- a/src/main/java/com/uci/orchestrator/Consumer/ReactiveConsumer.java +++ b/src/main/java/com/uci/orchestrator/Consumer/ReactiveConsumer.java @@ -146,13 +146,13 @@ public void accept(JsonNode campaign) { String appId = campaign.get("id").asText(); JsonNode firstTransformer = campaign.findValues("transformers").get(0).get(0); log.info("firstTransformer: "+firstTransformer); - resolveUserNew(msg, appId) + resolveUserNew(msg, appId) // look here .doOnNext(new Consumer() { @Override public void accept(XMessage msg) { SenderReceiverInfo from = msg.getFrom(); // msg.setFrom(from); - getLastMessageID(msg) + getLastMessageID(msg) // look here too .doOnNext(lastMessageID -> { logTimeTaken(startTime, 4); msg.setLastMessageID(lastMessageID); @@ -165,7 +165,7 @@ public void accept(XMessage msg) { try { if(firstTransformer.get("id").asText().equals("774cd134-6657-4688-85f6-6338e2323dde") && firstTransformer.get("type").asText().equals("broadcast")) { - XMessage message = setXMessageMeta(msg, campaign, firstTransformer); + XMessage message = setXMessageMeta(msg, campaign, firstTransformer); // critical one kafkaProducer.send(broadcastTransformerTopic, message.toXML()); } else { kafkaProducer.send(odkTransformerTopic, msg.toXML()); @@ -299,7 +299,7 @@ private Mono resolveUserNew(XMessage xmsg, String appId) { String encodedBase64Key = encodeKey(secret); String deviceID = AESWrapper.encrypt(deviceString, encodedBase64Key); log.info("deviceString: "+deviceString+", encyprted deviceString: "+deviceID); - String userID = getFAUserIdForApp(deviceID, appID); + String userID = getFAUserIdForApp(deviceID, appID); // try mocking this if (userID != null && !userID.isEmpty()) { log.info("Found FA user id"); diff --git a/src/main/java/com/uci/orchestrator/Controllers/Health/ServiceStatusController.java b/src/main/java/com/uci/orchestrator/Controllers/Health/ServiceStatusController.java index 5a54ebd..e140505 100644 --- a/src/main/java/com/uci/orchestrator/Controllers/Health/ServiceStatusController.java +++ b/src/main/java/com/uci/orchestrator/Controllers/Health/ServiceStatusController.java @@ -13,8 +13,6 @@ import java.io.IOException; -import org.apache.logging.log4j.LogManager; -import org.apache.logging.log4j.Logger; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.http.ResponseEntity; import org.springframework.web.bind.annotation.RequestMapping; diff --git a/src/test/java/com/uci/orchestrator/ApplicationConfiguration.java b/src/test/java/com/uci/orchestrator/ApplicationConfiguration.java index d16990d..d43ae3a 100644 --- a/src/test/java/com/uci/orchestrator/ApplicationConfiguration.java +++ b/src/test/java/com/uci/orchestrator/ApplicationConfiguration.java @@ -1,60 +1,286 @@ package com.uci.orchestrator; -import java.util.HashMap; -import java.util.Map; - +import com.github.benmanes.caffeine.cache.Cache; +import com.uci.orchestrator.Consumer.ReactiveConsumer; +import com.uci.utils.BotService; +import com.uci.utils.CampaignService; +import com.uci.utils.cache.service.RedisCacheService; +import com.uci.utils.kafka.ReactiveProducer; +import com.uci.utils.kafka.SimpleProducer; +import com.uci.utils.service.UserService; +import io.fusionauth.client.FusionAuthClient; +import org.apache.kafka.clients.consumer.*; import org.apache.kafka.clients.producer.ProducerConfig; +import org.apache.kafka.common.TopicPartition; +import org.mockito.Mockito; +import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Value; -import org.springframework.boot.context.properties.ConfigurationProperties; import org.springframework.context.annotation.Bean; -import org.springframework.context.annotation.Configuration; -import org.springframework.context.annotation.PropertySource; -import org.springframework.context.annotation.PropertySources; +import org.springframework.data.redis.core.RedisTemplate; import org.springframework.kafka.core.DefaultKafkaProducerFactory; import org.springframework.kafka.core.KafkaTemplate; import org.springframework.kafka.core.ProducerFactory; -import org.springframework.test.context.TestPropertySource; +import org.springframework.kafka.support.serializer.JsonDeserializer; import org.springframework.web.reactive.function.client.WebClient; - -import com.uci.utils.CampaignService; -import com.uci.utils.kafka.ReactiveProducer; -import com.uci.utils.kafka.SimpleProducer; - -import io.fusionauth.client.FusionAuthClient; +import reactor.core.CoreSubscriber; +import reactor.core.publisher.Flux; +import reactor.core.publisher.Mono; +import reactor.kafka.receiver.KafkaReceiver; +import reactor.kafka.receiver.ReceiverOffset; +import reactor.kafka.receiver.ReceiverOptions; +import reactor.kafka.receiver.ReceiverRecord; import reactor.kafka.sender.KafkaSender; import reactor.kafka.sender.SenderOptions; -@Configuration -@ConfigurationProperties -@TestPropertySource("classpath:test-application.properties") +import java.time.LocalTime; +import java.util.Arrays; +import java.util.HashMap; +import java.util.Map; + +//@Configuration +//@ConfigurationProperties +//@TestPropertySource("classpath:test-application.properties") public class ApplicationConfiguration{ - @Value("${campaign.url}") - public String CAMPAIGN_URL; - - @Value("${campaign.admin.token}") - private String CAMPAIGN_ADMIN_TOKEN; - - @Value("${fusionauth.url}") - private String fusionAuthUrl; +// @Value("${campaign.url}") +// public String CAMPAIGN_URL; +// +// @Value("${campaign.admin.token}") +// private String CAMPAIGN_ADMIN_TOKEN; +// +// @Value("${fusionauth.url}") +// private String fusionAuthUrl; +// +// @Value("${fusionauth.key}") +// private String fusionAuthKey; +// +// @Value("${spring.kafka.bootstrap-servers}") +// private String BOOTSTRAP_SERVERS; + +// @Bean +// public CampaignService getCampaignService() throws JsonProcessingException { +// ObjectMapper objectMapper = new ObjectMapper(); +// JsonNode botNode = objectMapper.readTree("{\"id\":\"api.bot.getByParam\",\"ver\":\"1.0\",\"ts\":\"2022-04-21T19:16:52.914Z\",\"params\":{\"resmsgid\":\"9a01a120-c1a7-11ec-afae-4f4769c7c758\",\"msgid\":\"9a00b6c0-c1a7-11ec-afae-4f4769c7c758\",\"status\":\"successful\",\"err\":null,\"errmsg\":null},\"responseCode\":\"OK\",\"result\":{\"data\":{\"id\":\"d655cf03-1f6f-4510-acf6-d3f51b488a5e\",\"name\":\"UCI Demo\",\"startingMessage\":\"Hi UCI\",\"users\":[],\"logicIDs\":[\"e96b0865-5a76-4566-8694-c09361b8ae32\"],\"owners\":null,\"created_at\":\"2021-07-08T18:48:37.740Z\",\"updated_at\":\"2022-02-11T14:09:53.570Z\",\"status\":\"enabled\",\"description\":\"For Internal Demo\",\"startDate\":\"2022-02-01T00:00:00.000Z\",\"endDate\":null,\"purpose\":\"For Internal Demo\",\"ownerOrgID\":\"ORG_001\",\"ownerID\":\"95e4942d-cbe8-477d-aebd-ad8e6de4bfc8\",\"logic\":[{\"id\":\"e96b0865-5a76-4566-8694-c09361b8ae32\",\"transformers\":[{\"id\":\"bbf56981-b8c9-40e9-8067-468c2c753659\",\"meta\":{\"form\":\"https://hosted.my.form.here.com\",\"formID\":\"UCI-demo-1\"}}],\"adapter\":\"44a9df72-3d7a-4ece-94c5-98cf26307324\",\"name\":\"UCI Demo\",\"created_at\":\"2021-07-08T18:47:44.925Z\",\"updated_at\":\"2022-02-03T12:29:32.959Z\",\"description\":null}]}}}\n"); +// Cache cache = Mockito.mock(Cache.class); +// Mockito.when(cache.getIfPresent("campaign-node-by-id:d655cf03-1f6f-4510-acf6-d3f51b488a5e")).thenReturn(botNode); +// return new CampaignService(getWebClient(), getFusionAuthClient(), cache); +// } +// + + @Autowired + Flux> reactiveKafkaReceiver; + + @Bean + public UserService getUserService(){ + return new UserService(); + } + + @Bean + public RedisCacheService getRedisCacheService(){ + return new RedisCacheService(new RedisTemplate<>()); + } - @Value("${fusionauth.key}") - private String fusionAuthKey; + @Bean + public Cache getCache(){ + return Mockito.mock(Cache.class); + } - @Value("${spring.kafka.bootstrap-servers}") - private String BOOTSTRAP_SERVERS; - @Bean - public WebClient getWebClient() { - return WebClient.builder().baseUrl(CAMPAIGN_URL).defaultHeader("admin-token", CAMPAIGN_ADMIN_TOKEN).build(); + public SimpleProducer getSimpleProducer(){ + return new SimpleProducer(kafkaTemplate()); } - + +// @Bean +// public ReactiveConsumer getReactiveConsumer(){ +// return new ReactiveConsumer(new Flux>() { +// @Override +// public void subscribe(CoreSubscriber> coreSubscriber) { +// +// +// } +// }); +// } + @Bean - public FusionAuthClient getFusionAuthClient() { - return new FusionAuthClient(fusionAuthKey, fusionAuthUrl); + public BotService getBotService(){ + WebClient webClient = WebClient.builder() + .baseUrl("CAMPAIGN_URL") + .defaultHeader("admin-token", "CAMPAIGN_ADMIN_TOKEN") + .build(); + return new BotService(webClient, getFAClient(), getCache()); } - + + + // from application configuration : + + /** + * below these methods are from AppConfigOrchestrator.java + * @return + */ + + @Bean + public FusionAuthClient getFAClient() { + return new FusionAuthClient("FUSIONAUTH_KEY", "FUSIONAUTH_URL"); + } + + @Bean + public CampaignService getCampaignService() { + WebClient webClient = WebClient.builder() + .baseUrl("CAMPAIGN_URL") + .defaultHeader("admin-token", "CAMPAIGN_ADMIN_TOKEN") + .build(); + return new CampaignService(webClient, getFAClient(), getCache()); + } + @Bean - public CampaignService campaignService() { - return new CampaignService(getWebClient(), getFusionAuthClient()); - } + public ReactiveConsumer getReactiveConsumer(){ + return new ReactiveConsumer(reactiveKafkaReceiver); + } + + @Bean + Map kafkaConsumerConfiguration() { + Map configuration = new HashMap<>(); + configuration.put(ConsumerConfig.BOOTSTRAP_SERVERS_CONFIG, "165.232.182.146:9094"); + configuration.put(ConsumerConfig.GROUP_ID_CONFIG, "sample-producer"); + configuration.put(ConsumerConfig.KEY_DESERIALIZER_CLASS_CONFIG, org.springframework.kafka.support.serializer.JsonSerializer.class); + configuration.put(ConsumerConfig.VALUE_DESERIALIZER_CLASS_CONFIG, org.springframework.kafka.support.serializer.JsonSerializer.class); + configuration.put(ConsumerConfig.AUTO_OFFSET_RESET_CONFIG, "latest"); + configuration.put(ProducerConfig.ACKS_CONFIG, "all"); + return configuration; + } + + @Bean + Map kafkaProducerConfiguration() { + Map configuration = new HashMap<>(); + configuration.put(ProducerConfig.BOOTSTRAP_SERVERS_CONFIG, "165.232.182.146:9094"); + configuration.put(ProducerConfig.CLIENT_ID_CONFIG, "sample-producer"); + configuration.put(ProducerConfig.ACKS_CONFIG, "all"); + configuration.put(org.springframework.kafka.support.serializer.JsonSerializer.ADD_TYPE_INFO_HEADERS, false); + configuration.put(ProducerConfig.KEY_SERIALIZER_CLASS_CONFIG, org.springframework.kafka.support.serializer.JsonSerializer.class); + configuration.put(ProducerConfig.VALUE_SERIALIZER_CLASS_CONFIG, org.springframework.kafka.support.serializer.JsonSerializer.class); + return configuration; + } + + @Bean + ReceiverOptions kafkaReceiverOptions(@Value("inbound-processed") String[] inTopicName) { + ReceiverOptions options = ReceiverOptions.create(kafkaConsumerConfiguration()); + return options.subscription(Arrays.asList(inTopicName)) + .withKeyDeserializer(new JsonDeserializer<>()) + .withValueDeserializer(new JsonDeserializer(String.class)); + } + + @Bean + SenderOptions kafkaSenderOptions() { + return SenderOptions.create(kafkaProducerConfiguration()); + } + + @Bean + Flux> reactiveKafkaReceiver(@Autowired ReceiverOptions kafkaReceiverOptions) { + KafkaReceiver kafkaReceiver = KafkaReceiver.create(kafkaReceiverOptions); + Consumer consumer = new MockConsumer(OffsetResetStrategy.EARLIEST); +// ConsumerRecord consumerRecord = new ConsumerRecord("inbound-processed", 0, 33, null, +// "\n" + +// "\n" + +// " 897fb6ea-cb07-4891-b714-1e86784ef610\n" + +// " WhatsApp\n" + +// " WhatsApp\n" + +// " \n" + +// " 0\n" + +// " STARTING\n" + +// " \n" + +// " Gupshup\n" + +// " Gupshup\n" + +// " 1595137277407\n" + +// " \n" + +// " 2\n" + +// " \n" + +// " \n" + +// " Form\n" + +// " RQ\n" + +// " \n" + +// " \n" + +// " \n" + +// "\n" +// ); + + ConsumerRecord consumerRecord = new ConsumerRecord("inbound-processed", 0, 33, null, + "\n" + + "\n" + + " UCI Demo\n" + + " WhatsApp\n" + + " WhatsApp\n" + + " \n" + + " false\n" + + " false\n" + + " PHONE\n" + + " 7823807161\n" + + " \n" + + " \n" + + " ABEGkZlgQyWAAgo-sDVSUOa9jH0z\n" + + " \n" + + " REPLIED\n" + + " TEXT\n" + + " \n" + + " Hi UCI\n" + + " \n" + + " Netcore\n" + + " Netcore\n" + + " 1636621428000\n" + + " \n" + + " false\n" + + " false\n" + + " admin\n" + + " \n" + + "" + ); + + ReceiverOffset receiverOffset = new ReceiverOffset() { + @Override + public TopicPartition topicPartition() { + return new TopicPartition("inbound-processed", 0); + } + + @Override + public long offset() { + return 0; + } + + @Override + public void acknowledge() { + + } + + @Override + public Mono commit() { + return null; + } + }; + ReceiverRecord receiverRecord = new ReceiverRecord(consumerRecord, receiverOffset); +// return KafkaReceiver.create(kafkaReceiverOptions).receive(); + return Flux.just(receiverRecord); + } + + + + + @Bean + KafkaSender reactiveKafkaSender(SenderOptions kafkaSenderOptions) { + return KafkaSender.create(kafkaSenderOptions); + } + + @Bean + ReactiveProducer kafkaReactiveProducer() { + return new ReactiveProducer(); + } + + @Bean + ProducerFactory producerFactory(){ + ProducerFactory producerFactory = new DefaultKafkaProducerFactory<>(kafkaProducerConfiguration()); + return producerFactory; + } + + @Bean + KafkaTemplate kafkaTemplate() { + KafkaTemplate kafkaTemplate = new KafkaTemplate<>(producerFactory()); + return (KafkaTemplate) kafkaTemplate; + } } diff --git a/src/test/java/com/uci/orchestrator/Consumer/CampaignConsumerTest.java b/src/test/java/com/uci/orchestrator/Consumer/CampaignConsumerTest.java index 809f41a..bd3636e 100644 --- a/src/test/java/com/uci/orchestrator/Consumer/CampaignConsumerTest.java +++ b/src/test/java/com/uci/orchestrator/Consumer/CampaignConsumerTest.java @@ -1,94 +1,69 @@ package com.uci.orchestrator.Consumer; -import static org.mockito.Mockito.when; - -import org.apache.logging.log4j.Logger; -import org.apache.logging.log4j.LogManager; -import org.junit.Before; -import org.junit.jupiter.api.BeforeEach; -import org.junit.jupiter.api.Test; -import org.junit.jupiter.api.extension.ExtendWith; -import org.junit.runner.RunWith; -import org.mockito.InjectMocks; -import org.mockito.Mock; -import org.mockito.Mockito; -import org.mockito.junit.jupiter.MockitoExtension; -import org.springframework.boot.test.context.SpringBootTest; -import org.springframework.test.context.junit4.SpringRunner; -import org.springframework.web.reactive.function.client.WebClient; - -import com.fasterxml.jackson.core.JsonProcessingException; -import com.fasterxml.jackson.databind.JsonMappingException; import com.fasterxml.jackson.databind.JsonNode; import com.fasterxml.jackson.databind.ObjectMapper; +import com.uci.orchestrator.ApplicationConfiguration; import com.uci.utils.CampaignService; - -import io.fusionauth.client.FusionAuthClient; -import lombok.SneakyThrows; -import lombok.extern.slf4j.Slf4j; +import com.uci.utils.kafka.SimpleProducer; import messagerosa.core.model.XMessage; +import org.junit.jupiter.api.Test; +import org.junit.runner.RunWith; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.boot.test.context.SpringBootTest; +import org.springframework.test.context.junit4.SpringRunner; import reactor.core.publisher.Mono; import reactor.test.StepVerifier; -import static org.mockito.ArgumentMatchers.any; -import static org.mockito.ArgumentMatchers.anyString; - -@ExtendWith(MockitoExtension.class) -@RunWith(SpringRunner.class) -@Slf4j -//@SpringBootTest() +//@ExtendWith(MockitoExtension.class) +//@RunWith(SpringRunner.class) +@SpringBootTest(classes = ApplicationConfiguration.class) public class CampaignConsumerTest { - private static Logger LOGGER = null; - - @Mock - public WebClient webClient; - - @Mock - public FusionAuthClient fusionAuthClient; - - + + @Autowired + SimpleProducer kafkaProducer; + + @Autowired public CampaignService campaignService; - + + @Autowired public CampaignConsumer campaignConsumer; - -// public CampaignConsumer campaignConsumer; - - - -// @Before - @SneakyThrows - @BeforeEach - public void init() throws JsonMappingException, JsonProcessingException { -// System.out.println("setupp"); - - System.setProperty("log4j.configurationFile","log4j2-testconfig.xml"); - LOGGER = LogManager.getLogger(); - -// - WebClient client = Mockito.mock(WebClient.class); - - System.out.println(client); - - System.out.println(client.get()); - - campaignService = new CampaignService(client, fusionAuthClient); - CampaignConsumer campaignConsumer = new CampaignConsumer(); - - ObjectMapper mapper = new ObjectMapper(); - JsonNode json = mapper.readTree("{\"id\":\"api.bot.getByParam\",\"ver\":\"1.0\",\"ts\":\"2021-09-07T09:13:15.692Z\",\"params\":{\"resmsgid\":\"d5809ec0-0fbb-11ec-8e04-21de24b1fc83\",\"msgid\":\"d57f6640-0fbb-11ec-8e04-21de24b1fc83\",\"status\":\"successful\",\"err\":null,\"errmsg\":null},\"responseCode\":\"OK\",\"result\":{\"data\":{\"id\":\"d655cf03-1f6f-4510-acf6-d3f51b488a5e\",\"name\":\"UCI Demo\",\"startingMessage\":\"Hi UCI\",\"users\":[],\"logicIDs\":[\"e96b0865-5a76-4566-8694-c09361b8ae32\"],\"owners\":null,\"created_at\":\"2021-07-08T18:48:37.740Z\",\"updated_at\":\"2021-07-14T16:59:09.088Z\",\"status\":\"Draft\",\"description\":\"For Internal Demo\",\"startDate\":\"2021-07-07T18:30:00.000Z\",\"endDate\":\"2021-07-22T18:30:00.000Z\",\"purpose\":\"For Internal Demo\",\"ownerOrgID\":null,\"ownerID\":null,\"logic\":[{\"id\":\"e96b0865-5a76-4566-8694-c09361b8ae32\",\"transformers\":[{\"id\":\"bbf56981-b8c9-40e9-8067-468c2c753659\",\"meta\":{\"form\":\"https://hosted.my.form.here.com\",\"formID\":\"UCI-demo-4\"}}],\"adapter\":\"44a9df72-3d7a-4ece-94c5-98cf26307324\",\"name\":\"UCI Demo\",\"created_at\":\"2021-07-08T18:47:44.925Z\",\"updated_at\":\"2021-07-08T18:47:44.925Z\",\"description\":null,\"ownerOrgID\":null,\"ownerID\":null}]}}}"); - -// Mockito.when(campaignService.getCampaignFromID("d655cf03-1f6f-4510-acf6-d3f51b488a5e")).thenReturn(Mono.just(json)); - + +//// @Before +// @SneakyThrows +// @BeforeAll +// public static void init() throws JsonMappingException, JsonProcessingException { +//// System.out.println("setupp"); +// +// System.setProperty("log4j.configurationFile","log4j2-testconfig.xml"); +// LOGGER = LogManager.getLogger(); +// +//// +//// WebClient client = Mockito.mock(WebClient.class); +//// +//// System.out.println(client); +//// +//// System.out.println(client.get()); +//// +//// campaignService = new CampaignService(client, fusionAuthClient,null); +//// +//// CampaignConsumer campaignConsumer = new CampaignConsumer(); +// +// +//// Mockito.when(campaignService.getCampaignFromID("d655cf03-1f6f-4510-acf6-d3f51b488a5e")).thenReturn(Mono.just(json)); +// +// } + + @Test + void consumeMessage() { } - + @Test - public void processMessageTest() throws Exception { -// System.out.println("test"); - LOGGER.info("test"); - + void processMessage() throws Exception { + ObjectMapper mapper = new ObjectMapper(); + JsonNode json = mapper.readTree("{\"id\":\"api.bot.getByParam\",\"ver\":\"1.0\",\"ts\":\"2021-09-07T09:13:15.692Z\",\"params\":{\"resmsgid\":\"d5809ec0-0fbb-11ec-8e04-21de24b1fc83\",\"msgid\":\"d57f6640-0fbb-11ec-8e04-21de24b1fc83\",\"status\":\"successful\",\"err\":null,\"errmsg\":null},\"responseCode\":\"OK\",\"result\":{\"data\":{\"id\":\"d655cf03-1f6f-4510-acf6-d3f51b488a5e\",\"name\":\"UCI Demo\",\"startingMessage\":\"Hi UCI\",\"users\":[],\"logicIDs\":[\"e96b0865-5a76-4566-8694-c09361b8ae32\"],\"owners\":null,\"created_at\":\"2021-07-08T18:48:37.740Z\",\"updated_at\":\"2021-07-14T16:59:09.088Z\",\"status\":\"Draft\",\"description\":\"For Internal Demo\",\"startDate\":\"2021-07-07T18:30:00.000Z\",\"endDate\":\"2021-07-22T18:30:00.000Z\",\"purpose\":\"For Internal Demo\",\"ownerOrgID\":null,\"ownerID\":null,\"logic\":[{\"id\":\"e96b0865-5a76-4566-8694-c09361b8ae32\",\"transformers\":[{\"id\":\"bbf56981-b8c9-40e9-8067-468c2c753659\",\"meta\":{\"form\":\"https://hosted.my.form.here.com\",\"formID\":\"UCI-demo-4\"}}],\"adapter\":\"44a9df72-3d7a-4ece-94c5-98cf26307324\",\"name\":\"UCI Demo\",\"created_at\":\"2021-07-08T18:47:44.925Z\",\"updated_at\":\"2021-07-08T18:47:44.925Z\",\"description\":null,\"ownerOrgID\":null,\"ownerID\":null}]}}}"); + Mono response = campaignConsumer.processMessage("d655cf03-1f6f-4510-acf6-d3f51b488a5e"); - StepVerifier.create(response).verifyComplete(); } } diff --git a/src/test/java/com/uci/orchestrator/Consumer/CampaignConsumerTest2.java b/src/test/java/com/uci/orchestrator/Consumer/CampaignConsumerTest2.java deleted file mode 100644 index 5db8231..0000000 --- a/src/test/java/com/uci/orchestrator/Consumer/CampaignConsumerTest2.java +++ /dev/null @@ -1,88 +0,0 @@ -package com.uci.orchestrator.Consumer; - -import static org.mockito.Mockito.when; - -import org.apache.logging.log4j.Logger; -import org.apache.logging.log4j.LogManager; -import org.junit.Before; -import org.junit.jupiter.api.BeforeEach; -import org.junit.jupiter.api.Test; -import org.junit.jupiter.api.extension.ExtendWith; -import org.junit.runner.RunWith; -import org.mockito.InjectMocks; -import org.mockito.Mock; -import org.mockito.Mockito; -import org.mockito.junit.jupiter.MockitoExtension; -import org.springframework.beans.factory.annotation.Autowired; -import org.springframework.boot.test.context.SpringBootTest; -import org.springframework.test.context.TestPropertySource; -import org.springframework.test.context.junit4.SpringRunner; -import org.springframework.web.reactive.function.client.WebClient; - -import com.fasterxml.jackson.core.JsonProcessingException; -import com.fasterxml.jackson.databind.JsonMappingException; -import com.fasterxml.jackson.databind.JsonNode; -import com.fasterxml.jackson.databind.ObjectMapper; -import com.uci.orchestrator.ApplicationConfiguration; -import com.uci.utils.CampaignService; - -import io.fusionauth.client.FusionAuthClient; -import lombok.SneakyThrows; -import lombok.extern.slf4j.Slf4j; -import messagerosa.core.model.XMessage; -import reactor.core.publisher.Mono; -import reactor.test.StepVerifier; - -import static org.mockito.ArgumentMatchers.any; -import static org.mockito.ArgumentMatchers.anyString; - -@ExtendWith(MockitoExtension.class) -@RunWith(SpringRunner.class) -@Slf4j -@SpringBootTest(classes=ApplicationConfiguration.class) -@TestPropertySource("classpath:test-application.properties") -//@SpringBootTest() -public class CampaignConsumerTest2 { - private static Logger LOGGER = null; - - @Autowired - public WebClient webClient; - - @Autowired - public FusionAuthClient fusionAuthClient; - - @Autowired - public CampaignService campaignService; - - @Mock - public CampaignConsumer campaignConsumer; - -// public CampaignConsumer campaignConsumer; - - - -// @Before - @SneakyThrows - @BeforeEach - public void init() throws JsonMappingException, JsonProcessingException { - System.setProperty("log4j.configurationFile","log4j2-testconfig.xml"); - LOGGER = LogManager.getLogger(); - - campaignConsumer = new CampaignConsumer(); - -// ObjectMapper mapper = new ObjectMapper(); -// JsonNode json = mapper.readTree("{\"id\":\"api.bot.getByParam\",\"ver\":\"1.0\",\"ts\":\"2021-09-07T09:13:15.692Z\",\"params\":{\"resmsgid\":\"d5809ec0-0fbb-11ec-8e04-21de24b1fc83\",\"msgid\":\"d57f6640-0fbb-11ec-8e04-21de24b1fc83\",\"status\":\"successful\",\"err\":null,\"errmsg\":null},\"responseCode\":\"OK\",\"result\":{\"data\":{\"id\":\"d655cf03-1f6f-4510-acf6-d3f51b488a5e\",\"name\":\"UCI Demo\",\"startingMessage\":\"Hi UCI\",\"users\":[],\"logicIDs\":[\"e96b0865-5a76-4566-8694-c09361b8ae32\"],\"owners\":null,\"created_at\":\"2021-07-08T18:48:37.740Z\",\"updated_at\":\"2021-07-14T16:59:09.088Z\",\"status\":\"Draft\",\"description\":\"For Internal Demo\",\"startDate\":\"2021-07-07T18:30:00.000Z\",\"endDate\":\"2021-07-22T18:30:00.000Z\",\"purpose\":\"For Internal Demo\",\"ownerOrgID\":null,\"ownerID\":null,\"logic\":[{\"id\":\"e96b0865-5a76-4566-8694-c09361b8ae32\",\"transformers\":[{\"id\":\"bbf56981-b8c9-40e9-8067-468c2c753659\",\"meta\":{\"form\":\"https://hosted.my.form.here.com\",\"formID\":\"UCI-demo-4\"}}],\"adapter\":\"44a9df72-3d7a-4ece-94c5-98cf26307324\",\"name\":\"UCI Demo\",\"created_at\":\"2021-07-08T18:47:44.925Z\",\"updated_at\":\"2021-07-08T18:47:44.925Z\",\"description\":null,\"ownerOrgID\":null,\"ownerID\":null}]}}}"); -// Mockito.when(campaignService.getCampaignFromID(anyString())).thenReturn(Mono.just(json)); - - } - - @Test - public void processMessageTest() throws Exception { -// System.out.println("test"); - LOGGER.info("test"); - - Mono response = campaignConsumer.processMessage("d655cf03-1f6f-4510-acf6-d3f51b488a5e"); - - StepVerifier.create(response).verifyComplete(); - } -} diff --git a/src/test/java/com/uci/orchestrator/Consumer/ReactiveConsumerTest.java b/src/test/java/com/uci/orchestrator/Consumer/ReactiveConsumerTest.java index 48a4ce3..bd7708d 100644 --- a/src/test/java/com/uci/orchestrator/Consumer/ReactiveConsumerTest.java +++ b/src/test/java/com/uci/orchestrator/Consumer/ReactiveConsumerTest.java @@ -1,12 +1,88 @@ package com.uci.orchestrator.Consumer; +import com.fasterxml.jackson.core.JsonProcessingException; +import com.fasterxml.jackson.databind.JsonNode; +import com.fasterxml.jackson.databind.ObjectMapper; +import com.uci.dao.models.XMessageDAO; +import com.uci.dao.repository.XMessageRepository; +import com.uci.orchestrator.ApplicationConfiguration; +import com.uci.utils.BotService; +import com.uci.utils.CampaignService; +import com.uci.utils.cache.service.RedisCacheService; +import com.uci.utils.kafka.ReactiveProducer; +import com.uci.utils.kafka.SimpleProducer; +import com.uci.utils.service.UserService; +import org.apache.kafka.clients.consumer.ConsumerRecord; +import org.apache.kafka.clients.consumer.MockConsumer; +import org.apache.kafka.clients.consumer.OffsetAndMetadata; +import org.apache.kafka.clients.consumer.OffsetResetStrategy; +import org.json.JSONArray; +import org.junit.Before; +import org.junit.jupiter.api.BeforeAll; +import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.extension.ExtendWith; +import org.mockito.Mockito; +import org.mockito.junit.jupiter.MockitoExtension; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.boot.test.context.SpringBootTest; +import org.springframework.boot.test.mock.mockito.MockBean; +import org.springframework.data.redis.connection.stream.Consumer; +import reactor.core.CoreSubscriber; +import reactor.core.publisher.Flux; +import reactor.core.publisher.Mono; +import reactor.kafka.receiver.ReceiverRecord; -import static org.junit.jupiter.api.Assertions.*; +import java.time.LocalDateTime; + +//@Slf4j +@SpringBootTest(classes = ApplicationConfiguration.class) +@ExtendWith(MockitoExtension.class) class ReactiveConsumerTest { + @Autowired + ReactiveConsumer reactiveConsumer; + + @MockBean + XMessageRepository xMessageRepository; + + @Autowired + public SimpleProducer kafkaProducer; + + @Autowired + public ReactiveProducer reactiveProducer; + + @MockBean + public BotService botService; + + @MockBean + public CampaignService campaignService; + + @MockBean + public UserService userService; + + @MockBean + public RedisCacheService redisCacheService; + + + @BeforeAll + public static void setup(){ + MockConsumer mockConsumer = new MockConsumer(OffsetResetStrategy.EARLIEST); + } + @Test - void onMessage() { + void onMessage() throws JsonProcessingException { + + ObjectMapper objectMapper = new ObjectMapper(); + Mockito.when(botService.getCurrentAdapter("UCI Demo")).thenReturn(Mono.just("44a9df72-3d7a-4ece-94c5-98cf26307324")); + JsonNode campaignNode = objectMapper.readTree("{\"id\":\"d655cf03-1f6f-4510-acf6-d3f51b488a5e\",\"name\":\"UCI Demo\",\"startingMessage\":\"Hi UCI\",\"users\":[],\"logicIDs\":[\"e96b0865-5a76-4566-8694-c09361b8ae32\"],\"owners\":null,\"created_at\":\"2021-07-08T18:48:37.740Z\",\"updated_at\":\"2022-02-11T14:09:53.570Z\",\"status\":\"enabled\",\"description\":\"For Internal Demo\",\"startDate\":\"2022-02-01T00:00:00.000Z\",\"endDate\":null,\"purpose\":\"For Internal Demo\",\"ownerOrgID\":\"ORG_001\",\"ownerID\":\"95e4942d-cbe8-477d-aebd-ad8e6de4bfc8\",\"userSegments\":[],\"logic\":[{\"id\":\"e96b0865-5a76-4566-8694-c09361b8ae32\",\"transformers\":[{\"id\":\"bbf56981-b8c9-40e9-8067-468c2c753659\",\"meta\":{\"form\":\"https://hosted.my.form.here.com\",\"formID\":\"UCI-demo-1\"}}],\"adapter\":{\"id\":\"44a9df72-3d7a-4ece-94c5-98cf26307324\",\"channel\":\"WhatsApp\",\"provider\":\"gupshup\",\"config\":{\"2WAY\":\"2000193033\",\"phone\":\"9876543210\",\"HSM_ID\":\"2000193031\",\"credentials\":{\"vault\":\"samagra\",\"variable\":\"gupshupSamagraProd\"}},\"name\":\"SamagraProd\",\"updated_at\":\"2021-06-16T06:02:39.125Z\",\"created_at\":\"2021-06-16T06:02:41.823Z\"},\"name\":\"UCI Demo\",\"created_at\":\"2021-07-08T18:47:44.925Z\",\"updated_at\":\"2022-02-03T12:29:32.959Z\",\"description\":null}]}"); + Mockito.when(campaignService.getCampaignFromNameTransformer("UCI Demo")).thenReturn(Mono.just(campaignNode)); + userService.CAMPAIGN_URL = "http://localhost"; + Mockito.when(userService.getUsersFromFederatedServers(Mockito.anyString())).thenReturn(new JSONArray()); + Mockito.when(redisCacheService.getFAUserIDForAppCache("yOJcM+Gm7yVkKeQqPhdDKNb0wsmh8St/ty+pM5Q+4W4=" + "-" + "d655cf03-1f6f-4510-acf6-d3f51b488a5e")).thenReturn("91311fd1-5c1c-4f81-b9eb-2d259159554a"); + Mockito.when(xMessageRepository.findAllByUserIdAndTimestampAfter("7823807161", Mockito.any())).thenReturn(Flux.just(new XMessageDAO())); + reactiveConsumer.onMessage(); + } } \ No newline at end of file diff --git a/src/test/java/com/uci/orchestrator/Controllers/MessageRosaTest.java b/src/test/java/com/uci/orchestrator/Controllers/MessageRosaTest.java deleted file mode 100644 index ec6a0a4..0000000 --- a/src/test/java/com/uci/orchestrator/Controllers/MessageRosaTest.java +++ /dev/null @@ -1,16 +0,0 @@ -package com.uci.orchestrator.Controllers; - -import org.junit.jupiter.api.Test; - -import static org.junit.jupiter.api.Assertions.*; - -class MessageRosaTest { - - @Test - void greeting() { - } - - @Test - void deleteLastMessage() { - } -} \ No newline at end of file diff --git a/src/test/java/com/uci/orchestrator/IntegrationTest.java b/src/test/java/com/uci/orchestrator/IntegrationTest.java index 2ce929d..25d33a5 100644 --- a/src/test/java/com/uci/orchestrator/IntegrationTest.java +++ b/src/test/java/com/uci/orchestrator/IntegrationTest.java @@ -1,22 +1,22 @@ package com.uci.orchestrator; -import com.uci.orchestrator.Drools.DroolsBeanFactory; +//import com.uci.orchestrator.Drools.DroolsBeanFactory; import messagerosa.core.model.XMessage; -import org.junit.Before; +//import org.junit.Before; import org.junit.Test; -import org.kie.api.io.Resource; -import org.kie.api.runtime.KieSession; -import org.kie.internal.io.ResourceFactory; +//import org.kie.api.io.Resource; +//import org.kie.api.runtime.KieSession; +//import org.kie.internal.io.ResourceFactory; public class IntegrationTest { - private KieSession kSession; - - @Before - public void setup() { - Resource resource = ResourceFactory.newClassPathResource("OrchestratorRules.xlsx", getClass()); - kSession = new DroolsBeanFactory().getKieSession(resource); - System.out.println(new DroolsBeanFactory().getDrlFromExcel("OrchestratorRules.xlsx")); - } +// private KieSession kSession; +// +// @Before +// public void setup() { +// Resource resource = ResourceFactory.newClassPathResource("OrchestratorRules.xlsx", getClass()); +// kSession = new DroolsBeanFactory().getKieSession(resource); +// System.out.println(new DroolsBeanFactory().getDrlFromExcel("OrchestratorRules.xlsx")); +// } @Test public void testChangeInChannel() throws Exception { @@ -26,8 +26,8 @@ public void testChangeInChannel() throws Exception { xMessage.setApp("ResumeBuilder"); xMessage.setTimestamp((long) 1592900000); System.out.println(xMessage.secondsSinceLastMessage()); - kSession.insert(xMessage); - kSession.fireAllRules(); +// kSession.insert(xMessage); +// kSession.fireAllRules(); System.out.println(xMessage.getTransformers()); System.out.println(xMessage.toXML()); } @@ -38,8 +38,8 @@ public void testForTransformer() throws Exception { xMessage.setMessageState(XMessage.MessageState.REPLIED); xMessage.setApp("Test"); System.out.println(xMessage.secondsSinceLastMessage()); - kSession.insert(xMessage); - kSession.fireAllRules(); +// kSession.insert(xMessage); +// kSession.fireAllRules(); System.out.println(xMessage.getTransformers()); System.out.println(xMessage.toXML()); } diff --git a/src/test/java/com/uci/orchestrator/User/CampaignServiceTest.java b/src/test/java/com/uci/orchestrator/User/CampaignServiceTest.java deleted file mode 100644 index 10e73c6..0000000 --- a/src/test/java/com/uci/orchestrator/User/CampaignServiceTest.java +++ /dev/null @@ -1,25 +0,0 @@ -package com.uci.orchestrator.User; - -import com.fasterxml.jackson.databind.JsonNode; -import com.uci.utils.CampaignService; -import io.fusionauth.domain.Application; -import org.junit.Assert; -import org.junit.jupiter.api.Test; - -import java.util.ArrayList; -import java.util.function.Function; - -public class CampaignServiceTest { - - @Test - public void testRetrieveApplicationData() throws Exception { -// JsonNode application = new CampaignService().getCampaignFromID("897fb6ea-cb07-4891-b714-1e86784ef610").map(new Function() { -// @Override -// public Object apply(JsonNode jsonNode) { -// return null; -// } -// }); -// ArrayList transformers = (ArrayList)application.data.get("transformers"); -// Assert.assertNotEquals("The strings didn't match for the expected and actual transformers", "Broadcast::SMS_1", transformers.get(0)); - } -} diff --git a/src/test/java/com/uci/orchestrator/User/TestConfig.java b/src/test/java/com/uci/orchestrator/User/TestConfig.java deleted file mode 100644 index da82030..0000000 --- a/src/test/java/com/uci/orchestrator/User/TestConfig.java +++ /dev/null @@ -1,82 +0,0 @@ -package com.uci.orchestrator.User; - -import com.fasterxml.jackson.core.JsonProcessingException; -import com.fasterxml.jackson.databind.JsonNode; -import com.fasterxml.jackson.databind.ObjectMapper; -import com.github.benmanes.caffeine.cache.Cache; -import com.uci.orchestrator.Consumer.CampaignConsumer; -import com.uci.utils.CampaignService; -import com.uci.utils.kafka.SimpleProducer; -import io.fusionauth.client.FusionAuthClient; -import lombok.extern.slf4j.Slf4j; -import org.apache.kafka.clients.producer.Producer; -import org.apache.kafka.clients.producer.ProducerConfig; -import org.apache.logging.log4j.LogManager; -import org.apache.logging.log4j.Logger; -import org.mockito.Mock; -import org.mockito.Mockito; -import org.springframework.beans.factory.annotation.Autowired; -import org.springframework.boot.test.context.TestConfiguration; -import org.springframework.context.annotation.Bean; -import org.springframework.context.annotation.Configuration; -import org.springframework.kafka.core.DefaultKafkaProducerFactory; -import org.springframework.kafka.core.KafkaTemplate; -import org.springframework.kafka.core.ProducerFactory; -import org.springframework.web.reactive.function.client.WebClient; - -import java.util.HashMap; -import java.util.Map; - - -public class TestConfig { - - @Autowired - SimpleProducer simpleProducer; - - @Bean - public Logger getLogger(){ - return LogManager.getLogger(); - } - - @Bean - public CampaignService getCampaignService() throws JsonProcessingException { - ObjectMapper objectMapper = new ObjectMapper(); - JsonNode botNode = objectMapper.readTree("{\"id\":\"api.bot.getByParam\",\"ver\":\"1.0\",\"ts\":\"2022-04-21T19:16:52.914Z\",\"params\":{\"resmsgid\":\"9a01a120-c1a7-11ec-afae-4f4769c7c758\",\"msgid\":\"9a00b6c0-c1a7-11ec-afae-4f4769c7c758\",\"status\":\"successful\",\"err\":null,\"errmsg\":null},\"responseCode\":\"OK\",\"result\":{\"data\":{\"id\":\"d655cf03-1f6f-4510-acf6-d3f51b488a5e\",\"name\":\"UCI Demo\",\"startingMessage\":\"Hi UCI\",\"users\":[],\"logicIDs\":[\"e96b0865-5a76-4566-8694-c09361b8ae32\"],\"owners\":null,\"created_at\":\"2021-07-08T18:48:37.740Z\",\"updated_at\":\"2022-02-11T14:09:53.570Z\",\"status\":\"enabled\",\"description\":\"For Internal Demo\",\"startDate\":\"2022-02-01T00:00:00.000Z\",\"endDate\":null,\"purpose\":\"For Internal Demo\",\"ownerOrgID\":\"ORG_001\",\"ownerID\":\"95e4942d-cbe8-477d-aebd-ad8e6de4bfc8\",\"logic\":[{\"id\":\"e96b0865-5a76-4566-8694-c09361b8ae32\",\"transformers\":[{\"id\":\"bbf56981-b8c9-40e9-8067-468c2c753659\",\"meta\":{\"form\":\"https://hosted.my.form.here.com\",\"formID\":\"UCI-demo-1\"}}],\"adapter\":\"44a9df72-3d7a-4ece-94c5-98cf26307324\",\"name\":\"UCI Demo\",\"created_at\":\"2021-07-08T18:47:44.925Z\",\"updated_at\":\"2022-02-03T12:29:32.959Z\",\"description\":null}]}}}\n"); - Cache cache = Mockito.mock(Cache.class); - Mockito.when(cache.getIfPresent("campaign-node-by-id:d655cf03-1f6f-4510-acf6-d3f51b488a5e")).thenReturn(botNode); - return new CampaignService(getWebClient(), getFusionAuthClient(), cache); - } - - @Bean - public CampaignConsumer getCampaignConsumer(){ - return new CampaignConsumer(); - } - - @Bean - public FusionAuthClient getFusionAuthClient() { - return new FusionAuthClient("c0VY85LRCYnsk64xrjdXNVFFJ3ziTJ91r08Cm0Pcjbc", "http://134.209.150.161:9011"); - } - - @Bean - public WebClient getWebClient(){ - return WebClient.builder().build(); - } - - @Bean - public Cache getCache(){ - return null; - } - - @Bean - public SimpleProducer getSimpleProducer(){ - Map configuration = new HashMap<>(); - configuration.put(ProducerConfig.BOOTSTRAP_SERVERS_CONFIG, "165.232.182.146:9094"); - configuration.put(ProducerConfig.CLIENT_ID_CONFIG, "sample-producer"); - configuration.put(ProducerConfig.ACKS_CONFIG, "all"); - configuration.put(ProducerConfig.KEY_SERIALIZER_CLASS_CONFIG, org.springframework.kafka.support.serializer.JsonSerializer.class); - configuration.put(ProducerConfig.VALUE_SERIALIZER_CLASS_CONFIG, org.springframework.kafka.support.serializer.JsonSerializer.class); - - ProducerFactory producerFactory = new DefaultKafkaProducerFactory(configuration); - return new SimpleProducer(new KafkaTemplate(producerFactory)); - } -} \ No newline at end of file diff --git a/src/test/java/com/uci/orchestrator/User/UserServiceTest.java b/src/test/java/com/uci/orchestrator/User/UserServiceTest.java deleted file mode 100644 index 258695b..0000000 --- a/src/test/java/com/uci/orchestrator/User/UserServiceTest.java +++ /dev/null @@ -1,31 +0,0 @@ -package com.uci.orchestrator.User; - -import com.uci.orchestrator.Consumer.CampaignConsumer; -import io.fusionauth.domain.User; -import lombok.SneakyThrows; -import org.junit.jupiter.api.Test; - -import java.util.List; - -import static org.junit.jupiter.api.Assertions.*; -class UserServiceTest { - String email = "chakshu@samagragovernance.in"; - -// @Test -// public void testFindByEmail(){ -// User user = UserService.findByEmail(email); -// assertEquals("4ee2ab81-6c3f-460b-94b2-de49cf55f27f", user.id.toString()); -// } -// -// @Test -// public void testFindUsersForCampaign() throws Exception { -// List user = UserService.findUsersForCampaign("Campaign 1"); -// assertNotEquals(2, user.size()); -// } -// -// @SneakyThrows -// @Test -// public void testCampaignAddition() throws Exception { -// // CampaignConsumer.processMessage("897fb6ea-cb07-4891-b714-1e86784ef610"); -// } -} \ No newline at end of file diff --git a/src/test/resources/log4j2-testconfig.xml b/src/test/resources/log4j2-testconfig.xml deleted file mode 100644 index c95590c..0000000 --- a/src/test/resources/log4j2-testconfig.xml +++ /dev/null @@ -1,14 +0,0 @@ - - - - - - - - - - - - \ No newline at end of file From 8f135b8af991c745f03e5ada7b9cbb8a3a849cd7 Mon Sep 17 00:00:00 2001 From: Yashwant Date: Fri, 29 Apr 2022 17:31:14 +0530 Subject: [PATCH 8/8] test cases for Orchestrator --- .../Consumer/ReactiveConsumer.java | 8 +- .../ApplicationConfiguration.java | 93 ++++++++----------- .../Consumer/ReactiveConsumerTest.java | 67 +------------ 3 files changed, 44 insertions(+), 124 deletions(-) diff --git a/src/main/java/com/uci/orchestrator/Consumer/ReactiveConsumer.java b/src/main/java/com/uci/orchestrator/Consumer/ReactiveConsumer.java index c90a17b..d984c2e 100644 --- a/src/main/java/com/uci/orchestrator/Consumer/ReactiveConsumer.java +++ b/src/main/java/com/uci/orchestrator/Consumer/ReactiveConsumer.java @@ -146,13 +146,13 @@ public void accept(JsonNode campaign) { String appId = campaign.get("id").asText(); JsonNode firstTransformer = campaign.findValues("transformers").get(0).get(0); log.info("firstTransformer: "+firstTransformer); - resolveUserNew(msg, appId) // look here + resolveUserNew(msg, appId) .doOnNext(new Consumer() { @Override public void accept(XMessage msg) { SenderReceiverInfo from = msg.getFrom(); // msg.setFrom(from); - getLastMessageID(msg) // look here too + getLastMessageID(msg) .doOnNext(lastMessageID -> { logTimeTaken(startTime, 4); msg.setLastMessageID(lastMessageID); @@ -165,7 +165,7 @@ public void accept(XMessage msg) { try { if(firstTransformer.get("id").asText().equals("774cd134-6657-4688-85f6-6338e2323dde") && firstTransformer.get("type").asText().equals("broadcast")) { - XMessage message = setXMessageMeta(msg, campaign, firstTransformer); // critical one + XMessage message = setXMessageMeta(msg, campaign, firstTransformer); kafkaProducer.send(broadcastTransformerTopic, message.toXML()); } else { kafkaProducer.send(odkTransformerTopic, msg.toXML()); @@ -299,7 +299,7 @@ private Mono resolveUserNew(XMessage xmsg, String appId) { String encodedBase64Key = encodeKey(secret); String deviceID = AESWrapper.encrypt(deviceString, encodedBase64Key); log.info("deviceString: "+deviceString+", encyprted deviceString: "+deviceID); - String userID = getFAUserIdForApp(deviceID, appID); // try mocking this + String userID = getFAUserIdForApp(deviceID, appID); if (userID != null && !userID.isEmpty()) { log.info("Found FA user id"); diff --git a/src/test/java/com/uci/orchestrator/ApplicationConfiguration.java b/src/test/java/com/uci/orchestrator/ApplicationConfiguration.java index d43ae3a..f82c7d7 100644 --- a/src/test/java/com/uci/orchestrator/ApplicationConfiguration.java +++ b/src/test/java/com/uci/orchestrator/ApplicationConfiguration.java @@ -1,6 +1,11 @@ package com.uci.orchestrator; +import com.fasterxml.jackson.core.JsonProcessingException; +import com.fasterxml.jackson.databind.JsonNode; +import com.fasterxml.jackson.databind.ObjectMapper; import com.github.benmanes.caffeine.cache.Cache; +import com.google.common.util.concurrent.ListenableFuture; +import com.uci.dao.repository.XMessageRepository; import com.uci.orchestrator.Consumer.ReactiveConsumer; import com.uci.utils.BotService; import com.uci.utils.CampaignService; @@ -12,14 +17,17 @@ import org.apache.kafka.clients.consumer.*; import org.apache.kafka.clients.producer.ProducerConfig; import org.apache.kafka.common.TopicPartition; +import org.json.JSONArray; import org.mockito.Mockito; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Value; +import org.springframework.boot.test.mock.mockito.MockBean; import org.springframework.context.annotation.Bean; import org.springframework.data.redis.core.RedisTemplate; import org.springframework.kafka.core.DefaultKafkaProducerFactory; import org.springframework.kafka.core.KafkaTemplate; import org.springframework.kafka.core.ProducerFactory; +import org.springframework.kafka.support.SendResult; import org.springframework.kafka.support.serializer.JsonDeserializer; import org.springframework.web.reactive.function.client.WebClient; import reactor.core.CoreSubscriber; @@ -56,19 +64,30 @@ public class ApplicationConfiguration{ // @Value("${spring.kafka.bootstrap-servers}") // private String BOOTSTRAP_SERVERS; -// @Bean -// public CampaignService getCampaignService() throws JsonProcessingException { -// ObjectMapper objectMapper = new ObjectMapper(); -// JsonNode botNode = objectMapper.readTree("{\"id\":\"api.bot.getByParam\",\"ver\":\"1.0\",\"ts\":\"2022-04-21T19:16:52.914Z\",\"params\":{\"resmsgid\":\"9a01a120-c1a7-11ec-afae-4f4769c7c758\",\"msgid\":\"9a00b6c0-c1a7-11ec-afae-4f4769c7c758\",\"status\":\"successful\",\"err\":null,\"errmsg\":null},\"responseCode\":\"OK\",\"result\":{\"data\":{\"id\":\"d655cf03-1f6f-4510-acf6-d3f51b488a5e\",\"name\":\"UCI Demo\",\"startingMessage\":\"Hi UCI\",\"users\":[],\"logicIDs\":[\"e96b0865-5a76-4566-8694-c09361b8ae32\"],\"owners\":null,\"created_at\":\"2021-07-08T18:48:37.740Z\",\"updated_at\":\"2022-02-11T14:09:53.570Z\",\"status\":\"enabled\",\"description\":\"For Internal Demo\",\"startDate\":\"2022-02-01T00:00:00.000Z\",\"endDate\":null,\"purpose\":\"For Internal Demo\",\"ownerOrgID\":\"ORG_001\",\"ownerID\":\"95e4942d-cbe8-477d-aebd-ad8e6de4bfc8\",\"logic\":[{\"id\":\"e96b0865-5a76-4566-8694-c09361b8ae32\",\"transformers\":[{\"id\":\"bbf56981-b8c9-40e9-8067-468c2c753659\",\"meta\":{\"form\":\"https://hosted.my.form.here.com\",\"formID\":\"UCI-demo-1\"}}],\"adapter\":\"44a9df72-3d7a-4ece-94c5-98cf26307324\",\"name\":\"UCI Demo\",\"created_at\":\"2021-07-08T18:47:44.925Z\",\"updated_at\":\"2022-02-03T12:29:32.959Z\",\"description\":null}]}}}\n"); -// Cache cache = Mockito.mock(Cache.class); -// Mockito.when(cache.getIfPresent("campaign-node-by-id:d655cf03-1f6f-4510-acf6-d3f51b488a5e")).thenReturn(botNode); -// return new CampaignService(getWebClient(), getFusionAuthClient(), cache); -// } -// - @Autowired Flux> reactiveKafkaReceiver; + @MockBean + XMessageRepository xMessageRepository; + + @Autowired + public SimpleProducer kafkaProducer; + + @Autowired + public ReactiveProducer reactiveProducer; + + @MockBean + public BotService botService; + + @MockBean + public CampaignService campaignService; + + @MockBean + public UserService userService; + + @MockBean + public RedisCacheService redisCacheService; + @Bean public UserService getUserService(){ return new UserService(); @@ -89,17 +108,6 @@ public SimpleProducer getSimpleProducer(){ return new SimpleProducer(kafkaTemplate()); } -// @Bean -// public ReactiveConsumer getReactiveConsumer(){ -// return new ReactiveConsumer(new Flux>() { -// @Override -// public void subscribe(CoreSubscriber> coreSubscriber) { -// -// -// } -// }); -// } - @Bean public BotService getBotService(){ WebClient webClient = WebClient.builder() @@ -109,14 +117,6 @@ public BotService getBotService(){ return new BotService(webClient, getFAClient(), getCache()); } - - // from application configuration : - - /** - * below these methods are from AppConfigOrchestrator.java - * @return - */ - @Bean public FusionAuthClient getFAClient() { return new FusionAuthClient("FUSIONAUTH_KEY", "FUSIONAUTH_URL"); @@ -132,7 +132,15 @@ public CampaignService getCampaignService() { } @Bean - public ReactiveConsumer getReactiveConsumer(){ + public ReactiveConsumer getReactiveConsumer() throws JsonProcessingException { + ObjectMapper objectMapper = new ObjectMapper(); + Mockito.when(botService.getCurrentAdapter("UCI Demo")).thenReturn(Mono.just("44a9df72-3d7a-4ece-94c5-98cf26307324")); + JsonNode campaignNode = objectMapper.readTree("{\"id\":\"d655cf03-1f6f-4510-acf6-d3f51b488a5e\",\"name\":\"UCI Demo\",\"startingMessage\":\"Hi UCI\",\"users\":[],\"logicIDs\":[\"e96b0865-5a76-4566-8694-c09361b8ae32\"],\"owners\":null,\"created_at\":\"2021-07-08T18:48:37.740Z\",\"updated_at\":\"2022-02-11T14:09:53.570Z\",\"status\":\"enabled\",\"description\":\"For Internal Demo\",\"startDate\":\"2022-02-01T00:00:00.000Z\",\"endDate\":null,\"purpose\":\"For Internal Demo\",\"ownerOrgID\":\"ORG_001\",\"ownerID\":\"95e4942d-cbe8-477d-aebd-ad8e6de4bfc8\",\"userSegments\":[],\"logic\":[{\"id\":\"e96b0865-5a76-4566-8694-c09361b8ae32\",\"transformers\":[{\"id\":\"bbf56981-b8c9-40e9-8067-468c2c753659\",\"meta\":{\"form\":\"https://hosted.my.form.here.com\",\"formID\":\"UCI-demo-1\"}}],\"adapter\":{\"id\":\"44a9df72-3d7a-4ece-94c5-98cf26307324\",\"channel\":\"WhatsApp\",\"provider\":\"gupshup\",\"config\":{\"2WAY\":\"2000193033\",\"phone\":\"9876543210\",\"HSM_ID\":\"2000193031\",\"credentials\":{\"vault\":\"samagra\",\"variable\":\"gupshupSamagraProd\"}},\"name\":\"SamagraProd\",\"updated_at\":\"2021-06-16T06:02:39.125Z\",\"created_at\":\"2021-06-16T06:02:41.823Z\"},\"name\":\"UCI Demo\",\"created_at\":\"2021-07-08T18:47:44.925Z\",\"updated_at\":\"2022-02-03T12:29:32.959Z\",\"description\":null}]}"); + Mockito.when(campaignService.getCampaignFromNameTransformer("UCI Demo")).thenReturn(Mono.just(campaignNode)); + userService.CAMPAIGN_URL = "http://localhost"; + Mockito.when(userService.getUsersFromFederatedServers(Mockito.anyString())).thenReturn(new JSONArray()); + Mockito.when(redisCacheService.getFAUserIDForAppCache("yOJcM+Gm7yVkKeQqPhdDKNb0wsmh8St/ty+pM5Q+4W4=" + "-" + "d655cf03-1f6f-4510-acf6-d3f51b488a5e")).thenReturn("91311fd1-5c1c-4f81-b9eb-2d259159554a"); + Mockito.when(xMessageRepository.findAllByUserIdAndTimestampAfter(Mockito.any(), Mockito.any())).thenReturn(Flux.just()); return new ReactiveConsumer(reactiveKafkaReceiver); } @@ -177,31 +185,6 @@ SenderOptions kafkaSenderOptions() { Flux> reactiveKafkaReceiver(@Autowired ReceiverOptions kafkaReceiverOptions) { KafkaReceiver kafkaReceiver = KafkaReceiver.create(kafkaReceiverOptions); Consumer consumer = new MockConsumer(OffsetResetStrategy.EARLIEST); -// ConsumerRecord consumerRecord = new ConsumerRecord("inbound-processed", 0, 33, null, -// "\n" + -// "\n" + -// " 897fb6ea-cb07-4891-b714-1e86784ef610\n" + -// " WhatsApp\n" + -// " WhatsApp\n" + -// " \n" + -// " 0\n" + -// " STARTING\n" + -// " \n" + -// " Gupshup\n" + -// " Gupshup\n" + -// " 1595137277407\n" + -// " \n" + -// " 2\n" + -// " \n" + -// " \n" + -// " Form\n" + -// " RQ\n" + -// " \n" + -// " \n" + -// " \n" + -// "\n" -// ); - ConsumerRecord consumerRecord = new ConsumerRecord("inbound-processed", 0, 33, null, "\n" + "\n" + diff --git a/src/test/java/com/uci/orchestrator/Consumer/ReactiveConsumerTest.java b/src/test/java/com/uci/orchestrator/Consumer/ReactiveConsumerTest.java index bd7708d..d3ef2de 100644 --- a/src/test/java/com/uci/orchestrator/Consumer/ReactiveConsumerTest.java +++ b/src/test/java/com/uci/orchestrator/Consumer/ReactiveConsumerTest.java @@ -1,42 +1,16 @@ package com.uci.orchestrator.Consumer; import com.fasterxml.jackson.core.JsonProcessingException; -import com.fasterxml.jackson.databind.JsonNode; -import com.fasterxml.jackson.databind.ObjectMapper; -import com.uci.dao.models.XMessageDAO; -import com.uci.dao.repository.XMessageRepository; import com.uci.orchestrator.ApplicationConfiguration; -import com.uci.utils.BotService; -import com.uci.utils.CampaignService; -import com.uci.utils.cache.service.RedisCacheService; -import com.uci.utils.kafka.ReactiveProducer; -import com.uci.utils.kafka.SimpleProducer; -import com.uci.utils.service.UserService; -import org.apache.kafka.clients.consumer.ConsumerRecord; -import org.apache.kafka.clients.consumer.MockConsumer; -import org.apache.kafka.clients.consumer.OffsetAndMetadata; -import org.apache.kafka.clients.consumer.OffsetResetStrategy; -import org.json.JSONArray; -import org.junit.Before; -import org.junit.jupiter.api.BeforeAll; -import org.junit.jupiter.api.BeforeEach; +import lombok.extern.slf4j.Slf4j; import org.junit.jupiter.api.Test; import org.junit.jupiter.api.extension.ExtendWith; -import org.mockito.Mockito; import org.mockito.junit.jupiter.MockitoExtension; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.boot.test.context.SpringBootTest; -import org.springframework.boot.test.mock.mockito.MockBean; -import org.springframework.data.redis.connection.stream.Consumer; -import reactor.core.CoreSubscriber; -import reactor.core.publisher.Flux; -import reactor.core.publisher.Mono; -import reactor.kafka.receiver.ReceiverRecord; -import java.time.LocalDateTime; - -//@Slf4j +@Slf4j @SpringBootTest(classes = ApplicationConfiguration.class) @ExtendWith(MockitoExtension.class) class ReactiveConsumerTest { @@ -44,45 +18,8 @@ class ReactiveConsumerTest { @Autowired ReactiveConsumer reactiveConsumer; - @MockBean - XMessageRepository xMessageRepository; - - @Autowired - public SimpleProducer kafkaProducer; - - @Autowired - public ReactiveProducer reactiveProducer; - - @MockBean - public BotService botService; - - @MockBean - public CampaignService campaignService; - - @MockBean - public UserService userService; - - @MockBean - public RedisCacheService redisCacheService; - - - @BeforeAll - public static void setup(){ - MockConsumer mockConsumer = new MockConsumer(OffsetResetStrategy.EARLIEST); - } - @Test void onMessage() throws JsonProcessingException { - - ObjectMapper objectMapper = new ObjectMapper(); - Mockito.when(botService.getCurrentAdapter("UCI Demo")).thenReturn(Mono.just("44a9df72-3d7a-4ece-94c5-98cf26307324")); - JsonNode campaignNode = objectMapper.readTree("{\"id\":\"d655cf03-1f6f-4510-acf6-d3f51b488a5e\",\"name\":\"UCI Demo\",\"startingMessage\":\"Hi UCI\",\"users\":[],\"logicIDs\":[\"e96b0865-5a76-4566-8694-c09361b8ae32\"],\"owners\":null,\"created_at\":\"2021-07-08T18:48:37.740Z\",\"updated_at\":\"2022-02-11T14:09:53.570Z\",\"status\":\"enabled\",\"description\":\"For Internal Demo\",\"startDate\":\"2022-02-01T00:00:00.000Z\",\"endDate\":null,\"purpose\":\"For Internal Demo\",\"ownerOrgID\":\"ORG_001\",\"ownerID\":\"95e4942d-cbe8-477d-aebd-ad8e6de4bfc8\",\"userSegments\":[],\"logic\":[{\"id\":\"e96b0865-5a76-4566-8694-c09361b8ae32\",\"transformers\":[{\"id\":\"bbf56981-b8c9-40e9-8067-468c2c753659\",\"meta\":{\"form\":\"https://hosted.my.form.here.com\",\"formID\":\"UCI-demo-1\"}}],\"adapter\":{\"id\":\"44a9df72-3d7a-4ece-94c5-98cf26307324\",\"channel\":\"WhatsApp\",\"provider\":\"gupshup\",\"config\":{\"2WAY\":\"2000193033\",\"phone\":\"9876543210\",\"HSM_ID\":\"2000193031\",\"credentials\":{\"vault\":\"samagra\",\"variable\":\"gupshupSamagraProd\"}},\"name\":\"SamagraProd\",\"updated_at\":\"2021-06-16T06:02:39.125Z\",\"created_at\":\"2021-06-16T06:02:41.823Z\"},\"name\":\"UCI Demo\",\"created_at\":\"2021-07-08T18:47:44.925Z\",\"updated_at\":\"2022-02-03T12:29:32.959Z\",\"description\":null}]}"); - Mockito.when(campaignService.getCampaignFromNameTransformer("UCI Demo")).thenReturn(Mono.just(campaignNode)); - userService.CAMPAIGN_URL = "http://localhost"; - Mockito.when(userService.getUsersFromFederatedServers(Mockito.anyString())).thenReturn(new JSONArray()); - Mockito.when(redisCacheService.getFAUserIDForAppCache("yOJcM+Gm7yVkKeQqPhdDKNb0wsmh8St/ty+pM5Q+4W4=" + "-" + "d655cf03-1f6f-4510-acf6-d3f51b488a5e")).thenReturn("91311fd1-5c1c-4f81-b9eb-2d259159554a"); - Mockito.when(xMessageRepository.findAllByUserIdAndTimestampAfter("7823807161", Mockito.any())).thenReturn(Flux.just(new XMessageDAO())); reactiveConsumer.onMessage(); - } } \ No newline at end of file