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