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