Fix new data types not found in UI
[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             resourceBusinessLogic.getApplicationDataTypeCache().refreshDataTypesCacheIfStale();
136             final Map<String, DataTypeDefinition> dataTypes = resourceBusinessLogic.getComponentsUtils()
137                 .getAllDataTypes(resourceBusinessLogic.getApplicationDataTypeCache(), modelName);
138             String dataTypeJson = gson.toJson(dataTypes);
139             Response okResponse = buildOkResponse(getComponentsUtils().getResponseFormat(ActionStatus.OK), dataTypeJson);
140             responseWrapper.setInnerElement(okResponse);
141         }
142         return responseWrapper.getInnerElement();
143     }
144
145     @GET
146     @Path("interfaceLifecycleTypes")
147     @Consumes(MediaType.APPLICATION_JSON)
148     @Produces(MediaType.APPLICATION_JSON)
149     @Operation(description = "Get interface lifecycle types", method = "GET", summary = "Returns interface lifecycle types", responses = {
150         @ApiResponse(content = @Content(array = @ArraySchema(schema = @Schema(implementation = Response.class)))),
151         @ApiResponse(responseCode = "200", description = "Interface lifecycle types"),
152         @ApiResponse(responseCode = "403", description = "Restricted operation"),
153         @ApiResponse(responseCode = "400", description = "Invalid content / Missing content"),
154         @ApiResponse(responseCode = "404", description = "Interface lifecycle types not found")})
155     @PermissionAllowed(AafPermission.PermNames.INTERNAL_ALL_VALUE)
156     public Response getInterfaceLifecycleTypes(@Context final HttpServletRequest request,
157                                                @HeaderParam(value = Constants.USER_ID_HEADER) String userId,
158                                                @Parameter(description = "model") @QueryParam("model") String modelName) {
159         Wrapper<Response> responseWrapper = new Wrapper<>();
160         Wrapper<User> userWrapper = new Wrapper<>();
161         try {
162             validateUserExist(responseWrapper, userWrapper, userId);
163             if (responseWrapper.isEmpty()) {
164                 String url = request.getMethod() + " " + request.getRequestURI();
165                 log.info("Start handle request of {} | modifier id is {}", url, userId);
166                 Either<Map<String, InterfaceDefinition>, ResponseFormat> allInterfaceLifecycleTypes = interfaceOperationBusinessLogic
167                     .getAllInterfaceLifecycleTypes(modelName);
168                 if (allInterfaceLifecycleTypes.isRight()) {
169                     log.info("Failed to get all interface lifecycle types. Reason - {}", allInterfaceLifecycleTypes.right().value());
170                     Response errorResponse = buildErrorResponse(allInterfaceLifecycleTypes.right().value());
171                     responseWrapper.setInnerElement(errorResponse);
172                 } else {
173                     String interfaceLifecycleTypeJson = gson.toJson(allInterfaceLifecycleTypes.left().value());
174                     Response okResponse = buildOkResponse(getComponentsUtils().getResponseFormat(ActionStatus.OK), interfaceLifecycleTypeJson);
175                     responseWrapper.setInnerElement(okResponse);
176                 }
177             }
178             return responseWrapper.getInnerElement();
179         } catch (Exception e) {
180             log.debug("get all interface lifecycle types failed with exception", e);
181             ResponseFormat responseFormat = getComponentsUtils().getResponseFormat(ActionStatus.GENERAL_ERROR);
182             return buildErrorResponse(responseFormat);
183         }
184     }
185
186     @GET
187     @Path("capabilityTypes")
188     @Consumes(MediaType.APPLICATION_JSON)
189     @Produces(MediaType.APPLICATION_JSON)
190     @Operation(description = "Get capability types", method = "GET", summary = "Returns capability types", responses = {
191         @ApiResponse(content = @Content(array = @ArraySchema(schema = @Schema(implementation = Response.class)))),
192         @ApiResponse(responseCode = "200", description = "capabilityTypes"), @ApiResponse(responseCode = "403", description = "Restricted operation"),
193         @ApiResponse(responseCode = "400", description = "Invalid content / Missing content"),
194         @ApiResponse(responseCode = "404", description = "Capability types not found")})
195     @PermissionAllowed(AafPermission.PermNames.INTERNAL_ALL_VALUE)
196     public Response getAllCapabilityTypesServlet(@Context final HttpServletRequest request,
197                                                  @HeaderParam(value = Constants.USER_ID_HEADER) String userId,
198                                                  @Parameter(description = "model", required = false) @QueryParam("model") String modelName) {
199         Wrapper<Response> responseWrapper = new Wrapper<>();
200         Wrapper<User> userWrapper = new Wrapper<>();
201         try {
202             init();
203             validateUserExist(responseWrapper, userWrapper, userId);
204             modelName = ValidationUtils.sanitizeInputString(modelName);
205             if (responseWrapper.isEmpty()) {
206                 String url = request.getMethod() + " " + request.getRequestURI();
207                 log.debug("Start handle request of {} | modifier id is {}", url, userId);
208                 Either<Map<String, CapabilityTypeDefinition>, ResponseFormat> allDataTypes = capabilitiesBusinessLogic.getAllCapabilityTypes(modelName);
209                 if (allDataTypes.isRight()) {
210                     log.info("Failed to get all capability types. Reason - {}", allDataTypes.right().value());
211                     Response errorResponse = buildErrorResponse(allDataTypes.right().value());
212                     responseWrapper.setInnerElement(errorResponse);
213                 } else {
214                     Map<String, CapabilityTypeDefinition> dataTypes = allDataTypes.left().value();
215                     String dataTypeJson = gson.toJson(dataTypes);
216                     Response okResponse = buildOkResponse(getComponentsUtils().getResponseFormat(ActionStatus.OK), dataTypeJson);
217                     responseWrapper.setInnerElement(okResponse);
218                 }
219             }
220             return responseWrapper.getInnerElement();
221         } catch (Exception e) {
222             BeEcompErrorManager.getInstance().logBeRestApiGeneralError("Get Capability Types");
223             log.debug("get all capability types failed with exception", e);
224             ResponseFormat responseFormat = getComponentsUtils().getResponseFormat(ActionStatus.GENERAL_ERROR);
225             return buildErrorResponse(responseFormat);
226         }
227     }
228
229     @GET
230     @Path("relationshipTypes")
231     @Consumes(MediaType.APPLICATION_JSON)
232     @Produces(MediaType.APPLICATION_JSON)
233     @Operation(description = "Get relationship types", method = "GET", summary = "Returns relationship types", responses = {
234         @ApiResponse(content = @Content(array = @ArraySchema(schema = @Schema(implementation = Response.class)))),
235         @ApiResponse(responseCode = "200", description = "relationshipTypes"),
236         @ApiResponse(responseCode = "403", description = "Restricted operation"),
237         @ApiResponse(responseCode = "400", description = "Invalid content / Missing content"),
238         @ApiResponse(responseCode = "404", description = "Relationship types not found")})
239     @PermissionAllowed(AafPermission.PermNames.INTERNAL_ALL_VALUE)
240     public Response getAllRelationshipTypesServlet(@Context final HttpServletRequest request,
241                                                    @HeaderParam(value = Constants.USER_ID_HEADER) String userId,
242                                                    @Parameter(description = "model", required = false) @QueryParam("model") String modelName) {
243         Wrapper<Response> responseWrapper = new Wrapper<>();
244         Wrapper<User> userWrapper = new Wrapper<>();
245         try {
246             init();
247             validateUserExist(responseWrapper, userWrapper, userId);
248             modelName = ValidationUtils.sanitizeInputString(modelName);
249             if (responseWrapper.isEmpty()) {
250                 String url = request.getMethod() + " " + request.getRequestURI();
251                 log.debug("Start handle request of {} | modifier id is {}", url, userId);
252                 Either<Map<String, RelationshipTypeDefinition>, ResponseFormat> allDataTypes = relationshipTypeBusinessLogic
253                     .getAllRelationshipTypes(modelName);
254                 if (allDataTypes.isRight()) {
255                     log.info("Failed to get all relationship types. Reason - {}", allDataTypes.right().value());
256                     Response errorResponse = buildErrorResponse(allDataTypes.right().value());
257                     responseWrapper.setInnerElement(errorResponse);
258                 } else {
259                     Map<String, RelationshipTypeDefinition> dataTypes = allDataTypes.left().value();
260                     String dataTypeJson = gson.toJson(dataTypes);
261                     Response okResponse = buildOkResponse(getComponentsUtils().getResponseFormat(ActionStatus.OK), dataTypeJson);
262                     responseWrapper.setInnerElement(okResponse);
263                 }
264             }
265             return responseWrapper.getInnerElement();
266         } catch (Exception e) {
267             BeEcompErrorManager.getInstance().logBeRestApiGeneralError("Get Relationship Types");
268             log.debug("get all relationship types failed with exception", e);
269             ResponseFormat responseFormat = getComponentsUtils().getResponseFormat(ActionStatus.GENERAL_ERROR);
270             return buildErrorResponse(responseFormat);
271         }
272     }
273
274     @GET
275     @Path("nodeTypes")
276     @Consumes(MediaType.APPLICATION_JSON)
277     @Produces(MediaType.APPLICATION_JSON)
278     @Operation(description = "Get node types", method = "GET", summary = "Returns node types", responses = {
279         @ApiResponse(content = @Content(array = @ArraySchema(schema = @Schema(implementation = Response.class)))),
280         @ApiResponse(responseCode = "200", description = "nodeTypes"), @ApiResponse(responseCode = "403", description = "Restricted operation"),
281         @ApiResponse(responseCode = "400", description = "Invalid content / Missing content"),
282         @ApiResponse(responseCode = "404", description = "Node types not found")})
283     @PermissionAllowed(AafPermission.PermNames.INTERNAL_ALL_VALUE)
284     public Response getAllNodeTypesServlet(@Context final HttpServletRequest request, @HeaderParam(value = Constants.USER_ID_HEADER) String userId) {
285         Wrapper<Response> responseWrapper = new Wrapper<>();
286         Wrapper<User> userWrapper = new Wrapper<>();
287         ServletContext context = request.getSession().getServletContext();
288         Either<Map<String, Component>, Response> response;
289         Map<String, Component> componentMap;
290         try {
291             init();
292             validateUserExist(responseWrapper, userWrapper, userId);
293             if (responseWrapper.isEmpty()) {
294                 String url = request.getMethod() + " " + request.getRequestURI();
295                 log.debug("Start handle request of {} | modifier id is {}", url, userId);
296                 response = getComponent(resourceBusinessLogic, true, userId);
297                 if (response.isRight()) {
298                     return response.right().value();
299                 }
300                 componentMap = new HashMap<>(response.left().value());
301                 response = getComponent(resourceBusinessLogic, false, userId);
302                 if (response.isRight()) {
303                     return response.right().value();
304                 }
305                 componentMap.putAll(response.left().value());
306                 String nodeTypesJson = gson.toJson(componentMap);
307                 Response okResponse = buildOkResponse(getComponentsUtils().getResponseFormat(ActionStatus.OK), nodeTypesJson);
308                 responseWrapper.setInnerElement(okResponse);
309             }
310             return responseWrapper.getInnerElement();
311         } catch (Exception e) {
312             BeEcompErrorManager.getInstance().logBeRestApiGeneralError("Get Node Types");
313             log.debug("get all node types failed with exception", e);
314             ResponseFormat responseFormat = getComponentsUtils().getResponseFormat(ActionStatus.GENERAL_ERROR);
315             return buildErrorResponse(responseFormat);
316         }
317     }
318
319     @GET
320     @Path("/artifactTypes")
321     @Operation(description = "Get Tosca ArtifactTypes", method = "GET", summary = "Returns tosca artifact types", responses = {
322         @ApiResponse(content = @Content(array = @ArraySchema(schema = @Schema(implementation = Response.class)))),
323         @ApiResponse(responseCode = "200", description = "Listing successful"),
324         @ApiResponse(responseCode = "400", description = "Invalid content / Missing content"),
325         @ApiResponse(responseCode = "403", description = "Restricted operation"),
326         @ApiResponse(responseCode = "404", description = "Tosca Artifact Types not found")})
327     @PermissionAllowed(AafPermission.PermNames.INTERNAL_ALL_VALUE)
328     public Response getAllToscaArtifactTypes(@Parameter(description = "Model name") @QueryParam("model") String model,
329                                              @Context final HttpServletRequest request, @HeaderParam("USER_ID") String creator) {
330         try {
331             return buildOkResponse(getComponentsUtils().getResponseFormat(ActionStatus.OK), artifactsBusinessLogic.getAllToscaArtifacts(model));
332         } catch (final BusinessException e) {
333             throw e;
334         } catch (final Exception e) {
335             final var errorMsg = "Unexpected error while listing the Tosca Artifact types";
336             BeEcompErrorManager.getInstance().logBeRestApiGeneralError(errorMsg);
337             log.error(EcompLoggerErrorCode.UNKNOWN_ERROR, this.getClass().getName(), errorMsg, e);
338             return buildErrorResponse(getComponentsUtils().getResponseFormat(ActionStatus.GENERAL_ERROR));
339         }
340
341     }
342
343
344     private Either<Map<String, Component>, Response> getComponent(ComponentBusinessLogic resourceBL, boolean isAbstract, String userId) {
345         Either<List<Component>, ResponseFormat> actionResponse;
346         List<Component> componentList;
347         actionResponse = resourceBL
348             .getLatestVersionNotAbstractComponentsMetadata(isAbstract, HighestFilterEnum.HIGHEST_ONLY, ComponentTypeEnum.RESOURCE, null, userId,
349                 null, false);
350         if (actionResponse.isRight()) {
351             log.debug(FAILED_TO_GET_ALL_NON_ABSTRACT, ComponentTypeEnum.RESOURCE.getValue());
352             return Either.right(buildErrorResponse(actionResponse.right().value()));
353         }
354         componentList = actionResponse.left().value();
355         return Either.left(ListUtils.emptyIfNull(componentList).stream().filter(component ->
356             ((ResourceMetadataDataDefinition) component.getComponentMetadataDefinition().getMetadataDataDefinition()).getToscaResourceName() != null)
357             .collect(Collectors.toMap(
358                 component -> ((ResourceMetadataDataDefinition) component.getComponentMetadataDefinition().getMetadataDataDefinition())
359                     .getToscaResourceName(), component -> component, (component1, component2) -> component1)));
360     }
361 }