Sync Integ to Master
[sdc.git] / catalog-be / src / main / java / org / openecomp / sdc / be / servlets / InputsServlet.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.fasterxml.jackson.databind.ObjectMapper;
24 import com.jcabi.aspects.Loggable;
25 import fj.data.Either;
26 import io.swagger.annotations.Api;
27 import io.swagger.annotations.ApiOperation;
28 import io.swagger.annotations.ApiParam;
29 import io.swagger.annotations.ApiResponse;
30 import io.swagger.annotations.ApiResponses;
31 import org.openecomp.sdc.be.components.impl.InputsBusinessLogic;
32 import org.openecomp.sdc.be.config.BeEcompErrorManager;
33 import org.openecomp.sdc.be.dao.api.ActionStatus;
34 import org.openecomp.sdc.be.datatypes.enums.ComponentTypeEnum;
35 import org.openecomp.sdc.be.impl.WebAppContextWrapper;
36 import org.openecomp.sdc.be.model.ComponentInstInputsMap;
37 import org.openecomp.sdc.be.model.ComponentInstanceInput;
38 import org.openecomp.sdc.be.model.ComponentInstanceProperty;
39 import org.openecomp.sdc.be.model.InputDefinition;
40 import org.openecomp.sdc.be.model.Resource;
41 import org.openecomp.sdc.be.model.User;
42 import org.openecomp.sdc.be.resources.data.auditing.AuditingActionEnum;
43 import org.openecomp.sdc.common.api.Constants;
44 import org.openecomp.sdc.common.config.EcompErrorName;
45 import org.openecomp.sdc.exception.ResponseFormat;
46 import org.slf4j.Logger;
47 import org.slf4j.LoggerFactory;
48 import org.springframework.web.context.WebApplicationContext;
49
50 import javax.inject.Singleton;
51 import javax.servlet.ServletContext;
52 import javax.servlet.http.HttpServletRequest;
53 import javax.ws.rs.Consumes;
54 import javax.ws.rs.DELETE;
55 import javax.ws.rs.GET;
56 import javax.ws.rs.HeaderParam;
57 import javax.ws.rs.POST;
58 import javax.ws.rs.Path;
59 import javax.ws.rs.PathParam;
60 import javax.ws.rs.Produces;
61 import javax.ws.rs.core.Context;
62 import javax.ws.rs.core.MediaType;
63 import javax.ws.rs.core.Response;
64 import java.util.Arrays;
65 import java.util.List;
66 @Loggable(prepend = true, value = Loggable.DEBUG, trim = false)
67 @Api(value = "Input Catalog", description = "Input Servlet")
68 @Path("/v1/catalog")
69 @Singleton
70 @Consumes(MediaType.APPLICATION_JSON)
71 @Produces(MediaType.APPLICATION_JSON)
72 public class InputsServlet extends AbstractValidationsServlet {
73
74     private static final Logger log = LoggerFactory.getLogger(InputsServlet.class);
75
76     @POST
77     @Path("/{containerComponentType}/{componentId}/update/inputs")
78     @ApiOperation(value = "Update resource  inputs", httpMethod = "POST", notes = "Returns updated input", response = Response.class)
79     @ApiResponses(value = { @ApiResponse(code = 200, message = "Input updated"), @ApiResponse(code = 403, message = "Restricted operation"), @ApiResponse(code = 400, message = "Invalid content / Missing content") })
80     public Response updateComponentInputs(
81             @ApiParam(value = "valid values: resources / services", allowableValues = ComponentTypeEnum.RESOURCE_PARAM_NAME + "," + ComponentTypeEnum.SERVICE_PARAM_NAME) @PathParam("containerComponentType") final String containerComponentType,
82             @PathParam("componentId") final String componentId,
83             @ApiParam(value = "json describe the input", required = true) String data, @Context final HttpServletRequest request) {
84
85         String url = request.getMethod() + " " + request.getRequestURI();
86         log.debug("Start handle request of {}", url);
87         String userId = request.getHeader(Constants.USER_ID_HEADER);
88
89         try {
90             User modifier = new User();
91             modifier.setUserId(userId);
92             log.debug("modifier id is {}", userId);
93
94             Either<InputDefinition[], ResponseFormat> inputsEither = getComponentsUtils()
95                     .convertJsonToObjectUsingObjectMapper(data, modifier, InputDefinition[].class,
96                             AuditingActionEnum.UPDATE_RESOURCE_METADATA, ComponentTypeEnum.SERVICE);
97             if(inputsEither.isRight()){
98                 log.debug("Failed to convert data to input definition. Status is {}", inputsEither.right().value());
99                 return buildErrorResponse(getComponentsUtils().getResponseFormat(ActionStatus.INVALID_CONTENT));
100             }
101             List<InputDefinition> inputsToUpdate = Arrays.asList(inputsEither.left().value());
102
103             log.debug("Start handle request of updateComponentInputs. Received inputs are {}", inputsToUpdate);
104
105             ServletContext context = request.getSession().getServletContext();
106             ComponentTypeEnum componentType = ComponentTypeEnum.findByParamName(containerComponentType);
107
108             InputsBusinessLogic businessLogic = getInputBL(context);
109             if (businessLogic == null) {
110                 log.debug("Unsupported component type {}", containerComponentType);
111                 return buildErrorResponse(getComponentsUtils().getResponseFormat(ActionStatus.UNSUPPORTED_ERROR));
112             }
113
114             Either<List<InputDefinition>, ResponseFormat> actionResponse = businessLogic.updateInputsValue(componentType, componentId, inputsToUpdate, userId, true, false);
115
116             if (actionResponse.isRight()) {
117                 return buildErrorResponse(actionResponse.right().value());
118             }
119
120             List<InputDefinition> componentInputs = actionResponse.left().value();
121             ObjectMapper mapper = new ObjectMapper();
122             String result = mapper.writeValueAsString(componentInputs);
123             return buildOkResponse(getComponentsUtils().getResponseFormat(ActionStatus.OK), result);
124
125         }
126         catch (Exception e) {
127             log.error("create and associate RI failed with exception: {}", e.getMessage(), e);
128             return buildErrorResponse(getComponentsUtils().getResponseFormat(ActionStatus.GENERAL_ERROR));
129         }
130     }
131
132
133     @GET
134     @Path("/{componentType}/{componentId}/componentInstances/{instanceId}/{originComponentUid}/inputs")
135     @ApiOperation(value = "Get Inputs only", httpMethod = "GET", notes = "Returns Inputs list", response = Resource.class)
136     @ApiResponses(value = { @ApiResponse(code = 200, message = "Component found"), @ApiResponse(code = 403, message = "Restricted operation"), @ApiResponse(code = 404, message = "Component not found") })
137     public Response getComponentInstanceInputs(@PathParam("componentType") final String componentType, @PathParam("componentId") final String componentId, @PathParam("instanceId") final String instanceId,
138                                                @PathParam("originComponentUid") final String originComponentUid, @Context final HttpServletRequest request, @HeaderParam(value = Constants.USER_ID_HEADER) String userId) {
139
140         ServletContext context = request.getSession().getServletContext();
141         String url = request.getMethod() + " " + request.getRequestURI();
142         log.debug("(get) Start handle request of {}", url);
143         Response response;
144
145         try {
146             InputsBusinessLogic businessLogic = getInputBL(context);
147
148             Either<List<ComponentInstanceInput>, ResponseFormat> inputsResponse = businessLogic.getComponentInstanceInputs(userId, componentId, instanceId);
149             if (inputsResponse.isRight()) {
150                 log.debug("failed to get component instance inputs {}", componentType);
151                 return buildErrorResponse(inputsResponse.right().value());
152             }
153             Object inputs = RepresentationUtils.toRepresentation(inputsResponse.left().value());
154             return buildOkResponse(getComponentsUtils().getResponseFormat(ActionStatus.OK), inputs);
155
156         } catch (Exception e) {
157             BeEcompErrorManager.getInstance().logBeRestApiGeneralError("Get Inputs " + componentType);
158             log.debug("getInputs failed with exception", e);
159             response = buildErrorResponse(getComponentsUtils().getResponseFormat(ActionStatus.GENERAL_ERROR));
160             return response;
161
162         }
163     }
164
165     @GET
166     @Path("/{componentType}/{componentId}/componentInstances/{instanceId}/{inputId}/properties")
167     @ApiOperation(value = "Get properties", httpMethod = "GET", notes = "Returns properties list", response = Resource.class)
168     @ApiResponses(value = { @ApiResponse(code = 200, message = "Component found"), @ApiResponse(code = 403, message = "Restricted operation"), @ApiResponse(code = 404, message = "Component not found") })
169     public Response getInputPropertiesForComponentInstance(@PathParam("componentType") final String componentType, @PathParam("componentId") final String componentId, @PathParam("instanceId") final String instanceId,
170             @PathParam("inputId") final String inputId, @Context final HttpServletRequest request, @HeaderParam(value = Constants.USER_ID_HEADER) String userId) {
171
172         ServletContext context = request.getSession().getServletContext();
173         String url = request.getMethod() + " " + request.getRequestURI();
174         log.debug("(GET) Start handle request of {}", url);
175         Response response = null;
176
177         try {
178             InputsBusinessLogic businessLogic = getInputBL(context);
179
180             Either<List<ComponentInstanceProperty>, ResponseFormat> inputPropertiesRes = businessLogic.getComponentInstancePropertiesByInputId(userId, componentId, instanceId, inputId);
181             if (inputPropertiesRes.isRight()) {
182                 log.debug("failed to get properties of input: {}, with instance id: {}", inputId, instanceId);
183                 return buildErrorResponse(inputPropertiesRes.right().value());
184             }
185             Object properties = RepresentationUtils.toRepresentation(inputPropertiesRes.left().value());
186             return buildOkResponse(getComponentsUtils().getResponseFormat(ActionStatus.OK), properties);
187
188         } catch (Exception e) {
189             BeEcompErrorManager.getInstance().logBeRestApiGeneralError("Get Properites by input id: " + inputId + " for instance with id: " + instanceId);
190             log.debug("getInputPropertiesForComponentInstance failed with exception", e);
191             response = buildErrorResponse(getComponentsUtils().getResponseFormat(ActionStatus.GENERAL_ERROR));
192             return response;
193
194         }
195     }
196
197     @GET
198     @Path("/{componentType}/{componentId}/inputs/{inputId}/inputs")
199     @ApiOperation(value = "Get inputs", httpMethod = "GET", notes = "Returns inputs list", response = Resource.class)
200     @ApiResponses(value = { @ApiResponse(code = 200, message = "Component found"), @ApiResponse(code = 403, message = "Restricted operation"), @ApiResponse(code = 404, message = "Component not found") })
201     public Response getInputsForComponentInput(@PathParam("componentType") final String componentType, @PathParam("componentId") final String componentId, @PathParam("inputId") final String inputId, @Context final HttpServletRequest request,
202             @HeaderParam(value = Constants.USER_ID_HEADER) String userId) {
203
204         ServletContext context = request.getSession().getServletContext();
205         String url = request.getMethod() + " " + request.getRequestURI();
206         log.debug("(get) Start handle request of {}", url);
207         Response response;
208         try {
209             InputsBusinessLogic businessLogic = getInputBL(context);
210
211             Either<List<ComponentInstanceInput>, ResponseFormat> inputsRes = businessLogic.getInputsForComponentInput(userId, componentId, inputId);
212
213             if (inputsRes.isRight()) {
214                 log.debug("failed to get inputs of input: {}, with instance id: {}", inputId, componentId);
215                 return buildErrorResponse(inputsRes.right().value());
216             }
217             Object properties = RepresentationUtils.toRepresentation(inputsRes.left().value());
218             return buildOkResponse(getComponentsUtils().getResponseFormat(ActionStatus.OK), properties);
219
220         } catch (Exception e) {
221             BeEcompErrorManager.getInstance().logBeRestApiGeneralError("Get inputs by input id: " + inputId + " for component with id: " + componentId);
222             log.debug("getInputsForComponentInput failed with exception", e);
223             response = buildErrorResponse(getComponentsUtils().getResponseFormat(ActionStatus.GENERAL_ERROR));
224             return response;
225
226         }
227     }
228
229     @GET
230     @Path("/{componentType}/{componentId}/inputs/{inputId}")
231     @ApiOperation(value = "Get inputs", httpMethod = "GET", notes = "Returns inputs list", 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 getInputsAndPropertiesForComponentInput(@PathParam("componentType") final String componentType, @PathParam("componentId") final String componentId, @PathParam("inputId") final String inputId, @Context final HttpServletRequest request,
234             @HeaderParam(value = Constants.USER_ID_HEADER) String userId) {
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;
240
241         try {
242             InputsBusinessLogic businessLogic = getInputBL(context);
243
244             Either<InputDefinition, ResponseFormat> inputsRes = businessLogic.getInputsAndPropertiesForComponentInput(userId, componentId, inputId, false);
245
246             if (inputsRes.isRight()) {
247                 log.debug("failed to get inputs of input: {}, with instance id: {}", inputId, componentId);
248                 return buildErrorResponse(inputsRes.right().value());
249             }
250             Object properties = RepresentationUtils.toRepresentation(inputsRes.left().value());
251             return buildOkResponse(getComponentsUtils().getResponseFormat(ActionStatus.OK), properties);
252
253         } catch (Exception e) {
254             BeEcompErrorManager.getInstance().logBeRestApiGeneralError("Get inputs by input id: " + inputId + " for component with id: " + componentId);
255             log.debug("getInputsForComponentInput failed with exception", e);
256             response = buildErrorResponse(getComponentsUtils().getResponseFormat(ActionStatus.GENERAL_ERROR));
257             return response;
258
259         }
260     }
261
262     private Either<ComponentInstInputsMap, ResponseFormat> parseToComponentInstanceMap(String serviceJson, User user) {
263         return getComponentsUtils().convertJsonToObjectUsingObjectMapper(serviceJson, user, ComponentInstInputsMap.class, AuditingActionEnum.CREATE_RESOURCE, ComponentTypeEnum.SERVICE);
264     }
265
266     @POST
267     @Path("/{componentType}/{componentId}/create/inputs")
268     @ApiOperation(value = "Create inputs on service", httpMethod = "POST", notes = "Return inputs list", response = Resource.class)
269     @ApiResponses(value = { @ApiResponse(code = 200, message = "Component found"), @ApiResponse(code = 403, message = "Restricted operation"), @ApiResponse(code = 404, message = "Component not found") })
270     public Response createMultipleInputs(@PathParam("componentType") final String componentType, @PathParam("componentId") final String componentId, @Context final HttpServletRequest request,
271             @HeaderParam(value = Constants.USER_ID_HEADER) String userId, @ApiParam(value = "ComponentIns Inputs Object to be created", required = true) String componentInstInputsMapObj) {
272
273         ServletContext context = request.getSession().getServletContext();
274         String url = request.getMethod() + " " + request.getRequestURI();
275         log.debug("(get) Start handle request of {}", url);
276         Response response = null;
277
278         try {
279             InputsBusinessLogic businessLogic = getInputBL(context);
280
281             // get modifier id
282             User modifier = new User();
283             modifier.setUserId(userId);
284             log.debug("modifier id is {}", userId);
285
286             Either<ComponentInstInputsMap, ResponseFormat> componentInstInputsMapRes = parseToComponentInstanceMap(componentInstInputsMapObj, modifier);
287             if (componentInstInputsMapRes.isRight()) {
288                 log.debug("failed to parse componentInstInputsMap");
289                 response = buildErrorResponse(componentInstInputsMapRes.right().value());
290                 return response;
291             }
292
293             ComponentTypeEnum componentTypeEnum = ComponentTypeEnum.findByParamName(componentType);
294             ComponentInstInputsMap componentInstInputsMap = componentInstInputsMapRes.left().value();
295
296             Either<List<InputDefinition>, ResponseFormat> inputPropertiesRes = businessLogic.createMultipleInputs(userId, componentId, componentTypeEnum, componentInstInputsMap, true, false);
297             if (inputPropertiesRes.isRight()) {
298                 log.debug("failed to create inputs  for service: {}", componentId);
299                 return buildErrorResponse(inputPropertiesRes.right().value());
300             }
301             Object properties = RepresentationUtils.toRepresentation(inputPropertiesRes.left().value());
302             return buildOkResponse(getComponentsUtils().getResponseFormat(ActionStatus.OK), properties);
303
304         } catch (Exception e) {
305             BeEcompErrorManager.getInstance().logBeRestApiGeneralError("Create inputs for service with id: " + componentId);
306             log.debug("createMultipleInputs failed with exception", e);
307             response = buildErrorResponse(getComponentsUtils().getResponseFormat(ActionStatus.GENERAL_ERROR));
308             return response;
309         }
310     }
311
312
313
314     @DELETE
315     @Path("/{componentType}/{componentId}/delete/{inputId}/input")
316     @ApiOperation(value = "Delete input from service", httpMethod = "DELETE", notes = "Delete service input", response = Resource.class)
317     @ApiResponses(value = { @ApiResponse(code = 200, message = "Input deleted"), @ApiResponse(code = 403, message = "Restricted operation"), @ApiResponse(code = 404, message = "Input not found") })
318     public Response deleteInput (
319             @PathParam("componentType") final String componentType,
320             @PathParam("componentId") final String componentId,
321             @PathParam("inputId") final String inputId,
322             @Context final HttpServletRequest request,
323             @HeaderParam(value = Constants.USER_ID_HEADER) String userId,
324             @ApiParam(value = "Service Input to be deleted", required = true) String componentInstInputsMapObj) {
325
326         ServletContext context = request.getSession().getServletContext();
327         String url = request.getMethod() + " " + request.getRequestURI();
328         log.debug("(get) Start handle request of {}", url);
329         Response response = null;
330
331         try {
332             InputsBusinessLogic businessLogic = getInputBL(context);
333             Either<InputDefinition, ResponseFormat> deleteInput = businessLogic.deleteInput(componentId, userId, inputId);
334             if (deleteInput.isRight()){
335                 ResponseFormat deleteResponseFormat = deleteInput.right().value();
336                 response = buildErrorResponse(deleteResponseFormat);
337                 return response;
338             }
339             return buildOkResponse(getComponentsUtils().getResponseFormat(ActionStatus.OK), deleteInput.left().value());
340         } catch (Exception e){
341             BeEcompErrorManager.getInstance().logBeRestApiGeneralError("Delete input for service + " + componentId + " + with id: " + inputId);
342             log.debug("Delete input failed with exception", e);
343             response = buildErrorResponse(getComponentsUtils().getResponseFormat(ActionStatus.GENERAL_ERROR));
344             return response;
345
346         }
347     }
348
349     private InputsBusinessLogic getInputBL(ServletContext context) {
350         WebAppContextWrapper webApplicationContextWrapper = (WebAppContextWrapper) context.getAttribute(Constants.WEB_APPLICATION_CONTEXT_WRAPPER_ATTR);
351         WebApplicationContext webApplicationContext = webApplicationContextWrapper.getWebAppContext(context);
352         return webApplicationContext.getBean(InputsBusinessLogic.class);
353     }
354
355 }