Added oparent to sdc main
[sdc.git] / test-apis-ci / src / test / java / org / openecomp / sdc / cucumber / steps / StepsTenantIsolationCI.java
1 /*-
2  * ============LICENSE_START=======================================================
3  * SDC
4  * ================================================================================
5  * Copyright (C) 2019 AT&T Intellectual Property. All rights reserved.
6  * ================================================================================
7  * Licensed under the Apache License, Version 2.0 (the "License");
8  * you may not use this file except in compliance with the License.
9  * You may obtain a copy of the License at
10  * 
11  *      http://www.apache.org/licenses/LICENSE-2.0
12  * 
13  * Unless required by applicable law or agreed to in writing, software
14  * distributed under the License is distributed on an "AS IS" BASIS,
15  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
16  * See the License for the specific language governing permissions and
17  * limitations under the License.
18  * ============LICENSE_END=========================================================
19  */
20
21 package org.openecomp.sdc.cucumber.steps;
22
23 import com.google.common.base.Strings;
24 import com.google.common.net.HttpHeaders;
25 import com.google.gson.JsonElement;
26 import com.google.gson.JsonParser;
27 import cucumber.api.java.After;
28 import cucumber.api.java.Before;
29 import cucumber.api.java.en.Given;
30 import cucumber.api.java.en.Then;
31 import cucumber.api.java.en.When;
32 import fj.data.Either;
33 import org.apache.commons.collections.CollectionUtils;
34 import org.apache.commons.lang3.StringUtils;
35 import org.apache.http.HttpStatus;
36 import org.apache.http.entity.ContentType;
37 import org.apache.http.entity.StringEntity;
38 import org.mockserver.integration.ClientAndServer;
39 import org.mockserver.model.Header;
40 import org.mockserver.model.HttpRequest;
41 import org.openecomp.sdc.api.IDistributionClient;
42 import org.openecomp.sdc.api.consumer.IConfiguration;
43 import org.openecomp.sdc.api.consumer.IFinalDistrStatusMessage;
44 import org.openecomp.sdc.api.consumer.INotificationCallback;
45 import org.openecomp.sdc.api.notification.IArtifactInfo;
46 import org.openecomp.sdc.api.notification.INotificationData;
47 import org.openecomp.sdc.api.results.IDistributionClientDownloadResult;
48 import org.openecomp.sdc.api.results.IDistributionClientResult;
49 import org.openecomp.sdc.be.dao.cassandra.CassandraOperationStatus;
50 import org.openecomp.sdc.be.dao.cassandra.OperationalEnvironmentDao;
51 import org.openecomp.sdc.be.datatypes.enums.EnvironmentStatusEnum;
52 import org.openecomp.sdc.be.resources.data.OperationalEnvironmentEntry;
53 import org.openecomp.sdc.common.datastructure.FunctionalInterfaces;
54 import org.openecomp.sdc.common.datastructure.Wrapper;
55 import org.openecomp.sdc.cucumber.spring.ImportTableConfig;
56 import org.openecomp.sdc.http.HttpAsdcClient;
57 import org.openecomp.sdc.http.HttpAsdcResponse;
58 import org.openecomp.sdc.http.IHttpAsdcClient;
59 import org.openecomp.sdc.impl.DistributionClientFactory;
60 import org.openecomp.sdc.utils.ArtifactTypeEnum;
61 import org.openecomp.sdc.utils.DistributionActionResultEnum;
62 import org.openecomp.sdc.utils.DistributionStatusEnum;
63 import org.springframework.context.annotation.AnnotationConfigApplicationContext;
64
65 import java.util.*;
66 import java.util.function.Function;
67 import java.util.stream.Collectors;
68
69 import static org.hamcrest.MatcherAssert.assertThat;
70 import static org.hamcrest.Matchers.is;
71 import static org.mockserver.model.HttpClassCallback.callback;
72 import static org.mockserver.model.HttpRequest.request;
73 import static org.mockserver.model.HttpResponse.response;
74 import static org.openecomp.sdc.common.datastructure.FunctionalInterfaces.retryMethodOnResult;
75 import static org.testng.Assert.assertEquals;
76 import static org.testng.Assert.assertNotNull;
77
78 //import org.openecomp.sdc.dmaap.DmaapPublisher;
79
80 public class StepsTenantIsolationCI {
81
82         private Map<String, OperationalEnvironmentEntry> recordMap = new HashMap<>();
83         private OperationalEnvironmentDao operationalEnvironmentDao;
84         private ClientAndServer aaiMockServer;
85         private ClientAndServer msoMockServer;
86         private List<IDistributionClient> distributionClients = new ArrayList<>();
87
88         private List<String> wdFinalStatusSent = new ArrayList<>();
89
90         private HttpRequest msoHttpRequest;
91         private List<String> uuidServicesList;
92         private boolean cleanFlag = true;
93         private int maxStepWaitTimeMs;
94
95         private List<String> envIds = new ArrayList<>();
96         private List<OperationalEnvironmentEntry> envList = new ArrayList<>();
97         private String asdcAddress;
98         private volatile int numberOfFinalDistributionsSentByASDC;
99         private int numOfArtifactsToDownload;
100         private volatile int totalNumOfArtifactsToDownload;
101         private List<String> envNames = new ArrayList<>(Arrays.asList("Apple", "Orange", "Grape", "Pear", "Watermelon", "Bannana", "Cherry", "Coconut", "Fig", "Mango", "Peach", "Pineapple", "Plum", "Strawberries", "Apricot"));
102
103         private static final String AAI_RESPONSE_BODY_FMT = "{\"operational-environment-id\":\"UUID of Operational Environment\","
104                         + "\"operational-environment-name\":\"Op Env Name\"," + "\"operational-environment-type\":\"ECOMP\","
105                         + "\"operational-environment-status\":\"Activate\"," + "\"tenant-context\":\"%s\","
106                         + "\"workload-context\":\"%s\"," + "\"resource-version\":\"1505228226913\"," + "\"relationship-list\":{}}";
107
108         private static final String AAI_PATH_REGEX = "/aai/v12/cloud-infrastructure/operational-environments/.*";
109
110         private static final String MSO_PATH_REGEX = "/onap/mso/infra/modelDistributions/v1/distributions/.*";
111
112         @Before
113         public void beforeScenario() {
114                 Collections.shuffle(envNames);
115                 aaiMockServer = ClientAndServer.startClientAndServer(1111);
116                 msoMockServer = ClientAndServer.startClientAndServer(1112);
117
118                 this.operationalEnvironmentDao = createDaoObj();
119         }
120
121         @After
122         public void afterScenario() {
123                 System.out.println("Cleaning Up After Scenario...");
124                 aaiMockServer.stop();
125                 msoMockServer.stop();
126                 if (cleanFlag) {
127                         envIds.stream().forEach(operationalEnvironmentDao::delete);
128                 }
129                 distributionClients.stream().forEach(IDistributionClient::stop);
130                 System.out.println("Cleaning Up After Scenario Done");
131         }
132
133         // ############################# Given - Start #############################
134
135         @Given("^clean db after test is (.*)$")
136         public void clean_db_after_test_is(boolean cleanFlag) {
137                 this.cleanFlag = cleanFlag;
138         }
139
140         @Given("^AAI returns (.*) and aai_body contains (.*) and (.*)$")
141         public void aai_returns(int retCode, String tenant, String workload) throws Throwable {
142                 String aaiResponseBody = String.format(AAI_RESPONSE_BODY_FMT, tenant, workload);
143
144                 setAaiMockServer(aaiResponseBody);
145
146                 System.out.println(aaiMockServer.getClass());
147         }
148
149         @Given("^MSO-WD Simulators Started with topic name (.*)$")
150         public void notification_listner_simulators_started(String topicName) throws Throwable {
151                 envList.forEach(env -> {
152                         final IDistributionClient distClientSim = simulateDistributionClientWD(topicName, env);
153                         distributionClients.add(distClientSim);
154                 });
155
156         }
157
158         @Given("^MSO Final Distribution Simulator is UP$")
159         public void mso_Final_Distribution_Simulator_is_UP() throws Throwable {
160                 msoHttpRequest = request().withPath(MSO_PATH_REGEX);
161                 msoMockServer.when(msoHttpRequest).forward(
162                                 callback().withCallbackClass("org.openecomp.sdc.cucumber.steps.PrecannedTestExpectationCallback"));
163         }
164
165         @Given("^ASDC Address is (.*)$")
166         public void asdc_Address_is(String asdcAddress) throws Throwable {
167                 this.asdcAddress = asdcAddress;
168
169         }
170
171         @Given("^ASDC Contains the following services (.*)$")
172         public void asdc_Contains_the_following_services(String listOfServicesUUID) throws Throwable {
173                 uuidServicesList = Arrays.asList(listOfServicesUUID.split(",")).stream().map(String::trim)
174                                 .collect(Collectors.toList());
175
176                 int maxMinWait = uuidServicesList.size() * envIds.size();
177                 this.maxStepWaitTimeMs = 60000 * maxMinWait;
178                 System.out.println(String.format("Set Max Step Wait Time To: %s Minutes", maxMinWait));
179         }
180
181         @Given("^The number of complete environments is (.*)$")
182         public void the_number_of_complete_environments_is(int envNum) throws Throwable {
183
184                 int counter = 1;
185                 while( envNum > envNames.size()){
186                         envNames.add(String.valueOf(counter));
187                         counter++;
188                 }
189                 
190                 
191                 for (int i = 0; i < envNum; i++) {
192                         OperationalEnvironmentEntry preSaveEntry = new OperationalEnvironmentEntry();
193
194                         preSaveEntry.setStatus(EnvironmentStatusEnum.COMPLETED);
195                         preSaveEntry.setLastModified(new Date(System.currentTimeMillis()));
196
197                         Set<String> uebAdresses = new HashSet<>();
198                         uebAdresses.add("uebsb92sfdc.it.att.com");
199                         preSaveEntry.setDmaapUebAddress(uebAdresses);
200                         preSaveEntry.setIsProduction(false);
201                         preSaveEntry.setUebApikey("sSJc5qiBnKy2qrlc");
202                         preSaveEntry.setUebSecretKey("4ZRPzNJfEUK0sSNBvccd2m7X");
203                         preSaveEntry.setTenant("TEST");
204                         preSaveEntry.setEcompWorkloadContext("ECOMP_E2E-IST");
205
206                         // String envId = UUID.randomUUID().toString();
207                         String envId = envNames.get(i);
208                         preSaveEntry.setEnvironmentId(envId);
209                         envIds.add(envId);
210                         envList.add(preSaveEntry);
211                         operationalEnvironmentDao.save(preSaveEntry);
212                 }
213         }
214
215         @Given("^The number of artifacts each Simulator downloads from a service is (.*)$")
216         public void number_of_artifacts_each_simulator_downloads(int numOfArtifactsToDownload) throws Throwable {
217                 this.numOfArtifactsToDownload = numOfArtifactsToDownload;
218         }
219
220         // ############################# Given - End #############################
221
222         // ############################# When - Start #############################
223         @When("^Distribution Requests are Sent By MSO$")
224         public void distribution_Requests_are_Sent_By_MSO() throws Throwable {
225                 envList.stream().forEach(this::distributeServiceInEnv);
226
227         }
228
229         @When("^The Number Of Operational Envrinoments that created is (.*) and Records are added with data (.*)$")
230         public void operational_envrinoments_records_are_added_with_data(int numOfRecords, String recordData)
231                         throws Throwable {
232                 for (int i = 0; i < numOfRecords; i++) {
233                         OperationalEnvironmentEntry preSaveEntry = new OperationalEnvironmentEntry();
234                         JsonElement root = new JsonParser().parse(recordData);
235
236                         String originalStatus = root.getAsJsonObject().get("status").getAsString();
237                         int delta = root.getAsJsonObject().get("last_modified_delta").getAsInt();
238                         preSaveEntry.setStatus(EnvironmentStatusEnum.getByName(originalStatus));
239                         long last_modified = System.currentTimeMillis() + delta * 1000;
240                         preSaveEntry.setLastModified(new Date(last_modified));
241                         String envId = UUID.randomUUID().toString();
242                         preSaveEntry.setEnvironmentId(envId);
243                         envIds.add(envId);
244                         // envrionmentIds.add(envId);
245                         operationalEnvironmentDao.save(preSaveEntry);
246
247                 }
248
249         }
250
251         // ############################# When - End #############################
252
253         // ############################# Then - Start #############################
254         @Then("^Operational Environment record contains tenant field (.*$)")
255         public void operational_environment_record_contains_tenant(boolean tenantExist) throws Throwable {
256                 envIds.forEach(envId -> {
257                         validateStringFieldPresent(tenantExist, OperationalEnvironmentEntry::getTenant, envId,
258                                         "Tenant is not as expected");
259                 });
260         }
261
262         @Then("^Operational Environment record contains workload field (.*$)")
263         public void operational_environment_record_contains_workload(boolean workloadExist) throws Throwable {
264                 envIds.forEach(envId -> {
265                         validateStringFieldPresent(workloadExist, OperationalEnvironmentEntry::getEcompWorkloadContext, envId,
266                                         "Workload is not as expected");
267                 });
268         }
269
270         @Then("^Operational Environment record contains UEB Address field (.*$)")
271         public void operational_environment_record_contains_ueb_address(boolean uebAddresExist) throws Throwable {
272                 envIds.forEach(envId -> {
273                         validateStringFieldPresent(uebAddresExist, this::convertUebAddressToList, envId,
274                                         "UEB Address is not as expected");
275                 });
276         }
277
278         @Then("^The Number Of Environment is (.*) with status (.*)$")
279         public void the_Number_Of_Environment_Created_is(int numberOfEnvsCreated, String status) throws Throwable {
280                 // Write code here that turns the phrase above into concrete actions
281
282                 retryMethodOnResult(() -> getCurrentEnvironmets(status), envList -> envList.size() == numberOfEnvsCreated,
283                                 40000, 500);
284
285                 List<OperationalEnvironmentEntry> environmentsFound = getCurrentEnvironmets(status);
286
287                 assertThat(environmentsFound.size(), is(numberOfEnvsCreated));
288
289                 environmentsFound.forEach(env -> recordMap.put(env.getEnvironmentId(), env));
290                 envList.addAll(environmentsFound);
291         }
292
293         @Then("^MSO Final Distribution Recieved Correct Number Of Request$")
294         public void mso_final_distribution_recieved_request() throws Throwable {
295                 int expectedNumberOfRequestsSentByASDC = calculateExcpectedNumberOfDistributionRequets();
296                 Function<Integer, Boolean> resultVerifier = actualStatusList -> actualStatusList >= expectedNumberOfRequestsSentByASDC;
297                 retryMethodOnResult(() -> numberOfFinalDistributionsSentByASDC(expectedNumberOfRequestsSentByASDC),
298                                 resultVerifier, maxStepWaitTimeMs, 500);
299                 int actualNumberOfRequestsSentByASDC = numberOfFinalDistributionsSentByASDC(expectedNumberOfRequestsSentByASDC);
300                 assertThat(actualNumberOfRequestsSentByASDC, is(expectedNumberOfRequestsSentByASDC));
301         }
302
303         @Then("^All MSO-WD Simulators Sent The Distribution Complete Notifications$")
304         public void all_mso_wd_simulators_sent_the_distribution_complete_notifications() {
305                 // Wait Watch Dogs To Send Final Distribution
306                 int excpectedNumberOfDistributionCompleteNotifications = calculateExcpectedNumberOfDistributionRequets();
307                 final Function<List<String>, Boolean> resultVerifier = actualStatusList -> actualStatusList
308                                 .size() == excpectedNumberOfDistributionCompleteNotifications;
309                 retryMethodOnResult(() -> wdFinalStatusSent, resultVerifier, maxStepWaitTimeMs, 500);
310                 assertThat(wdFinalStatusSent.size(), is(excpectedNumberOfDistributionCompleteNotifications));
311         }
312         @Then("^All Artifacts were downloaded by Simulators$")
313         public void all_artifacts_downloaded() {
314                 // Wait Watch Dogs To Send Final Distribution
315                 int excpectedNumberOfArtifactsToDownload = numOfArtifactsToDownload * envIds.size() * uuidServicesList.size();
316                 assertThat(totalNumOfArtifactsToDownload, is(excpectedNumberOfArtifactsToDownload));
317         }
318         // ############################# Then - End #############################
319
320         private List<OperationalEnvironmentEntry> getCurrentEnvironmets(String status) {
321                 Either<List<OperationalEnvironmentEntry>, CassandraOperationStatus> eitherStatus = operationalEnvironmentDao
322                                 .getByEnvironmentsStatus(EnvironmentStatusEnum.getByName(status));
323                 assertThat(eitherStatus.isLeft(), is(true));
324
325                 List<OperationalEnvironmentEntry> environmentsRetrieved = eitherStatus.left().value();
326
327                 List<OperationalEnvironmentEntry> environmentsFound = environmentsRetrieved.stream()
328                                 .filter(env -> envIds.contains(env.getEnvironmentId())).collect(Collectors.toList());
329                 return environmentsFound;
330         }
331
332         private int numberOfFinalDistributionsSentByASDC(int expectedNumberOfRequestsSentByASDC) {
333                 final int newVal = msoMockServer.retrieveRecordedRequests(msoHttpRequest).length;
334                 if (newVal != numberOfFinalDistributionsSentByASDC) {
335                         System.out.println(String.format(
336                                         "MSO Server Simulator Recieved %s/%s Final Distribution Complete Rest Reports From ASDC", newVal,
337                                         expectedNumberOfRequestsSentByASDC));
338                         numberOfFinalDistributionsSentByASDC = newVal;
339                 }
340
341                 return newVal;
342         }
343
344         private int calculateExcpectedNumberOfDistributionRequets() {
345                 int numberOfDistributionRequests = envList.size() * uuidServicesList.size();
346                 return numberOfDistributionRequests;
347         }
348
349         private static OperationalEnvironmentDao createDaoObj() {
350                 AnnotationConfigApplicationContext context = new AnnotationConfigApplicationContext(ImportTableConfig.class);
351                 final OperationalEnvironmentDao openvDao = (OperationalEnvironmentDao) context
352                                 .getBean("operational-environment-dao");
353                 return openvDao;
354         }
355
356         private OperationalEnvironmentEntry getRecord(String environmentId) {
357                 Either<OperationalEnvironmentEntry, CassandraOperationStatus> result = operationalEnvironmentDao
358                                 .get(environmentId);
359                 return result.isLeft() ? result.left().value() : null;
360         }
361
362         private void validateStringFieldPresent(boolean fieldExist,
363                         Function<OperationalEnvironmentEntry, String> getFieldFunc, String envId, String msg) {
364                 OperationalEnvironmentEntry record = recordMap.computeIfAbsent(envId, this::getRecord);
365
366                 assertNotNull(record, "Expected DB record was not found");
367
368                 String actualValue = getFieldFunc.apply(record);
369
370                 assertEquals(fieldExist, !Strings.isNullOrEmpty(actualValue), msg);
371         }
372
373         private void setAaiMockServer(String aaiResponseBody) {
374                 HttpRequest httpRequest = request().withMethod("GET").withPath(AAI_PATH_REGEX)
375                                 .withHeaders(new Header(HttpHeaders.CONTENT_TYPE, ContentType.APPLICATION_JSON.getMimeType()));
376
377                 aaiMockServer.when(httpRequest)
378                                 .respond(response()
379                                                 .withHeaders(new Header(HttpHeaders.CONTENT_TYPE, ContentType.APPLICATION_JSON.getMimeType()))
380                                                 .withBody(aaiResponseBody));
381         }
382
383         private IDistributionClient simulateDistributionClientWD(String topicName, OperationalEnvironmentEntry opEnv) {
384
385                 IDistributionClient client = DistributionClientFactory.createDistributionClient();
386                 final IConfiguration buildDistributionClientConfiguration = buildDistributionClientConfiguration(topicName,
387                                 opEnv);
388                 IDistributionClientResult initResult = client.init(buildDistributionClientConfiguration,
389                                 new INotificationCallback() {
390
391                                         @Override
392                                         public void activateCallback(INotificationData data) {
393                                                 buildWdSimulatorCallback(opEnv, client, buildDistributionClientConfiguration, data);
394
395                                         }
396
397                                 });
398                 assertThat(initResult.getDistributionActionResult(), is(DistributionActionResultEnum.SUCCESS));
399                 IDistributionClientResult startResult = client.start();
400                 assertThat(startResult.getDistributionActionResult(), is(DistributionActionResultEnum.SUCCESS));
401                 System.out.println(String.format("WD Simulator On Environment:\"%s\" Started Successfully",
402                                 buildDistributionClientConfiguration.getConsumerID()));
403                 return client;
404         }
405
406         private IFinalDistrStatusMessage buildFinalDistribution() {
407                 return new IFinalDistrStatusMessage() {
408
409                         @Override
410                         public long getTimestamp() {
411                                 return System.currentTimeMillis();
412                         }
413
414                         @Override
415                         public DistributionStatusEnum getStatus() {
416                                 return DistributionStatusEnum.DISTRIBUTION_COMPLETE_OK;
417                         }
418
419                         @Override
420                         public String getDistributionID() {
421                                 return "FakeDistributionId";
422                         }
423                 };
424         }
425
426         private IConfiguration buildDistributionClientConfiguration(String topicName, OperationalEnvironmentEntry opEnv) {
427                 return new IConfiguration() {
428
429                         public String getUser() {
430                                 return "ci";
431                         }
432
433                         public int getPollingTimeout() {
434                                 return 20;
435                         }
436
437                         public int getPollingInterval() {
438                                 return 20;
439                         }
440
441                         public String getPassword() {
442                                 return "123456";
443                         }
444
445                         public String getEnvironmentName() {
446                                 return topicName;
447                         }
448
449                         public String getConsumerID() {
450                                 return opEnv.getEnvironmentId();
451                         }
452
453                         public String getConsumerGroup() {
454                                 return String.format("BenchMarkDistributionClientConsumerGroup%s", opEnv.getEnvironmentId());
455                         }
456
457                         public String getAsdcAddress() {
458                                 return String.format("%s:8443", asdcAddress);
459                         }
460
461                         @Override
462                         public String getKeyStorePath() {
463                                 // TODO Auto-generated method stub
464                                 return null;
465                         }
466
467                         @Override
468                         public String getKeyStorePassword() {
469                                 // TODO Auto-generated method stub
470                                 return null;
471                         }
472
473                         @Override
474                         public boolean activateServerTLSAuth() {
475                                 // TODO Auto-generated method stub
476                                 return false;
477                         }
478
479                         @Override
480                         public List<String> getRelevantArtifactTypes() {
481                                 return Arrays.asList(ArtifactTypeEnum.values()).stream()
482                                                 .map(artifactTypeEnum -> artifactTypeEnum.name()).collect(Collectors.toList());
483                         }
484
485                         @Override
486                         public boolean isFilterInEmptyResources() {
487                                 // TODO Auto-generated method stub
488                                 return false;
489                         }
490
491                         @Override
492                         public Boolean isUseHttpsWithDmaap() {
493                                 return null;
494                         }
495
496                         @Override
497                         public List<String> getMsgBusAddress() {
498                                 return opEnv.getDmaapUebAddress().stream().map(this::extractHost).collect(Collectors.toList());
499                         }
500
501                         private String extractHost(String url) {
502                                 return url.split(":")[0];
503                         }
504                 };
505         }
506
507         private void distributeServiceInEnv(OperationalEnvironmentEntry env) {
508                 uuidServicesList.stream().forEach(serviceUUID -> distributeSingleService(env, serviceUUID));
509         }
510
511         private void distributeSingleService(OperationalEnvironmentEntry env, String serviceUUID) {
512                 IHttpAsdcClient client = new HttpAsdcClient(buildDistributionClientConfiguration(StringUtils.EMPTY, env));
513                 String pattern = "/sdc/v1/catalog/services/%s/distribution/%s/activate";
514                 String requestUrl = String.format(pattern, serviceUUID, env.getEnvironmentId());
515                 String requestBody = String.format("{\"workloadContext\":\"%s\"}", env.getEnvironmentId());
516                 StringEntity body = new StringEntity(requestBody, ContentType.APPLICATION_JSON);
517                 Map<String, String> headersMap = new HashMap<>();
518                 headersMap.put("USER_ID", "cs0008");
519                 headersMap.put("X-ECOMP-InstanceID", "test");
520                 headersMap.put("Content-Type", "application/json");
521
522                 HttpAsdcResponse postRequest = FunctionalInterfaces.retryMethodOnResult(
523                                 () -> distributeMethod(client, requestUrl, serviceUUID, body, headersMap, env.getEnvironmentId()),
524                                 resp -> resp.getStatus() == HttpStatus.SC_ACCEPTED);
525                 assertThat(postRequest.getStatus(), is(HttpStatus.SC_ACCEPTED));
526
527         }
528
529         private HttpAsdcResponse distributeMethod(IHttpAsdcClient client, String requestUrl, String serviceUUID,
530                         StringEntity body, Map<String, String> headersMap, String envId) {
531
532                 final HttpAsdcResponse postRequest = client.postRequest(requestUrl, body, headersMap);
533                 final String message = String.format(
534                                 "MSO Client Simulator Distributes Service:%s On Environment:\"%s\" - Recieved Response: %s", serviceUUID, envId,
535                                 postRequest.getStatus());
536                 if (postRequest.getStatus() != HttpStatus.SC_ACCEPTED) {
537                         System.err.println(message);
538                 } else {
539                         System.out.println(message);
540                 }
541
542                 return postRequest;
543         }
544
545         private String convertUebAddressToList(OperationalEnvironmentEntry op) {
546                 Set<String> dmaapUebAddress = op.getDmaapUebAddress();
547                 Wrapper<String> resultWrapper = new Wrapper<>(StringUtils.EMPTY);
548                 if (!CollectionUtils.isEmpty(dmaapUebAddress)) {
549                         dmaapUebAddress.stream()
550                                         .forEach(uebAddress -> resultWrapper.setInnerElement(resultWrapper.getInnerElement() + uebAddress));
551                 }
552
553                 return resultWrapper.getInnerElement();
554         }
555
556         private void buildWdSimulatorCallback(OperationalEnvironmentEntry opEnv, IDistributionClient client,
557                         final IConfiguration buildDistributionClientConfiguration, INotificationData data) {
558                 if (StringUtils.equals(data.getWorkloadContext(), opEnv.getEnvironmentId())) {
559                         
560                         final String expectedArtifactType = org.openecomp.sdc.common.api.ArtifactTypeEnum.MODEL_INVENTORY_PROFILE.name();
561                         Optional<IArtifactInfo> optional = data.getServiceArtifacts().stream().filter( artifact -> {
562                                 return StringUtils.equals(artifact.getArtifactType(), expectedArtifactType);
563                         }).findAny();
564                         
565                         for (int i = 0; i < numOfArtifactsToDownload; i++) {
566                                 optional.ifPresent( artifactInfo -> simulateDownload(client , artifactInfo, data) );
567                                 optional.orElseThrow( () -> handleArtifactNotFound(expectedArtifactType, data));
568                                 
569                         }
570                         if(  numOfArtifactsToDownload > 0 ){
571                                 System.out.println(String.format(
572                                                 "ASDC Consumer Simulator On Environment:\"%s\" Downloaded %s Artifacts From ASDC Service with UUID:%s  Total Artifacts Downloaded from ASDC is: %s",
573                                                 data.getWorkloadContext(), numOfArtifactsToDownload,
574                                                 data.getServiceUUID(), totalNumOfArtifactsToDownload));
575                         }
576                         
577                         IDistributionClientResult finalDistrStatus = client.sendFinalDistrStatus(buildFinalDistribution());
578                         assertThat(finalDistrStatus.getDistributionActionResult(), is(DistributionActionResultEnum.SUCCESS));
579                         wdFinalStatusSent.add(data.getWorkloadContext());
580
581                         System.out.println(String.format(
582                                         "WD Simulator On Environment:\"%s\" Recieved Notification From ASDC On WorkLoad: %s And Service UUID:%s And Sends Distribution Complete Notification",
583                                         buildDistributionClientConfiguration.getConsumerID(), data.getWorkloadContext(),
584                                         data.getServiceUUID()));
585                 }
586         }
587         
588         private IllegalStateException handleArtifactNotFound(String expectedArtifactType, INotificationData data ){
589                 final String stringMessage = String.format("Did Not Find Artifact of type: %s to download from service with UUID:%s", expectedArtifactType, data.getServiceUUID());
590                 System.err.println(stringMessage); 
591                 return new IllegalStateException(stringMessage);
592          
593         }
594         
595         private void simulateDownload(IDistributionClient client, IArtifactInfo info, INotificationData data){
596                 IDistributionClientDownloadResult downloadResult = client.download(info);
597                 if( downloadResult.getDistributionActionResult() != DistributionActionResultEnum.SUCCESS ){
598                         System.err.println(String.format("Client Simulator %s Failed to download artifact from service : %s", client.getConfiguration().getConsumerID(), data.getServiceUUID()));
599                         assertThat(downloadResult.getDistributionActionResult(), is(DistributionActionResultEnum.SUCCESS));
600                 }
601                 else{
602                         totalNumOfArtifactsToDownload++;
603                 
604                 }
605         }
606 }