Support for adding artifact types
[sdc.git] / catalog-be / src / main / java / org / openecomp / sdc / be / servlets / TypesFetchServlet.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 package org.openecomp.sdc.be.servlets;
21
22 import com.jcabi.aspects.Loggable;
23 import fj.data.Either;
24 import io.swagger.v3.oas.annotations.Operation;
25 import io.swagger.v3.oas.annotations.Parameter;
26 import io.swagger.v3.oas.annotations.media.ArraySchema;
27 import io.swagger.v3.oas.annotations.media.Content;
28 import io.swagger.v3.oas.annotations.media.Schema;
29 import io.swagger.v3.oas.annotations.responses.ApiResponse;
30 import io.swagger.v3.oas.annotations.servers.Server;
31 import io.swagger.v3.oas.annotations.servers.Servers;
32 import io.swagger.v3.oas.annotations.tags.Tag;
33 import io.swagger.v3.oas.annotations.tags.Tags;
34 import java.util.HashMap;
35 import java.util.List;
36 import java.util.Map;
37 import java.util.stream.Collectors;
38 import javax.inject.Inject;
39 import javax.servlet.ServletContext;
40 import javax.servlet.http.HttpServletRequest;
41 import javax.ws.rs.Consumes;
42 import javax.ws.rs.GET;
43 import javax.ws.rs.HeaderParam;
44 import javax.ws.rs.Path;
45 import javax.ws.rs.Produces;
46 import javax.ws.rs.QueryParam;
47 import javax.ws.rs.core.Context;
48 import javax.ws.rs.core.MediaType;
49 import javax.ws.rs.core.Response;
50 import org.apache.commons.collections4.ListUtils;
51 import org.openecomp.sdc.be.components.impl.ArtifactsBusinessLogic;
52 import org.openecomp.sdc.be.components.impl.CapabilitiesBusinessLogic;
53 import org.openecomp.sdc.be.components.impl.ComponentBusinessLogic;
54 import org.openecomp.sdc.be.components.impl.ComponentInstanceBusinessLogic;
55 import org.openecomp.sdc.be.components.impl.InterfaceOperationBusinessLogic;
56 import org.openecomp.sdc.be.components.impl.PropertyBusinessLogic;
57 import org.openecomp.sdc.be.components.impl.RelationshipTypeBusinessLogic;
58 import org.openecomp.sdc.be.components.impl.ResourceBusinessLogic;
59 import org.openecomp.sdc.be.components.impl.ResourceImportManager;
60 import org.openecomp.sdc.be.components.impl.aaf.AafPermission;
61 import org.openecomp.sdc.be.components.impl.aaf.PermissionAllowed;
62 import org.openecomp.sdc.be.config.BeEcompErrorManager;
63 import org.openecomp.sdc.be.dao.api.ActionStatus;
64 import org.openecomp.sdc.be.datamodel.api.HighestFilterEnum;
65 import org.openecomp.sdc.be.datatypes.components.ResourceMetadataDataDefinition;
66 import org.openecomp.sdc.be.datatypes.enums.ComponentTypeEnum;
67 import org.openecomp.sdc.be.exception.BusinessException;
68 import org.openecomp.sdc.be.impl.ComponentsUtils;
69 import org.openecomp.sdc.be.impl.ServletUtils;
70 import org.openecomp.sdc.be.model.CapabilityTypeDefinition;
71 import org.openecomp.sdc.be.model.Component;
72 import org.openecomp.sdc.be.model.DataTypeDefinition;
73 import org.openecomp.sdc.be.model.InterfaceDefinition;
74 import org.openecomp.sdc.be.model.RelationshipTypeDefinition;
75 import org.openecomp.sdc.be.model.User;
76 import org.openecomp.sdc.be.user.UserBusinessLogic;
77 import org.openecomp.sdc.common.api.Constants;
78 import org.openecomp.sdc.common.datastructure.Wrapper;
79 import org.openecomp.sdc.common.log.enums.EcompLoggerErrorCode;
80 import org.openecomp.sdc.common.log.wrappers.Logger;
81 import org.openecomp.sdc.common.util.ValidationUtils;
82 import org.openecomp.sdc.exception.ResponseFormat;
83 import org.springframework.stereotype.Controller;
84
85 @Loggable(prepend = true, value = Loggable.DEBUG, trim = false)
86 @Path("/v1/catalog")
87 @Tags({@Tag(name = "SDCE-2 APIs")})
88 @Servers({@Server(url = "/sdc2/rest")})
89 @Controller
90 public class TypesFetchServlet extends AbstractValidationsServlet {
91
92     private static final Logger log = Logger.getLogger(TypesFetchServlet.class);
93     private static final String FAILED_TO_GET_ALL_NON_ABSTRACT = "failed to get all non abstract {}";
94     private final PropertyBusinessLogic propertyBusinessLogic;
95     private final RelationshipTypeBusinessLogic relationshipTypeBusinessLogic;
96     private final CapabilitiesBusinessLogic capabilitiesBusinessLogic;
97     private final InterfaceOperationBusinessLogic interfaceOperationBusinessLogic;
98     private final ResourceBusinessLogic resourceBusinessLogic;
99     private final ArtifactsBusinessLogic artifactsBusinessLogic;
100
101     @Inject
102     public TypesFetchServlet(UserBusinessLogic userBusinessLogic, ComponentInstanceBusinessLogic componentInstanceBL, ComponentsUtils componentsUtils,
103                              ServletUtils servletUtils, ResourceImportManager resourceImportManager, PropertyBusinessLogic propertyBusinessLogic,
104                              RelationshipTypeBusinessLogic relationshipTypeBusinessLogic, CapabilitiesBusinessLogic capabilitiesBusinessLogic,
105                              InterfaceOperationBusinessLogic interfaceOperationBusinessLogic, ResourceBusinessLogic resourceBusinessLogic,
106                              ArtifactsBusinessLogic artifactsBusinessLogic) {
107         super(userBusinessLogic, componentInstanceBL, componentsUtils, servletUtils, resourceImportManager);
108         this.propertyBusinessLogic = propertyBusinessLogic;
109         this.relationshipTypeBusinessLogic = relationshipTypeBusinessLogic;
110         this.capabilitiesBusinessLogic = capabilitiesBusinessLogic;
111         this.interfaceOperationBusinessLogic = interfaceOperationBusinessLogic;
112         this.resourceBusinessLogic = resourceBusinessLogic;
113         this.artifactsBusinessLogic = artifactsBusinessLogic;
114     }
115
116     @GET
117     @Path("dataTypes")
118     @Consumes(MediaType.APPLICATION_JSON)
119     @Produces(MediaType.APPLICATION_JSON)
120     @Operation(description = "Get data types", method = "GET", summary = "Returns data types", responses = {
121         @ApiResponse(content = @Content(array = @ArraySchema(schema = @Schema(implementation = Response.class)))),
122         @ApiResponse(responseCode = "200", description = "datatypes"), @ApiResponse(responseCode = "403", description = "Restricted operation"),
123         @ApiResponse(responseCode = "400", description = "Invalid content / Missing content"),
124         @ApiResponse(responseCode = "404", description = "Data types not found")})
125     @PermissionAllowed(AafPermission.PermNames.INTERNAL_ALL_VALUE)
126     public Response getAllDataTypesServlet(@Context final HttpServletRequest request, @HeaderParam(value = Constants.USER_ID_HEADER) String userId,
127                                            @Parameter(description = "model") @QueryParam("model") String modelName) {
128         Wrapper<Response> responseWrapper = new Wrapper<>();
129         Wrapper<User> userWrapper = new Wrapper<>();
130         init();
131         validateUserExist(responseWrapper, userWrapper, userId);
132         if (responseWrapper.isEmpty()) {
133             String url = request.getMethod() + " " + request.getRequestURI();
134             log.debug("Start handle request of {} - modifier id is {}", url, userId);
135             final Map<String, DataTypeDefinition> dataTypes = resourceBusinessLogic.getComponentsUtils()
136                 .getAllDataTypes(resourceBusinessLogic.getApplicationDataTypeCache(), modelName);
137             String dataTypeJson = gson.toJson(dataTypes);
138             Response okResponse = buildOkResponse(getComponentsUtils().getResponseFormat(ActionStatus.OK), dataTypeJson);
139             responseWrapper.setInnerElement(okResponse);
140         }
141         return responseWrapper.getInnerElement();
142     }
143
144     @GET
145     @Path("interfaceLifecycleTypes")
146     @Consumes(MediaType.APPLICATION_JSON)
147     @Produces(MediaType.APPLICATION_JSON)
148     @Operation(description = "Get interface lifecycle types", method = "GET", summary = "Returns interface lifecycle types", responses = {
149         @ApiResponse(content = @Content(array = @ArraySchema(schema = @Schema(implementation = Response.class)))),
150         @ApiResponse(responseCode = "200", description = "Interface lifecycle types"),
151         @ApiResponse(responseCode = "403", description = "Restricted operation"),
152         @ApiResponse(responseCode = "400", description = "Invalid content / Missing content"),
153         @ApiResponse(responseCode = "404", description = "Interface lifecycle types not found")})
154     @PermissionAllowed(AafPermission.PermNames.INTERNAL_ALL_VALUE)
155     public Response getInterfaceLifecycleTypes(@Context final HttpServletRequest request,
156                                                @HeaderParam(value = Constants.USER_ID_HEADER) String userId,
157                                                @Parameter(description = "model") @QueryParam("model") String modelName) {
158         Wrapper<Response> responseWrapper = new Wrapper<>();
159         Wrapper<User> userWrapper = new Wrapper<>();
160         try {
161             validateUserExist(responseWrapper, userWrapper, userId);
162             if (responseWrapper.isEmpty()) {
163                 String url = request.getMethod() + " " + request.getRequestURI();
164                 log.info("Start handle request of {} | modifier id is {}", url, userId);
165                 Either<Map<String, InterfaceDefinition>, ResponseFormat> allInterfaceLifecycleTypes = interfaceOperationBusinessLogic
166                     .getAllInterfaceLifecycleTypes(modelName);
167                 if (allInterfaceLifecycleTypes.isRight()) {
168                     log.info("Failed to get all interface lifecycle types. Reason - {}", allInterfaceLifecycleTypes.right().value());
169                     Response errorResponse = buildErrorResponse(allInterfaceLifecycleTypes.right().value());
170                     responseWrapper.setInnerElement(errorResponse);
171                 } else {
172                     String interfaceLifecycleTypeJson = gson.toJson(allInterfaceLifecycleTypes.left().value());
173                     Response okResponse = buildOkResponse(getComponentsUtils().getResponseFormat(ActionStatus.OK), interfaceLifecycleTypeJson);
174                     responseWrapper.setInnerElement(okResponse);
175                 }
176             }
177             return responseWrapper.getInnerElement();
178         } catch (Exception e) {
179             log.debug("get all interface lifecycle types failed with exception", e);
180             ResponseFormat responseFormat = getComponentsUtils().getResponseFormat(ActionStatus.GENERAL_ERROR);
181             return buildErrorResponse(responseFormat);
182         }
183     }
184
185     @GET
186     @Path("capabilityTypes")
187     @Consumes(MediaType.APPLICATION_JSON)
188     @Produces(MediaType.APPLICATION_JSON)
189     @Operation(description = "Get capability types", method = "GET", summary = "Returns capability types", responses = {
190         @ApiResponse(content = @Content(array = @ArraySchema(schema = @Schema(implementation = Response.class)))),
191         @ApiResponse(responseCode = "200", description = "capabilityTypes"), @ApiResponse(responseCode = "403", description = "Restricted operation"),
192         @ApiResponse(responseCode = "400", description = "Invalid content / Missing content"),
193         @ApiResponse(responseCode = "404", description = "Capability types not found")})
194     @PermissionAllowed(AafPermission.PermNames.INTERNAL_ALL_VALUE)
195     public Response getAllCapabilityTypesServlet(@Context final HttpServletRequest request,
196                                                  @HeaderParam(value = Constants.USER_ID_HEADER) String userId,
197                                                  @Parameter(description = "model", required = false) @QueryParam("model") String modelName) {
198         Wrapper<Response> responseWrapper = new Wrapper<>();
199         Wrapper<User> userWrapper = new Wrapper<>();
200         try {
201             init();
202             validateUserExist(responseWrapper, userWrapper, userId);
203             modelName = ValidationUtils.sanitizeInputString(modelName);
204             if (responseWrapper.isEmpty()) {
205                 String url = request.getMethod() + " " + request.getRequestURI();
206                 log.debug("Start handle request of {} | modifier id is {}", url, userId);
207                 Either<Map<String, CapabilityTypeDefinition>, ResponseFormat> allDataTypes = capabilitiesBusinessLogic.getAllCapabilityTypes(modelName);
208                 if (allDataTypes.isRight()) {
209                     log.info("Failed to get all capability types. Reason - {}", allDataTypes.right().value());
210                     Response errorResponse = buildErrorResponse(allDataTypes.right().value());
211                     responseWrapper.setInnerElement(errorResponse);
212                 } else {
213                     Map<String, CapabilityTypeDefinition> dataTypes = allDataTypes.left().value();
214                     String dataTypeJson = gson.toJson(dataTypes);
215                     Response okResponse = buildOkResponse(getComponentsUtils().getResponseFormat(ActionStatus.OK), dataTypeJson);
216                     responseWrapper.setInnerElement(okResponse);
217                 }
218             }
219             return responseWrapper.getInnerElement();
220         } catch (Exception e) {
221             BeEcompErrorManager.getInstance().logBeRestApiGeneralError("Get Capability Types");
222             log.debug("get all capability types failed with exception", e);
223             ResponseFormat responseFormat = getComponentsUtils().getResponseFormat(ActionStatus.GENERAL_ERROR);
224             return buildErrorResponse(responseFormat);
225         }
226     }
227
228     @GET
229     @Path("relationshipTypes")
230     @Consumes(MediaType.APPLICATION_JSON)
231     @Produces(MediaType.APPLICATION_JSON)
232     @Operation(description = "Get relationship types", method = "GET", summary = "Returns relationship types", responses = {
233         @ApiResponse(content = @Content(array = @ArraySchema(schema = @Schema(implementation = Response.class)))),
234         @ApiResponse(responseCode = "200", description = "relationshipTypes"),
235         @ApiResponse(responseCode = "403", description = "Restricted operation"),
236         @ApiResponse(responseCode = "400", description = "Invalid content / Missing content"),
237         @ApiResponse(responseCode = "404", description = "Relationship types not found")})
238     @PermissionAllowed(AafPermission.PermNames.INTERNAL_ALL_VALUE)
239     public Response getAllRelationshipTypesServlet(@Context final HttpServletRequest request,
240                                                    @HeaderParam(value = Constants.USER_ID_HEADER) String userId,
241                                                    @Parameter(description = "model", required = false) @QueryParam("model") String modelName) {
242         Wrapper<Response> responseWrapper = new Wrapper<>();
243         Wrapper<User> userWrapper = new Wrapper<>();
244         try {
245             init();
246             validateUserExist(responseWrapper, userWrapper, userId);
247             modelName = ValidationUtils.sanitizeInputString(modelName);
248             if (responseWrapper.isEmpty()) {
249                 String url = request.getMethod() + " " + request.getRequestURI();
250                 log.debug("Start handle request of {} | modifier id is {}", url, userId);
251                 Either<Map<String, RelationshipTypeDefinition>, ResponseFormat> allDataTypes = relationshipTypeBusinessLogic
252                     .getAllRelationshipTypes(modelName);
253                 if (allDataTypes.isRight()) {
254                     log.info("Failed to get all relationship types. Reason - {}", allDataTypes.right().value());
255                     Response errorResponse = buildErrorResponse(allDataTypes.right().value());
256                     responseWrapper.setInnerElement(errorResponse);
257                 } else {
258                     Map<String, RelationshipTypeDefinition> dataTypes = allDataTypes.left().value();
259                     String dataTypeJson = gson.toJson(dataTypes);
260                     Response okResponse = buildOkResponse(getComponentsUtils().getResponseFormat(ActionStatus.OK), dataTypeJson);
261                     responseWrapper.setInnerElement(okResponse);
262                 }
263             }
264             return responseWrapper.getInnerElement();
265         } catch (Exception e) {
266             BeEcompErrorManager.getInstance().logBeRestApiGeneralError("Get Relationship Types");
267             log.debug("get all relationship types failed with exception", e);
268             ResponseFormat responseFormat = getComponentsUtils().getResponseFormat(ActionStatus.GENERAL_ERROR);
269             return buildErrorResponse(responseFormat);
270         }
271     }
272
273     @GET
274     @Path("nodeTypes")
275     @Consumes(MediaType.APPLICATION_JSON)
276     @Produces(MediaType.APPLICATION_JSON)
277     @Operation(description = "Get node types", method = "GET", summary = "Returns node types", responses = {
278         @ApiResponse(content = @Content(array = @ArraySchema(schema = @Schema(implementation = Response.class)))),
279         @ApiResponse(responseCode = "200", description = "nodeTypes"), @ApiResponse(responseCode = "403", description = "Restricted operation"),
280         @ApiResponse(responseCode = "400", description = "Invalid content / Missing content"),
281         @ApiResponse(responseCode = "404", description = "Node types not found")})
282     @PermissionAllowed(AafPermission.PermNames.INTERNAL_ALL_VALUE)
283     public Response getAllNodeTypesServlet(@Context final HttpServletRequest request, @HeaderParam(value = Constants.USER_ID_HEADER) String userId) {
284         Wrapper<Response> responseWrapper = new Wrapper<>();
285         Wrapper<User> userWrapper = new Wrapper<>();
286         ServletContext context = request.getSession().getServletContext();
287         Either<Map<String, Component>, Response> response;
288         Map<String, Component> componentMap;
289         try {
290             init();
291             validateUserExist(responseWrapper, userWrapper, userId);
292             if (responseWrapper.isEmpty()) {
293                 String url = request.getMethod() + " " + request.getRequestURI();
294                 log.debug("Start handle request of {} | modifier id is {}", url, userId);
295                 response = getComponent(resourceBusinessLogic, true, userId);
296                 if (response.isRight()) {
297                     return response.right().value();
298                 }
299                 componentMap = new HashMap<>(response.left().value());
300                 response = getComponent(resourceBusinessLogic, false, userId);
301                 if (response.isRight()) {
302                     return response.right().value();
303                 }
304                 componentMap.putAll(response.left().value());
305                 String nodeTypesJson = gson.toJson(componentMap);
306                 Response okResponse = buildOkResponse(getComponentsUtils().getResponseFormat(ActionStatus.OK), nodeTypesJson);
307                 responseWrapper.setInnerElement(okResponse);
308             }
309             return responseWrapper.getInnerElement();
310         } catch (Exception e) {
311             BeEcompErrorManager.getInstance().logBeRestApiGeneralError("Get Node Types");
312             log.debug("get all node types failed with exception", e);
313             ResponseFormat responseFormat = getComponentsUtils().getResponseFormat(ActionStatus.GENERAL_ERROR);
314             return buildErrorResponse(responseFormat);
315         }
316     }
317
318     @GET
319     @Path("/artifactTypes")
320     @Operation(description = "Get Tosca ArtifactTypes", method = "GET", summary = "Returns tosca artifact types", responses = {
321         @ApiResponse(content = @Content(array = @ArraySchema(schema = @Schema(implementation = Response.class)))),
322         @ApiResponse(responseCode = "200", description = "Listing successful"),
323         @ApiResponse(responseCode = "400", description = "Invalid content / Missing content"),
324         @ApiResponse(responseCode = "403", description = "Restricted operation"),
325         @ApiResponse(responseCode = "404", description = "Tosca Artifact Types not found")})
326     @PermissionAllowed(AafPermission.PermNames.INTERNAL_ALL_VALUE)
327     public Response getAllToscaArtifactTypes(@Parameter(description = "Model name") @QueryParam("model") String model,
328                                              @Context final HttpServletRequest request, @HeaderParam("USER_ID") String creator) {
329         try {
330             return buildOkResponse(getComponentsUtils().getResponseFormat(ActionStatus.OK), artifactsBusinessLogic.getAllToscaArtifacts(model));
331         } catch (final BusinessException e) {
332             throw e;
333         } catch (final Exception e) {
334             final var errorMsg = "Unexpected error while listing the Tosca Artifact types";
335             BeEcompErrorManager.getInstance().logBeRestApiGeneralError(errorMsg);
336             log.error(EcompLoggerErrorCode.UNKNOWN_ERROR, this.getClass().getName(), errorMsg, e);
337             return buildErrorResponse(getComponentsUtils().getResponseFormat(ActionStatus.GENERAL_ERROR));
338         }
339
340     }
341
342
343     private Either<Map<String, Component>, Response> getComponent(ComponentBusinessLogic resourceBL, boolean isAbstract, String userId) {
344         Either<List<Component>, ResponseFormat> actionResponse;
345         List<Component> componentList;
346         actionResponse = resourceBL
347             .getLatestVersionNotAbstractComponentsMetadata(isAbstract, HighestFilterEnum.HIGHEST_ONLY, ComponentTypeEnum.RESOURCE, null, userId,
348                 null, false);
349         if (actionResponse.isRight()) {
350             log.debug(FAILED_TO_GET_ALL_NON_ABSTRACT, ComponentTypeEnum.RESOURCE.getValue());
351             return Either.right(buildErrorResponse(actionResponse.right().value()));
352         }
353         componentList = actionResponse.left().value();
354         return Either.left(ListUtils.emptyIfNull(componentList).stream().filter(component ->
355             ((ResourceMetadataDataDefinition) component.getComponentMetadataDefinition().getMetadataDataDefinition()).getToscaResourceName() != null)
356             .collect(Collectors.toMap(
357                 component -> ((ResourceMetadataDataDefinition) component.getComponentMetadataDefinition().getMetadataDataDefinition())
358                     .getToscaResourceName(), component -> component, (component1, component2) -> component1)));
359     }
360 }