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