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