catalog-be servlets refactoring
[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 java.util.Arrays;
32 import java.util.List;
33 import javax.inject.Inject;
34 import javax.inject.Singleton;
35 import javax.servlet.ServletContext;
36 import javax.servlet.http.HttpServletRequest;
37 import javax.ws.rs.Consumes;
38 import javax.ws.rs.DELETE;
39 import javax.ws.rs.GET;
40 import javax.ws.rs.HeaderParam;
41 import javax.ws.rs.POST;
42 import javax.ws.rs.Path;
43 import javax.ws.rs.PathParam;
44 import javax.ws.rs.Produces;
45 import javax.ws.rs.core.Context;
46 import javax.ws.rs.core.MediaType;
47 import javax.ws.rs.core.Response;
48 import org.apache.commons.lang3.builder.ReflectionToStringBuilder;
49 import org.openecomp.sdc.be.components.impl.ComponentInstanceBusinessLogic;
50 import org.openecomp.sdc.be.components.impl.DataTypeBusinessLogic;
51 import org.openecomp.sdc.be.components.impl.GroupBusinessLogic;
52 import org.openecomp.sdc.be.components.impl.InputsBusinessLogic;
53 import org.openecomp.sdc.be.components.impl.ResourceImportManager;
54 import org.openecomp.sdc.be.config.BeEcompErrorManager;
55 import org.openecomp.sdc.be.dao.api.ActionStatus;
56 import org.openecomp.sdc.be.datatypes.enums.ComponentTypeEnum;
57 import org.openecomp.sdc.be.impl.ComponentsUtils;
58 import org.openecomp.sdc.be.impl.ServletUtils;
59 import org.openecomp.sdc.be.model.operations.api.StorageOperationStatus;
60 import org.openecomp.sdc.be.datatypes.enums.DeclarationTypeEnum;
61 import org.openecomp.sdc.be.model.ComponentInstInputsMap;
62 import org.openecomp.sdc.be.model.ComponentInstanceInput;
63 import org.openecomp.sdc.be.model.ComponentInstanceProperty;
64 import org.openecomp.sdc.be.model.InputDefinition;
65 import org.openecomp.sdc.be.model.Resource;
66 import org.openecomp.sdc.be.model.User;
67 import org.openecomp.sdc.be.model.ComponentInstListInput;
68 import org.openecomp.sdc.be.model.DataTypeDefinition;
69 import org.openecomp.sdc.be.resources.data.auditing.AuditingActionEnum;
70 import org.openecomp.sdc.be.user.UserBusinessLogic;
71 import org.openecomp.sdc.common.api.Constants;
72 import org.openecomp.sdc.common.log.wrappers.Logger;
73 import org.openecomp.sdc.exception.ResponseFormat;
74
75 @Loggable(prepend = true, value = Loggable.DEBUG, trim = false)
76 @Api(value = "Input Catalog", description = "Input Servlet")
77 @Path("/v1/catalog")
78 @Singleton
79 @Consumes(MediaType.APPLICATION_JSON)
80 @Produces(MediaType.APPLICATION_JSON)
81 public class InputsServlet extends AbstractValidationsServlet {
82
83     private static final Logger log = Logger.getLogger(InputsServlet.class);
84
85     private final DataTypeBusinessLogic businessLogic;
86     private final InputsBusinessLogic inputsBusinessLogic;
87
88     @Inject
89     public InputsServlet(UserBusinessLogic userBusinessLogic,
90         InputsBusinessLogic inputsBusinessLogic,
91         ComponentInstanceBusinessLogic componentInstanceBL,
92         ComponentsUtils componentsUtils, ServletUtils servletUtils,
93         ResourceImportManager resourceImportManager,
94         DataTypeBusinessLogic dataTypeBusinessLogic) {
95         super(userBusinessLogic, componentInstanceBL, componentsUtils, servletUtils, resourceImportManager);
96         this.inputsBusinessLogic = inputsBusinessLogic;
97         this.businessLogic = dataTypeBusinessLogic;
98     }
99
100     @POST
101     @Path("/{containerComponentType}/{componentId}/update/inputs")
102     @ApiOperation(value = "Update resource  inputs", httpMethod = "POST", notes = "Returns updated input", response = Response.class)
103     @ApiResponses(value = { @ApiResponse(code = 200, message = "Input updated"), @ApiResponse(code = 403, message = "Restricted operation"), @ApiResponse(code = 400, message = "Invalid content / Missing content") })
104     public Response updateComponentInputs(
105             @ApiParam(value = "valid values: resources / services", allowableValues = ComponentTypeEnum.RESOURCE_PARAM_NAME + "," + ComponentTypeEnum.SERVICE_PARAM_NAME) @PathParam("containerComponentType") final String containerComponentType,
106             @PathParam("componentId") final String componentId,
107             @ApiParam(value = "json describe the input", required = true) String data, @Context final HttpServletRequest request) {
108
109         String url = request.getMethod() + " " + request.getRequestURI();
110         log.debug("Start handle request of {}", url);
111         String userId = request.getHeader(Constants.USER_ID_HEADER);
112
113         try {
114             User modifier = new User();
115             modifier.setUserId(userId);
116             log.debug("modifier id is {}", userId);
117
118             Either<InputDefinition[], ResponseFormat> inputsEither = getComponentsUtils()
119                     .convertJsonToObjectUsingObjectMapper(data, modifier, InputDefinition[].class,
120                             AuditingActionEnum.UPDATE_RESOURCE_METADATA, ComponentTypeEnum.SERVICE);
121             if(inputsEither.isRight()){
122                 log.debug("Failed to convert data to input definition. Status is {}", inputsEither.right().value());
123                 return buildErrorResponse(getComponentsUtils().getResponseFormat(ActionStatus.INVALID_CONTENT));
124             }
125             List<InputDefinition> inputsToUpdate = Arrays.asList(inputsEither.left().value());
126
127             log.debug("Start handle request of updateComponentInputs. Received inputs are {}", inputsToUpdate);
128
129             ServletContext context = request.getSession().getServletContext();
130             ComponentTypeEnum componentType = ComponentTypeEnum.findByParamName(containerComponentType);
131
132             if (businessLogic == null) {
133                 log.debug("Unsupported component type {}", containerComponentType);
134                 return buildErrorResponse(getComponentsUtils().getResponseFormat(ActionStatus.UNSUPPORTED_ERROR));
135             }
136
137             Either<List<InputDefinition>, ResponseFormat> actionResponse = inputsBusinessLogic.updateInputsValue(componentType, componentId, inputsToUpdate, userId, true, false);
138
139             if (actionResponse.isRight()) {
140                 return buildErrorResponse(actionResponse.right().value());
141             }
142
143             List<InputDefinition> componentInputs = actionResponse.left().value();
144             ObjectMapper mapper = new ObjectMapper();
145             String result = mapper.writeValueAsString(componentInputs);
146             return buildOkResponse(getComponentsUtils().getResponseFormat(ActionStatus.OK), result);
147
148         }
149         catch (Exception e) {
150             log.error("create and associate RI failed with exception: {}", e.getMessage(), e);
151             return buildErrorResponse(getComponentsUtils().getResponseFormat(ActionStatus.GENERAL_ERROR));
152         }
153     }
154
155
156     @GET
157     @Path("/{componentType}/{componentId}/componentInstances/{instanceId}/{originComponentUid}/inputs")
158     @ApiOperation(value = "Get Inputs only", httpMethod = "GET", notes = "Returns Inputs list", response = Resource.class)
159     @ApiResponses(value = { @ApiResponse(code = 200, message = "Component found"), @ApiResponse(code = 403, message = "Restricted operation"), @ApiResponse(code = 404, message = "Component not found") })
160     public Response getComponentInstanceInputs(@PathParam("componentType") final String componentType, @PathParam("componentId") final String componentId, @PathParam("instanceId") final String instanceId,
161                                                @PathParam("originComponentUid") final String originComponentUid, @Context final HttpServletRequest request, @HeaderParam(value = Constants.USER_ID_HEADER) String userId) {
162
163         ServletContext context = request.getSession().getServletContext();
164         String url = request.getMethod() + " " + request.getRequestURI();
165         log.debug("(get) Start handle request of {}", url);
166         Response response;
167
168         try {
169             Either<List<ComponentInstanceInput>, ResponseFormat> inputsResponse = inputsBusinessLogic.getComponentInstanceInputs(userId, componentId, instanceId);
170             if (inputsResponse.isRight()) {
171                 log.debug("failed to get component instance inputs {}", componentType);
172                 return buildErrorResponse(inputsResponse.right().value());
173             }
174             Object inputs = RepresentationUtils.toRepresentation(inputsResponse.left().value());
175             return buildOkResponse(getComponentsUtils().getResponseFormat(ActionStatus.OK), inputs);
176
177         } catch (Exception e) {
178             BeEcompErrorManager.getInstance().logBeRestApiGeneralError("Get Inputs " + componentType);
179             log.debug("getInputs failed with exception", e);
180             response = buildErrorResponse(getComponentsUtils().getResponseFormat(ActionStatus.GENERAL_ERROR));
181             return response;
182
183         }
184     }
185
186     @GET
187     @Path("/{componentType}/{componentId}/componentInstances/{instanceId}/{inputId}/properties")
188     @ApiOperation(value = "Get properties", httpMethod = "GET", notes = "Returns properties list", response = Resource.class)
189     @ApiResponses(value = { @ApiResponse(code = 200, message = "Component found"), @ApiResponse(code = 403, message = "Restricted operation"), @ApiResponse(code = 404, message = "Component not found") })
190     public Response getInputPropertiesForComponentInstance(@PathParam("componentType") final String componentType, @PathParam("componentId") final String componentId, @PathParam("instanceId") final String instanceId,
191             @PathParam("inputId") final String inputId, @Context final HttpServletRequest request, @HeaderParam(value = Constants.USER_ID_HEADER) String userId) {
192
193         ServletContext context = request.getSession().getServletContext();
194         String url = request.getMethod() + " " + request.getRequestURI();
195         log.debug("(GET) Start handle request of {}", url);
196         Response response = null;
197
198         try {
199             Either<List<ComponentInstanceProperty>, ResponseFormat> inputPropertiesRes = inputsBusinessLogic.getComponentInstancePropertiesByInputId(userId, componentId, instanceId, inputId);
200             if (inputPropertiesRes.isRight()) {
201                 log.debug("failed to get properties of input: {}, with instance id: {}", inputId, instanceId);
202                 return buildErrorResponse(inputPropertiesRes.right().value());
203             }
204             Object properties = RepresentationUtils.toRepresentation(inputPropertiesRes.left().value());
205             return buildOkResponse(getComponentsUtils().getResponseFormat(ActionStatus.OK), properties);
206
207         } catch (Exception e) {
208             BeEcompErrorManager.getInstance().logBeRestApiGeneralError("Get Properites by input id: " + inputId + " for instance with id: " + instanceId);
209             log.debug("getInputPropertiesForComponentInstance failed with exception", e);
210             response = buildErrorResponse(getComponentsUtils().getResponseFormat(ActionStatus.GENERAL_ERROR));
211             return response;
212
213         }
214     }
215
216     @GET
217     @Path("/{componentType}/{componentId}/inputs/{inputId}/inputs")
218     @ApiOperation(value = "Get inputs", httpMethod = "GET", notes = "Returns inputs list", response = Resource.class)
219     @ApiResponses(value = { @ApiResponse(code = 200, message = "Component found"), @ApiResponse(code = 403, message = "Restricted operation"), @ApiResponse(code = 404, message = "Component not found") })
220     public Response getInputsForComponentInput(@PathParam("componentType") final String componentType, @PathParam("componentId") final String componentId, @PathParam("inputId") final String inputId, @Context final HttpServletRequest request,
221             @HeaderParam(value = Constants.USER_ID_HEADER) String userId) {
222
223         ServletContext context = request.getSession().getServletContext();
224         String url = request.getMethod() + " " + request.getRequestURI();
225         log.debug("(get) Start handle request of {}", url);
226         Response response;
227         try {
228             Either<List<ComponentInstanceInput>, ResponseFormat> inputsRes = inputsBusinessLogic.getInputsForComponentInput(userId, componentId, inputId);
229
230             if (inputsRes.isRight()) {
231                 log.debug("failed to get inputs of input: {}, with instance id: {}", inputId, componentId);
232                 return buildErrorResponse(inputsRes.right().value());
233             }
234             Object properties = RepresentationUtils.toRepresentation(inputsRes.left().value());
235             return buildOkResponse(getComponentsUtils().getResponseFormat(ActionStatus.OK), properties);
236
237         } catch (Exception e) {
238             BeEcompErrorManager.getInstance().logBeRestApiGeneralError("Get inputs by input id: " + inputId + " for component with id: " + componentId);
239             log.debug("getInputsForComponentInput failed with exception", e);
240             response = buildErrorResponse(getComponentsUtils().getResponseFormat(ActionStatus.GENERAL_ERROR));
241             return response;
242
243         }
244     }
245
246     @GET
247     @Path("/{componentType}/{componentId}/inputs/{inputId}")
248     @ApiOperation(value = "Get inputs", httpMethod = "GET", notes = "Returns inputs list", response = Resource.class)
249     @ApiResponses(value = { @ApiResponse(code = 200, message = "Component found"), @ApiResponse(code = 403, message = "Restricted operation"), @ApiResponse(code = 404, message = "Component not found") })
250     public Response getInputsAndPropertiesForComponentInput(@PathParam("componentType") final String componentType, @PathParam("componentId") final String componentId, @PathParam("inputId") final String inputId, @Context final HttpServletRequest request,
251             @HeaderParam(value = Constants.USER_ID_HEADER) String userId) {
252
253         ServletContext context = request.getSession().getServletContext();
254         String url = request.getMethod() + " " + request.getRequestURI();
255         log.debug("(get) Start handle request of {}", url);
256         Response response;
257
258         try {
259             Either<InputDefinition, ResponseFormat> inputsRes = inputsBusinessLogic.getInputsAndPropertiesForComponentInput(userId, componentId, inputId, false);
260
261             if (inputsRes.isRight()) {
262                 log.debug("failed to get inputs of input: {}, with instance id: {}", inputId, componentId);
263                 return buildErrorResponse(inputsRes.right().value());
264             }
265             Object properties = RepresentationUtils.toRepresentation(inputsRes.left().value());
266             return buildOkResponse(getComponentsUtils().getResponseFormat(ActionStatus.OK), properties);
267
268         } catch (Exception e) {
269             BeEcompErrorManager.getInstance().logBeRestApiGeneralError("Get inputs by input id: " + inputId + " for component with id: " + componentId);
270             log.debug("getInputsForComponentInput failed with exception", e);
271             response = buildErrorResponse(getComponentsUtils().getResponseFormat(ActionStatus.GENERAL_ERROR));
272             return response;
273
274         }
275     }
276
277     private Either<ComponentInstInputsMap, ResponseFormat> parseToComponentInstanceMap(String serviceJson, User user) {
278         return getComponentsUtils().convertJsonToObjectUsingObjectMapper(serviceJson, user, ComponentInstInputsMap.class, AuditingActionEnum.CREATE_RESOURCE, ComponentTypeEnum.SERVICE);
279     }
280
281     private Either<ComponentInstListInput, ResponseFormat> parseToComponentInstListInput(String json, User user) {
282         return getComponentsUtils().convertJsonToObjectUsingObjectMapper(json, user, ComponentInstListInput.class, AuditingActionEnum.CREATE_RESOURCE, ComponentTypeEnum.SERVICE);
283     }
284
285     @POST
286     @Path("/{componentType}/{componentId}/create/inputs")
287     @ApiOperation(value = "Create inputs on service", httpMethod = "POST", notes = "Return inputs list", response = Resource.class)
288     @ApiResponses(value = { @ApiResponse(code = 200, message = "Component found"), @ApiResponse(code = 403, message = "Restricted operation"), @ApiResponse(code = 404, message = "Component not found") })
289     public Response createMultipleInputs(@PathParam("componentType") final String componentType, @PathParam("componentId") final String componentId, @Context final HttpServletRequest request,
290             @HeaderParam(value = Constants.USER_ID_HEADER) String userId, @ApiParam(value = "ComponentIns Inputs Object to be created", required = true) String componentInstInputsMapObj) {
291
292         return super.declareProperties(userId, componentId, componentType, componentInstInputsMapObj,
293                 DeclarationTypeEnum.INPUT, request);
294     }
295
296
297     /**
298      * Creates a "list input" and updates given list of properties to get value from the input.
299      * also a data type which has same properties is created.
300      * the data type will be the entry_schema of the list input.
301      * @param componentType the container type (service, resource, ...)
302      * @param componentId the container ID
303      * @param request HttpServletRequest object
304      * @param userId the User ID
305      * @param componentInstInputsMapObj the list of properties to be declared and the "list input" to be created.
306      *                                  the type of the input must be "list".
307      *                                  schema.type of the input will be the name of new data type.
308      * @return the created input
309      */
310     @POST
311     @Path("/{componentType}/{componentId}/create/listInput")
312     @ApiOperation(value = "Create a list input on service", httpMethod = "POST", notes = "Return input", response = Resource.class)
313     @ApiResponses(value = { @ApiResponse(code = 200, message = "Component found"), @ApiResponse(code = 403, message = "Restricted operation"), @ApiResponse(code = 404, message = "Component not found") })
314     public Response createListInput(@PathParam("componentType") final String componentType, @PathParam("componentId") final String componentId, @Context final HttpServletRequest request,
315                                          @HeaderParam(value = Constants.USER_ID_HEADER) String userId, @ApiParam(value = "ComponentIns Inputs Object to be created", required = true) String componentInstInputsMapObj) {
316
317         ServletContext context = request.getSession().getServletContext();
318         String url = request.getMethod() + " " + request.getRequestURI();
319         log.debug("#createListInput: Start handle request of {}", url);
320         Response response = null;
321
322         try {
323             // get modifier id
324             User modifier = new User();
325             modifier.setUserId(userId);
326             log.debug("modifier id is {}", userId);
327
328             Either<ComponentInstListInput, ResponseFormat> componentInstInputsMapRes =
329                 parseToComponentInstListInput(componentInstInputsMapObj, modifier);
330             if (componentInstInputsMapRes.isRight()) {
331                 log.debug("failed to parse componentInstInputsMap");
332                 response = buildErrorResponse(componentInstInputsMapRes.right().value());
333                 return response;
334             }
335
336             ComponentTypeEnum componentTypeEnum = ComponentTypeEnum.findByParamName(componentType);
337             ComponentInstListInput componentInstInputsMap = componentInstInputsMapRes.left().value();
338             if (log.isDebugEnabled()) {
339                 // for inspection on debug
340                 log.debug("parsed componentInstInputsMap={}", ReflectionToStringBuilder.toString(componentInstInputsMap));
341             }
342
343             Either<List<InputDefinition>, ResponseFormat> inputPropertiesRes = inputsBusinessLogic.createListInput(
344                 userId, componentId, componentTypeEnum, componentInstInputsMap, true, false);
345             if (inputPropertiesRes.isRight()) {
346                 log.debug("failed to create list input for service: {}", componentId);
347                 return buildErrorResponse(inputPropertiesRes.right().value());
348             }
349             Object properties = RepresentationUtils.toRepresentation(inputPropertiesRes.left().value());
350             return buildOkResponse(getComponentsUtils().getResponseFormat(ActionStatus.OK), properties);
351
352         } catch (Exception e) {
353             BeEcompErrorManager.getInstance().logBeRestApiGeneralError("Create list input for service with id: " + componentId);
354             log.debug("createListInput failed with exception", e);
355             response = buildErrorResponse(getComponentsUtils().getResponseFormat(ActionStatus.GENERAL_ERROR));
356             return response;
357         }
358     }
359
360
361     @DELETE
362     @Path("/{componentType}/{componentId}/delete/{inputId}/input")
363     @ApiOperation(value = "Delete input from service", httpMethod = "DELETE", notes = "Delete service input", response = Resource.class)
364     @ApiResponses(value = { @ApiResponse(code = 200, message = "Input deleted"), @ApiResponse(code = 403, message = "Restricted operation"), @ApiResponse(code = 404, message = "Input not found") })
365     public Response deleteInput (
366             @PathParam("componentType") final String componentType,
367             @PathParam("componentId") final String componentId,
368             @PathParam("inputId") final String inputId,
369             @Context final HttpServletRequest request,
370             @HeaderParam(value = Constants.USER_ID_HEADER) String userId,
371             @ApiParam(value = "Service Input to be deleted", required = true) String componentInstInputsMapObj) {
372
373         ServletContext context = request.getSession().getServletContext();
374         String url = request.getMethod() + " " + request.getRequestURI();
375         log.debug("(get) Start handle request of {}", url);
376         Response response = null;
377
378         try {
379             Either<InputDefinition, ResponseFormat> deleteInput = inputsBusinessLogic.deleteInput(componentId, userId, inputId);
380             if (deleteInput.isRight()){
381                 ResponseFormat deleteResponseFormat = deleteInput.right().value();
382                 response = buildErrorResponse(deleteResponseFormat);
383                 return response;
384             }
385             return buildOkResponse(getComponentsUtils().getResponseFormat(ActionStatus.OK), deleteInput.left().value());
386         } catch (Exception e){
387             BeEcompErrorManager.getInstance().logBeRestApiGeneralError("Delete input for service + " + componentId + " + with id: " + inputId);
388             log.debug("Delete input failed with exception", e);
389             response = buildErrorResponse(getComponentsUtils().getResponseFormat(ActionStatus.GENERAL_ERROR));
390             return response;
391
392         }
393     }
394
395     /**
396      * Gets a specific data type associated with a component.
397      * @param componentType the container type (service, resource, ...)
398      * @param componentId the container ID
399      * @param dataTypeName the data type name
400      * @param request HttpServletRequest object
401      * @return the data type info
402      */
403     @GET
404     @Path("/{componentType}/{componentId}/dataType/{dataTypeName}")
405     @ApiOperation(value = "Get data type in service", httpMethod = "GET", notes = "Get data type in service",
406             response = DataTypeDefinition.class)
407     @ApiResponses(value = {
408             @ApiResponse(code = 200, message = "Data type found"),
409             @ApiResponse(code = 403, message = "Restricted operation"),
410             @ApiResponse(code = 404, message = "Data type not found")})
411     public Response getDataType(
412             @PathParam("componentType") final String componentType,
413             @PathParam("componentId") final String componentId,
414             @PathParam("dataTypeName") final String dataTypeName,
415             @Context final HttpServletRequest request
416     ) {
417         ComponentsUtils componentsUtils = getComponentsUtils();
418         String url = request.getMethod() + " " + request.getRequestURI();
419         log.debug("(getDataType) Start handle request of {}", url);
420         Response response;
421
422         try {
423             Either<DataTypeDefinition, StorageOperationStatus> getResult = businessLogic.getPrivateDataType(componentId, dataTypeName);
424             if (getResult.isRight()) {
425                 ActionStatus actionStatus = componentsUtils.convertFromStorageResponse(getResult.right().value());
426                 return buildErrorResponse(componentsUtils.getResponseFormat(actionStatus));
427             }
428             Object json = RepresentationUtils.toRepresentation(getResult.left().value());
429             return buildOkResponse(componentsUtils.getResponseFormat(ActionStatus.OK), json);
430         } catch (Exception e) {
431             BeEcompErrorManager.getInstance().logBeRestApiGeneralError("Get data type from service + " + componentId + " + with name: " + dataTypeName);
432             log.debug("Get data type failed with exception", e);
433             response = buildErrorResponse(componentsUtils.getResponseFormat(ActionStatus.GENERAL_ERROR));
434             return response;
435         }
436     }
437
438     /**
439      * Gets a list of data types which a component has.
440      * @param componentType the container type (service, resource, ...)
441      * @param componentId the container ID
442      * @param request HttpServletRequest object
443      * @return the list of data types in the component
444      */
445     @GET
446     @Path("/{componentType}/{componentId}/dataTypes")
447     @ApiOperation(value = "Get data types that service has", httpMethod = "GET", notes = "Get data types in service",
448             response = Resource.class)
449     @ApiResponses(value = {
450             @ApiResponse(code = 200, message = "Data type found"),
451             @ApiResponse(code = 403, message = "Restricted operation"),
452             @ApiResponse(code = 404, message = "Component not found")})
453     public Response getDataTypes(
454             @PathParam("componentType") final String componentType,
455             @PathParam("componentId") final String componentId,
456             @Context final HttpServletRequest request
457     ) {
458         ServletContext context = request.getSession().getServletContext();
459         ComponentsUtils componentsUtils = getComponentsUtils();
460         String url = request.getMethod() + " " + request.getRequestURI();
461         log.debug("(getDataType) Start handle request of {}", url);
462         Response response;
463
464         try {
465             Either<List<DataTypeDefinition>, StorageOperationStatus> getResult = businessLogic.getPrivateDataTypes(componentId);
466             if (getResult.isRight()) {
467                 ActionStatus actionStatus = componentsUtils.convertFromStorageResponse(getResult.right().value());
468                 return buildErrorResponse(componentsUtils.getResponseFormat(actionStatus));
469             }
470             Object json = RepresentationUtils.toRepresentation(getResult.left().value());
471             return buildOkResponse(componentsUtils.getResponseFormat(ActionStatus.OK), json);
472         } catch (Exception e) {
473             BeEcompErrorManager.getInstance().logBeRestApiGeneralError("Get data type from service + " + componentId);
474             log.debug("Get data type failed with exception", e);
475             response = buildErrorResponse(componentsUtils.getResponseFormat(ActionStatus.GENERAL_ERROR));
476             return response;
477         }
478     }
479
480     /**
481      * Deletes a data type from a component.
482      * @param componentType the container type (service, resource, ...)
483      * @param componentId the container ID
484      * @param dataTypeName the data type name to be deleted
485      * @param request HttpServletRequest object
486      * @return operation result
487      */
488     @DELETE
489     @Path("/{componentType}/{componentId}/dataType/{dataTypeName}")
490     @ApiOperation(value = "Delete data type from service", httpMethod = "DELETE", notes = "Delete service input",
491             response = Resource.class)
492     @ApiResponses(value = {
493             @ApiResponse(code = 200, message = "Data type deleted"),
494             @ApiResponse(code = 403, message = "Restricted operation"),
495             @ApiResponse(code = 404, message = "Data type not found")})
496     public Response deleteDataType(
497             @PathParam("componentType") final String componentType,
498             @PathParam("componentId") final String componentId,
499             @PathParam("dataTypeName") final String dataTypeName,
500             @Context final HttpServletRequest request
501     ) {
502         ServletContext context = request.getSession().getServletContext();
503         ComponentsUtils componentsUtils = getComponentsUtils();
504         String url = request.getMethod() + " " + request.getRequestURI();
505         log.debug("(get) Start handle request of {}", url);
506         Response response;
507
508         try {
509             Either<DataTypeDefinition, StorageOperationStatus> deleteResult = businessLogic.deletePrivateDataType(componentId, dataTypeName);
510             if (deleteResult.isRight()) {
511                 ActionStatus actionStatus = componentsUtils.convertFromStorageResponse(deleteResult.right().value());
512                 return buildErrorResponse(componentsUtils.getResponseFormat(actionStatus));
513             }
514             Object json = RepresentationUtils.toRepresentation(deleteResult.left().value());
515             return buildOkResponse(componentsUtils.getResponseFormat(ActionStatus.OK), json);
516         } catch (Exception e) {
517             BeEcompErrorManager.getInstance().logBeRestApiGeneralError("Delete data type for service + " + componentId + " + with name: " + dataTypeName);
518             log.debug("Delete data type failed with exception", e);
519             response = buildErrorResponse(componentsUtils.getResponseFormat(ActionStatus.GENERAL_ERROR));
520             return response;
521         }
522     }
523 }