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