Fix 'Data type cache not updated when data type updated'-bug
[sdc.git] / catalog-be / src / main / java / org / openecomp / sdc / be / servlets / DataTypeServlet.java
1 /*
2  * ============LICENSE_START=======================================================
3  * SDC
4  * ================================================================================
5  * Copyright (C) 2022 Nordix Foundation. 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.jcabi.aspects.Loggable;
24 import io.swagger.v3.oas.annotations.Operation;
25 import io.swagger.v3.oas.annotations.Parameter;
26 import io.swagger.v3.oas.annotations.enums.ParameterIn;
27 import io.swagger.v3.oas.annotations.media.ArraySchema;
28 import io.swagger.v3.oas.annotations.media.Content;
29 import io.swagger.v3.oas.annotations.media.Schema;
30 import io.swagger.v3.oas.annotations.parameters.RequestBody;
31 import io.swagger.v3.oas.annotations.responses.ApiResponse;
32 import io.swagger.v3.oas.annotations.servers.Server;
33 import io.swagger.v3.oas.annotations.tags.Tag;
34 import java.util.List;
35 import java.util.Optional;
36 import javax.servlet.http.HttpServletRequest;
37 import javax.ws.rs.Consumes;
38 import javax.ws.rs.GET;
39 import javax.ws.rs.HeaderParam;
40 import javax.ws.rs.POST;
41 import javax.ws.rs.Path;
42 import javax.ws.rs.PathParam;
43 import javax.ws.rs.Produces;
44 import javax.ws.rs.core.Context;
45 import javax.ws.rs.core.MediaType;
46 import javax.ws.rs.core.Response;
47 import javax.ws.rs.core.Response.Status;
48 import org.openecomp.sdc.be.components.impl.DataTypeBusinessLogic;
49 import org.openecomp.sdc.be.components.impl.aaf.AafPermission;
50 import org.openecomp.sdc.be.components.impl.aaf.PermissionAllowed;
51 import org.openecomp.sdc.be.config.BeEcompErrorManager;
52 import org.openecomp.sdc.be.dao.api.ActionStatus;
53 import org.openecomp.sdc.be.datatypes.elements.DataTypeDataDefinition;
54 import org.openecomp.sdc.be.exception.BusinessException;
55 import org.openecomp.sdc.be.impl.ComponentsUtils;
56 import org.openecomp.sdc.be.model.PropertyDefinition;
57 import org.openecomp.sdc.be.model.dto.PropertyDefinitionDto;
58 import org.openecomp.sdc.be.model.jsonjanusgraph.operations.exception.OperationException;
59 import org.openecomp.sdc.be.model.operations.impl.DataTypeOperation;
60 import org.openecomp.sdc.common.api.Constants;
61 import org.openecomp.sdc.common.log.enums.EcompLoggerErrorCode;
62 import org.openecomp.sdc.common.log.wrappers.Logger;
63 import org.springframework.stereotype.Controller;
64
65 @Loggable(prepend = true, value = Loggable.DEBUG, trim = false)
66 @Path("/v1/catalog/data-types")
67 @Tag(name = "SDCE-2 APIs")
68 @Server(url = "/sdc2/rest")
69 @Controller
70 public class DataTypeServlet extends BeGenericServlet {
71
72     private static final Logger log = Logger.getLogger(DataTypeServlet.class);
73     private final DataTypeOperation dataTypeOperation;
74     private final DataTypeBusinessLogic dataTypeBusinessLogic;
75
76     public DataTypeServlet(final ComponentsUtils componentsUtils,
77                            final DataTypeOperation dataTypeOperation, DataTypeBusinessLogic dataTypeBusinessLogic) {
78         super(componentsUtils);
79         this.dataTypeOperation = dataTypeOperation;
80         this.dataTypeBusinessLogic = dataTypeBusinessLogic;
81     }
82
83     @GET
84     @Path("{dataTypeUid}")
85     @Consumes(MediaType.APPLICATION_JSON)
86     @Produces(MediaType.APPLICATION_JSON)
87     @Operation(description = "Get data types", method = "GET", summary = "Returns data types", responses = {
88         @ApiResponse(content = @Content(schema = @Schema(implementation = DataTypeDataDefinition.class))),
89         @ApiResponse(responseCode = "200", description = "Data type found"),
90         @ApiResponse(responseCode = "403", description = "Restricted operation"),
91         @ApiResponse(responseCode = "400", description = "Invalid content / Missing content"),
92         @ApiResponse(responseCode = "404", description = "Data types not found")})
93     @PermissionAllowed(AafPermission.PermNames.INTERNAL_ALL_VALUE)
94     public Response fetchDataType(@Context final HttpServletRequest request,
95                                   @HeaderParam(value = Constants.USER_ID_HEADER) String userId,
96                                   @PathParam("dataTypeUid") String dataTypeUid) {
97         final String url = request.getMethod() + " " + request.getRequestURI();
98         log.debug("Start handle request of {} - modifier id is {}", url, userId);
99         final Optional<DataTypeDataDefinition> dataTypeFoundOptional;
100         try {
101             dataTypeFoundOptional = dataTypeOperation.getDataTypeByUid(dataTypeUid);
102         } catch (final BusinessException e) {
103             throw e;
104         } catch (final Exception ex) {
105             final String errorMsg = "Unexpected error while listing the Tosca DataType";
106             BeEcompErrorManager.getInstance().logBeRestApiGeneralError(errorMsg);
107             log.error(EcompLoggerErrorCode.UNKNOWN_ERROR, this.getClass().getName(), errorMsg, ex);
108             return buildErrorResponse(getComponentsUtils().getResponseFormat(ActionStatus.GENERAL_ERROR));
109         }
110         var dataType = dataTypeFoundOptional.orElseThrow(() -> new OperationException(ActionStatus.DATA_TYPE_NOT_FOUND, dataTypeUid));
111         return buildOkResponse(getComponentsUtils().getResponseFormat(ActionStatus.OK), dataType);
112     }
113
114     @GET
115     @Path("{id}/properties")
116     @Consumes(MediaType.APPLICATION_JSON)
117     @Produces(MediaType.APPLICATION_JSON)
118     @Operation(description = "Get a data type properties", method = "GET", summary = "Returns the data type properties", responses = {
119         @ApiResponse(content = @Content(array = @ArraySchema(schema = @Schema(implementation = PropertyDefinition.class)))),
120         @ApiResponse(responseCode = "200", description = "Data type found, properties may be empty"),
121         @ApiResponse(responseCode = "403", description = "Restricted operation"),
122         @ApiResponse(responseCode = "404", description = "Data type not found")})
123     @PermissionAllowed(AafPermission.PermNames.INTERNAL_ALL_VALUE)
124     public Response fetchProperties(@Parameter(in = ParameterIn.PATH, required = true, description = "The data type id")
125                                     @PathParam("id") final String id) {
126         final List<PropertyDefinition> allProperties = dataTypeOperation.findAllProperties(id);
127         return buildOkResponse(allProperties);
128     }
129
130     @POST
131     @Path("{id}/properties")
132     @Consumes(MediaType.APPLICATION_JSON)
133     @Produces(MediaType.APPLICATION_JSON)
134     @Operation(summary = "Create a property in the given data type", method = "POST", description = "Create a property in the given data type",
135         responses = {
136             @ApiResponse(content = @Content(schema = @Schema(implementation = PropertyDefinitionDto.class))),
137             @ApiResponse(responseCode = "201", description = "Property created in the data type"),
138             @ApiResponse(responseCode = "400", description = "Invalid payload"),
139             @ApiResponse(responseCode = "409", description = "Property already exists in the data type"),
140             @ApiResponse(responseCode = "403", description = "Restricted operation"),
141             @ApiResponse(responseCode = "404", description = "Data type not found")
142         })
143     @PermissionAllowed(AafPermission.PermNames.INTERNAL_ALL_VALUE)
144     public Response createProperty(@Parameter(in = ParameterIn.PATH, required = true, description = "The data type id")
145                                    @PathParam("id") final String id,
146                                    @RequestBody(description = "Property to add", required = true) final PropertyDefinitionDto propertyDefinitionDto) {
147         final PropertyDefinitionDto property = dataTypeOperation.createProperty(id, propertyDefinitionDto);
148         dataTypeBusinessLogic.updateApplicationDataTypeCache(id);
149         return Response.status(Status.CREATED).entity(property).build();
150     }
151
152 }