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