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