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