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