22f5de64d55684652c225b5862adbce3632270ab
[sdc.git] / catalog-be / src / test / java / org / openecomp / sdc / be / externalapi / servlet / ExternalRefServletTest.java
1 /*-
2  * ============LICENSE_START=======================================================
3  * SDC
4  * ================================================================================
5  * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved.
6  * ================================================================================
7  * Licensed under the Apache License, Version 2.0 (the "License");
8  * you may not use this file except in compliance with the License.
9  * You may obtain a copy of the License at
10  *
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  * Modifications copyright (c) 2019 Nokia
20  * ================================================================================
21  */
22
23 package org.openecomp.sdc.be.externalapi.servlet;
24
25 import static org.assertj.core.api.Assertions.assertThat;
26 import static org.mockito.ArgumentMatchers.any;
27 import static org.mockito.ArgumentMatchers.eq;
28 import static org.mockito.Mockito.doThrow;
29 import static org.mockito.Mockito.when;
30
31 import fj.data.Either;
32 import java.util.HashMap;
33 import java.util.LinkedList;
34 import java.util.List;
35 import java.util.Map;
36 import javax.servlet.ServletContext;
37 import javax.servlet.http.HttpServletRequest;
38 import javax.ws.rs.client.Entity;
39 import javax.ws.rs.core.Application;
40 import javax.ws.rs.core.GenericType;
41 import javax.ws.rs.core.MediaType;
42 import javax.ws.rs.core.Response;
43 import org.glassfish.jersey.server.ResourceConfig;
44 import org.glassfish.jersey.test.JerseyTest;
45 import org.junit.jupiter.api.AfterEach;
46 import org.junit.jupiter.api.BeforeAll;
47 import org.junit.jupiter.api.BeforeEach;
48 import org.junit.jupiter.api.Disabled;
49 import org.junit.jupiter.api.Test;
50 import org.junit.jupiter.api.TestInstance;
51 import org.junit.jupiter.api.TestInstance.Lifecycle;
52 import org.junit.jupiter.api.extension.ExtendWith;
53 import org.mockito.Mock;
54 import org.mockito.MockitoAnnotations;
55 import org.mockito.junit.jupiter.MockitoExtension;
56 import org.openecomp.sdc.be.components.impl.ComponentLocker;
57 import org.openecomp.sdc.be.components.impl.ExternalRefsBusinessLogic;
58 import org.openecomp.sdc.be.components.impl.exceptions.ByResponseFormatComponentException;
59 import org.openecomp.sdc.be.components.path.utils.GraphTestUtils;
60 import org.openecomp.sdc.be.components.validation.AccessValidations;
61 import org.openecomp.sdc.be.config.ConfigurationManager;
62 import org.openecomp.sdc.be.dao.DAOJanusGraphStrategy;
63 import org.openecomp.sdc.be.dao.JanusGraphClientStrategy;
64 import org.openecomp.sdc.be.dao.api.ActionStatus;
65 import org.openecomp.sdc.be.dao.impl.HealingPipelineDao;
66 import org.openecomp.sdc.be.dao.janusgraph.HealingJanusGraphGenericDao;
67 import org.openecomp.sdc.be.dao.janusgraph.JanusGraphClient;
68 import org.openecomp.sdc.be.dao.janusgraph.JanusGraphGenericDao;
69 import org.openecomp.sdc.be.dao.janusgraph.JanusGraphOperationStatus;
70 import org.openecomp.sdc.be.dao.jsongraph.GraphVertex;
71 import org.openecomp.sdc.be.dao.jsongraph.HealingJanusGraphDao;
72 import org.openecomp.sdc.be.datatypes.enums.ResourceTypeEnum;
73 import org.openecomp.sdc.be.dto.ExternalRefDTO;
74 import org.openecomp.sdc.be.impl.ComponentsUtils;
75 import org.openecomp.sdc.be.impl.ServletUtils;
76 import org.openecomp.sdc.be.impl.WebAppContextWrapper;
77 import org.openecomp.sdc.be.model.Component;
78 import org.openecomp.sdc.be.model.User;
79 import org.openecomp.sdc.be.model.jsonjanusgraph.config.ContainerInstanceTypesData;
80 import org.openecomp.sdc.be.model.jsonjanusgraph.operations.ArchiveOperation;
81 import org.openecomp.sdc.be.model.jsonjanusgraph.operations.CategoryOperation;
82 import org.openecomp.sdc.be.model.jsonjanusgraph.operations.ExternalReferencesOperation;
83 import org.openecomp.sdc.be.model.jsonjanusgraph.operations.GroupsOperation;
84 import org.openecomp.sdc.be.model.jsonjanusgraph.operations.NodeTemplateOperation;
85 import org.openecomp.sdc.be.model.jsonjanusgraph.operations.NodeTypeOperation;
86 import org.openecomp.sdc.be.model.jsonjanusgraph.operations.TopologyTemplateOperation;
87 import org.openecomp.sdc.be.model.jsonjanusgraph.operations.ToscaOperationFacade;
88 import org.openecomp.sdc.be.model.jsonjanusgraph.utils.IdMapper;
89 import org.openecomp.sdc.be.model.operations.api.IGraphLockOperation;
90 import org.openecomp.sdc.be.model.operations.impl.OperationUtils;
91 import org.openecomp.sdc.be.servlets.exception.ComponentExceptionMapper;
92 import org.openecomp.sdc.be.servlets.exception.DefaultExceptionMapper;
93 import org.openecomp.sdc.be.servlets.exception.StorageExceptionMapper;
94 import org.openecomp.sdc.be.user.Role;
95 import org.openecomp.sdc.be.user.UserBusinessLogic;
96 import org.openecomp.sdc.common.api.ConfigurationSource;
97 import org.openecomp.sdc.common.api.Constants;
98 import org.openecomp.sdc.common.impl.ExternalConfiguration;
99 import org.openecomp.sdc.common.impl.FSConfigurationSource;
100 import org.openecomp.sdc.exception.ResponseFormat;
101 import org.springframework.context.ApplicationContext;
102 import org.springframework.context.annotation.AnnotationConfigApplicationContext;
103 import org.springframework.context.annotation.Bean;
104 import org.springframework.context.annotation.Configuration;
105 import org.springframework.context.annotation.PropertySource;
106 import org.springframework.http.HttpStatus;
107 import org.springframework.web.context.WebApplicationContext;
108
109 @TestInstance(Lifecycle.PER_CLASS)
110 @ExtendWith(MockitoExtension.class)
111 @Disabled("Investigate 'org.springframework.beans.factory.UnsatisfiedDependencyException: "
112     + "Error creating bean with name 'externalRefServletTest.TestSpringConfig': "
113     + "Unsatisfied dependency expressed through constructor parameter 0; nested exception is org.springframework.beans.factory.NoSuchBeanDefinitionException: "
114     + "No qualifying bean of type 'org.openecomp.sdc.be.externalapi.servlet.ExternalRefServletTest' available: expected at least 1 bean which qualifies as autowire candidate."
115     + "Dependency annotations: {}'")
116 class ExternalRefServletTest extends JerseyTest {
117
118     private static final String COMPONENT_ID = "ci-MyComponentName";
119     private static final String FAKE_COMPONENT_ID = "ci-MyFAKEComponentName";
120     private static final String MONITORING_OBJECT_TYPE = "monitoring";
121     private static final String WORKFLOW_OBJECT_TYPE = "workflow";
122     private static final String VERSION = "0.1";
123     private static final String FAKE_VERSION = "0.5";
124     private static final String REF_1 = "ref1";
125     private static final String REF_2 = "ref2";
126     private static final String REF_3 = "ref3";
127     private static final String REF_4 = "ref4";
128     private static final String REF_5 = "ref5";
129     //workflow
130     private static final String REF_6 = "ref6";
131     private static boolean setupDone = false;
132     private static String serviceVertexUuid;
133     private static String resourceVertexUuid;
134     /* Users */
135     private static final User adminUser = new User("admin", "admin", "admin", "admin@email.com", Role.ADMIN.name(),
136         System.currentTimeMillis());
137     private static final User designerUser = new User("designer", "designer", "designer", "designer@email.com",
138         Role.DESIGNER.name(), System
139         .currentTimeMillis());
140     private static final User otherDesignerUser = new User("otherDesigner", "otherDesigner", "otherDesigner",
141         "otherDesigner@email.com", Role.DESIGNER
142         .name(), System.currentTimeMillis());
143     private static final User otherUser = new User("other", "other", "other", "other@email.com", Role.DESIGNER.name(),
144         System.currentTimeMillis());
145
146     @Mock
147     public WebAppContextWrapper webAppContextWrapper;
148     @Mock
149     private ServletContext servletContext;
150     @Mock
151     private WebApplicationContext webApplicationContext;
152     @Mock
153     private ServletUtils servletUtils;
154     @Mock
155     private UserBusinessLogic userAdmin;
156     @Mock
157     private ComponentsUtils componentUtils;
158     @Mock
159     private ResponseFormat responseFormat;
160     @Mock
161     private ResponseFormat notFoundResponseFormat;
162     @Mock
163     private ResponseFormat badRequestResponseFormat;
164     @Mock
165     private ToscaOperationFacade toscaOperationFacadeMock;
166     @Mock
167     private AccessValidations accessValidationsMock;
168     @Mock
169     private ComponentLocker componentLocker;
170     @Mock
171     private HealingJanusGraphGenericDao janusGraphGenericDao;
172     @Mock
173     private IGraphLockOperation graphLockOperation;
174     @Mock
175     private HttpServletRequest request;
176     @Mock
177     private ByResponseFormatComponentException ce;
178     @Mock
179     private Component resourceComponentMock;
180     @Mock
181     private Component serviceComponentMock;
182
183     @BeforeAll
184     public void setup() {
185         MockitoAnnotations.initMocks(this);
186
187         //Needed for User Authorization
188         //========================================================================================================================
189         when(servletContext.getAttribute(Constants.WEB_APPLICATION_CONTEXT_WRAPPER_ATTR))
190             .thenReturn(webAppContextWrapper);
191         when(webAppContextWrapper.getWebAppContext(servletContext)).thenReturn(webApplicationContext);
192         when(webApplicationContext.getBean(ServletUtils.class)).thenReturn(servletUtils);
193         when(servletUtils.getUserAdmin()).thenReturn(userAdmin);
194         when(servletUtils.getComponentsUtils()).thenReturn(componentUtils);
195         when(componentUtils.getResponseFormat(ActionStatus.RESTRICTED_OPERATION)).thenReturn(responseFormat);
196         when(responseFormat.getStatus()).thenReturn(HttpStatus.UNAUTHORIZED.value());
197
198         String[] params = {otherDesignerUser.getUserId()};
199         when(ce.getResponseFormat()).thenReturn(responseFormat);
200         doThrow(ce).when(accessValidationsMock)
201             .validateUserCanWorkOnComponent(any(), any(), eq(otherDesignerUser.getUserId()), any());
202         doThrow(ce).when(accessValidationsMock)
203             .validateUserCanWorkOnComponent(any(), any(), eq(otherUser.getUserId()), any());
204
205         //Needed for error configuration
206         when(notFoundResponseFormat.getStatus()).thenReturn(HttpStatus.NOT_FOUND.value());
207         when(badRequestResponseFormat.getStatus()).thenReturn(HttpStatus.BAD_REQUEST.value());
208         when(componentUtils.getResponseFormat(eq(ActionStatus.RESOURCE_NOT_FOUND), (String[]) any()))
209             .thenReturn(notFoundResponseFormat);
210         when(componentUtils.getResponseFormat(eq(ActionStatus.COMPONENT_VERSION_NOT_FOUND), (String[]) any()))
211             .thenReturn(notFoundResponseFormat);
212         when(componentUtils.getResponseFormat(eq(ActionStatus.COMPONENT_INSTANCE_NOT_FOUND), (String[]) any()))
213             .thenReturn(notFoundResponseFormat);
214         when(componentUtils.getResponseFormat(eq(ActionStatus.EXT_REF_NOT_FOUND), (String[]) any()))
215             .thenReturn(notFoundResponseFormat);
216         when(componentUtils.getResponseFormat(eq(ActionStatus.MISSING_X_ECOMP_INSTANCE_ID), (String[]) any()))
217             .thenReturn(badRequestResponseFormat);
218         when(userAdmin.getUser(adminUser.getUserId(), false)).thenReturn(adminUser);
219         when(userAdmin.getUser(designerUser.getUserId(), false)).thenReturn(designerUser);
220         when(userAdmin.getUser(otherUser.getUserId(), false)).thenReturn(otherUser);
221         //========================================================================================================================
222
223         String appConfigDir = "src/test/resources/config/catalog-be";
224         ConfigurationSource configurationSource = new FSConfigurationSource(ExternalConfiguration.getChangeListener(),
225             appConfigDir);
226         ConfigurationManager configurationManager = new ConfigurationManager(configurationSource);
227
228         org.openecomp.sdc.be.config.Configuration configuration = new org.openecomp.sdc.be.config.Configuration();
229         configuration.setJanusGraphInMemoryGraph(true);
230         org.openecomp.sdc.be.config.Configuration.HeatDeploymentArtifactTimeout heatDeploymentArtifactTimeout = new org.openecomp.sdc.be.config.Configuration.HeatDeploymentArtifactTimeout();
231         heatDeploymentArtifactTimeout.setDefaultMinutes(30);
232         configuration.setAafAuthNeeded(false);
233         configuration.setHeatArtifactDeploymentTimeout(heatDeploymentArtifactTimeout);
234         configurationManager.setConfiguration(configuration);
235         ExternalConfiguration.setAppName("catalog-be");
236     }
237
238     @BeforeEach
239     public void before() throws Exception {
240         super.setUp();
241
242         when(resourceComponentMock.getVersion()).thenReturn(VERSION);
243         when(resourceComponentMock.getUniqueId()).thenReturn(resourceVertexUuid);
244
245         when(serviceComponentMock.getVersion()).thenReturn(VERSION);
246         when(serviceComponentMock.getUniqueId()).thenReturn(serviceVertexUuid);
247
248         List<Component> listComponents = new LinkedList<>();
249         listComponents.add(serviceComponentMock);
250
251         when(toscaOperationFacadeMock.getComponentListByUuid(eq(serviceVertexUuid), any()))
252             .thenReturn(Either.left(listComponents));
253         when(toscaOperationFacadeMock.getComponentByUuidAndVersion(serviceVertexUuid, VERSION))
254             .thenReturn(Either.left(serviceComponentMock));
255         when(toscaOperationFacadeMock.getComponentByUuidAndVersion(resourceVertexUuid, VERSION))
256             .thenReturn(Either.left(resourceComponentMock));
257         when(toscaOperationFacadeMock.getLatestComponentByUuid(eq(serviceVertexUuid), any()))
258             .thenReturn(Either.left(listComponents.get(0)));
259         when(toscaOperationFacadeMock.getLatestComponentByUuid(eq(resourceVertexUuid), any()))
260             .thenReturn(Either.left(resourceComponentMock));
261     }
262
263     @AfterEach
264     void after() throws Exception {
265         super.tearDown();
266     }
267
268     @Test
269     void testGetExternalRefsForExistingComponentInstance() {
270         String path = String
271             .format("/v1/catalog/services/%s/version/%s/resourceInstances/%s/externalReferences/%s", serviceVertexUuid,
272                 VERSION, COMPONENT_ID, MONITORING_OBJECT_TYPE);
273
274         Response response = target()
275             .path(path)
276             .request()
277             .accept(MediaType.APPLICATION_JSON)
278             .header(Constants.X_ECOMP_INSTANCE_ID_HEADER, "mockXEcompInstanceId")
279             .header(Constants.USER_ID_HEADER, designerUser.getUserId())
280             .get();
281
282         List<String> dto = response.readEntity(new GenericType<List<String>>() {
283         });
284         assertThat(dto).containsExactly(REF_1, REF_2, REF_3, REF_5);
285         assertThat(response.getStatus()).isEqualTo(HttpStatus.OK.value());
286     }
287
288     @Test
289     void testGetExternalRefsForAsset() {
290         String path = String
291             .format("/v1/catalog/services/%s/version/%s/externalReferences/%s", serviceVertexUuid, VERSION,
292                 MONITORING_OBJECT_TYPE);
293
294         Response response = target()
295             .path(path)
296             .request()
297             .accept(MediaType.APPLICATION_JSON)
298             .header(Constants.X_ECOMP_INSTANCE_ID_HEADER, "mockXEcompInstanceId")
299             .header(Constants.USER_ID_HEADER, designerUser.getUserId())
300             .get();
301
302         Map<String, List<String>> dtoMap = response.readEntity(new GenericType<HashMap<String, List<String>>>() {
303         });
304         assertThat(dtoMap.get(COMPONENT_ID)).containsExactly(REF_1, REF_2, REF_3, REF_5);
305         assertThat(response.getStatus()).isEqualTo(HttpStatus.OK.value());
306     }
307
308     @Test
309     void testGetExternalRefsForAssetWithMissingEcompHeader() {
310         String path = String
311             .format("/v1/catalog/services/%s/version/%s/externalReferences/%s", serviceVertexUuid, VERSION,
312                 MONITORING_OBJECT_TYPE);
313
314         //No X-Ecomp-Instance-ID header
315         Response response = target()
316             .path(path)
317             .request()
318             .accept(MediaType.APPLICATION_JSON)
319             .header(Constants.USER_ID_HEADER, designerUser.getUserId())
320             .get();
321
322         assertThat(response.getStatus()).isEqualTo(HttpStatus.BAD_REQUEST.value());
323     }
324
325     @Test
326     void testAddExternalRefForResource() {
327         String path = String
328             .format("/v1/catalog/resources/%s/resourceInstances/%s/externalReferences/%s", resourceVertexUuid,
329                 COMPONENT_ID, MONITORING_OBJECT_TYPE);
330         String getPath = String
331             .format("/v1/catalog/resources/%s/version/%s/externalReferences/%s", resourceVertexUuid, VERSION,
332                 MONITORING_OBJECT_TYPE);
333
334         Response response = target()
335             .path(path)
336             .request(MediaType.APPLICATION_JSON)
337             .accept(MediaType.APPLICATION_JSON)
338             .header(Constants.X_ECOMP_INSTANCE_ID_HEADER, "mockXEcompInstanceId")
339             .header(Constants.USER_ID_HEADER, designerUser.getUserId())
340             .post(Entity.json(new ExternalRefDTO(REF_1)));
341
342         assertThat(response.getStatus()).isEqualTo(HttpStatus.CREATED.value());
343
344         //Check that GET will include the new reference
345         response = target()
346             .path(getPath)
347             .request()
348             .accept(MediaType.APPLICATION_JSON)
349             .header(Constants.X_ECOMP_INSTANCE_ID_HEADER, "mockXEcompInstanceId")
350             .header(Constants.USER_ID_HEADER, adminUser.getUserId())
351             .get();
352
353         Map<String, List<String>> dto = response.readEntity(new GenericType<Map<String, List<String>>>() {
354         });
355         assertThat(dto.get(COMPONENT_ID)).containsExactlyInAnyOrder(REF_1);
356         assertThat(response.getStatus()).isEqualTo(HttpStatus.OK.value());
357     }
358
359     @Test
360     void testAddExternalRefForExistingComponentInstance() {
361         String path = String
362             .format("/v1/catalog/services/%s/resourceInstances/%s/externalReferences/%s", serviceVertexUuid,
363                 COMPONENT_ID, MONITORING_OBJECT_TYPE);
364         String getPath = String
365             .format("/v1/catalog/services/%s/version/%s/resourceInstances/%s/externalReferences/%s", serviceVertexUuid,
366                 VERSION, COMPONENT_ID, MONITORING_OBJECT_TYPE);
367         Response response = target()
368             .path(path)
369             .request(MediaType.APPLICATION_JSON)
370             .accept(MediaType.APPLICATION_JSON)
371             .header(Constants.X_ECOMP_INSTANCE_ID_HEADER, "mockXEcompInstanceId")
372             .header(Constants.USER_ID_HEADER, designerUser.getUserId())
373             .post(Entity.json(new ExternalRefDTO(REF_4)));
374
375         assertThat(response.getStatus()).isEqualTo(HttpStatus.CREATED.value());
376
377         //Check that GET will include the new reference
378         response = target()
379             .path(getPath)
380             .request()
381             .accept(MediaType.APPLICATION_JSON)
382             .header(Constants.X_ECOMP_INSTANCE_ID_HEADER, "mockXEcompInstanceId")
383             .header(Constants.USER_ID_HEADER, adminUser.getUserId())
384             .get();
385
386         List<String> dto = response.readEntity(new GenericType<List<String>>() {
387         });
388         assertThat(dto).containsExactlyInAnyOrder(REF_1, REF_2, REF_3, REF_4, REF_5);
389         assertThat(response.getStatus()).isEqualTo(HttpStatus.OK.value());
390     }
391
392     @Test
393     void testDeleteExternalRefForExistingComponentInstance() {
394         String deletePath = String
395             .format("/v1/catalog/services/%s/resourceInstances/%s/externalReferences/%s/%s", serviceVertexUuid,
396                 COMPONENT_ID, MONITORING_OBJECT_TYPE, REF_5);
397         String getPath = String
398             .format("/v1/catalog/services/%s/version/%s/resourceInstances/%s/externalReferences/%s", serviceVertexUuid,
399                 VERSION, COMPONENT_ID, MONITORING_OBJECT_TYPE);
400         Response response = target()
401             .path(deletePath)
402             .request(MediaType.APPLICATION_JSON)
403             .accept(MediaType.APPLICATION_JSON)
404             .header(Constants.X_ECOMP_INSTANCE_ID_HEADER, "mockXEcompInstanceId")
405             .header(Constants.USER_ID_HEADER, designerUser.getUserId())
406             .delete();
407
408         //Verify that the deleted reference is returned in body
409         ExternalRefDTO dto = response.readEntity(ExternalRefDTO.class);
410         assertThat(dto.getReferenceUUID()).isEqualTo(REF_5);
411         assertThat(response.getStatus()).isEqualTo(HttpStatus.OK.value());
412
413         //Check that GET will NOT include the deleted reference
414         response = target()
415             .path(getPath)
416             .request()
417             .accept(MediaType.APPLICATION_JSON)
418             .header(Constants.X_ECOMP_INSTANCE_ID_HEADER, "mockXEcompInstanceId")
419             .header(Constants.USER_ID_HEADER, designerUser.getUserId())
420             .get();
421
422         List<String> getResponse = response.readEntity(new GenericType<List<String>>() {
423         });
424         assertThat(getResponse).containsExactlyInAnyOrder(REF_1, REF_2, REF_3);
425         assertThat(response.getStatus()).isEqualTo(HttpStatus.OK.value());
426     }
427
428     @Test
429     void testUpdateExternalRefForExistingComponentInstance() {
430         String updatePath = String
431             .format("/v1/catalog/services/%s/resourceInstances/%s/externalReferences/%s/%s", serviceVertexUuid,
432                 COMPONENT_ID, MONITORING_OBJECT_TYPE, REF_5);
433         String getPath = String
434             .format("/v1/catalog/services/%s/version/%s/resourceInstances/%s/externalReferences/%s", serviceVertexUuid,
435                 VERSION, COMPONENT_ID, MONITORING_OBJECT_TYPE);
436         Response response = target()
437             .path(updatePath)
438             .request(MediaType.APPLICATION_JSON)
439             .accept(MediaType.APPLICATION_JSON)
440             .header(Constants.X_ECOMP_INSTANCE_ID_HEADER, "mockXEcompInstanceId")
441             .header(Constants.USER_ID_HEADER, designerUser.getUserId())
442             .put(Entity.json(new ExternalRefDTO(REF_4)));
443
444         //Verify that the updated reference is returned in body
445         ExternalRefDTO putResponseBody = response.readEntity(ExternalRefDTO.class);
446         assertThat(putResponseBody.getReferenceUUID()).isEqualTo(REF_4);
447         assertThat(response.getStatus()).isEqualTo(HttpStatus.OK.value());
448
449         //Check that GET will include the updated reference
450         response = target()
451             .path(getPath)
452             .request()
453             .accept(MediaType.APPLICATION_JSON)
454             .header(Constants.X_ECOMP_INSTANCE_ID_HEADER, "mockXEcompInstanceId")
455             .header(Constants.USER_ID_HEADER, designerUser.getUserId())
456             .get();
457
458         List<String> dto = response.readEntity(new GenericType<List<String>>() {
459         });
460         assertThat(dto).containsExactlyInAnyOrder(REF_1, REF_2, REF_3, REF_4);
461         assertThat(response.getStatus()).isEqualTo(HttpStatus.OK.value());
462     }
463
464     /*
465      * Rainy Scenarios
466      */
467     @Test
468     void testAddExternalRefForNonExistingAssetId() {
469         String path = String
470             .format("/v1/catalog/services/%s/resourceInstances/%s/externalReferences/%s", "non-existing-uuid",
471                 COMPONENT_ID, MONITORING_OBJECT_TYPE);
472         Response response = target()
473             .path(path)
474             .request(MediaType.APPLICATION_JSON)
475             .accept(MediaType.APPLICATION_JSON)
476             .header(Constants.X_ECOMP_INSTANCE_ID_HEADER, "mockXEcompInstanceId")
477             .header(Constants.USER_ID_HEADER, designerUser.getUserId())
478             .post(Entity.json(new ExternalRefDTO(REF_4)));
479
480         assertThat(response.getStatus()).isEqualTo(HttpStatus.NOT_FOUND.value());
481     }
482
483     @Test
484     void testAddExternalRefForNonExistingCompInstId() {
485         String path = String
486             .format("/v1/catalog/services/%s/resourceInstances/%s/externalReferences/%s", serviceVertexUuid,
487                 "FAKE_COM_ID", MONITORING_OBJECT_TYPE);
488         Response response = target()
489             .path(path)
490             .request(MediaType.APPLICATION_JSON)
491             .accept(MediaType.APPLICATION_JSON)
492             .header(Constants.X_ECOMP_INSTANCE_ID_HEADER, "mockXEcompInstanceId")
493             .header(Constants.USER_ID_HEADER, designerUser.getUserId())
494             .post(Entity.json(new ExternalRefDTO(REF_4)));
495
496         assertThat(response.getStatus()).isEqualTo(HttpStatus.NOT_FOUND.value());
497     }
498
499     @Test
500     void testAddExistingExternalRef() {
501         String path = String
502             .format("/v1/catalog/services/%s/resourceInstances/%s/externalReferences/%s", serviceVertexUuid,
503                 COMPONENT_ID, MONITORING_OBJECT_TYPE);
504         Response response = target()
505             .path(path)
506             .request(MediaType.APPLICATION_JSON)
507             .accept(MediaType.APPLICATION_JSON)
508             .header(Constants.X_ECOMP_INSTANCE_ID_HEADER, "mockXEcompInstanceId")
509             .header(Constants.USER_ID_HEADER, designerUser.getUserId())
510             .post(Entity.json(new ExternalRefDTO(REF_1)));
511
512         assertThat(response.getStatus()).isEqualTo(HttpStatus.OK.value()); //Ref not created but still OK is returned
513     }
514
515     @Test
516     void testUpdateExternalRefForNonExistingAssetId() {
517         String updatePath = String.format("/v1/catalog/services/%s/resourceInstances/%s/externalReferences/%s/%s",
518             "nonExistingServiceVertexUuid", COMPONENT_ID, MONITORING_OBJECT_TYPE, REF_5);
519
520         Response response = target()
521             .path(updatePath)
522             .request(MediaType.APPLICATION_JSON)
523             .accept(MediaType.APPLICATION_JSON)
524             .header(Constants.X_ECOMP_INSTANCE_ID_HEADER, "mockXEcompInstanceId")
525             .header(Constants.USER_ID_HEADER, designerUser.getUserId())
526             .put(Entity.json(new ExternalRefDTO(REF_4)));
527
528         //Verify that the 404 is returned
529         assertThat(response.getStatus()).isEqualTo(HttpStatus.NOT_FOUND.value());
530
531     }
532
533     @Test
534     void testUpdateExternalRefForNonExistingObjectIdOrOldRef() {
535         String updatePath = String
536             .format("/v1/catalog/services/%s/resourceInstances/%s/externalReferences/%s/%s", serviceVertexUuid,
537                 COMPONENT_ID, "FAKE_OBJ_TYPE", REF_5);
538
539         Response response = target()
540             .path(updatePath)
541             .request(MediaType.APPLICATION_JSON)
542             .accept(MediaType.APPLICATION_JSON)
543             .header(Constants.X_ECOMP_INSTANCE_ID_HEADER, "mockXEcompInstanceId")
544             .header(Constants.USER_ID_HEADER, designerUser.getUserId())
545             .put(Entity.json(new ExternalRefDTO(REF_4)));
546
547         assertThat(response.getStatus()).isEqualTo(HttpStatus.NOT_FOUND.value());
548     }
549
550     @Test
551     void testDeleteExternalRefForNonExistingAssetId() {
552         String deletePath = String
553             .format("/v1/catalog/services/%s/resourceInstances/%s/externalReferences/%s/%s", "non-existing-asset",
554                 COMPONENT_ID, MONITORING_OBJECT_TYPE, REF_5);
555         Response response = target()
556             .path(deletePath)
557             .request(MediaType.APPLICATION_JSON)
558             .accept(MediaType.APPLICATION_JSON)
559             .header(Constants.X_ECOMP_INSTANCE_ID_HEADER, "mockXEcompInstanceId")
560             .header(Constants.USER_ID_HEADER, designerUser.getUserId())
561             .delete();
562
563         assertThat(response.getStatus()).isEqualTo(HttpStatus.NOT_FOUND.value());
564     }
565
566     @Test
567     void testDeleteExternalRefForNonExistingRef() {
568         String deletePath = String
569             .format("/v1/catalog/services/%s/resourceInstances/%s/externalReferences/%s/%s", serviceVertexUuid,
570                 COMPONENT_ID, MONITORING_OBJECT_TYPE, "FAKE_REF");
571         Response response = target()
572             .path(deletePath)
573             .request(MediaType.APPLICATION_JSON)
574             .accept(MediaType.APPLICATION_JSON)
575             .header(Constants.X_ECOMP_INSTANCE_ID_HEADER, "mockXEcompInstanceId")
576             .delete();
577
578         assertThat(response.getStatus()).isEqualTo(HttpStatus.NOT_FOUND.value());
579     }
580
581     @Test
582     void testGetExternalRefsForNonExistingAsset() {
583         String path = String
584             .format("/v1/catalog/services/%s/version/%s/resourceInstances/%s/externalReferences/%s", "fake-asset-id",
585                 VERSION, COMPONENT_ID, MONITORING_OBJECT_TYPE);
586
587         Response response = target()
588             .path(path)
589             .request()
590             .accept(MediaType.APPLICATION_JSON)
591             .header(Constants.X_ECOMP_INSTANCE_ID_HEADER, "mockXEcompInstanceId")
592             .header(Constants.USER_ID_HEADER, designerUser.getUserId())
593             .get();
594
595         assertThat(response.getStatus()).isEqualTo(HttpStatus.NOT_FOUND.value());
596     }
597
598     @Test
599     void testGetExternalRefsForNonExistingVersion() {
600         String path = String
601             .format("/v1/catalog/services/%s/version/%s/resourceInstances/%s/externalReferences/%s", serviceVertexUuid,
602                 FAKE_VERSION, COMPONENT_ID, MONITORING_OBJECT_TYPE);
603
604         Response response = target()
605             .path(path)
606             .request()
607             .accept(MediaType.APPLICATION_JSON)
608             .header(Constants.X_ECOMP_INSTANCE_ID_HEADER, "mockXEcompInstanceId")
609             .header(Constants.USER_ID_HEADER, designerUser.getUserId())
610             .get();
611
612         assertThat(response.getStatus()).isEqualTo(HttpStatus.NOT_FOUND.value());
613     }
614
615     @Test
616     void testDeleteExternalRefsForExistingComponentInstanceWithUnauthorizedUser() {
617         String path = String
618             .format("/v1/catalog/services/%s/resourceInstances/%s/externalReferences/%s/%s", serviceVertexUuid,
619                 COMPONENT_ID, MONITORING_OBJECT_TYPE, REF_5);
620
621         Response response = target()
622             .path(path)
623             .request()
624             .accept(MediaType.APPLICATION_JSON)
625             .header(Constants.X_ECOMP_INSTANCE_ID_HEADER, "mockXEcompInstanceId")
626             .header(Constants.USER_ID_HEADER, otherUser.getUserId())
627             .delete();
628
629         assertThat(response.getStatus()).isEqualTo(HttpStatus.UNAUTHORIZED.value());
630     }
631
632     @Test
633     void testDeleteExternalRefForUserWhichIsNotCurrentUpdater() {
634         String deletePath = String
635             .format("/v1/catalog/services/%s/resourceInstances/%s/externalReferences/%s/%s", serviceVertexUuid,
636                 COMPONENT_ID, MONITORING_OBJECT_TYPE, REF_5);
637         Response response = target()
638             .path(deletePath)
639             .request(MediaType.APPLICATION_JSON)
640             .accept(MediaType.APPLICATION_JSON)
641             .header(Constants.X_ECOMP_INSTANCE_ID_HEADER, "mockXEcompInstanceId")
642             .header(Constants.USER_ID_HEADER, otherDesignerUser.getUserId())
643             .delete();
644
645         assertThat(response.getStatus()).isEqualTo(HttpStatus.UNAUTHORIZED.value());
646     }
647
648     @Override
649     protected Application configure() {
650         ApplicationContext context = new AnnotationConfigApplicationContext(TestSpringConfig.class);
651         return new ResourceConfig(ExternalRefsServlet.class)
652             .register(DefaultExceptionMapper.class)
653             .register(ComponentExceptionMapper.class)
654             .register(StorageExceptionMapper.class)
655             .property("contextConfig", context);
656     }
657
658     @Configuration
659     @PropertySource("classpath:dao.properties")
660     public class TestSpringConfig {
661
662         private GraphVertex serviceVertex;
663         private GraphVertex resourceVertex;
664         private ExternalReferencesOperation externalReferenceOperation;
665         private HealingJanusGraphDao janusGraphDao;
666         @Mock
667         private IdMapper idMapper;
668
669         @Bean
670         ExternalRefsServlet externalRefsServlet() {
671             return new ExternalRefsServlet(userAdmin, componentUtils, externalRefsBusinessLogic());
672         }
673
674         @Bean
675         OperationUtils operationUtils() {
676             return new OperationUtils(janusGraphDao());
677         }
678
679         @Bean
680         ComponentExceptionMapper componentExceptionMapper() {
681             return new ComponentExceptionMapper(componentUtils);
682         }
683
684         @Bean
685         StorageExceptionMapper storageExceptionMapper() {
686             return new StorageExceptionMapper(componentUtils);
687         }
688
689         @Bean
690         DefaultExceptionMapper defaultExceptionMapper() {
691             return new DefaultExceptionMapper();
692         }
693
694         @Bean
695         ExternalRefsBusinessLogic externalRefsBusinessLogic() {
696             return new ExternalRefsBusinessLogic(externalReferencesOperation(), toscaOperationFacade(),
697                 accessValidations(), componentLocker());
698         }
699
700         @Bean
701         AccessValidations accessValidations() {
702             return accessValidationsMock;
703         }
704
705         @Bean
706         ExternalReferencesOperation externalReferencesOperation() {
707             this.externalReferenceOperation = new ExternalReferencesOperation(janusGraphDao(), nodeTypeOpertaion(),
708                 topologyTemplateOperation(), idMapper());
709             this.externalReferenceOperation.setHealingPipelineDao(healingPipelineDao());
710             GraphTestUtils.clearGraph(janusGraphDao);
711             initGraphForTest();
712             return this.externalReferenceOperation;
713         }
714
715         @Bean
716         ToscaOperationFacade toscaOperationFacade() {
717             return toscaOperationFacadeMock;
718         }
719
720         @Bean
721         IdMapper idMapper() {
722             when(idMapper.mapComponentNameToUniqueId(eq(COMPONENT_ID), any(GraphVertex.class)))
723                 .thenReturn(COMPONENT_ID);
724             when(idMapper.mapUniqueIdToComponentNameTo(eq(COMPONENT_ID), any(GraphVertex.class)))
725                 .thenReturn(COMPONENT_ID);
726             when(idMapper.mapComponentNameToUniqueId(eq(FAKE_COMPONENT_ID), any(GraphVertex.class))).thenReturn(null);
727             return idMapper;
728         }
729
730         @Bean
731         TopologyTemplateOperation topologyTemplateOperation() {
732             return new TopologyTemplateOperation();
733         }
734
735         @Bean
736         ArchiveOperation archiveOperation() {
737             return new ArchiveOperation(janusGraphDao(), graphLockOperation());
738         }
739
740         @Bean
741         IGraphLockOperation graphLockOperation() {
742             return graphLockOperation;
743         }
744
745         @Bean
746         NodeTypeOperation nodeTypeOpertaion() {
747             return new NodeTypeOperation(null);
748         }
749
750         @Bean
751         NodeTemplateOperation nodeTemplateOperation() {
752             return new NodeTemplateOperation();
753         }
754
755         @Bean
756         GroupsOperation groupsOperation() {
757             return new GroupsOperation();
758         }
759
760         @Bean
761         HealingJanusGraphDao janusGraphDao() {
762             this.janusGraphDao = new HealingJanusGraphDao(healingPipelineDao(), janusGraphClient());
763             return janusGraphDao;
764         }
765
766         @Bean
767         JanusGraphClient janusGraphClient() {
768             return new JanusGraphClient(janusGraphClientStrategy());
769         }
770
771         @Bean
772         JanusGraphClientStrategy janusGraphClientStrategy() {
773             return new DAOJanusGraphStrategy();
774         }
775
776         @Bean
777         CategoryOperation categoryOperation() {
778             return new CategoryOperation();
779         }
780
781         @Bean
782         ComponentLocker componentLocker() {
783             return componentLocker;
784         }
785
786         @Bean
787         JanusGraphGenericDao janusGraphGenericDao() {
788             return janusGraphGenericDao;
789         }
790
791         @Bean("healingPipelineDao")
792         HealingPipelineDao healingPipelineDao() {
793             HealingPipelineDao healingPipelineDao = new HealingPipelineDao();
794             healingPipelineDao.setHealVersion(1);
795             healingPipelineDao.initHealVersion();
796             return healingPipelineDao;
797         }
798
799         @Bean
800         ContainerInstanceTypesData containerInstanceTypesData() {
801             return new ContainerInstanceTypesData();
802         }
803
804         private void initGraphForTest() {
805             if (!setupDone) {
806
807                 resourceVertex = GraphTestUtils
808                     .createResourceVertex(janusGraphDao, new HashMap<>(), ResourceTypeEnum.VF);
809                 resourceVertexUuid = resourceVertex.getUniqueId();
810
811                 //create a service and add ref
812                 serviceVertex = GraphTestUtils.createServiceVertex(janusGraphDao, new HashMap<>());
813                 serviceVertexUuid = this.serviceVertex.getUniqueId();
814
815                 //monitoring references
816                 externalReferenceOperation
817                     .addExternalReference(serviceVertexUuid, COMPONENT_ID, MONITORING_OBJECT_TYPE, REF_1);
818                 externalReferenceOperation
819                     .addExternalReference(serviceVertexUuid, COMPONENT_ID, MONITORING_OBJECT_TYPE, REF_2);
820                 externalReferenceOperation
821                     .addExternalReference(serviceVertexUuid, COMPONENT_ID, MONITORING_OBJECT_TYPE, REF_3);
822                 externalReferenceOperation
823                     .addExternalReference(serviceVertexUuid, COMPONENT_ID, MONITORING_OBJECT_TYPE, REF_5);
824
825                 //workflow references
826                 externalReferenceOperation
827                     .addExternalReference(serviceVertexUuid, COMPONENT_ID, WORKFLOW_OBJECT_TYPE, REF_6);
828
829                 final JanusGraphOperationStatus commit = this.janusGraphDao.commit();
830                 assertThat(commit).isEqualTo(JanusGraphOperationStatus.OK);
831             }
832         }
833
834
835     }
836 }