Fix bugs introduced by new code
[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     private IdMapper idMapper;
148     @Mock
149     public WebAppContextWrapper webAppContextWrapper;
150     @Mock
151     private ServletContext servletContext;
152     @Mock
153     private WebApplicationContext webApplicationContext;
154     @Mock
155     private ServletUtils servletUtils;
156     @Mock
157     private UserBusinessLogic userAdmin;
158     @Mock
159     private ComponentsUtils componentUtils;
160     @Mock
161     private ResponseFormat responseFormat;
162     @Mock
163     private ResponseFormat notFoundResponseFormat;
164     @Mock
165     private ResponseFormat badRequestResponseFormat;
166     @Mock
167     private ToscaOperationFacade toscaOperationFacadeMock;
168     @Mock
169     private AccessValidations accessValidationsMock;
170     @Mock
171     private ComponentLocker componentLocker;
172     @Mock
173     private HealingJanusGraphGenericDao janusGraphGenericDao;
174     @Mock
175     private IGraphLockOperation graphLockOperation;
176     @Mock
177     private HttpServletRequest request;
178     @Mock
179     private ByResponseFormatComponentException ce;
180     @Mock
181     private Component resourceComponentMock;
182     @Mock
183     private Component serviceComponentMock;
184
185     @BeforeAll
186     public void setup() {
187
188         //Needed for User Authorization
189         //========================================================================================================================
190         when(servletContext.getAttribute(Constants.WEB_APPLICATION_CONTEXT_WRAPPER_ATTR))
191             .thenReturn(webAppContextWrapper);
192         when(webAppContextWrapper.getWebAppContext(servletContext)).thenReturn(webApplicationContext);
193         when(webApplicationContext.getBean(ServletUtils.class)).thenReturn(servletUtils);
194         when(servletUtils.getUserAdmin()).thenReturn(userAdmin);
195         when(servletUtils.getComponentsUtils()).thenReturn(componentUtils);
196         when(componentUtils.getResponseFormat(ActionStatus.RESTRICTED_OPERATION)).thenReturn(responseFormat);
197         when(responseFormat.getStatus()).thenReturn(HttpStatus.UNAUTHORIZED.value());
198
199         String[] params = {otherDesignerUser.getUserId()};
200         when(ce.getResponseFormat()).thenReturn(responseFormat);
201         doThrow(ce).when(accessValidationsMock)
202             .validateUserCanWorkOnComponent(any(), any(), eq(otherDesignerUser.getUserId()), any());
203         doThrow(ce).when(accessValidationsMock)
204             .validateUserCanWorkOnComponent(any(), any(), eq(otherUser.getUserId()), any());
205
206         //Needed for error configuration
207         when(notFoundResponseFormat.getStatus()).thenReturn(HttpStatus.NOT_FOUND.value());
208         when(badRequestResponseFormat.getStatus()).thenReturn(HttpStatus.BAD_REQUEST.value());
209         when(componentUtils.getResponseFormat(eq(ActionStatus.RESOURCE_NOT_FOUND), (String[]) any()))
210             .thenReturn(notFoundResponseFormat);
211         when(componentUtils.getResponseFormat(eq(ActionStatus.COMPONENT_VERSION_NOT_FOUND), (String[]) any()))
212             .thenReturn(notFoundResponseFormat);
213         when(componentUtils.getResponseFormat(eq(ActionStatus.COMPONENT_INSTANCE_NOT_FOUND), (String[]) any()))
214             .thenReturn(notFoundResponseFormat);
215         when(componentUtils.getResponseFormat(eq(ActionStatus.EXT_REF_NOT_FOUND), (String[]) any()))
216             .thenReturn(notFoundResponseFormat);
217         when(componentUtils.getResponseFormat(eq(ActionStatus.MISSING_X_ECOMP_INSTANCE_ID), (String[]) any()))
218             .thenReturn(badRequestResponseFormat);
219         when(userAdmin.getUser(adminUser.getUserId(), false)).thenReturn(adminUser);
220         when(userAdmin.getUser(designerUser.getUserId(), false)).thenReturn(designerUser);
221         when(userAdmin.getUser(otherUser.getUserId(), false)).thenReturn(otherUser);
222         //========================================================================================================================
223
224         String appConfigDir = "src/test/resources/config/catalog-be";
225         ConfigurationSource configurationSource = new FSConfigurationSource(ExternalConfiguration.getChangeListener(),
226             appConfigDir);
227         ConfigurationManager configurationManager = new ConfigurationManager(configurationSource);
228
229         org.openecomp.sdc.be.config.Configuration configuration = new org.openecomp.sdc.be.config.Configuration();
230         configuration.setJanusGraphInMemoryGraph(true);
231         org.openecomp.sdc.be.config.Configuration.HeatDeploymentArtifactTimeout heatDeploymentArtifactTimeout = new org.openecomp.sdc.be.config.Configuration.HeatDeploymentArtifactTimeout();
232         heatDeploymentArtifactTimeout.setDefaultMinutes(30);
233         configuration.setAafAuthNeeded(false);
234         configuration.setHeatArtifactDeploymentTimeout(heatDeploymentArtifactTimeout);
235         configurationManager.setConfiguration(configuration);
236         ExternalConfiguration.setAppName("catalog-be");
237     }
238
239     @BeforeEach
240     public void before() throws Exception {
241         super.setUp();
242         MockitoAnnotations.openMocks(this);
243
244         when(resourceComponentMock.getVersion()).thenReturn(VERSION);
245         when(resourceComponentMock.getUniqueId()).thenReturn(resourceVertexUuid);
246
247         when(serviceComponentMock.getVersion()).thenReturn(VERSION);
248         when(serviceComponentMock.getUniqueId()).thenReturn(serviceVertexUuid);
249
250         List<Component> listComponents = new LinkedList<>();
251         listComponents.add(serviceComponentMock);
252
253         when(toscaOperationFacadeMock.getComponentListByUuid(eq(serviceVertexUuid), any()))
254             .thenReturn(Either.left(listComponents));
255         when(toscaOperationFacadeMock.getComponentByUuidAndVersion(serviceVertexUuid, VERSION))
256             .thenReturn(Either.left(serviceComponentMock));
257         when(toscaOperationFacadeMock.getComponentByUuidAndVersion(resourceVertexUuid, VERSION))
258             .thenReturn(Either.left(resourceComponentMock));
259         when(toscaOperationFacadeMock.getLatestComponentByUuid(eq(serviceVertexUuid), any()))
260             .thenReturn(Either.left(listComponents.get(0)));
261         when(toscaOperationFacadeMock.getLatestComponentByUuid(eq(resourceVertexUuid), any()))
262             .thenReturn(Either.left(resourceComponentMock));
263     }
264
265     @AfterEach
266     void after() throws Exception {
267         super.tearDown();
268     }
269
270     @Test
271     void testGetExternalRefsForExistingComponentInstance() {
272         String path = String
273             .format("/v1/catalog/services/%s/version/%s/resourceInstances/%s/externalReferences/%s", serviceVertexUuid,
274                 VERSION, COMPONENT_ID, MONITORING_OBJECT_TYPE);
275
276         Response response = target()
277             .path(path)
278             .request()
279             .accept(MediaType.APPLICATION_JSON)
280             .header(Constants.X_ECOMP_INSTANCE_ID_HEADER, "mockXEcompInstanceId")
281             .header(Constants.USER_ID_HEADER, designerUser.getUserId())
282             .get();
283
284         List<String> dto = response.readEntity(new GenericType<List<String>>() {
285         });
286         assertThat(dto).containsExactly(REF_1, REF_2, REF_3, REF_5);
287         assertThat(response.getStatus()).isEqualTo(HttpStatus.OK.value());
288     }
289
290     @Test
291     void testGetExternalRefsForAsset() {
292         String path = String
293             .format("/v1/catalog/services/%s/version/%s/externalReferences/%s", serviceVertexUuid, VERSION,
294                 MONITORING_OBJECT_TYPE);
295
296         Response response = target()
297             .path(path)
298             .request()
299             .accept(MediaType.APPLICATION_JSON)
300             .header(Constants.X_ECOMP_INSTANCE_ID_HEADER, "mockXEcompInstanceId")
301             .header(Constants.USER_ID_HEADER, designerUser.getUserId())
302             .get();
303
304         Map<String, List<String>> dtoMap = response.readEntity(new GenericType<HashMap<String, List<String>>>() {
305         });
306         assertThat(dtoMap.get(COMPONENT_ID)).containsExactly(REF_1, REF_2, REF_3, REF_5);
307         assertThat(response.getStatus()).isEqualTo(HttpStatus.OK.value());
308     }
309
310     @Test
311     void testGetExternalRefsForAssetWithMissingEcompHeader() {
312         String path = String
313             .format("/v1/catalog/services/%s/version/%s/externalReferences/%s", serviceVertexUuid, VERSION,
314                 MONITORING_OBJECT_TYPE);
315
316         //No X-Ecomp-Instance-ID header
317         Response response = target()
318             .path(path)
319             .request()
320             .accept(MediaType.APPLICATION_JSON)
321             .header(Constants.USER_ID_HEADER, designerUser.getUserId())
322             .get();
323
324         assertThat(response.getStatus()).isEqualTo(HttpStatus.BAD_REQUEST.value());
325     }
326
327     @Test
328     void testAddExternalRefForResource() {
329         String path = String
330             .format("/v1/catalog/resources/%s/resourceInstances/%s/externalReferences/%s", resourceVertexUuid,
331                 COMPONENT_ID, MONITORING_OBJECT_TYPE);
332         String getPath = String
333             .format("/v1/catalog/resources/%s/version/%s/externalReferences/%s", resourceVertexUuid, VERSION,
334                 MONITORING_OBJECT_TYPE);
335
336         Response response = target()
337             .path(path)
338             .request(MediaType.APPLICATION_JSON)
339             .accept(MediaType.APPLICATION_JSON)
340             .header(Constants.X_ECOMP_INSTANCE_ID_HEADER, "mockXEcompInstanceId")
341             .header(Constants.USER_ID_HEADER, designerUser.getUserId())
342             .post(Entity.json(new ExternalRefDTO(REF_1)));
343
344         assertThat(response.getStatus()).isEqualTo(HttpStatus.CREATED.value());
345
346         //Check that GET will include the new reference
347         response = target()
348             .path(getPath)
349             .request()
350             .accept(MediaType.APPLICATION_JSON)
351             .header(Constants.X_ECOMP_INSTANCE_ID_HEADER, "mockXEcompInstanceId")
352             .header(Constants.USER_ID_HEADER, adminUser.getUserId())
353             .get();
354
355         Map<String, List<String>> dto = response.readEntity(new GenericType<Map<String, List<String>>>() {
356         });
357         assertThat(dto.get(COMPONENT_ID)).containsExactlyInAnyOrder(REF_1);
358         assertThat(response.getStatus()).isEqualTo(HttpStatus.OK.value());
359     }
360
361     @Test
362     void testAddExternalRefForExistingComponentInstance() {
363         String path = String
364             .format("/v1/catalog/services/%s/resourceInstances/%s/externalReferences/%s", serviceVertexUuid,
365                 COMPONENT_ID, MONITORING_OBJECT_TYPE);
366         String getPath = String
367             .format("/v1/catalog/services/%s/version/%s/resourceInstances/%s/externalReferences/%s", serviceVertexUuid,
368                 VERSION, COMPONENT_ID, MONITORING_OBJECT_TYPE);
369         Response response = target()
370             .path(path)
371             .request(MediaType.APPLICATION_JSON)
372             .accept(MediaType.APPLICATION_JSON)
373             .header(Constants.X_ECOMP_INSTANCE_ID_HEADER, "mockXEcompInstanceId")
374             .header(Constants.USER_ID_HEADER, designerUser.getUserId())
375             .post(Entity.json(new ExternalRefDTO(REF_4)));
376
377         assertThat(response.getStatus()).isEqualTo(HttpStatus.CREATED.value());
378
379         //Check that GET will include the new reference
380         response = target()
381             .path(getPath)
382             .request()
383             .accept(MediaType.APPLICATION_JSON)
384             .header(Constants.X_ECOMP_INSTANCE_ID_HEADER, "mockXEcompInstanceId")
385             .header(Constants.USER_ID_HEADER, adminUser.getUserId())
386             .get();
387
388         List<String> dto = response.readEntity(new GenericType<List<String>>() {
389         });
390         assertThat(dto).containsExactlyInAnyOrder(REF_1, REF_2, REF_3, REF_4, REF_5);
391         assertThat(response.getStatus()).isEqualTo(HttpStatus.OK.value());
392     }
393
394     @Test
395     void testDeleteExternalRefForExistingComponentInstance() {
396         String deletePath = String
397             .format("/v1/catalog/services/%s/resourceInstances/%s/externalReferences/%s/%s", serviceVertexUuid,
398                 COMPONENT_ID, MONITORING_OBJECT_TYPE, REF_5);
399         String getPath = String
400             .format("/v1/catalog/services/%s/version/%s/resourceInstances/%s/externalReferences/%s", serviceVertexUuid,
401                 VERSION, COMPONENT_ID, MONITORING_OBJECT_TYPE);
402         Response response = target()
403             .path(deletePath)
404             .request(MediaType.APPLICATION_JSON)
405             .accept(MediaType.APPLICATION_JSON)
406             .header(Constants.X_ECOMP_INSTANCE_ID_HEADER, "mockXEcompInstanceId")
407             .header(Constants.USER_ID_HEADER, designerUser.getUserId())
408             .delete();
409
410         //Verify that the deleted reference is returned in body
411         ExternalRefDTO dto = response.readEntity(ExternalRefDTO.class);
412         assertThat(dto.getReferenceUUID()).isEqualTo(REF_5);
413         assertThat(response.getStatus()).isEqualTo(HttpStatus.OK.value());
414
415         //Check that GET will NOT include the deleted reference
416         response = target()
417             .path(getPath)
418             .request()
419             .accept(MediaType.APPLICATION_JSON)
420             .header(Constants.X_ECOMP_INSTANCE_ID_HEADER, "mockXEcompInstanceId")
421             .header(Constants.USER_ID_HEADER, designerUser.getUserId())
422             .get();
423
424         List<String> getResponse = response.readEntity(new GenericType<List<String>>() {
425         });
426         assertThat(getResponse).containsExactlyInAnyOrder(REF_1, REF_2, REF_3);
427         assertThat(response.getStatus()).isEqualTo(HttpStatus.OK.value());
428     }
429
430     @Test
431     void testUpdateExternalRefForExistingComponentInstance() {
432         String updatePath = String
433             .format("/v1/catalog/services/%s/resourceInstances/%s/externalReferences/%s/%s", serviceVertexUuid,
434                 COMPONENT_ID, MONITORING_OBJECT_TYPE, REF_5);
435         String getPath = String
436             .format("/v1/catalog/services/%s/version/%s/resourceInstances/%s/externalReferences/%s", serviceVertexUuid,
437                 VERSION, COMPONENT_ID, MONITORING_OBJECT_TYPE);
438         Response response = target()
439             .path(updatePath)
440             .request(MediaType.APPLICATION_JSON)
441             .accept(MediaType.APPLICATION_JSON)
442             .header(Constants.X_ECOMP_INSTANCE_ID_HEADER, "mockXEcompInstanceId")
443             .header(Constants.USER_ID_HEADER, designerUser.getUserId())
444             .put(Entity.json(new ExternalRefDTO(REF_4)));
445
446         //Verify that the updated reference is returned in body
447         ExternalRefDTO putResponseBody = response.readEntity(ExternalRefDTO.class);
448         assertThat(putResponseBody.getReferenceUUID()).isEqualTo(REF_4);
449         assertThat(response.getStatus()).isEqualTo(HttpStatus.OK.value());
450
451         //Check that GET will include the updated reference
452         response = target()
453             .path(getPath)
454             .request()
455             .accept(MediaType.APPLICATION_JSON)
456             .header(Constants.X_ECOMP_INSTANCE_ID_HEADER, "mockXEcompInstanceId")
457             .header(Constants.USER_ID_HEADER, designerUser.getUserId())
458             .get();
459
460         List<String> dto = response.readEntity(new GenericType<List<String>>() {
461         });
462         assertThat(dto).containsExactlyInAnyOrder(REF_1, REF_2, REF_3, REF_4);
463         assertThat(response.getStatus()).isEqualTo(HttpStatus.OK.value());
464     }
465
466     /*
467      * Rainy Scenarios
468      */
469     @Test
470     void testAddExternalRefForNonExistingAssetId() {
471         String path = String
472             .format("/v1/catalog/services/%s/resourceInstances/%s/externalReferences/%s", "non-existing-uuid",
473                 COMPONENT_ID, MONITORING_OBJECT_TYPE);
474         Response response = target()
475             .path(path)
476             .request(MediaType.APPLICATION_JSON)
477             .accept(MediaType.APPLICATION_JSON)
478             .header(Constants.X_ECOMP_INSTANCE_ID_HEADER, "mockXEcompInstanceId")
479             .header(Constants.USER_ID_HEADER, designerUser.getUserId())
480             .post(Entity.json(new ExternalRefDTO(REF_4)));
481
482         assertThat(response.getStatus()).isEqualTo(HttpStatus.NOT_FOUND.value());
483     }
484
485     @Test
486     void testAddExternalRefForNonExistingCompInstId() {
487         String path = String
488             .format("/v1/catalog/services/%s/resourceInstances/%s/externalReferences/%s", serviceVertexUuid,
489                 "FAKE_COM_ID", MONITORING_OBJECT_TYPE);
490         Response response = target()
491             .path(path)
492             .request(MediaType.APPLICATION_JSON)
493             .accept(MediaType.APPLICATION_JSON)
494             .header(Constants.X_ECOMP_INSTANCE_ID_HEADER, "mockXEcompInstanceId")
495             .header(Constants.USER_ID_HEADER, designerUser.getUserId())
496             .post(Entity.json(new ExternalRefDTO(REF_4)));
497
498         assertThat(response.getStatus()).isEqualTo(HttpStatus.NOT_FOUND.value());
499     }
500
501     @Test
502     void testAddExistingExternalRef() {
503         String path = String
504             .format("/v1/catalog/services/%s/resourceInstances/%s/externalReferences/%s", serviceVertexUuid,
505                 COMPONENT_ID, MONITORING_OBJECT_TYPE);
506         Response response = target()
507             .path(path)
508             .request(MediaType.APPLICATION_JSON)
509             .accept(MediaType.APPLICATION_JSON)
510             .header(Constants.X_ECOMP_INSTANCE_ID_HEADER, "mockXEcompInstanceId")
511             .header(Constants.USER_ID_HEADER, designerUser.getUserId())
512             .post(Entity.json(new ExternalRefDTO(REF_1)));
513
514         assertThat(response.getStatus()).isEqualTo(HttpStatus.OK.value()); //Ref not created but still OK is returned
515     }
516
517     @Test
518     void testUpdateExternalRefForNonExistingAssetId() {
519         String updatePath = String.format("/v1/catalog/services/%s/resourceInstances/%s/externalReferences/%s/%s",
520             "nonExistingServiceVertexUuid", COMPONENT_ID, MONITORING_OBJECT_TYPE, REF_5);
521
522         Response response = target()
523             .path(updatePath)
524             .request(MediaType.APPLICATION_JSON)
525             .accept(MediaType.APPLICATION_JSON)
526             .header(Constants.X_ECOMP_INSTANCE_ID_HEADER, "mockXEcompInstanceId")
527             .header(Constants.USER_ID_HEADER, designerUser.getUserId())
528             .put(Entity.json(new ExternalRefDTO(REF_4)));
529
530         //Verify that the 404 is returned
531         assertThat(response.getStatus()).isEqualTo(HttpStatus.NOT_FOUND.value());
532
533     }
534
535     @Test
536     void testUpdateExternalRefForNonExistingObjectIdOrOldRef() {
537         String updatePath = String
538             .format("/v1/catalog/services/%s/resourceInstances/%s/externalReferences/%s/%s", serviceVertexUuid,
539                 COMPONENT_ID, "FAKE_OBJ_TYPE", REF_5);
540
541         Response response = target()
542             .path(updatePath)
543             .request(MediaType.APPLICATION_JSON)
544             .accept(MediaType.APPLICATION_JSON)
545             .header(Constants.X_ECOMP_INSTANCE_ID_HEADER, "mockXEcompInstanceId")
546             .header(Constants.USER_ID_HEADER, designerUser.getUserId())
547             .put(Entity.json(new ExternalRefDTO(REF_4)));
548
549         assertThat(response.getStatus()).isEqualTo(HttpStatus.NOT_FOUND.value());
550     }
551
552     @Test
553     void testDeleteExternalRefForNonExistingAssetId() {
554         String deletePath = String
555             .format("/v1/catalog/services/%s/resourceInstances/%s/externalReferences/%s/%s", "non-existing-asset",
556                 COMPONENT_ID, MONITORING_OBJECT_TYPE, REF_5);
557         Response response = target()
558             .path(deletePath)
559             .request(MediaType.APPLICATION_JSON)
560             .accept(MediaType.APPLICATION_JSON)
561             .header(Constants.X_ECOMP_INSTANCE_ID_HEADER, "mockXEcompInstanceId")
562             .header(Constants.USER_ID_HEADER, designerUser.getUserId())
563             .delete();
564
565         assertThat(response.getStatus()).isEqualTo(HttpStatus.NOT_FOUND.value());
566     }
567
568     @Test
569     void testDeleteExternalRefForNonExistingRef() {
570         String deletePath = String
571             .format("/v1/catalog/services/%s/resourceInstances/%s/externalReferences/%s/%s", serviceVertexUuid,
572                 COMPONENT_ID, MONITORING_OBJECT_TYPE, "FAKE_REF");
573         Response response = target()
574             .path(deletePath)
575             .request(MediaType.APPLICATION_JSON)
576             .accept(MediaType.APPLICATION_JSON)
577             .header(Constants.X_ECOMP_INSTANCE_ID_HEADER, "mockXEcompInstanceId")
578             .delete();
579
580         assertThat(response.getStatus()).isEqualTo(HttpStatus.NOT_FOUND.value());
581     }
582
583     @Test
584     void testGetExternalRefsForNonExistingAsset() {
585         String path = String
586             .format("/v1/catalog/services/%s/version/%s/resourceInstances/%s/externalReferences/%s", "fake-asset-id",
587                 VERSION, COMPONENT_ID, MONITORING_OBJECT_TYPE);
588
589         Response response = target()
590             .path(path)
591             .request()
592             .accept(MediaType.APPLICATION_JSON)
593             .header(Constants.X_ECOMP_INSTANCE_ID_HEADER, "mockXEcompInstanceId")
594             .header(Constants.USER_ID_HEADER, designerUser.getUserId())
595             .get();
596
597         assertThat(response.getStatus()).isEqualTo(HttpStatus.NOT_FOUND.value());
598     }
599
600     @Test
601     void testGetExternalRefsForNonExistingVersion() {
602         String path = String
603             .format("/v1/catalog/services/%s/version/%s/resourceInstances/%s/externalReferences/%s", serviceVertexUuid,
604                 FAKE_VERSION, COMPONENT_ID, MONITORING_OBJECT_TYPE);
605
606         Response response = target()
607             .path(path)
608             .request()
609             .accept(MediaType.APPLICATION_JSON)
610             .header(Constants.X_ECOMP_INSTANCE_ID_HEADER, "mockXEcompInstanceId")
611             .header(Constants.USER_ID_HEADER, designerUser.getUserId())
612             .get();
613
614         assertThat(response.getStatus()).isEqualTo(HttpStatus.NOT_FOUND.value());
615     }
616
617     @Test
618     void testDeleteExternalRefsForExistingComponentInstanceWithUnauthorizedUser() {
619         String path = String
620             .format("/v1/catalog/services/%s/resourceInstances/%s/externalReferences/%s/%s", serviceVertexUuid,
621                 COMPONENT_ID, MONITORING_OBJECT_TYPE, REF_5);
622
623         Response response = target()
624             .path(path)
625             .request()
626             .accept(MediaType.APPLICATION_JSON)
627             .header(Constants.X_ECOMP_INSTANCE_ID_HEADER, "mockXEcompInstanceId")
628             .header(Constants.USER_ID_HEADER, otherUser.getUserId())
629             .delete();
630
631         assertThat(response.getStatus()).isEqualTo(HttpStatus.UNAUTHORIZED.value());
632     }
633
634     @Test
635     void testDeleteExternalRefForUserWhichIsNotCurrentUpdater() {
636         String deletePath = String
637             .format("/v1/catalog/services/%s/resourceInstances/%s/externalReferences/%s/%s", serviceVertexUuid,
638                 COMPONENT_ID, MONITORING_OBJECT_TYPE, REF_5);
639         Response response = target()
640             .path(deletePath)
641             .request(MediaType.APPLICATION_JSON)
642             .accept(MediaType.APPLICATION_JSON)
643             .header(Constants.X_ECOMP_INSTANCE_ID_HEADER, "mockXEcompInstanceId")
644             .header(Constants.USER_ID_HEADER, otherDesignerUser.getUserId())
645             .delete();
646
647         assertThat(response.getStatus()).isEqualTo(HttpStatus.UNAUTHORIZED.value());
648     }
649
650     @Override
651     protected Application configure() {
652         ApplicationContext context = new AnnotationConfigApplicationContext(TestSpringConfig.class);
653         return new ResourceConfig(ExternalRefsServlet.class)
654             .register(DefaultExceptionMapper.class)
655             .register(ComponentExceptionMapper.class)
656             .register(StorageExceptionMapper.class)
657             .property("contextConfig", context);
658     }
659
660     @Configuration
661     @PropertySource("classpath:dao.properties")
662     public class TestSpringConfig {
663
664         private GraphVertex serviceVertex;
665         private GraphVertex resourceVertex;
666         private ExternalReferencesOperation externalReferenceOperation;
667         private HealingJanusGraphDao janusGraphDao;
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 }