404c045decf57cbb05bd10fe3b75f256aa0e6a25
[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.DELETE;
39 import javax.ws.rs.GET;
40 import javax.ws.rs.HeaderParam;
41 import javax.ws.rs.POST;
42 import javax.ws.rs.PUT;
43 import javax.ws.rs.Path;
44 import javax.ws.rs.PathParam;
45 import javax.ws.rs.Produces;
46 import javax.ws.rs.core.Context;
47 import javax.ws.rs.core.MediaType;
48 import javax.ws.rs.core.Response;
49 import javax.ws.rs.core.Response.Status;
50 import org.apache.commons.lang3.StringUtils;
51 import org.openecomp.sdc.be.components.impl.DataTypeBusinessLogic;
52 import org.openecomp.sdc.be.components.impl.aaf.AafPermission;
53 import org.openecomp.sdc.be.components.impl.aaf.PermissionAllowed;
54 import org.openecomp.sdc.be.config.BeEcompErrorManager;
55 import org.openecomp.sdc.be.dao.api.ActionStatus;
56 import org.openecomp.sdc.be.datatypes.elements.DataTypeDataDefinition;
57 import org.openecomp.sdc.be.exception.BusinessException;
58 import org.openecomp.sdc.be.impl.ComponentsUtils;
59 import org.openecomp.sdc.be.model.PropertyDefinition;
60 import org.openecomp.sdc.be.model.dto.PropertyDefinitionDto;
61 import org.openecomp.sdc.be.model.jsonjanusgraph.operations.exception.OperationException;
62 import org.openecomp.sdc.be.model.normatives.ElementTypeEnum;
63 import org.openecomp.sdc.be.model.operations.impl.DataTypeOperation;
64 import org.openecomp.sdc.common.api.Constants;
65 import org.openecomp.sdc.common.log.enums.EcompLoggerErrorCode;
66 import org.openecomp.sdc.common.log.wrappers.Logger;
67 import org.springframework.stereotype.Controller;
68
69 @Loggable(prepend = true, value = Loggable.DEBUG, trim = false)
70 @Path("/v1/catalog/data-types")
71 @Tag(name = "SDCE-2 APIs")
72 @Server(url = "/sdc2/rest")
73 @Controller
74 public class DataTypeServlet extends BeGenericServlet {
75
76     private static final Logger log = Logger.getLogger(DataTypeServlet.class);
77     private final DataTypeOperation dataTypeOperation;
78     private final DataTypeBusinessLogic dataTypeBusinessLogic;
79
80     public DataTypeServlet(final ComponentsUtils componentsUtils,
81                            final DataTypeOperation dataTypeOperation, DataTypeBusinessLogic dataTypeBusinessLogic) {
82         super(componentsUtils);
83         this.dataTypeOperation = dataTypeOperation;
84         this.dataTypeBusinessLogic = dataTypeBusinessLogic;
85     }
86
87     @GET
88     @Path("{dataTypeUid}")
89     @Consumes(MediaType.APPLICATION_JSON)
90     @Produces(MediaType.APPLICATION_JSON)
91     @Operation(description = "Get data types", method = "GET", summary = "Returns data types", responses = {
92         @ApiResponse(content = @Content(schema = @Schema(implementation = DataTypeDataDefinition.class))),
93         @ApiResponse(responseCode = "200", description = "Data type found"),
94         @ApiResponse(responseCode = "403", description = "Restricted operation"),
95         @ApiResponse(responseCode = "400", description = "Invalid content / Missing content"),
96         @ApiResponse(responseCode = "404", description = "Data types not found")})
97     @PermissionAllowed(AafPermission.PermNames.INTERNAL_ALL_VALUE)
98     public Response fetchDataType(@Context final HttpServletRequest request,
99                                   @HeaderParam(value = Constants.USER_ID_HEADER) String userId,
100                                   @PathParam("dataTypeUid") String dataTypeUid) {
101         final String url = request.getMethod() + " " + request.getRequestURI();
102         log.debug("Start handle request of {} - modifier id is {}", url, userId);
103         final Optional<DataTypeDataDefinition> dataTypeFoundOptional;
104         try {
105             dataTypeFoundOptional = dataTypeOperation.getDataTypeByUid(dataTypeUid);
106         } catch (final BusinessException e) {
107             throw e;
108         } catch (final Exception ex) {
109             final String errorMsg = "Unexpected error while listing the Tosca DataType";
110             BeEcompErrorManager.getInstance().logBeRestApiGeneralError(errorMsg);
111             log.error(EcompLoggerErrorCode.UNKNOWN_ERROR, this.getClass().getName(), errorMsg, ex);
112             return buildErrorResponse(getComponentsUtils().getResponseFormat(ActionStatus.GENERAL_ERROR));
113         }
114         var dataType = dataTypeFoundOptional.orElseThrow(() -> new OperationException(ActionStatus.DATA_TYPE_NOT_FOUND, dataTypeUid));
115         return buildOkResponse(getComponentsUtils().getResponseFormat(ActionStatus.OK), dataType);
116     }
117
118     @GET
119     @Path("{id}/properties")
120     @Consumes(MediaType.APPLICATION_JSON)
121     @Produces(MediaType.APPLICATION_JSON)
122     @Operation(description = "Get a data type properties", method = "GET", summary = "Returns the data type properties", responses = {
123         @ApiResponse(content = @Content(array = @ArraySchema(schema = @Schema(implementation = PropertyDefinition.class)))),
124         @ApiResponse(responseCode = "200", description = "Data type found, properties may be empty"),
125         @ApiResponse(responseCode = "403", description = "Restricted operation"),
126         @ApiResponse(responseCode = "404", description = "Data type not found")})
127     @PermissionAllowed(AafPermission.PermNames.INTERNAL_ALL_VALUE)
128     public Response fetchProperties(@Parameter(in = ParameterIn.PATH, required = true, description = "The data type id")
129                                     @PathParam("id") final String id) {
130         final List<PropertyDefinition> allProperties = dataTypeOperation.findAllProperties(id);
131         return buildOkResponse(allProperties);
132     }
133
134     @POST
135     @Path("{id}/properties")
136     @Consumes(MediaType.APPLICATION_JSON)
137     @Produces(MediaType.APPLICATION_JSON)
138     @Operation(summary = "Create a property in the given data type", method = "POST", description = "Create a property in the given data type",
139         responses = {
140             @ApiResponse(content = @Content(schema = @Schema(implementation = PropertyDefinitionDto.class))),
141             @ApiResponse(responseCode = "201", description = "Property created in the data type"),
142             @ApiResponse(responseCode = "400", description = "Invalid payload"),
143             @ApiResponse(responseCode = "409", description = "Property already exists in the data type"),
144             @ApiResponse(responseCode = "403", description = "Restricted operation"),
145             @ApiResponse(responseCode = "404", description = "Data type not found")
146         })
147     @PermissionAllowed(AafPermission.PermNames.INTERNAL_ALL_VALUE)
148     public Response createProperty(@Parameter(in = ParameterIn.PATH, required = true, description = "The data type id")
149                                    @PathParam("id") final String id,
150                                    @RequestBody(description = "Property to add", required = true) final PropertyDefinitionDto propertyDefinitionDto) {
151         Optional<DataTypeDataDefinition> dataTypeOptional = dataTypeOperation.getDataTypeByUid(id);
152         dataTypeOptional.orElseThrow(() -> {
153             throw new OperationException(ActionStatus.DATA_TYPE_NOT_FOUND, String.format("Failed to find data type '%s'", id));
154         });
155         DataTypeDataDefinition dataType = dataTypeOptional.get();
156         String model = dataType.getModel();
157         Optional<DataTypeDataDefinition> propertyDataType = dataTypeOperation.getDataTypeByNameAndModel(propertyDefinitionDto.getType(), model);
158         if (propertyDataType.isEmpty()) {
159             if (StringUtils.isEmpty(model)) {
160                 model = Constants.DEFAULT_MODEL_NAME;
161             }
162             throw new OperationException(ActionStatus.INVALID_MODEL,
163                 String.format("Property model is not the same as the data type model. Must be '%s'", model));
164         }
165         if (StringUtils.isEmpty(dataType.getModel())) {
166             dataType.setModel(Constants.DEFAULT_MODEL_NAME);
167         }
168         final PropertyDefinitionDto property = dataTypeOperation.createProperty(id, propertyDefinitionDto);
169         dataTypeOperation.updatePropertyInAdditionalTypeDataType(dataType, property, true);
170         dataTypeBusinessLogic.updateApplicationDataTypeCache(id);
171         return Response.status(Status.CREATED).entity(property).build();
172     }
173
174     @PUT
175     @Path("{id}/properties")
176     @Consumes(MediaType.APPLICATION_JSON)
177     @Produces(MediaType.APPLICATION_JSON)
178     @Operation(summary = "Update a property in the given data type", method = "POST", description = "Update a property in the given data type",
179         responses = {
180             @ApiResponse(content = @Content(schema = @Schema(implementation = PropertyDefinitionDto.class))),
181             @ApiResponse(responseCode = "201", description = "Property updated in the data type"),
182             @ApiResponse(responseCode = "400", description = "Invalid payload"),
183             @ApiResponse(responseCode = "403", description = "Restricted operation"),
184             @ApiResponse(responseCode = "404", description = "Data type not found")
185         })
186     @PermissionAllowed(AafPermission.PermNames.INTERNAL_ALL_VALUE)
187     public Response updateProperty(@Parameter(in = ParameterIn.PATH, required = true, description = "The data type id")
188                                    @PathParam("id") final String id,
189                                    @RequestBody(description = "Property to update", required = true)
190                                    final PropertyDefinitionDto propertyDefinitionDto) {
191         Optional<DataTypeDataDefinition> dataTypeOptional = dataTypeOperation.getDataTypeByUid(id);
192         dataTypeOptional.orElseThrow(() -> {
193             throw new OperationException(ActionStatus.DATA_TYPE_NOT_FOUND, String.format("Failed to find data type '%s'", id));
194         });
195         DataTypeDataDefinition dataType = dataTypeOptional.get();
196         String model = dataType.getModel();
197         Optional<DataTypeDataDefinition> propertyDataType = dataTypeOperation.getDataTypeByNameAndModel(propertyDefinitionDto.getType(), model);
198         if (propertyDataType.isEmpty()) {
199             if (StringUtils.isEmpty(model)) {
200                 model = Constants.DEFAULT_MODEL_NAME;
201             }
202             throw new OperationException(ActionStatus.INVALID_MODEL,
203                 String.format("Property model is not the same as the data type model. Must be '%s'", model));
204         }
205         if (StringUtils.isEmpty(dataType.getModel())) {
206             dataType.setModel(Constants.DEFAULT_MODEL_NAME);
207         }
208         final PropertyDefinitionDto property = dataTypeOperation.updateProperty(id, propertyDefinitionDto);
209         dataTypeOperation.updatePropertyInAdditionalTypeDataType(dataType, property, true);
210         dataTypeBusinessLogic.updateApplicationDataTypeCache(id);
211         return Response.status(Status.CREATED).entity(property).build();
212     }
213
214     @GET
215     @Path("{dataTypeName}/models")
216     @Consumes(MediaType.APPLICATION_JSON)
217     @Produces(MediaType.APPLICATION_JSON)
218     @Operation(description = "Get models for type", method = "GET", summary = "Returns list of models for type", responses = {
219         @ApiResponse(content = @Content(array = @ArraySchema(schema = @Schema(implementation = Response.class)))),
220         @ApiResponse(responseCode = "200", description = "dataTypeModels"), @ApiResponse(responseCode = "403", description = "Restricted operation"),
221         @ApiResponse(responseCode = "400", description = "Invalid content / Missing content"),
222         @ApiResponse(responseCode = "403", description = "Restricted operation"),
223         @ApiResponse(responseCode = "404", description = "Data type not found")})
224     @PermissionAllowed(AafPermission.PermNames.INTERNAL_ALL_VALUE)
225     public Response getDataTypeModels(@PathParam("dataTypeName") String dataTypeName) {
226         return buildOkResponse(getComponentsUtils().getResponseFormat(ActionStatus.OK),
227             gson.toJson(dataTypeOperation.getAllDataTypeModels(dataTypeName)));
228     }
229
230     @DELETE
231     @Path("{dataTypeId}/{propertyId}")
232     public Response deleteProperty(@Parameter(in = ParameterIn.PATH, required = true, description = "The data type id")
233                                    @PathParam("dataTypeId") final String dataTypeId,
234                                    @Parameter(in = ParameterIn.PATH, required = true, description = "The property id to delete")
235                                    @PathParam("propertyId") final String propertyId) {
236         final Optional<DataTypeDataDefinition> dataTypeOptional = dataTypeOperation.getDataTypeByUid(dataTypeId);
237         dataTypeOptional.orElseThrow(() -> {
238             throw new OperationException(ActionStatus.DATA_TYPE_NOT_FOUND, String.format("Failed to find data type '%s'", dataTypeId));
239         });
240         final DataTypeDataDefinition dataTypeDataDefinition = dataTypeOptional.get();
241         if (StringUtils.isEmpty(dataTypeDataDefinition.getModel())) {
242             dataTypeDataDefinition.setModel(Constants.DEFAULT_MODEL_NAME);
243         }
244         final PropertyDefinitionDto propertyDefinitionDto;
245         try {
246             propertyDefinitionDto = dataTypeOperation.deleteProperty(dataTypeDataDefinition, propertyId);
247             dataTypeOperation.updatePropertyInAdditionalTypeDataType(dataTypeDataDefinition, propertyDefinitionDto, false);
248         } catch (OperationException e) {
249             final PropertyDefinitionDto dto = new PropertyDefinitionDto();
250             dto.setName(extractNameFromPropertyId(propertyId));
251             dataTypeOperation.updatePropertyInAdditionalTypeDataType(dataTypeDataDefinition, dto, false);
252             throw e;
253         } finally {
254             dataTypeBusinessLogic.updateApplicationDataTypeCache(dataTypeId);
255         }
256         return Response.status(Status.OK).entity(propertyDefinitionDto).build();
257     }
258
259     @DELETE
260     @Path("{dataTypeId}")
261     public Response deleteDatatype(@Parameter(in = ParameterIn.PATH, required = true, description = "The data type id")
262                                    @PathParam("dataTypeId") final String dataTypeId) {
263         final Optional<DataTypeDataDefinition> dataTypeOptional = dataTypeOperation.getDataTypeByUid(dataTypeId);
264         dataTypeOptional.orElseThrow(() -> {
265             throw new OperationException(ActionStatus.DATA_TYPE_NOT_FOUND, String.format("Failed to find data type '%s'", dataTypeId));
266         });
267         final DataTypeDataDefinition dataTypeDataDefinition = dataTypeOptional.get();
268         if (dataTypeDataDefinition.isNormative()) {
269             throw new OperationException(ActionStatus.CANNOT_DELETE_SYSTEM_DEPLOYED_RESOURCES, ElementTypeEnum.DATA_TYPE.getToscaEntryName(),
270                 dataTypeId);
271         }
272         if (StringUtils.isEmpty(dataTypeDataDefinition.getModel())) {
273             dataTypeDataDefinition.setModel(Constants.DEFAULT_MODEL_NAME);
274         }
275         try {
276             dataTypeOperation.deleteDataTypesByDataTypeId(dataTypeId);
277             dataTypeOperation.removeDataTypeFromAdditionalType(dataTypeDataDefinition);
278         } catch (Exception e) {
279             BeEcompErrorManager.getInstance().logBeRestApiGeneralError("Delete Datatype");
280             log.debug("delete datatype failed with exception ", e);
281             throw e;
282         }
283         return buildOkResponse(getComponentsUtils().getResponseFormat(ActionStatus.NO_CONTENT), null);
284     }
285
286     private String extractNameFromPropertyId(final String propertyId) {
287         final String[] split = propertyId.split("\\.");
288         return split[split.length - 1];
289     }
290 }