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