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