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