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