2 * ============LICENSE_START=======================================================
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
11 * http://www.apache.org/licenses/LICENSE-2.0
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 * ================================================================================
23 package org.openecomp.sdc.be.servlets;
25 import com.google.gson.Gson;
26 import com.google.gson.GsonBuilder;
27 import fj.data.Either;
28 import org.apache.commons.codec.binary.Base64;
29 import org.apache.commons.lang3.tuple.ImmutablePair;
30 import org.apache.commons.text.StrSubstitutor;
31 import org.apache.http.HttpStatus;
32 import org.glassfish.hk2.utilities.binding.AbstractBinder;
33 import org.glassfish.jersey.server.ResourceConfig;
34 import org.glassfish.jersey.test.JerseyTest;
35 import org.glassfish.jersey.test.TestProperties;
36 import org.json.JSONException;
37 import org.junit.Before;
38 import org.junit.BeforeClass;
39 import org.junit.Test;
40 import org.mockito.Mockito;
41 import org.openecomp.sdc.be.components.impl.ComponentInstanceBusinessLogic;
42 import org.openecomp.sdc.be.components.impl.GroupBusinessLogic;
43 import org.openecomp.sdc.be.components.impl.ResourceBusinessLogic;
44 import org.openecomp.sdc.be.components.impl.ResourceImportManager;
45 import org.openecomp.sdc.be.config.SpringConfig;
46 import org.openecomp.sdc.be.dao.api.ActionStatus;
47 import org.openecomp.sdc.be.datamodel.api.HighestFilterEnum;
48 import org.openecomp.sdc.be.datatypes.enums.ComponentTypeEnum;
49 import org.openecomp.sdc.be.datatypes.enums.ResourceTypeEnum;
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.Resource;
54 import org.openecomp.sdc.be.model.UploadResourceInfo;
55 import org.openecomp.sdc.be.model.User;
56 import org.openecomp.sdc.be.resources.data.auditing.AuditingActionEnum;
57 import org.openecomp.sdc.be.user.Role;
58 import org.openecomp.sdc.be.user.UserBusinessLogic;
59 import org.openecomp.sdc.common.api.Constants;
60 import org.openecomp.sdc.common.impl.ExternalConfiguration;
61 import org.openecomp.sdc.common.util.GeneralUtility;
62 import org.openecomp.sdc.exception.ResponseFormat;
63 import org.springframework.context.ApplicationContext;
64 import org.springframework.context.annotation.AnnotationConfigApplicationContext;
65 import org.springframework.web.context.WebApplicationContext;
67 import javax.servlet.ServletContext;
68 import javax.servlet.http.HttpServletRequest;
69 import javax.servlet.http.HttpSession;
70 import javax.ws.rs.client.Entity;
71 import javax.ws.rs.core.Application;
72 import javax.ws.rs.core.MediaType;
73 import javax.ws.rs.core.Response;
74 import java.io.IOException;
75 import java.util.Arrays;
76 import java.util.Collections;
77 import java.util.HashMap;
78 import java.util.List;
81 import static org.assertj.core.api.Assertions.assertThat;
82 import static org.junit.Assert.assertEquals;
83 import static org.mockito.ArgumentMatchers.any;
84 import static org.mockito.ArgumentMatchers.eq;
85 import static org.mockito.BDDMockito.given;
86 import static org.mockito.Mockito.when;
88 public class ResourceServletTest extends JerseyTest {
89 public static final HttpServletRequest request = Mockito.mock(HttpServletRequest.class);
90 public static final ResourceImportManager resourceImportManager = Mockito.mock(ResourceImportManager.class);
91 private static final HttpSession session = Mockito.mock(HttpSession.class);
92 private static final ServletContext servletContext = Mockito.mock(ServletContext.class);
93 private static final WebAppContextWrapper webAppContextWrapper = Mockito.mock(WebAppContextWrapper.class);
94 private static final WebApplicationContext webApplicationContext = Mockito.mock(WebApplicationContext.class);
95 public static final ServletUtils servletUtils = Mockito.mock(ServletUtils.class);
96 public static final ComponentsUtils componentUtils = Mockito.mock(ComponentsUtils.class);
97 private static final UserBusinessLogic userAdmin = Mockito.mock(UserBusinessLogic.class);
98 private static final UserBusinessLogic userBusinessLogic = Mockito.mock(UserBusinessLogic.class);
99 private static final GroupBusinessLogic groupBL = Mockito.mock(GroupBusinessLogic.class);
100 private static final ComponentInstanceBusinessLogic componentInstanceBL = Mockito.mock(ComponentInstanceBusinessLogic.class);
101 private static final ResourceBusinessLogic resourceBusinessLogic = Mockito.mock(ResourceBusinessLogic.class);
102 private static final Gson gson = new GsonBuilder().setPrettyPrinting().create();
103 private static final ResponseFormat okResponseFormat = new ResponseFormat(HttpStatus.SC_OK);
104 private static final ResponseFormat conflictResponseFormat = new ResponseFormat(HttpStatus.SC_CONFLICT);
105 private static final ResponseFormat generalErrorResponseFormat = new ResponseFormat(HttpStatus.SC_INTERNAL_SERVER_ERROR);
106 private static final ResponseFormat createdResponseFormat = new ResponseFormat(HttpStatus.SC_CREATED);
107 private static final ResponseFormat noContentResponseFormat = new ResponseFormat(HttpStatus.SC_NO_CONTENT);
108 private static final ResponseFormat notFoundResponseFormat = new ResponseFormat(HttpStatus.SC_NOT_FOUND);
109 private static final ResponseFormat badRequestResponseFormat = new ResponseFormat(HttpStatus.SC_BAD_REQUEST);
110 private static final String RESOURCE_NAME = "resourceName";
111 private static final String VERSION = "version";
112 private static final String RESOURCE_ID = "resourceId";
113 private static final String RESOURCE_VERSION = "resourceVersion";
114 private static final String SUBTYPE = "subtype";
115 private static final String CSAR_UUID = "csaruuid";
116 private static final String EMPTY_JSON = "{}";
117 private static final String NON_UI_IMPORT_JSON = "{\n" +
118 " \"node1\": \"value1\",\n" +
120 " \"level21\": \"value21\",\n" +
121 " \"level22\": \"value22\"\n" +
124 private static User user;
127 public static void setup() {
128 ExternalConfiguration.setAppName("catalog-be");
129 when(request.getSession()).thenReturn(session);
130 when(session.getServletContext()).thenReturn(servletContext);
131 when(servletContext.getAttribute(Constants.WEB_APPLICATION_CONTEXT_WRAPPER_ATTR)).thenReturn(webAppContextWrapper);
132 when(webAppContextWrapper.getWebAppContext(servletContext)).thenReturn(webApplicationContext);
133 when(webApplicationContext.getBean(ResourceImportManager.class)).thenReturn(resourceImportManager);
134 when(webApplicationContext.getBean(ServletUtils.class)).thenReturn(servletUtils);
135 when(servletUtils.getComponentsUtils()).thenReturn(componentUtils);
136 when(servletUtils.getUserAdmin()).thenReturn(userAdmin);
137 String userId = "jh0003";
139 user.setUserId(userId);
140 user.setRole(Role.ADMIN.name());
141 when(userAdmin.getUser(userId)).thenReturn(user);
142 when(request.getHeader(Constants.USER_ID_HEADER)).thenReturn(userId);
144 ImmutablePair<Resource, ActionStatus> pair = new ImmutablePair<>(new Resource(), ActionStatus.OK);
145 when(resourceImportManager.importUserDefinedResource(Mockito.anyString(), Mockito.any(UploadResourceInfo.class), Mockito.any(User.class), Mockito.anyBoolean())).thenReturn(pair);
146 when(webApplicationContext.getBean(ResourceBusinessLogic.class)).thenReturn(resourceBusinessLogic);
151 public void beforeTest() {
152 Mockito.reset(componentUtils);
153 Mockito.reset(resourceBusinessLogic);
155 when(componentUtils.getResponseFormat(ActionStatus.OK)) .thenReturn(okResponseFormat);
156 when(componentUtils.getResponseFormat(ActionStatus.CREATED)).thenReturn(createdResponseFormat);
157 when(componentUtils.getResponseFormat(ActionStatus.NO_CONTENT)).thenReturn(noContentResponseFormat);
158 when(componentUtils.getResponseFormat(ActionStatus.INVALID_CONTENT)).thenReturn(badRequestResponseFormat);
159 when(componentUtils.getResponseFormat(ActionStatus.GENERAL_ERROR)) .thenReturn(generalErrorResponseFormat);
160 when(componentUtils.getResponseFormat(ActionStatus.ARTIFACT_NOT_FOUND)) .thenReturn(notFoundResponseFormat);
164 public void testHappyScenarioTest() {
165 when(componentUtils.getResponseFormat(ActionStatus.OK)) .thenReturn(createdResponseFormat);
167 UploadResourceInfo validJson = buildValidJson();
168 setMD5OnRequest(true, validJson);
169 Response response = target().path("/v1/catalog/resources").request(MediaType.APPLICATION_JSON).post(Entity.json(gson.toJson(validJson)), Response.class);
170 Mockito.verify(componentUtils, Mockito.times(1)).getResponseFormat(Mockito.any(ActionStatus.class));
171 Mockito.verify(componentUtils, Mockito.times(1)).getResponseFormat(ActionStatus.OK);
172 assertEquals(HttpStatus.SC_CREATED, response.getStatus());
177 public void testNonValidMd5Fail() {
178 UploadResourceInfo validJson = buildValidJson();
180 setMD5OnRequest(false, validJson);
182 Response response = target().path("/v1/catalog/resources").request(MediaType.APPLICATION_JSON).post(Entity.json(gson.toJson(validJson)), Response.class);
183 Mockito.verify(componentUtils, Mockito.times(1)).getResponseFormat(Mockito.any(ActionStatus.class));
184 Mockito.verify(componentUtils, Mockito.times(1)).getResponseFormat(ActionStatus.INVALID_RESOURCE_CHECKSUM);
185 assertEquals(response.getStatus(), HttpStatus.SC_INTERNAL_SERVER_ERROR);
190 public void testNonValidPayloadNameFail() {
191 UploadResourceInfo mdJson = buildValidJson();
192 mdJson.setPayloadName("myCompute.xml");
194 runAndVerifyActionStatusError(mdJson, ActionStatus.INVALID_TOSCA_FILE_EXTENSION);
199 public void testNullPayloadFail() {
200 UploadResourceInfo mdJson = buildValidJson();
201 mdJson.setPayloadData(null);
202 runAndVerifyActionStatusError(mdJson, ActionStatus.INVALID_RESOURCE_PAYLOAD);
207 public void testNonYmlPayloadFail() {
208 UploadResourceInfo mdJson = buildValidJson();
209 String payload = "{ json : { isNot : yaml } ";
210 encodeAndSetPayload(mdJson, payload);
211 runAndVerifyActionStatusError(mdJson, ActionStatus.INVALID_YAML_FILE);
216 public void testNonToscaPayloadFail() {
217 UploadResourceInfo mdJson = buildValidJson();
219 String payload = "node_types: \r\n" + " org.openecomp.resource.importResource4test:\r\n" + " derived_from: tosca.nodes.Root\r\n" + " description: update update";
220 encodeAndSetPayload(mdJson, payload);
221 runAndVerifyActionStatusError(mdJson, ActionStatus.INVALID_TOSCA_TEMPLATE);
226 public void testServiceToscaPayloadFail() {
227 UploadResourceInfo mdJson = buildValidJson();
229 String payload = "tosca_definitions_version: tosca_simple_yaml_1_0_0\r\n" + "node_types: \r\n" + " org.openecomp.resource.importResource4test:\r\n" + " derived_from: tosca.nodes.Root\r\n" + " topology_template: thisIsService\r\n"
230 + " description: update update";
232 encodeAndSetPayload(mdJson, payload);
233 runAndVerifyActionStatusError(mdJson, ActionStatus.NOT_RESOURCE_TOSCA_TEMPLATE);
238 public void testMultipleResourcesInPayloadFail() {
239 UploadResourceInfo mdJson = buildValidJson();
241 String payload = "tosca_definitions_version: tosca_simple_yaml_1_0_0\r\n" + "node_types: \r\n" + " org.openecomp.resource.importResource4test2:\r\n" + " derived_from: tosca.nodes.Root\r\n" + " org.openecomp.resource.importResource4test:\r\n"
242 + " derived_from: tosca.nodes.Root\r\n" + " description: update update";
244 encodeAndSetPayload(mdJson, payload);
245 runAndVerifyActionStatusError(mdJson, ActionStatus.NOT_SINGLE_RESOURCE);
250 public void testNonValidNameSpaceInPayloadFail() {
251 UploadResourceInfo mdJson = buildValidJson();
253 String payload = "tosca_definitions_version: tosca_simple_yaml_1_0_0\r\n" + "node_types: \r\n" + " org.openecomp.resourceX.importResource4test:\r\n" + " derived_from: tosca.nodes.Root\r\n" + " description: update update";
255 encodeAndSetPayload(mdJson, payload);
256 runAndVerifyActionStatusError(mdJson, ActionStatus.INVALID_RESOURCE_NAMESPACE);
261 public void deleteResourceTryDeleteNonExistingResourceTest() {
262 String resourceId = "resourceId";
263 Map<String,String> parametersMap = new HashMap<>();
264 parametersMap.put("resourceId", resourceId);
266 String formatEndpoint = "/v1/catalog/resources/{resourceId}";
267 String path = StrSubstitutor.replace(formatEndpoint, parametersMap, "{","}");
269 when(resourceBusinessLogic.deleteResource(any(), any(User.class)))
270 .thenReturn(notFoundResponseFormat);
272 Response response = target()
275 .accept(MediaType.APPLICATION_JSON)
276 .header(Constants.USER_ID_HEADER, user.getUserId())
279 assertThat(response.getStatus()).isEqualTo(HttpStatus.SC_NOT_FOUND);
283 public void deleteResourceExceptionDuringDeletingTest() {
284 String resourceId = RESOURCE_ID;
285 Map<String,String> parametersMap = new HashMap<>();
286 parametersMap.put(RESOURCE_ID, resourceId);
288 String formatEndpoint = "/v1/catalog/resources/{resourceId}";
289 String path = StrSubstitutor.replace(formatEndpoint, parametersMap, "{","}");
291 when(resourceBusinessLogic.deleteResource(any(), any(User.class)))
292 .thenThrow(new JSONException("Test exception: deleteResource"));
294 Response response = target()
297 .accept(MediaType.APPLICATION_JSON)
298 .header(Constants.USER_ID_HEADER, user.getUserId())
301 assertThat(response.getStatus()).isEqualTo(HttpStatus.SC_INTERNAL_SERVER_ERROR);
305 public void deleteResourceCategoryTest() {
306 String resourceId = "resourceId";
307 Map<String,String> parametersMap = new HashMap<>();
308 parametersMap.put("resourceId", resourceId);
310 String formatEndpoint = "/v1/catalog/resources/{resourceId}";
311 String path = StrSubstitutor.replace(formatEndpoint, parametersMap, "{","}");
313 when(resourceBusinessLogic.deleteResource(eq(resourceId.toLowerCase()), any(User.class)))
314 .thenReturn(noContentResponseFormat);
316 Response response = target()
319 .accept(MediaType.APPLICATION_JSON)
320 .header(Constants.USER_ID_HEADER, user.getUserId())
323 assertThat(response.getStatus()).isEqualTo(org.apache.http.HttpStatus.SC_NO_CONTENT);
327 public void deleteResourceByNameAndVersionTryDeleteNonExistingResourceTest() {
328 String resourceName = RESOURCE_NAME;
329 String version = VERSION;
330 Map<String,String> parametersMap = new HashMap<>();
331 parametersMap.put(RESOURCE_NAME, resourceName);
332 parametersMap.put(VERSION, version);
334 String formatEndpoint = "/v1/catalog/resources/{resourceName}/{version}";
335 String path = StrSubstitutor.replace(formatEndpoint, parametersMap, "{","}");
337 when(resourceBusinessLogic.deleteResourceByNameAndVersion(eq(resourceName), eq(version), any(User.class)))
338 .thenReturn(notFoundResponseFormat);
340 Response response = target()
343 .accept(MediaType.APPLICATION_JSON)
344 .header(Constants.USER_ID_HEADER, user.getUserId())
347 assertThat(response.getStatus()).isEqualTo(HttpStatus.SC_NOT_FOUND);
351 public void deleteResourceByNameAndVersionExceptionDuringDeletingTest() {
352 String resourceName = RESOURCE_NAME;
353 String version = VERSION;
354 Map<String,String> parametersMap = new HashMap<>();
355 parametersMap.put(RESOURCE_NAME, resourceName);
356 parametersMap.put(VERSION, version);
358 String formatEndpoint = "/v1/catalog/resources/{resourceName}/{version}";
359 String path = StrSubstitutor.replace(formatEndpoint, parametersMap, "{","}");
361 when(resourceBusinessLogic.deleteResourceByNameAndVersion(eq(resourceName), eq(version), any(User.class)))
362 .thenThrow(new JSONException("Test exception: deleteResourceByNameAndVersion"));
364 Response response = target()
367 .accept(MediaType.APPLICATION_JSON)
368 .header(Constants.USER_ID_HEADER, user.getUserId())
371 assertThat(response.getStatus()).isEqualTo(HttpStatus.SC_INTERNAL_SERVER_ERROR);
375 public void deleteResourceByNameAndVersionCategoryTest() {
376 String resourceName = RESOURCE_NAME;
377 String version = VERSION;
378 Map<String,String> parametersMap = new HashMap<>();
379 parametersMap.put(RESOURCE_NAME, resourceName);
380 parametersMap.put(VERSION, version);
382 String formatEndpoint = "/v1/catalog/resources/{resourceName}/{version}";
383 String path = StrSubstitutor.replace(formatEndpoint, parametersMap, "{","}");
385 when(resourceBusinessLogic.deleteResourceByNameAndVersion(eq(resourceName), eq(version), any(User.class)))
386 .thenReturn(noContentResponseFormat);
388 Response response = target()
391 .accept(MediaType.APPLICATION_JSON)
392 .header(Constants.USER_ID_HEADER, user.getUserId())
395 assertThat(response.getStatus()).isEqualTo(HttpStatus.SC_NO_CONTENT);
399 public void getResourceByIdTryGetNonExistingResourceTest() {
400 String resourceId = RESOURCE_ID;
401 Map<String,String> parametersMap = new HashMap<>();
402 parametersMap.put(RESOURCE_ID, resourceId);
404 String formatEndpoint = "/v1/catalog/resources/{resourceId}";
405 String path = StrSubstitutor.replace(formatEndpoint, parametersMap, "{","}");
407 Either<Resource, ResponseFormat> getResourceByIdEither = Either.right(notFoundResponseFormat);
408 when(resourceBusinessLogic.getResource(eq(resourceId.toLowerCase()), any(User.class)))
409 .thenReturn(getResourceByIdEither);
411 Response response = target()
414 .accept(MediaType.APPLICATION_JSON)
415 .header(Constants.USER_ID_HEADER, user.getUserId())
418 assertThat(response.getStatus()).isEqualTo(HttpStatus.SC_NOT_FOUND);
422 public void getResourceByIdExceptionDuringSearchingTest() {
423 String resourceId = RESOURCE_ID;
424 Map<String,String> parametersMap = new HashMap<>();
425 parametersMap.put(RESOURCE_ID, resourceId);
427 String formatEndpoint = "/v1/catalog/resources/{resourceId}";
428 String path = StrSubstitutor.replace(formatEndpoint, parametersMap, "{","}");
430 given(resourceBusinessLogic.getResource(eq(resourceId.toLowerCase()), any(User.class)))
431 .willAnswer( invocation -> { throw new IOException("Test exception: getResourceById"); });
433 Response response = target()
436 .accept(MediaType.APPLICATION_JSON)
437 .header(Constants.USER_ID_HEADER, user.getUserId())
440 assertThat(response.getStatus()).isEqualTo(HttpStatus.SC_INTERNAL_SERVER_ERROR);
444 public void getResourceByIdTest() {
445 String resourceId = RESOURCE_ID;
446 Map<String,String> parametersMap = new HashMap<>();
447 parametersMap.put(RESOURCE_ID, resourceId);
449 String formatEndpoint = "/v1/catalog/resources/{resourceId}";
450 String path = StrSubstitutor.replace(formatEndpoint, parametersMap, "{","}");
452 Either<Resource, ResponseFormat> getResourceByIdEither = Either.left(new Resource());
453 when(resourceBusinessLogic.getResource(eq(resourceId.toLowerCase()), any(User.class)))
454 .thenReturn(getResourceByIdEither);
456 Response response = target()
459 .accept(MediaType.APPLICATION_JSON)
460 .header(Constants.USER_ID_HEADER, user.getUserId())
463 assertThat(response.getStatus()).isEqualTo(HttpStatus.SC_OK);
467 public void getResourceByNameAndVersionTryGetNonExistingResourceTest() {
468 String resourceName = RESOURCE_NAME;
469 String resourceVersion = RESOURCE_VERSION;
470 Map<String,String> parametersMap = new HashMap<>();
471 parametersMap.put(RESOURCE_NAME, resourceName);
472 parametersMap.put(RESOURCE_VERSION, resourceVersion);
474 String formatEndpoint = "/v1/catalog/resources/resourceName/{resourceName}/resourceVersion/{resourceVersion}";
475 String path = StrSubstitutor.replace(formatEndpoint, parametersMap, "{","}");
477 Either<Resource, ResponseFormat> getResourceByNameAndVersionEither = Either.right(notFoundResponseFormat);
478 when(resourceBusinessLogic.getResourceByNameAndVersion(eq(resourceName), eq(resourceVersion), eq(user.getUserId())))
479 .thenReturn(getResourceByNameAndVersionEither);
481 Response response = target()
484 .accept(MediaType.APPLICATION_JSON)
485 .header(Constants.USER_ID_HEADER, user.getUserId())
488 assertThat(response.getStatus()).isEqualTo(HttpStatus.SC_NOT_FOUND);
492 public void getResourceByNameAndVersionExceptionDuringSearchingTest() {
493 String resourceName = RESOURCE_NAME;
494 String resourceVersion = RESOURCE_VERSION;
495 Map<String,String> parametersMap = new HashMap<>();
496 parametersMap.put(RESOURCE_NAME, resourceName);
497 parametersMap.put(RESOURCE_VERSION, resourceVersion);
499 String formatEndpoint = "/v1/catalog/resources/resourceName/{resourceName}/resourceVersion/{resourceVersion}";
500 String path = StrSubstitutor.replace(formatEndpoint, parametersMap, "{","}");
502 given(resourceBusinessLogic.getResourceByNameAndVersion(eq(resourceName), eq(resourceVersion), eq(user.getUserId())))
503 .willAnswer( invocation -> { throw new IOException("Test exception: getResourceByNameAndVersion"); });
505 Response response = target()
508 .accept(MediaType.APPLICATION_JSON)
509 .header(Constants.USER_ID_HEADER, user.getUserId())
512 assertThat(response.getStatus()).isEqualTo(HttpStatus.SC_INTERNAL_SERVER_ERROR);
516 public void getResourceByNameAndVersionTest() {
517 String resourceName = RESOURCE_NAME;
518 String resourceVersion = RESOURCE_VERSION;
519 Map<String,String> parametersMap = new HashMap<>();
520 parametersMap.put(RESOURCE_NAME, resourceName);
521 parametersMap.put(RESOURCE_VERSION, resourceVersion);
523 String formatEndpoint = "/v1/catalog/resources/resourceName/{resourceName}/resourceVersion/{resourceVersion}";
524 String path = StrSubstitutor.replace(formatEndpoint, parametersMap, "{","}");
526 Either<Resource, ResponseFormat> getResourceByNameAndVersionEither = Either.left(new Resource());
527 when(resourceBusinessLogic.getResourceByNameAndVersion(eq(resourceName), eq(resourceVersion), eq(user.getUserId())))
528 .thenReturn(getResourceByNameAndVersionEither);
530 Response response = target()
533 .accept(MediaType.APPLICATION_JSON)
534 .header(Constants.USER_ID_HEADER, user.getUserId())
537 assertThat(response.getStatus()).isEqualTo(HttpStatus.SC_OK);
541 public void validateResourceNameTryValidateNonExistingResourceTest() {
542 String resourceName = RESOURCE_NAME;
543 String resourceType = "VFC";
544 Map<String,String> parametersMap = new HashMap<>();
545 parametersMap.put(RESOURCE_NAME, resourceName);
547 String formatEndpoint = "/v1/catalog/resources/validate-name/{resourceName}";
548 String path = StrSubstitutor.replace(formatEndpoint, parametersMap, "{","}");
550 Either<Map<String, Boolean>, ResponseFormat> validateResourceNameEither =
551 Either.right(notFoundResponseFormat);
552 ResourceTypeEnum resourceTypeEnum = ResourceTypeEnum.valueOf(resourceType);
553 when(resourceBusinessLogic.validateResourceNameExists(eq(resourceName), eq(resourceTypeEnum), eq(user.getUserId())))
554 .thenReturn(validateResourceNameEither);
556 Response response = target()
558 .queryParam(SUBTYPE, resourceType)
560 .accept(MediaType.APPLICATION_JSON)
561 .header(Constants.USER_ID_HEADER, user.getUserId())
564 assertThat(response.getStatus()).isEqualTo(HttpStatus.SC_NOT_FOUND);
568 public void validateResourceNameInvalidContentTest() {
569 String resourceName = RESOURCE_NAME;
570 String resourceType = "ThisIsInvalid";
571 Map<String,String> parametersMap = new HashMap<>();
572 parametersMap.put(RESOURCE_NAME, resourceName);
574 String formatEndpoint = "/v1/catalog/resources/validate-name/{resourceName}";
575 String path = StrSubstitutor.replace(formatEndpoint, parametersMap, "{","}");
577 Response response = target()
579 .queryParam(SUBTYPE, resourceType)
581 .accept(MediaType.APPLICATION_JSON)
582 .header(Constants.USER_ID_HEADER, user.getUserId())
585 assertThat(response.getStatus()).isEqualTo(HttpStatus.SC_BAD_REQUEST);
589 public void validateResourceNameTest() {
590 String resourceName = RESOURCE_NAME;
591 String resourceType = "VFC";
592 Map<String,String> parametersMap = new HashMap<>();
593 parametersMap.put(RESOURCE_NAME, resourceName);
595 String formatEndpoint = "/v1/catalog/resources/validate-name/{resourceName}";
596 String path = StrSubstitutor.replace(formatEndpoint, parametersMap, "{","}");
598 Either<Map<String, Boolean>, ResponseFormat> validateResourceNameEither =
599 Either.left(new HashMap<>());
600 ResourceTypeEnum resourceTypeEnum = ResourceTypeEnum.valueOf(resourceType);
601 when(resourceBusinessLogic.validateResourceNameExists(eq(resourceName), eq(resourceTypeEnum), eq(user.getUserId())))
602 .thenReturn(validateResourceNameEither);
604 Response response = target()
606 .queryParam(SUBTYPE, resourceType)
608 .accept(MediaType.APPLICATION_JSON)
609 .header(Constants.USER_ID_HEADER, user.getUserId())
612 assertThat(response.getStatus()).isEqualTo(HttpStatus.SC_OK);
616 public void getCertifiedAbstractResourcesExceptionDuringSearchingTest() {
617 String path = "/v1/catalog/resources/certified/abstract";
618 given(resourceBusinessLogic.getAllCertifiedResources(eq(true), eq(HighestFilterEnum.HIGHEST_ONLY),
619 eq(user.getUserId())))
620 .willAnswer( invocation -> { throw new IOException("Test exception: getCertifiedAbstractResources"); });
622 Response response = target()
625 .accept(MediaType.APPLICATION_JSON)
626 .header(Constants.USER_ID_HEADER, user.getUserId())
629 assertThat(response.getStatus()).isEqualTo(HttpStatus.SC_INTERNAL_SERVER_ERROR);
633 public void getCertifiedAbstractResourcesTest() {
634 String path = "/v1/catalog/resources/certified/abstract";
636 List<Resource> resources = Arrays.asList(new Resource(), new Resource());
637 when(resourceBusinessLogic.getAllCertifiedResources(eq(true), eq(HighestFilterEnum.HIGHEST_ONLY),
638 eq(user.getUserId())))
639 .thenReturn(resources);
641 Response response = target()
644 .accept(MediaType.APPLICATION_JSON)
645 .header(Constants.USER_ID_HEADER, user.getUserId())
648 assertThat(response.getStatus()).isEqualTo(HttpStatus.SC_OK);
652 public void getCertifiedNotAbstractResourcesExceptionDuringSearchingTest() {
653 String path = "/v1/catalog/resources/certified/notabstract";
654 given(resourceBusinessLogic.getAllCertifiedResources(eq(false), eq(HighestFilterEnum.ALL),
655 eq(user.getUserId())))
656 .willAnswer( invocation -> { throw new IOException("Test exception: getCertifiedNotAbstractResources"); });
658 Response response = target()
661 .accept(MediaType.APPLICATION_JSON)
662 .header(Constants.USER_ID_HEADER, user.getUserId())
665 assertThat(response.getStatus()).isEqualTo(HttpStatus.SC_INTERNAL_SERVER_ERROR);
669 public void getCertifiedNotAbstractResourcesTest() {
670 String path = "/v1/catalog/resources/certified/notabstract";
672 List<Resource> resources = Arrays.asList(new Resource(), new Resource());
673 when(resourceBusinessLogic.getAllCertifiedResources(eq(true), eq(HighestFilterEnum.ALL),
674 eq(user.getUserId())))
675 .thenReturn(resources);
677 Response response = target()
680 .accept(MediaType.APPLICATION_JSON)
681 .header(Constants.USER_ID_HEADER, user.getUserId())
684 assertThat(response.getStatus()).isEqualTo(HttpStatus.SC_OK);
688 public void updateResourceMetadataTryUpdateNonExistingResourceTest() {
689 String resourceId = RESOURCE_ID;
690 Map<String,String> parametersMap = new HashMap<>();
691 parametersMap.put(RESOURCE_ID, resourceId);
693 String formatEndpoint = "/v1/catalog/resources/{resourceId}/metadata";
694 String path = StrSubstitutor.replace(formatEndpoint, parametersMap, "{","}");
696 Either<Resource, ResponseFormat> updateResourceMetadataEither = Either.right(badRequestResponseFormat);
698 when(componentUtils.convertJsonToObjectUsingObjectMapper(any(), any(), eq(Resource.class),
699 eq(AuditingActionEnum.UPDATE_RESOURCE_METADATA), eq(ComponentTypeEnum.RESOURCE)))
700 .thenReturn(updateResourceMetadataEither);
702 when(resourceBusinessLogic.updateResourceMetadata(eq(resourceId.toLowerCase()), any(), any(), any(User.class),
704 .thenReturn(new Resource());
706 Response response = target()
709 .accept(MediaType.APPLICATION_JSON)
710 .header(Constants.USER_ID_HEADER, user.getUserId())
711 .put(Entity.json(EMPTY_JSON));
713 assertThat(response.getStatus()).isEqualTo(HttpStatus.SC_BAD_REQUEST);
717 public void updateResourceMetadataExceptionDuringUpdateTest() {
718 String resourceId = RESOURCE_ID;
719 Map<String,String> parametersMap = new HashMap<>();
720 parametersMap.put(RESOURCE_ID, resourceId);
722 String formatEndpoint = "/v1/catalog/resources/{resourceId}/metadata";
723 String path = StrSubstitutor.replace(formatEndpoint, parametersMap, "{","}");
725 given(componentUtils.convertJsonToObjectUsingObjectMapper(any(), any(), eq(Resource.class),
726 eq(AuditingActionEnum.UPDATE_RESOURCE_METADATA), eq(ComponentTypeEnum.RESOURCE)))
727 .willAnswer( invocation -> { throw new IOException("Test exception: updateResourceMetadata"); });
729 Response response = target()
732 .accept(MediaType.APPLICATION_JSON)
733 .header(Constants.USER_ID_HEADER, user.getUserId())
734 .put(Entity.json(EMPTY_JSON));
736 assertThat(response.getStatus()).isEqualTo(HttpStatus.SC_INTERNAL_SERVER_ERROR);
740 public void updateResourceMetadataCategoryTest() {
741 String resourceId = RESOURCE_ID;
742 Map<String,String> parametersMap = new HashMap<>();
743 parametersMap.put(RESOURCE_ID, resourceId);
745 String formatEndpoint = "/v1/catalog/resources/{resourceId}/metadata";
746 String path = StrSubstitutor.replace(formatEndpoint, parametersMap, "{","}");
748 Resource initialResource = new Resource();
749 Either<Resource, ResponseFormat> updateResourceMetadataEither = Either.left(initialResource);
751 when(componentUtils.convertJsonToObjectUsingObjectMapper(any(), any(), eq(Resource.class),
752 eq(AuditingActionEnum.UPDATE_RESOURCE_METADATA), eq(ComponentTypeEnum.RESOURCE)))
753 .thenReturn(updateResourceMetadataEither);
755 when(resourceBusinessLogic.updateResourceMetadata(eq(resourceId.toLowerCase()), eq(initialResource), any(),
756 any(User.class), eq(false)))
757 .thenReturn(new Resource());
759 Response response = target()
762 .accept(MediaType.APPLICATION_JSON)
763 .header(Constants.USER_ID_HEADER, user.getUserId())
764 .put(Entity.json(EMPTY_JSON));
766 assertThat(response.getStatus()).isEqualTo(HttpStatus.SC_OK);
770 public void updateResourceParsingUncussessfulTest() {
771 String resourceId = RESOURCE_ID;
772 Map<String,String> parametersMap = new HashMap<>();
773 parametersMap.put(RESOURCE_ID, resourceId);
775 String formatEndpoint = "/v1/catalog/resources/{resourceId}";
776 String path = StrSubstitutor.replace(formatEndpoint, parametersMap, "{","}");
778 Either<Resource, ResponseFormat> updateResourceEither = Either.right(badRequestResponseFormat);
780 when(componentUtils.convertJsonToObjectUsingObjectMapper(eq(NON_UI_IMPORT_JSON), any(User.class),
781 eq(Resource.class), eq(AuditingActionEnum.UPDATE_RESOURCE_METADATA), eq(ComponentTypeEnum.RESOURCE)))
782 .thenReturn(updateResourceEither);
784 Response response = target()
787 .accept(MediaType.APPLICATION_JSON)
788 .header(Constants.USER_ID_HEADER, user.getUserId())
789 .put(Entity.json(NON_UI_IMPORT_JSON));
791 assertThat(response.getStatus()).isEqualTo(HttpStatus.SC_BAD_REQUEST);
795 public void updateResourceExceptionDuringUpdateTest() {
796 String resourceId = RESOURCE_ID;
797 Map<String,String> parametersMap = new HashMap<>();
798 parametersMap.put(RESOURCE_ID, resourceId);
800 String formatEndpoint = "/v1/catalog/resources/{resourceId}";
801 String path = StrSubstitutor.replace(formatEndpoint, parametersMap, "{","}");
803 given(componentUtils.convertJsonToObjectUsingObjectMapper(eq(NON_UI_IMPORT_JSON), any(User.class),
804 eq(Resource.class), eq(AuditingActionEnum.UPDATE_RESOURCE_METADATA), eq(ComponentTypeEnum.RESOURCE)))
805 .willAnswer( invocation -> { throw new IOException("Test exception: updateResource"); });
807 Response response = target()
810 .accept(MediaType.APPLICATION_JSON)
811 .header(Constants.USER_ID_HEADER, user.getUserId())
812 .put(Entity.json(NON_UI_IMPORT_JSON));
814 assertThat(response.getStatus()).isEqualTo(HttpStatus.SC_INTERNAL_SERVER_ERROR);
818 public void updateResourceNonUiImportTest() {
819 String resourceId = RESOURCE_ID;
820 Map<String,String> parametersMap = new HashMap<>();
821 parametersMap.put(RESOURCE_ID, resourceId);
823 String formatEndpoint = "/v1/catalog/resources/{resourceId}";
824 String path = StrSubstitutor.replace(formatEndpoint, parametersMap, "{","}");
826 Either<Resource, ResponseFormat> updateResourceEither = Either.left(new Resource());
828 when(componentUtils.convertJsonToObjectUsingObjectMapper(eq(NON_UI_IMPORT_JSON), any(User.class), eq(Resource.class),
829 eq(AuditingActionEnum.UPDATE_RESOURCE_METADATA), eq(ComponentTypeEnum.RESOURCE)))
830 .thenReturn(updateResourceEither);
832 when(resourceBusinessLogic.validateAndUpdateResourceFromCsar(any(), any(), any(), any(), eq(resourceId)))
833 .thenReturn(new Resource());
835 Response response = target()
838 .accept(MediaType.APPLICATION_JSON)
839 .header(Constants.USER_ID_HEADER, user.getUserId())
840 .put(Entity.json(NON_UI_IMPORT_JSON));
842 assertThat(response.getStatus()).isEqualTo(HttpStatus.SC_OK);
846 public void getResourceFromCsarTryGetNonExistingResourceTest() {
847 String csarUuid = CSAR_UUID;
848 Map<String,String> parametersMap = new HashMap<>();
849 parametersMap.put(CSAR_UUID, csarUuid);
851 String formatEndpoint = "/v1/catalog/resources/csar/{csaruuid}";
852 String path = StrSubstitutor.replace(formatEndpoint, parametersMap, "{","}");
854 Either<Resource, ResponseFormat> getResourceFromCsarEither = Either.right(notFoundResponseFormat);
855 when(resourceBusinessLogic.getLatestResourceFromCsarUuid(eq(csarUuid), any(User.class)))
856 .thenReturn(getResourceFromCsarEither);
858 Response response = target()
861 .accept(MediaType.APPLICATION_JSON)
862 .header(Constants.USER_ID_HEADER, user.getUserId())
865 assertThat(response.getStatus()).isEqualTo(HttpStatus.SC_BAD_REQUEST);
869 public void getResourceFromCsarExceptionDuringGettingTest() {
870 String csarUuid = CSAR_UUID;
871 Map<String,String> parametersMap = new HashMap<>();
872 parametersMap.put(CSAR_UUID, csarUuid);
874 String formatEndpoint = "/v1/catalog/resources/csar/{csaruuid}";
875 String path = StrSubstitutor.replace(formatEndpoint, parametersMap, "{","}");
877 given(resourceBusinessLogic.getLatestResourceFromCsarUuid(eq(csarUuid), any(User.class)))
878 .willAnswer( invocation -> { throw new IOException("Test exception: getResourceFromCsar"); });
880 Response response = target()
883 .accept(MediaType.APPLICATION_JSON)
884 .header(Constants.USER_ID_HEADER, user.getUserId())
887 assertThat(response.getStatus()).isEqualTo(HttpStatus.SC_INTERNAL_SERVER_ERROR);
891 public void getResourceFromCsarTest() {
892 String csarUuid = CSAR_UUID;
893 Map<String,String> parametersMap = new HashMap<>();
894 parametersMap.put(CSAR_UUID, csarUuid);
896 String formatEndpoint = "/v1/catalog/resources/csar/{csaruuid}";
897 String path = StrSubstitutor.replace(formatEndpoint, parametersMap, "{","}");
899 Either<Resource, ResponseFormat> getResourceFromCsarEither = Either.left(new Resource());
900 when(resourceBusinessLogic.getLatestResourceFromCsarUuid(eq(csarUuid), any(User.class)))
901 .thenReturn(getResourceFromCsarEither);
903 Response response = target()
906 .accept(MediaType.APPLICATION_JSON)
907 .header(Constants.USER_ID_HEADER, user.getUserId())
910 assertThat(response.getStatus()).isEqualTo(HttpStatus.SC_OK);
914 public void createResourceExceptionDuringCreateTest() {
915 String path = "/v1/catalog/resources";
917 given(componentUtils.convertJsonToObjectUsingObjectMapper(eq(NON_UI_IMPORT_JSON), any(User.class),
918 eq(Resource.class), eq(AuditingActionEnum.CREATE_RESOURCE), eq(ComponentTypeEnum.RESOURCE)))
919 .willAnswer( invocation -> { throw new IOException("Test exception: createResource"); });
921 Response response = target()
924 .accept(MediaType.APPLICATION_JSON)
925 .header(Constants.USER_ID_HEADER, user.getUserId())
926 .post(Entity.json(NON_UI_IMPORT_JSON));
928 assertThat(response.getStatus()).isEqualTo(HttpStatus.SC_INTERNAL_SERVER_ERROR);
932 public void createResourceNonUiImportProcessingFailedTest() {
933 String path = "/v1/catalog/resources";
935 Either<Resource, ResponseFormat> createResourceEither = Either.right(badRequestResponseFormat);
937 when(componentUtils.convertJsonToObjectUsingObjectMapper(eq(NON_UI_IMPORT_JSON), any(User.class),
938 eq(Resource.class), eq(AuditingActionEnum.CREATE_RESOURCE), eq(ComponentTypeEnum.RESOURCE)))
939 .thenReturn(createResourceEither);
941 Response response = target()
944 .accept(MediaType.APPLICATION_JSON)
945 .header(Constants.USER_ID_HEADER, user.getUserId())
946 .post(Entity.json(NON_UI_IMPORT_JSON));
948 assertThat(response.getStatus()).isEqualTo(HttpStatus.SC_BAD_REQUEST);
952 public void createResourceNonUiImportTest() {
953 String path = "/v1/catalog/resources";
955 Either<Resource, ResponseFormat> createResourceEither = Either.left(new Resource());
957 when(componentUtils.convertJsonToObjectUsingObjectMapper(eq(NON_UI_IMPORT_JSON), any(User.class),
958 eq(Resource.class), eq(AuditingActionEnum.CREATE_RESOURCE), eq(ComponentTypeEnum.RESOURCE)))
959 .thenReturn(createResourceEither);
961 when(resourceBusinessLogic.createResource(eq(createResourceEither.left().value()), eq(AuditingActionEnum.CREATE_RESOURCE),
962 any(User.class), any(), any()))
963 .thenReturn(new Resource());
965 Response response = target()
968 .accept(MediaType.APPLICATION_JSON)
969 .header(Constants.USER_ID_HEADER, user.getUserId())
970 .post(Entity.json(NON_UI_IMPORT_JSON));
972 assertThat(response.getStatus()).isEqualTo(HttpStatus.SC_CREATED);
975 private void encodeAndSetPayload(UploadResourceInfo mdJson, String payload) {
976 byte[] encodedBase64Payload = Base64.encodeBase64(payload.getBytes());
977 mdJson.setPayloadData(new String(encodedBase64Payload));
980 private void runAndVerifyActionStatusError(UploadResourceInfo mdJson, ActionStatus invalidResourcePayload) {
981 setMD5OnRequest(true, mdJson);
982 Response response = target().path("/v1/catalog/resources").request(MediaType.APPLICATION_JSON).post(Entity.json(gson.toJson(mdJson)), Response.class);
983 Mockito.verify(componentUtils, Mockito.times(1)).getResponseFormat(Mockito.any(ActionStatus.class));
984 Mockito.verify(componentUtils, Mockito.times(1)).getResponseFormat(invalidResourcePayload);
985 assertEquals(response.getStatus(), HttpStatus.SC_INTERNAL_SERVER_ERROR);
988 private void setMD5OnRequest(boolean isValid, UploadResourceInfo json) {
989 String md5 = (isValid) ? GeneralUtility.calculateMD5Base64EncodedByString(gson.toJson(json)) : "stam=";
990 when(request.getHeader(Constants.MD5_HEADER)).thenReturn(md5);
994 private UploadResourceInfo buildValidJson() {
995 UploadResourceInfo ret = new UploadResourceInfo();
996 ret.setName("ciMyCompute");
997 ret.setPayloadName("ciMyCompute.yml");
998 ret.addSubCategory("Application Layer 4+", "Application Servers");
999 ret.setDescription("ResourceDescription");
1000 ret.setVendorName("VendorName");
1001 ret.setVendorRelease("VendorRelease");
1002 ret.setContactId("AT1234");
1003 ret.setIcon("router");
1004 ret.setTags(Collections.singletonList("ciMyCompute"));
1006 "dG9zY2FfZGVmaW5pdGlvbnNfdmVyc2lvbjogdG9zY2Ffc2ltcGxlX3lhbWxfMV8wXzANCm5vZGVfdHlwZXM6IA0KICBvcmcub3BlbmVjb21wLnJlc291cmNlLk15Q29tcHV0ZToNCiAgICBkZXJpdmVkX2Zyb206IHRvc2NhLm5vZGVzLlJvb3QNCiAgICBhdHRyaWJ1dGVzOg0KICAgICAgcHJpdmF0ZV9hZGRyZXNzOg0KICAgICAgICB0eXBlOiBzdHJpbmcNCiAgICAgIHB1YmxpY19hZGRyZXNzOg0KICAgICAgICB0eXBlOiBzdHJpbmcNCiAgICAgIG5ldHdvcmtzOg0KICAgICAgICB0eXBlOiBtYXANCiAgICAgICAgZW50cnlfc2NoZW1hOg0KICAgICAgICAgIHR5cGU6IHRvc2NhLmRhdGF0eXBlcy5uZXR3b3JrLk5ldHdvcmtJbmZvDQogICAgICBwb3J0czoNCiAgICAgICAgdHlwZTogbWFwDQogICAgICAgIGVudHJ5X3NjaGVtYToNCiAgICAgICAgICB0eXBlOiB0b3NjYS5kYXRhdHlwZXMubmV0d29yay5Qb3J0SW5mbw0KICAgIHJlcXVpcmVtZW50czoNCiAgICAgIC0gbG9jYWxfc3RvcmFnZTogDQogICAgICAgICAgY2FwYWJpbGl0eTogdG9zY2EuY2FwYWJpbGl0aWVzLkF0dGFjaG1lbnQNCiAgICAgICAgICBub2RlOiB0b3NjYS5ub2Rlcy5CbG9ja1N0b3JhZ2UNCiAgICAgICAgICByZWxhdGlvbnNoaXA6IHRvc2NhLnJlbGF0aW9uc2hpcHMuQXR0YWNoZXNUbw0KICAgICAgICAgIG9jY3VycmVuY2VzOiBbMCwgVU5CT1VOREVEXSAgDQogICAgY2FwYWJpbGl0aWVzOg0KICAgICAgaG9zdDogDQogICAgICAgIHR5cGU6IHRvc2NhLmNhcGFiaWxpdGllcy5Db250YWluZXINCiAgICAgICAgdmFsaWRfc291cmNlX3R5cGVzOiBbdG9zY2Eubm9kZXMuU29mdHdhcmVDb21wb25lbnRdIA0KICAgICAgZW5kcG9pbnQgOg0KICAgICAgICB0eXBlOiB0b3NjYS5jYXBhYmlsaXRpZXMuRW5kcG9pbnQuQWRtaW4gDQogICAgICBvczogDQogICAgICAgIHR5cGU6IHRvc2NhLmNhcGFiaWxpdGllcy5PcGVyYXRpbmdTeXN0ZW0NCiAgICAgIHNjYWxhYmxlOg0KICAgICAgICB0eXBlOiB0b3NjYS5jYXBhYmlsaXRpZXMuU2NhbGFibGUNCiAgICAgIGJpbmRpbmc6DQogICAgICAgIHR5cGU6IHRvc2NhLmNhcGFiaWxpdGllcy5uZXR3b3JrLkJpbmRhYmxl");
1011 protected Application configure() {
1012 ApplicationContext context = new AnnotationConfigApplicationContext(SpringConfig.class);
1013 forceSet(TestProperties.CONTAINER_PORT, "0");
1014 return new ResourceConfig(ResourcesServlet.class)
1015 .register(new AbstractBinder() {
1017 protected void configure() {
1018 bind(request).to(HttpServletRequest.class);
1019 bind(servletUtils).to(ServletUtils.class);
1020 bind(componentUtils).to(ComponentsUtils.class);
1021 bind(userBusinessLogic).to(UserBusinessLogic.class);
1022 bind(resourceBusinessLogic).to(ResourceBusinessLogic.class);
1023 bind(groupBL).to(GroupBusinessLogic.class);
1024 bind(componentInstanceBL).to(ComponentInstanceBusinessLogic.class);
1025 bind(resourceImportManager).to(ResourceImportManager.class);
1028 .property("contextConfig", context);