catalog-be servlets refactoring
[sdc.git] / catalog-be / src / main / java / org / openecomp / sdc / be / servlets / ComponentServlet.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.*;
26 import javax.inject.Inject;
27 import org.apache.commons.collections.CollectionUtils;
28 import org.openecomp.sdc.be.components.impl.ComponentBusinessLogic;
29 import org.openecomp.sdc.be.components.impl.ComponentBusinessLogicProvider;
30 import org.openecomp.sdc.be.components.impl.ComponentInstanceBusinessLogic;
31 import org.openecomp.sdc.be.components.impl.GroupBusinessLogic;
32 import org.openecomp.sdc.be.config.BeEcompErrorManager;
33 import org.openecomp.sdc.be.dao.api.ActionStatus;
34 import org.openecomp.sdc.be.datamodel.api.HighestFilterEnum;
35 import org.openecomp.sdc.be.datatypes.enums.ComponentTypeEnum;
36 import org.openecomp.sdc.be.datatypes.enums.FilterKeyEnum;
37 import org.openecomp.sdc.be.impl.ComponentsUtils;
38 import org.openecomp.sdc.be.mixin.GroupCompositionMixin;
39 import org.openecomp.sdc.be.mixin.PolicyCompositionMixin;
40 import org.openecomp.sdc.be.model.*;
41 import org.openecomp.sdc.be.ui.model.UiComponentDataTransfer;
42 import org.openecomp.sdc.be.user.UserBusinessLogic;
43 import org.openecomp.sdc.be.view.ResponseView;
44 import org.openecomp.sdc.common.api.Constants;
45 import org.openecomp.sdc.common.log.wrappers.Logger;
46 import org.openecomp.sdc.exception.ResponseFormat;
47 import org.springframework.beans.factory.annotation.Autowired;
48 import org.springframework.stereotype.Controller;
49
50 import javax.servlet.ServletContext;
51 import javax.servlet.http.HttpServletRequest;
52 import javax.ws.rs.*;
53 import javax.ws.rs.core.Context;
54 import javax.ws.rs.core.MediaType;
55 import javax.ws.rs.core.Response;
56 import java.util.ArrayList;
57 import java.util.EnumMap;
58 import java.util.List;
59 import java.util.Map;
60
61 @Loggable(prepend = true, value = Loggable.DEBUG, trim = false)
62 @Path("/v1/catalog")
63 @Api(value = "Component Servlet", description = "Component Servlet")
64 @Controller
65 public class ComponentServlet extends BeGenericServlet {
66     private static final String GET_CERTIFIED_NOT_ABSTRACT_COMPONENTS_FAILED_WITH_EXCEPTION = "getCertifiedNotAbstractComponents failed with exception";
67
68         private static final String GET_CERTIFIED_NON_ABSTRACT = "Get Certified Non Abstract";
69
70         private static final String FAILED_TO_GET_ALL_NON_ABSTRACT = "failed to get all non abstract {}";
71
72         private static final String START_HANDLE_REQUEST_OF = "Start handle request of {}";
73
74         private static final Logger log = Logger.getLogger(ComponentServlet.class);
75
76     private final ComponentBusinessLogicProvider componentBusinessLogicProvider;
77
78     @Inject
79     public ComponentServlet(UserBusinessLogic userBusinessLogic,
80         ComponentsUtils componentsUtils,
81         ComponentBusinessLogicProvider componentBusinessLogicProvider) {
82         super(userBusinessLogic, componentsUtils);
83         this.componentBusinessLogicProvider = componentBusinessLogicProvider;
84     }
85
86     @GET
87     @Path("/{componentType}/{componentUuid}/conformanceLevelValidation")
88     @Consumes(MediaType.APPLICATION_JSON)
89     @Produces(MediaType.APPLICATION_JSON)
90     @ApiOperation(value = "Validate Component Conformance Level", httpMethod = "GET", notes = "Returns the result according to conformance level in BE config", response = Resource.class)
91     @ApiResponses(value = { @ApiResponse(code = 200, message = "Component found"), @ApiResponse(code = 403, message = "Restricted operation"), @ApiResponse(code = 404, message = "Component not found") })
92     public Response conformanceLevelValidation(@PathParam("componentType") final String componentType, @PathParam("componentUuid") final String componentUuid, @Context final HttpServletRequest request,
93             @HeaderParam(value = Constants.USER_ID_HEADER) String userId) {
94         Response response;
95
96         String url = request.getMethod() + " " + request.getRequestURI();
97         log.debug(START_HANDLE_REQUEST_OF, url);
98
99         ComponentTypeEnum componentTypeEnum = ComponentTypeEnum.findByParamName(componentType);
100         if (componentTypeEnum != null) {
101             ComponentBusinessLogic compBL = componentBusinessLogicProvider.getInstance(componentTypeEnum);
102             Either<Boolean, ResponseFormat> eitherConformanceLevel = compBL.validateConformanceLevel(componentUuid, componentTypeEnum, userId);
103             if (eitherConformanceLevel.isRight()) {
104                 response = buildErrorResponse(eitherConformanceLevel.right().value());
105             } else {
106                 response = buildOkResponse(getComponentsUtils().getResponseFormat(ActionStatus.OK), gson.toJson(eitherConformanceLevel.left().value()));
107             }
108         } else {
109             response = buildErrorResponse(getComponentsUtils().getResponseFormat(ActionStatus.INVALID_CONTENT));
110         }
111
112         return response;
113     }
114
115     @GET
116     @Path("/{componentType}/{componentId}/requirmentsCapabilities")
117     @Consumes(MediaType.APPLICATION_JSON)
118     @Produces(MediaType.APPLICATION_JSON)
119     @ApiOperation(value = "Get Component Requirments And Capabilities", httpMethod = "GET", notes = "Returns Requirements And Capabilities according to componentId", response = Resource.class)
120     @ApiResponses(value = { @ApiResponse(code = 200, message = "Component found"), @ApiResponse(code = 403, message = "Restricted operation"), @ApiResponse(code = 404, message = "Component not found") })
121     public Response getRequirementAndCapabilities(@PathParam("componentType") final String componentType, @PathParam("componentId") final String componentId, @Context final HttpServletRequest request,
122             @HeaderParam(value = Constants.USER_ID_HEADER) String userId) {
123         Response response;
124
125         String url = request.getMethod() + " " + request.getRequestURI();
126         log.debug(START_HANDLE_REQUEST_OF, url);
127
128         ComponentTypeEnum componentTypeEnum = ComponentTypeEnum.findByParamName(componentType);
129         if (componentTypeEnum != null) {
130             try {
131                 ComponentBusinessLogic compBL = componentBusinessLogicProvider.getInstance(componentTypeEnum);
132                 Either<CapReqDef, ResponseFormat> eitherRequirementsAndCapabilities = compBL.getRequirementsAndCapabilities(componentId, componentTypeEnum, userId);
133                 if (eitherRequirementsAndCapabilities.isRight()) {
134                     response = buildErrorResponse(eitherRequirementsAndCapabilities.right().value());
135                 } else {
136                     response = buildOkResponse(getComponentsUtils().getResponseFormat(ActionStatus.OK), RepresentationUtils.toRepresentation(eitherRequirementsAndCapabilities.left().value()));
137                 }
138             } catch (Exception e) {
139                 BeEcompErrorManager.getInstance().logBeRestApiGeneralError("Get Capabilities and requirements for " + componentId);
140                 log.debug("getRequirementAndCapabilities failed with exception", e);
141                 response = buildErrorResponse(getComponentsUtils().getResponseFormat(ActionStatus.GENERAL_ERROR));
142             }
143         } else {
144             response = buildErrorResponse(getComponentsUtils().getResponseFormat(ActionStatus.INVALID_CONTENT));
145         }
146
147         return response;
148     }
149
150     @GET
151     @Path("/{componentType}/latestversion/notabstract")
152     @Consumes(MediaType.APPLICATION_JSON)
153     @Produces(MediaType.APPLICATION_JSON)
154     @ApiOperation(value = "Get Component Requirments And Capabilities", httpMethod = "GET", notes = "Returns Requirments And Capabilities according to componentId", response = Resource.class)
155     @ApiResponses(value = { @ApiResponse(code = 200, message = "Component found"), @ApiResponse(code = 403, message = "Restricted operation"), @ApiResponse(code = 404, message = "Component not found") })
156     public Response getLatestVersionNotAbstractCheckoutComponents(@PathParam("componentType") final String componentType, @Context final HttpServletRequest request, @QueryParam("internalComponentType") String internalComponentType,
157             @QueryParam("componentUids") List<String> componentUids, @HeaderParam(value = Constants.USER_ID_HEADER) String userId) {
158
159         String url = request.getMethod() + " " + request.getRequestURI();
160         log.debug("(get) Start handle request of {}", url);
161         Response response = null;
162
163         try {
164
165             ComponentTypeEnum componentTypeEnum = ComponentTypeEnum.findByParamName(componentType);
166             ComponentBusinessLogic businessLogic = componentBusinessLogicProvider.getInstance(componentTypeEnum);
167
168             log.debug("Received componentUids size is {}", componentUids == null ? 0 : componentUids.size());
169
170             Either<List<Component>, ResponseFormat> actionResponse = businessLogic.getLatestVersionNotAbstractComponents(false, componentTypeEnum, internalComponentType, componentUids, userId);
171
172             if (actionResponse.isRight()) {
173                 log.debug(FAILED_TO_GET_ALL_NON_ABSTRACT, componentType);
174                 return buildErrorResponse(actionResponse.right().value());
175             }
176             Object components = RepresentationUtils.toRepresentation(actionResponse.left().value());
177             return buildOkResponse(getComponentsUtils().getResponseFormat(ActionStatus.OK), components);
178
179         } catch (Exception e) {
180             BeEcompErrorManager.getInstance().logBeRestApiGeneralError(GET_CERTIFIED_NON_ABSTRACT + componentType);
181             log.debug(GET_CERTIFIED_NOT_ABSTRACT_COMPONENTS_FAILED_WITH_EXCEPTION, e);
182             response = buildErrorResponse(getComponentsUtils().getResponseFormat(ActionStatus.GENERAL_ERROR));
183             return response;
184
185         }
186
187     }
188
189     @POST
190     @Path("/{componentType}/latestversion/notabstract")
191     @Consumes(MediaType.APPLICATION_JSON)
192     @Produces(MediaType.APPLICATION_JSON)
193     @ApiOperation(value = "Get Component Requirments And Capabilities", httpMethod = "GET", notes = "Returns Requirments And Capabilities according to componentId", response = Resource.class)
194     @ApiResponses(value = { @ApiResponse(code = 200, message = "Component found"), @ApiResponse(code = 403, message = "Restricted operation"), @ApiResponse(code = 404, message = "Component not found") })
195     public Response getLatestVersionNotAbstractCheckoutComponentsByBody(@PathParam("componentType") final String componentType, @Context final HttpServletRequest request, @QueryParam("internalComponentType") String internalComponentType,
196             @HeaderParam(value = Constants.USER_ID_HEADER) String userId, @ApiParam(value = "Consumer Object to be created", required = true) List<String> data) {
197
198         String url = request.getMethod() + " " + request.getRequestURI();
199         log.debug("(GET) Start handle request of {}", url);
200         Response response = null;
201
202         try {
203
204             ComponentTypeEnum componentTypeEnum = ComponentTypeEnum.findByParamName(componentType);
205             ComponentBusinessLogic businessLogic = componentBusinessLogicProvider.getInstance(componentTypeEnum);
206             if (log.isDebugEnabled()) {
207                 log.debug("Received componentUids size is {}", data == null ? 0 : data.size());
208             }
209
210             Either<List<Component>, ResponseFormat> actionResponse = businessLogic.getLatestVersionNotAbstractComponents(false, componentTypeEnum, internalComponentType, data, userId);
211
212             if (actionResponse.isRight()) {
213                 log.debug(FAILED_TO_GET_ALL_NON_ABSTRACT, componentType);
214                 return buildErrorResponse(actionResponse.right().value());
215
216             }
217             Object components = RepresentationUtils.toRepresentation(actionResponse.left().value());
218             return  buildOkResponse(getComponentsUtils().getResponseFormat(ActionStatus.OK), components);
219
220
221
222         } catch (Exception e) {
223             BeEcompErrorManager.getInstance().logBeRestApiGeneralError(GET_CERTIFIED_NON_ABSTRACT + componentType);
224             log.debug(GET_CERTIFIED_NOT_ABSTRACT_COMPONENTS_FAILED_WITH_EXCEPTION, e);
225             response = buildErrorResponse(getComponentsUtils().getResponseFormat(ActionStatus.GENERAL_ERROR));
226             return response;
227
228         }
229
230     }
231
232     @GET
233     @Path("/{componentType}/latestversion/notabstract/metadata")
234     @Consumes(MediaType.APPLICATION_JSON)
235     @Produces(MediaType.APPLICATION_JSON)
236     @ApiOperation(value = "Get Component uid only", httpMethod = "GET", notes = "Returns componentId", response = Resource.class)
237     @ApiResponses(value = { @ApiResponse(code = 200, message = "Component found"), @ApiResponse(code = 403, message = "Restricted operation"), @ApiResponse(code = 404, message = "Component not found") })
238     public Response getLatestVersionNotAbstractCheckoutComponentsIdesOnly(@PathParam("componentType") final String componentType, @Context final HttpServletRequest request, @QueryParam("internalComponentType") String internalComponentType,
239             @HeaderParam(value = Constants.USER_ID_HEADER) String userId, @ApiParam(value = "uid list", required = true) String data) {
240
241         String url = request.getMethod() + " " + request.getRequestURI();
242         log.debug("(get) Start handle request of {}", url);
243         Response response = null;
244         try {
245             ComponentTypeEnum componentTypeEnum = ComponentTypeEnum.findByParamName(componentType);
246             ComponentBusinessLogic businessLogic = componentBusinessLogicProvider.getInstance(componentTypeEnum);
247
248             Either<List<Component>, ResponseFormat> actionResponse = businessLogic.getLatestVersionNotAbstractComponentsMetadata(false, HighestFilterEnum.HIGHEST_ONLY, componentTypeEnum, internalComponentType, userId);
249             if (actionResponse.isRight()) {
250                 log.debug(FAILED_TO_GET_ALL_NON_ABSTRACT, componentType);
251                 return buildErrorResponse(actionResponse.right().value());
252             }
253             Object components = RepresentationUtils.toRepresentation(actionResponse.left().value());
254             return buildOkResponse(getComponentsUtils().getResponseFormat(ActionStatus.OK), components);
255
256         } catch (Exception e) {
257             BeEcompErrorManager.getInstance().logBeRestApiGeneralError(GET_CERTIFIED_NON_ABSTRACT + componentType);
258             log.debug(GET_CERTIFIED_NOT_ABSTRACT_COMPONENTS_FAILED_WITH_EXCEPTION, e);
259             response = buildErrorResponse(getComponentsUtils().getResponseFormat(ActionStatus.GENERAL_ERROR));
260             return response;
261
262         }
263
264     }
265
266     @GET
267     @Path("/{componentType}/{componentId}/componentInstances")
268     @Consumes(MediaType.APPLICATION_JSON)
269     @Produces(MediaType.APPLICATION_JSON)
270     @ApiOperation(value = "Get Component instances", httpMethod = "GET", notes = "Returns component instances", response = Resource.class)
271     @ApiResponses(value = { @ApiResponse(code = 200, message = "Component found"), @ApiResponse(code = 403, message = "Restricted operation"), @ApiResponse(code = 404, message = "Component not found") })
272     public Response getComponentInstancesFilteredByPropertiesAndInputs(@PathParam("componentType") final String componentType, @PathParam("componentId") final String componentId, @Context final HttpServletRequest request,
273             @QueryParam("searchText") String searchText, @HeaderParam(value = Constants.USER_ID_HEADER) String userId, @ApiParam(value = "uid" + " " + "list", required = true) String data) {
274
275         String url = request.getMethod() + " " + request.getRequestURI();
276         log.debug("(GET) Start handle request of {}", url);
277         Response response = null;
278         try {
279             ComponentTypeEnum componentTypeEnum = ComponentTypeEnum.findByParamName(componentType);
280             ComponentBusinessLogic businessLogic = componentBusinessLogicProvider.getInstance(componentTypeEnum);
281
282             Either<List<ComponentInstance>, ResponseFormat> actionResponse = businessLogic.getComponentInstancesFilteredByPropertiesAndInputs(componentId, userId);
283             if (actionResponse.isRight()) {
284                 log.debug("failed to get all component instances filtered by properties and inputs", componentType);
285                 return buildErrorResponse(actionResponse.right().value());
286             }
287             Object components = RepresentationUtils.toRepresentation(actionResponse.left().value());
288             return buildOkResponse(getComponentsUtils().getResponseFormat(ActionStatus.OK), components);
289
290         } catch (Exception e) {
291             BeEcompErrorManager.getInstance().logBeRestApiGeneralError("Get Component Instances filtered by properties & inputs" + componentType);
292             log.debug("getComponentInstancesFilteredByPropertiesAndInputs failed with exception", e);
293             response = buildErrorResponse(getComponentsUtils().getResponseFormat(ActionStatus.GENERAL_ERROR));
294             return response;
295         }
296     }
297
298
299
300     /**
301      * This API is a generic api for ui - the api get a list of strings and return the data on the component according to to list.
302      * for example: list of the string "properties, inputs" will return component with the list of properties and inputs.
303      *
304      * @param componentType
305      * @param componentId
306      * @param dataParamsToReturn
307      * @param request
308      * @param userId
309      * @return
310      */
311
312     @GET
313     @Path("/{componentType}/{componentId}/filteredDataByParams")
314     @Consumes(MediaType.APPLICATION_JSON)
315     @Produces(MediaType.APPLICATION_JSON)
316     @ApiOperation(value = "Retrieve Resource", httpMethod = "GET", notes = "Returns resource according to resourceId", response = Resource.class)
317     @ResponseView(mixin = {GroupCompositionMixin.class, PolicyCompositionMixin.class})
318     @ApiResponses(value = { @ApiResponse(code = 200, message = "Resource found"), @ApiResponse(code = 403, message = "Restricted operation"), @ApiResponse(code = 404, message = "Resource not found") })
319     public Response getComponentDataFilteredByParams(@PathParam("componentType") final String componentType, @PathParam("componentId") final String componentId, @QueryParam("include") final List<String> dataParamsToReturn, @Context final HttpServletRequest request, @HeaderParam(value = Constants.USER_ID_HEADER) String userId) {
320
321         String url = request.getMethod() + " " + request.getRequestURI();
322         log.debug(START_HANDLE_REQUEST_OF , url);
323
324         // get modifier id
325         User modifier = new User();
326         modifier.setUserId(userId);
327         log.debug("modifier id is {}" , userId);
328
329         Response response;
330
331         try {
332             String resourceIdLower = componentId.toLowerCase();
333             ComponentTypeEnum componentTypeEnum = ComponentTypeEnum.findByParamName(componentType);
334             ComponentBusinessLogic businessLogic = componentBusinessLogicProvider.getInstance(componentTypeEnum);
335
336             log.trace("get component with id {} filtered by ui params", componentId);
337             Either<UiComponentDataTransfer, ResponseFormat> actionResponse = businessLogic.getComponentDataFilteredByParams(resourceIdLower, modifier, dataParamsToReturn);
338
339             if (actionResponse.isRight()) {
340                 log.debug("failed to get component data filtered by ui params");
341                 response = buildErrorResponse(actionResponse.right().value());
342                 return response;
343             }
344             RepresentationUtils.toRepresentation(actionResponse.left().value());
345             return buildOkResponse(actionResponse.left().value());
346
347         } catch (Exception e) {
348             BeEcompErrorManager.getInstance().logBeRestApiGeneralError("Get component filtered by ui params");
349             log.debug("get resource failed with exception", e);
350             return buildErrorResponse(getComponentsUtils().getResponseFormat(ActionStatus.GENERAL_ERROR));
351
352         }
353     }
354
355
356     @GET
357     @Path("/{componentType}/{componentId}/filteredproperties/{propertyNameFragment}")
358     @Consumes(MediaType.APPLICATION_JSON)
359     @Produces(MediaType.APPLICATION_JSON)
360     @ApiOperation(value = "Retrieve properties belonging to component instances of specific component by name and optionally resource type", httpMethod = "GET", notes = "Returns properties belonging to component instances of specific component by name and optionally resource type", response = Map.class)
361     @ApiResponses(value = { @ApiResponse(code = 200, message = "Component found"), @ApiResponse(code = 403, message = "Restricted operation"), @ApiResponse(code = 404, message = "Component not found") })
362     public Response getFilteredComponentInstanceProperties(
363             @PathParam("componentType") final String componentType,
364             @PathParam("componentId") final String componentId,
365             @PathParam("propertyNameFragment") final String propertyNameFragment,
366             @QueryParam("resourceType") List<String> resourceTypes,
367             @Context final HttpServletRequest request,
368             @HeaderParam(value = Constants.USER_ID_HEADER) String userId) {
369
370         User user = new User();
371         user.setUserId(userId);
372         log.debug("User Id is {}" , userId);
373         Response response;
374         try {
375             ComponentTypeEnum componentTypeEnum = ComponentTypeEnum.findByParamName(componentType);
376             ComponentBusinessLogic businessLogic = componentBusinessLogicProvider.getInstance(componentTypeEnum);
377             Map<FilterKeyEnum, List<String>> filters = new EnumMap<>(FilterKeyEnum.class);
378             List<String> propertyNameFragments = new ArrayList<>();
379             propertyNameFragments.add(propertyNameFragment);
380             filters.put(FilterKeyEnum.NAME_FRAGMENT, propertyNameFragments);
381             if(CollectionUtils.isNotEmpty(resourceTypes)){
382                 filters.put(FilterKeyEnum.RESOURCE_TYPE, resourceTypes);
383             }
384             Either<Map<String, List<IComponentInstanceConnectedElement>>, ResponseFormat> actionResponse = businessLogic.getFilteredComponentInstanceProperties(componentId, filters, userId);
385             if (actionResponse.isRight()) {
386                 response = buildErrorResponse(actionResponse.right().value());
387                 return response;
388             }
389             Object resource = RepresentationUtils.toRepresentation(actionResponse.left().value());
390             return buildOkResponse(getComponentsUtils().getResponseFormat(ActionStatus.OK), resource);
391
392         } catch (Exception e) {
393             BeEcompErrorManager.getInstance().logBeRestApiGeneralError("Get Filtered Component Instance Properties");
394             log.debug("Getting of filtered component instance properties failed with exception", e);
395             return buildErrorResponse(getComponentsUtils().getResponseFormat(ActionStatus.GENERAL_ERROR));
396
397         }
398     }
399 }