Remove legacy certificate handling
[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.setHeatArtifactDeploymentTimeout(heatDeploymentArtifactTimeout);
195         configurationManager.setConfiguration(configuration);
196         ExternalConfiguration.setAppName("catalog-be");
197     }
198
199     @BeforeEach
200     public void before() throws Exception {
201         super.setUp();
202
203         when(resourceComponentMock.getVersion()).thenReturn(VERSION);
204         when(resourceComponentMock.getUniqueId()).thenReturn(resourceVertexUuid);
205
206         when(serviceComponentMock.getVersion()).thenReturn(VERSION);
207         when(serviceComponentMock.getUniqueId()).thenReturn(serviceVertexUuid);
208
209         List<Component> listComponents = new LinkedList<>();
210         listComponents.add(serviceComponentMock);
211
212         when(toscaOperationFacadeMock.getComponentListByUuid(eq(serviceVertexUuid), any())).thenReturn(Either.left(listComponents));
213         when(toscaOperationFacadeMock.getComponentByUuidAndVersion(serviceVertexUuid, VERSION)).thenReturn(Either.left(serviceComponentMock));
214         when(toscaOperationFacadeMock.getComponentByUuidAndVersion(resourceVertexUuid, VERSION)).thenReturn(Either.left(resourceComponentMock));
215         when(toscaOperationFacadeMock.getLatestComponentByUuid(eq(serviceVertexUuid), any())).thenReturn(Either.left(listComponents.get(0)));
216         when(toscaOperationFacadeMock.getLatestComponentByUuid(eq(resourceVertexUuid), any())).thenReturn(Either.left(resourceComponentMock));
217     }
218
219     @AfterEach
220     void after() throws Exception {
221         super.tearDown();
222     }
223
224     @Test
225     void testGetExternalRefsForExistingComponentInstance() {
226         String path = String
227             .format("/v1/catalog/services/%s/version/%s/resourceInstances/%s/externalReferences/%s", serviceVertexUuid,
228                 VERSION, COMPONENT_ID, MONITORING_OBJECT_TYPE);
229
230         Response response = target()
231             .path(path)
232             .request()
233             .accept(MediaType.APPLICATION_JSON)
234             .header(Constants.X_ECOMP_INSTANCE_ID_HEADER, "mockXEcompInstanceId")
235             .header(Constants.USER_ID_HEADER, designerUser.getUserId())
236             .get();
237
238         List<String> dto = response.readEntity(new GenericType<List<String>>() {
239         });
240         assertThat(dto).containsExactly(REF_1, REF_2, REF_3, REF_5);
241         assertThat(response.getStatus()).isEqualTo(HttpStatus.OK.value());
242     }
243
244     @Test
245     void testGetExternalRefsForAsset() {
246         String path = String
247             .format("/v1/catalog/services/%s/version/%s/externalReferences/%s", serviceVertexUuid, VERSION,
248                 MONITORING_OBJECT_TYPE);
249
250         Response response = target()
251             .path(path)
252             .request()
253             .accept(MediaType.APPLICATION_JSON)
254             .header(Constants.X_ECOMP_INSTANCE_ID_HEADER, "mockXEcompInstanceId")
255             .header(Constants.USER_ID_HEADER, designerUser.getUserId())
256             .get();
257
258         Map<String, List<String>> dtoMap = response.readEntity(new GenericType<HashMap<String, List<String>>>() {
259         });
260         assertThat(dtoMap.get(COMPONENT_ID)).containsExactly(REF_1, REF_2, REF_3, REF_5);
261         assertThat(response.getStatus()).isEqualTo(HttpStatus.OK.value());
262     }
263
264     @Test
265     void testGetExternalRefsForAssetWithMissingEcompHeader() {
266         String path = String
267             .format("/v1/catalog/services/%s/version/%s/externalReferences/%s", serviceVertexUuid, VERSION,
268                 MONITORING_OBJECT_TYPE);
269
270         //No X-Ecomp-Instance-ID header
271         Response response = target()
272             .path(path)
273             .request()
274             .accept(MediaType.APPLICATION_JSON)
275             .header(Constants.USER_ID_HEADER, designerUser.getUserId())
276             .get();
277
278         assertThat(response.getStatus()).isEqualTo(HttpStatus.BAD_REQUEST.value());
279     }
280
281     @Test
282     void testAddExternalRefForResource() {
283         String path = String
284             .format("/v1/catalog/resources/%s/resourceInstances/%s/externalReferences/%s", resourceVertexUuid,
285                 COMPONENT_ID, MONITORING_OBJECT_TYPE);
286         String getPath = String
287             .format("/v1/catalog/resources/%s/version/%s/externalReferences/%s", resourceVertexUuid, VERSION,
288                 MONITORING_OBJECT_TYPE);
289
290         Response response = target()
291             .path(path)
292             .request(MediaType.APPLICATION_JSON)
293             .accept(MediaType.APPLICATION_JSON)
294             .header(Constants.X_ECOMP_INSTANCE_ID_HEADER, "mockXEcompInstanceId")
295             .header(Constants.USER_ID_HEADER, designerUser.getUserId())
296             .post(Entity.json(new ExternalRefDTO(REF_1)));
297
298         assertThat(response.getStatus()).isEqualTo(HttpStatus.CREATED.value());
299
300         //Check that GET will include the new reference
301         response = target()
302             .path(getPath)
303             .request()
304             .accept(MediaType.APPLICATION_JSON)
305             .header(Constants.X_ECOMP_INSTANCE_ID_HEADER, "mockXEcompInstanceId")
306             .header(Constants.USER_ID_HEADER, adminUser.getUserId())
307             .get();
308
309         Map<String, List<String>> dto = response.readEntity(new GenericType<Map<String, List<String>>>() {
310         });
311         assertThat(dto.get(COMPONENT_ID)).containsExactlyInAnyOrder(REF_1);
312         assertThat(response.getStatus()).isEqualTo(HttpStatus.OK.value());
313     }
314
315     @Test
316     void testAddExternalRefForExistingComponentInstance() {
317         String path = String
318             .format("/v1/catalog/services/%s/resourceInstances/%s/externalReferences/%s", serviceVertexUuid,
319                 COMPONENT_ID, MONITORING_OBJECT_TYPE);
320         String getPath = String
321             .format("/v1/catalog/services/%s/version/%s/resourceInstances/%s/externalReferences/%s", serviceVertexUuid,
322                 VERSION, COMPONENT_ID, MONITORING_OBJECT_TYPE);
323         Response response = target()
324             .path(path)
325             .request(MediaType.APPLICATION_JSON)
326             .accept(MediaType.APPLICATION_JSON)
327             .header(Constants.X_ECOMP_INSTANCE_ID_HEADER, "mockXEcompInstanceId")
328             .header(Constants.USER_ID_HEADER, designerUser.getUserId())
329             .post(Entity.json(new ExternalRefDTO(REF_4)));
330
331         assertThat(response.getStatus()).isEqualTo(HttpStatus.CREATED.value());
332
333         //Check that GET will include the new reference
334         response = target()
335             .path(getPath)
336             .request()
337             .accept(MediaType.APPLICATION_JSON)
338             .header(Constants.X_ECOMP_INSTANCE_ID_HEADER, "mockXEcompInstanceId")
339             .header(Constants.USER_ID_HEADER, adminUser.getUserId())
340             .get();
341
342         List<String> dto = response.readEntity(new GenericType<List<String>>() {
343         });
344         assertThat(dto).containsExactlyInAnyOrder(REF_1, REF_2, REF_3, REF_4, REF_5);
345         assertThat(response.getStatus()).isEqualTo(HttpStatus.OK.value());
346     }
347
348     @Test
349     void testDeleteExternalRefForExistingComponentInstance() {
350         String deletePath = String
351             .format("/v1/catalog/services/%s/resourceInstances/%s/externalReferences/%s/%s", serviceVertexUuid,
352                 COMPONENT_ID, MONITORING_OBJECT_TYPE, REF_5);
353         String getPath = String
354             .format("/v1/catalog/services/%s/version/%s/resourceInstances/%s/externalReferences/%s", serviceVertexUuid,
355                 VERSION, COMPONENT_ID, MONITORING_OBJECT_TYPE);
356         Response response = target()
357             .path(deletePath)
358             .request(MediaType.APPLICATION_JSON)
359             .accept(MediaType.APPLICATION_JSON)
360             .header(Constants.X_ECOMP_INSTANCE_ID_HEADER, "mockXEcompInstanceId")
361             .header(Constants.USER_ID_HEADER, designerUser.getUserId())
362             .delete();
363
364         //Verify that the deleted reference is returned in body
365         ExternalRefDTO dto = response.readEntity(ExternalRefDTO.class);
366         assertThat(dto.getReferenceUUID()).isEqualTo(REF_5);
367         assertThat(response.getStatus()).isEqualTo(HttpStatus.OK.value());
368
369         //Check that GET will NOT include the deleted reference
370         response = target()
371             .path(getPath)
372             .request()
373             .accept(MediaType.APPLICATION_JSON)
374             .header(Constants.X_ECOMP_INSTANCE_ID_HEADER, "mockXEcompInstanceId")
375             .header(Constants.USER_ID_HEADER, designerUser.getUserId())
376             .get();
377
378         List<String> getResponse = response.readEntity(new GenericType<List<String>>() {
379         });
380         assertThat(getResponse).containsExactlyInAnyOrder(REF_1, REF_2, REF_3);
381         assertThat(response.getStatus()).isEqualTo(HttpStatus.OK.value());
382     }
383
384     @Test
385     void testUpdateExternalRefForExistingComponentInstance() {
386         String updatePath = String
387             .format("/v1/catalog/services/%s/resourceInstances/%s/externalReferences/%s/%s", serviceVertexUuid,
388                 COMPONENT_ID, MONITORING_OBJECT_TYPE, REF_5);
389         String getPath = String
390             .format("/v1/catalog/services/%s/version/%s/resourceInstances/%s/externalReferences/%s", serviceVertexUuid,
391                 VERSION, COMPONENT_ID, MONITORING_OBJECT_TYPE);
392         Response response = target()
393             .path(updatePath)
394             .request(MediaType.APPLICATION_JSON)
395             .accept(MediaType.APPLICATION_JSON)
396             .header(Constants.X_ECOMP_INSTANCE_ID_HEADER, "mockXEcompInstanceId")
397             .header(Constants.USER_ID_HEADER, designerUser.getUserId())
398             .put(Entity.json(new ExternalRefDTO(REF_4)));
399
400         //Verify that the updated reference is returned in body
401         ExternalRefDTO putResponseBody = response.readEntity(ExternalRefDTO.class);
402         assertThat(putResponseBody.getReferenceUUID()).isEqualTo(REF_4);
403         assertThat(response.getStatus()).isEqualTo(HttpStatus.OK.value());
404
405         //Check that GET will include the updated reference
406         response = target()
407             .path(getPath)
408             .request()
409             .accept(MediaType.APPLICATION_JSON)
410             .header(Constants.X_ECOMP_INSTANCE_ID_HEADER, "mockXEcompInstanceId")
411             .header(Constants.USER_ID_HEADER, designerUser.getUserId())
412             .get();
413
414         List<String> dto = response.readEntity(new GenericType<List<String>>() {
415         });
416         assertThat(dto).containsExactlyInAnyOrder(REF_1, REF_2, REF_3, REF_4);
417         assertThat(response.getStatus()).isEqualTo(HttpStatus.OK.value());
418     }
419
420     /*
421      * Rainy Scenarios
422      */
423     @Test
424     void testAddExternalRefForNonExistingAssetId() {
425         String path = String
426             .format("/v1/catalog/services/%s/resourceInstances/%s/externalReferences/%s", "non-existing-uuid",
427                 COMPONENT_ID, MONITORING_OBJECT_TYPE);
428         Response response = target()
429             .path(path)
430             .request(MediaType.APPLICATION_JSON)
431             .accept(MediaType.APPLICATION_JSON)
432             .header(Constants.X_ECOMP_INSTANCE_ID_HEADER, "mockXEcompInstanceId")
433             .header(Constants.USER_ID_HEADER, designerUser.getUserId())
434             .post(Entity.json(new ExternalRefDTO(REF_4)));
435
436         assertThat(response.getStatus()).isEqualTo(HttpStatus.NOT_FOUND.value());
437     }
438
439     @Test
440     void testAddExternalRefForNonExistingCompInstId() {
441         String path = String
442             .format("/v1/catalog/services/%s/resourceInstances/%s/externalReferences/%s", serviceVertexUuid,
443                 "FAKE_COM_ID", MONITORING_OBJECT_TYPE);
444         Response response = target()
445             .path(path)
446             .request(MediaType.APPLICATION_JSON)
447             .accept(MediaType.APPLICATION_JSON)
448             .header(Constants.X_ECOMP_INSTANCE_ID_HEADER, "mockXEcompInstanceId")
449             .header(Constants.USER_ID_HEADER, designerUser.getUserId())
450             .post(Entity.json(new ExternalRefDTO(REF_4)));
451
452         assertThat(response.getStatus()).isEqualTo(HttpStatus.NOT_FOUND.value());
453     }
454
455     @Test
456     void testAddExistingExternalRef() {
457         String path = String
458             .format("/v1/catalog/services/%s/resourceInstances/%s/externalReferences/%s", serviceVertexUuid,
459                 COMPONENT_ID, MONITORING_OBJECT_TYPE);
460         Response response = target()
461             .path(path)
462             .request(MediaType.APPLICATION_JSON)
463             .accept(MediaType.APPLICATION_JSON)
464             .header(Constants.X_ECOMP_INSTANCE_ID_HEADER, "mockXEcompInstanceId")
465             .header(Constants.USER_ID_HEADER, designerUser.getUserId())
466             .post(Entity.json(new ExternalRefDTO(REF_1)));
467
468         assertThat(response.getStatus()).isEqualTo(HttpStatus.OK.value()); //Ref not created but still OK is returned
469     }
470
471     @Test
472     void testUpdateExternalRefForNonExistingAssetId() {
473         String updatePath = String.format("/v1/catalog/services/%s/resourceInstances/%s/externalReferences/%s/%s",
474             "nonExistingServiceVertexUuid", COMPONENT_ID, MONITORING_OBJECT_TYPE, REF_5);
475
476         Response response = target()
477             .path(updatePath)
478             .request(MediaType.APPLICATION_JSON)
479             .accept(MediaType.APPLICATION_JSON)
480             .header(Constants.X_ECOMP_INSTANCE_ID_HEADER, "mockXEcompInstanceId")
481             .header(Constants.USER_ID_HEADER, designerUser.getUserId())
482             .put(Entity.json(new ExternalRefDTO(REF_4)));
483
484         //Verify that the 404 is returned
485         assertThat(response.getStatus()).isEqualTo(HttpStatus.NOT_FOUND.value());
486
487     }
488
489     @Test
490     void testUpdateExternalRefForNonExistingObjectIdOrOldRef() {
491         String updatePath = String
492             .format("/v1/catalog/services/%s/resourceInstances/%s/externalReferences/%s/%s", serviceVertexUuid,
493                 COMPONENT_ID, "FAKE_OBJ_TYPE", REF_5);
494
495         Response response = target()
496             .path(updatePath)
497             .request(MediaType.APPLICATION_JSON)
498             .accept(MediaType.APPLICATION_JSON)
499             .header(Constants.X_ECOMP_INSTANCE_ID_HEADER, "mockXEcompInstanceId")
500             .header(Constants.USER_ID_HEADER, designerUser.getUserId())
501             .put(Entity.json(new ExternalRefDTO(REF_4)));
502
503         assertThat(response.getStatus()).isEqualTo(HttpStatus.NOT_FOUND.value());
504     }
505
506     @Test
507     void testDeleteExternalRefForNonExistingAssetId() {
508         String deletePath = String
509             .format("/v1/catalog/services/%s/resourceInstances/%s/externalReferences/%s/%s", "non-existing-asset",
510                 COMPONENT_ID, MONITORING_OBJECT_TYPE, REF_5);
511         Response response = target()
512             .path(deletePath)
513             .request(MediaType.APPLICATION_JSON)
514             .accept(MediaType.APPLICATION_JSON)
515             .header(Constants.X_ECOMP_INSTANCE_ID_HEADER, "mockXEcompInstanceId")
516             .header(Constants.USER_ID_HEADER, designerUser.getUserId())
517             .delete();
518
519         assertThat(response.getStatus()).isEqualTo(HttpStatus.NOT_FOUND.value());
520     }
521
522     @Test
523     void testDeleteExternalRefForNonExistingRef() {
524         String deletePath = String
525             .format("/v1/catalog/services/%s/resourceInstances/%s/externalReferences/%s/%s", serviceVertexUuid,
526                 COMPONENT_ID, MONITORING_OBJECT_TYPE, "FAKE_REF");
527         Response response = target()
528             .path(deletePath)
529             .request(MediaType.APPLICATION_JSON)
530             .accept(MediaType.APPLICATION_JSON)
531             .header(Constants.X_ECOMP_INSTANCE_ID_HEADER, "mockXEcompInstanceId")
532             .delete();
533
534         assertThat(response.getStatus()).isEqualTo(HttpStatus.NOT_FOUND.value());
535     }
536
537     @Test
538     void testGetExternalRefsForNonExistingAsset() {
539         String path = String
540             .format("/v1/catalog/services/%s/version/%s/resourceInstances/%s/externalReferences/%s", "fake-asset-id",
541                 VERSION, COMPONENT_ID, MONITORING_OBJECT_TYPE);
542
543         Response response = target()
544             .path(path)
545             .request()
546             .accept(MediaType.APPLICATION_JSON)
547             .header(Constants.X_ECOMP_INSTANCE_ID_HEADER, "mockXEcompInstanceId")
548             .header(Constants.USER_ID_HEADER, designerUser.getUserId())
549             .get();
550
551         assertThat(response.getStatus()).isEqualTo(HttpStatus.NOT_FOUND.value());
552     }
553
554     @Test
555     void testGetExternalRefsForNonExistingVersion() {
556         String path = String
557             .format("/v1/catalog/services/%s/version/%s/resourceInstances/%s/externalReferences/%s", serviceVertexUuid,
558                 FAKE_VERSION, COMPONENT_ID, MONITORING_OBJECT_TYPE);
559
560         Response response = target()
561             .path(path)
562             .request()
563             .accept(MediaType.APPLICATION_JSON)
564             .header(Constants.X_ECOMP_INSTANCE_ID_HEADER, "mockXEcompInstanceId")
565             .header(Constants.USER_ID_HEADER, designerUser.getUserId())
566             .get();
567
568         assertThat(response.getStatus()).isEqualTo(HttpStatus.NOT_FOUND.value());
569     }
570
571     @Test
572     void testDeleteExternalRefsForExistingComponentInstanceWithUnauthorizedUser() {
573         String path = String
574             .format("/v1/catalog/services/%s/resourceInstances/%s/externalReferences/%s/%s", serviceVertexUuid,
575                 COMPONENT_ID, MONITORING_OBJECT_TYPE, REF_5);
576
577         Response response = target()
578             .path(path)
579             .request()
580             .accept(MediaType.APPLICATION_JSON)
581             .header(Constants.X_ECOMP_INSTANCE_ID_HEADER, "mockXEcompInstanceId")
582             .header(Constants.USER_ID_HEADER, otherUser.getUserId())
583             .delete();
584
585         assertThat(response.getStatus()).isEqualTo(HttpStatus.UNAUTHORIZED.value());
586     }
587
588     @Test
589     void testDeleteExternalRefForUserWhichIsNotCurrentUpdater() {
590         String deletePath = String
591             .format("/v1/catalog/services/%s/resourceInstances/%s/externalReferences/%s/%s", serviceVertexUuid,
592                 COMPONENT_ID, MONITORING_OBJECT_TYPE, REF_5);
593         Response response = target()
594             .path(deletePath)
595             .request(MediaType.APPLICATION_JSON)
596             .accept(MediaType.APPLICATION_JSON)
597             .header(Constants.X_ECOMP_INSTANCE_ID_HEADER, "mockXEcompInstanceId")
598             .header(Constants.USER_ID_HEADER, otherDesignerUser.getUserId())
599             .delete();
600
601         assertThat(response.getStatus()).isEqualTo(HttpStatus.UNAUTHORIZED.value());
602     }
603
604     @Override
605     protected Application configure() {
606         ApplicationContext context = new AnnotationConfigApplicationContext(TestSpringConfig.class);
607         forceSet(TestProperties.CONTAINER_PORT, "0");
608         return new ResourceConfig(ExternalRefsServlet.class)
609             .register(DefaultExceptionMapper.class)
610             .register(ComponentExceptionMapper.class)
611             .register(StorageExceptionMapper.class)
612             .property("contextConfig", context);
613     }
614
615     @Configuration
616     @PropertySource("classpath:dao.properties")
617     static class TestSpringConfig {
618
619         private GraphVertex serviceVertex;
620         private GraphVertex resourceVertex;
621         private ExternalReferencesOperation externalReferenceOperation;
622         private HealingJanusGraphDao janusGraphDao;
623
624         @Bean
625         ExternalRefsServlet externalRefsServlet() {
626             return new ExternalRefsServlet(componentUtils, externalRefsBusinessLogic());
627         }
628
629         @Bean
630         OperationUtils operationUtils() {
631             return new OperationUtils(janusGraphDao());
632         }
633
634         @Bean
635         ComponentExceptionMapper componentExceptionMapper() {
636             return new ComponentExceptionMapper(componentUtils);
637         }
638
639         @Bean
640         StorageExceptionMapper storageExceptionMapper() {
641             return new StorageExceptionMapper(componentUtils);
642         }
643
644         @Bean
645         DefaultExceptionMapper defaultExceptionMapper() {
646             return new DefaultExceptionMapper();
647         }
648
649         @Bean
650         ExternalRefsBusinessLogic externalRefsBusinessLogic() {
651             return new ExternalRefsBusinessLogic(externalReferencesOperation(), toscaOperationFacade(),
652                 accessValidations(), componentLocker());
653         }
654
655         @Bean
656         AccessValidations accessValidations() {
657             return accessValidationsMock;
658         }
659
660         @Bean
661         ExternalReferencesOperation externalReferencesOperation() {
662             this.externalReferenceOperation = new ExternalReferencesOperation(janusGraphDao(), nodeTypeOpertaion(),
663                 topologyTemplateOperation(), idMapper());
664             this.externalReferenceOperation.setHealingPipelineDao(healingPipelineDao());
665             GraphTestUtils.clearGraph(janusGraphDao);
666             initGraphForTest();
667             return this.externalReferenceOperation;
668         }
669
670         @Bean
671         ToscaOperationFacade toscaOperationFacade() {
672             return toscaOperationFacadeMock;
673         }
674
675         @Bean
676         IdMapper idMapper() {
677             when(idMapper.mapComponentNameToUniqueId(eq(COMPONENT_ID), any(GraphVertex.class))).thenReturn(COMPONENT_ID);
678             when(idMapper.mapUniqueIdToComponentNameTo(eq(COMPONENT_ID), any(GraphVertex.class))).thenReturn(COMPONENT_ID);
679             when(idMapper.mapComponentNameToUniqueId(eq(FAKE_COMPONENT_ID), any(GraphVertex.class))).thenReturn(null);
680             return idMapper;
681         }
682
683         @Bean
684         TopologyTemplateOperation topologyTemplateOperation() {
685             return new TopologyTemplateOperation();
686         }
687
688         @Bean
689         ArchiveOperation archiveOperation() {
690             return new ArchiveOperation(janusGraphDao(), graphLockOperation());
691         }
692
693         @Bean
694         IGraphLockOperation graphLockOperation() {
695             return graphLockOperation;
696         }
697
698         @Bean
699         NodeTypeOperation nodeTypeOpertaion() {
700             return new NodeTypeOperation(null);
701         }
702
703         @Bean
704         NodeTemplateOperation nodeTemplateOperation() {
705             return new NodeTemplateOperation();
706         }
707
708         @Bean
709         GroupsOperation groupsOperation() {
710             return new GroupsOperation();
711         }
712
713         @Bean
714         HealingJanusGraphDao janusGraphDao() {
715             this.janusGraphDao = new HealingJanusGraphDao(healingPipelineDao(), janusGraphClient());
716             return janusGraphDao;
717         }
718
719         @Bean
720         JanusGraphClient janusGraphClient() {
721             return new JanusGraphClient(janusGraphClientStrategy());
722         }
723
724         @Bean
725         JanusGraphClientStrategy janusGraphClientStrategy() {
726             return new DAOJanusGraphStrategy();
727         }
728
729         @Bean
730         CategoryOperation categoryOperation() {
731             return new CategoryOperation();
732         }
733
734         @Bean
735         ComponentLocker componentLocker() {
736             return componentLocker;
737         }
738
739         @Bean
740         JanusGraphGenericDao janusGraphGenericDao() {
741             return janusGraphGenericDao;
742         }
743
744         @Bean
745         ModelOperation modelOperation() {
746             return modelOperation;
747         }
748
749         @Bean
750         ModelElementOperation modelElementOperation() {
751             return modelElementOperation;
752         }
753
754         @Bean("healingPipelineDao")
755         HealingPipelineDao healingPipelineDao() {
756             HealingPipelineDao healingPipelineDao = new HealingPipelineDao();
757             healingPipelineDao.setHealVersion(1);
758             healingPipelineDao.initHealVersion();
759             return healingPipelineDao;
760         }
761
762         @Bean
763         ContainerInstanceTypesData containerInstanceTypesData() {
764             return new ContainerInstanceTypesData();
765         }
766
767         private void initGraphForTest() {
768             resourceVertex = GraphTestUtils.createResourceVertex(janusGraphDao, new HashMap<>(), ResourceTypeEnum.VF);
769             resourceVertexUuid = resourceVertex.getUniqueId();
770
771             //create a service and add ref
772             serviceVertex = GraphTestUtils.createServiceVertex(janusGraphDao, new HashMap<>());
773             serviceVertexUuid = this.serviceVertex.getUniqueId();
774
775             //monitoring references
776             externalReferenceOperation.addExternalReference(serviceVertexUuid, COMPONENT_ID, MONITORING_OBJECT_TYPE, REF_1);
777             externalReferenceOperation.addExternalReference(serviceVertexUuid, COMPONENT_ID, MONITORING_OBJECT_TYPE, REF_2);
778             externalReferenceOperation.addExternalReference(serviceVertexUuid, COMPONENT_ID, MONITORING_OBJECT_TYPE, REF_3);
779             externalReferenceOperation.addExternalReference(serviceVertexUuid, COMPONENT_ID, MONITORING_OBJECT_TYPE, REF_5);
780
781             //workflow references
782             externalReferenceOperation.addExternalReference(serviceVertexUuid, COMPONENT_ID, WORKFLOW_OBJECT_TYPE, REF_6);
783
784             final JanusGraphOperationStatus commit = this.janusGraphDao.commit();
785             assertThat(commit).isEqualTo(JanusGraphOperationStatus.OK);
786         }
787
788     }
789 }