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