2 * ============LICENSE_START=======================================================
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
11 * http://www.apache.org/licenses/LICENSE-2.0
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=========================================================
21 package org.openecomp.sdc.be.servlets;
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.config.BeEcompErrorManager;
53 import org.openecomp.sdc.be.dao.api.ActionStatus;
54 import org.openecomp.sdc.be.datatypes.elements.DataTypeDataDefinition;
55 import org.openecomp.sdc.be.exception.BusinessException;
56 import org.openecomp.sdc.be.impl.ComponentsUtils;
57 import org.openecomp.sdc.be.model.PropertyDefinition;
58 import org.openecomp.sdc.be.model.dto.PropertyDefinitionDto;
59 import org.openecomp.sdc.be.model.jsonjanusgraph.operations.exception.OperationException;
60 import org.openecomp.sdc.be.model.normatives.ElementTypeEnum;
61 import org.openecomp.sdc.be.model.operations.impl.DataTypeOperation;
62 import org.openecomp.sdc.common.api.Constants;
63 import org.openecomp.sdc.common.log.enums.EcompLoggerErrorCode;
64 import org.openecomp.sdc.common.log.wrappers.Logger;
65 import org.springframework.stereotype.Controller;
67 @Loggable(prepend = true, value = Loggable.DEBUG, trim = false)
68 @Path("/v1/catalog/data-types")
69 @Tag(name = "SDCE-2 APIs")
70 @Server(url = "/sdc2/rest")
72 public class DataTypeServlet extends BeGenericServlet {
74 private static final Logger log = Logger.getLogger(DataTypeServlet.class);
75 private final DataTypeOperation dataTypeOperation;
76 private final DataTypeBusinessLogic dataTypeBusinessLogic;
78 public DataTypeServlet(final ComponentsUtils componentsUtils,
79 final DataTypeOperation dataTypeOperation, DataTypeBusinessLogic dataTypeBusinessLogic) {
80 super(componentsUtils);
81 this.dataTypeOperation = dataTypeOperation;
82 this.dataTypeBusinessLogic = dataTypeBusinessLogic;
86 @Path("{dataTypeUid}")
87 @Consumes(MediaType.APPLICATION_JSON)
88 @Produces(MediaType.APPLICATION_JSON)
89 @Operation(description = "Get data types", method = "GET", summary = "Returns data types", responses = {
90 @ApiResponse(content = @Content(schema = @Schema(implementation = DataTypeDataDefinition.class))),
91 @ApiResponse(responseCode = "200", description = "Data type found"),
92 @ApiResponse(responseCode = "403", description = "Restricted operation"),
93 @ApiResponse(responseCode = "400", description = "Invalid content / Missing content"),
94 @ApiResponse(responseCode = "404", description = "Data types not found")})
95 public Response fetchDataType(@Context final HttpServletRequest request,
96 @HeaderParam(value = Constants.USER_ID_HEADER) String userId,
97 @PathParam("dataTypeUid") String dataTypeUid) {
98 final String url = request.getMethod() + " " + request.getRequestURI();
99 log.debug("Start handle request of {} - modifier id is {}", url, userId);
100 final Optional<DataTypeDataDefinition> dataTypeFoundOptional;
102 dataTypeFoundOptional = dataTypeOperation.getDataTypeByUid(dataTypeUid);
103 } catch (final BusinessException e) {
105 } catch (final Exception ex) {
106 final String errorMsg = "Unexpected error while listing the Tosca DataType";
107 BeEcompErrorManager.getInstance().logBeRestApiGeneralError(errorMsg);
108 log.error(EcompLoggerErrorCode.UNKNOWN_ERROR, this.getClass().getName(), errorMsg, ex);
109 return buildErrorResponse(getComponentsUtils().getResponseFormat(ActionStatus.GENERAL_ERROR));
111 var dataType = dataTypeFoundOptional.orElseThrow(() -> new OperationException(ActionStatus.DATA_TYPE_NOT_FOUND, dataTypeUid));
112 return buildOkResponse(getComponentsUtils().getResponseFormat(ActionStatus.OK), dataType);
116 @Path("{id}/properties")
117 @Consumes(MediaType.APPLICATION_JSON)
118 @Produces(MediaType.APPLICATION_JSON)
119 @Operation(description = "Get a data type properties", method = "GET", summary = "Returns the data type properties", responses = {
120 @ApiResponse(content = @Content(array = @ArraySchema(schema = @Schema(implementation = PropertyDefinition.class)))),
121 @ApiResponse(responseCode = "200", description = "Data type found, properties may be empty"),
122 @ApiResponse(responseCode = "403", description = "Restricted operation"),
123 @ApiResponse(responseCode = "404", description = "Data type not found")})
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);
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",
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")
143 public Response createProperty(@Parameter(in = ParameterIn.PATH, required = true, description = "The data type id")
144 @PathParam("id") final String id,
145 @RequestBody(description = "Property to add", required = true) final PropertyDefinitionDto propertyDefinitionDto) {
146 Optional<DataTypeDataDefinition> dataTypeOptional = dataTypeOperation.getDataTypeByUid(id);
147 dataTypeOptional.orElseThrow(() -> {
148 throw new OperationException(ActionStatus.DATA_TYPE_NOT_FOUND, String.format("Failed to find data type '%s'", id));
150 DataTypeDataDefinition dataType = dataTypeOptional.get();
151 String model = dataType.getModel();
152 Optional<DataTypeDataDefinition> propertyDataType = dataTypeOperation.getDataTypeByNameAndModel(propertyDefinitionDto.getType(), model);
153 if (propertyDataType.isEmpty()) {
154 if (StringUtils.isEmpty(model)) {
155 model = Constants.DEFAULT_MODEL_NAME;
157 throw new OperationException(ActionStatus.INVALID_MODEL,
158 String.format("Property model is not the same as the data type model. Must be '%s'", model));
160 if (StringUtils.isEmpty(dataType.getModel())) {
161 dataType.setModel(Constants.DEFAULT_MODEL_NAME);
163 final PropertyDefinitionDto property = dataTypeOperation.createProperty(id, propertyDefinitionDto);
164 dataTypeOperation.updatePropertyInAdditionalTypeDataType(dataType, property, true);
165 dataTypeBusinessLogic.updateApplicationDataTypeCache(id);
166 return Response.status(Status.CREATED).entity(property).build();
170 @Path("{id}/properties")
171 @Consumes(MediaType.APPLICATION_JSON)
172 @Produces(MediaType.APPLICATION_JSON)
173 @Operation(summary = "Update a property in the given data type", method = "POST", description = "Update a property in the given data type",
175 @ApiResponse(content = @Content(schema = @Schema(implementation = PropertyDefinitionDto.class))),
176 @ApiResponse(responseCode = "201", description = "Property updated in the data type"),
177 @ApiResponse(responseCode = "400", description = "Invalid payload"),
178 @ApiResponse(responseCode = "403", description = "Restricted operation"),
179 @ApiResponse(responseCode = "404", description = "Data type not found")
181 public Response updateProperty(@Parameter(in = ParameterIn.PATH, required = true, description = "The data type id")
182 @PathParam("id") final String id,
183 @RequestBody(description = "Property to update", required = true)
184 final PropertyDefinitionDto propertyDefinitionDto) {
185 Optional<DataTypeDataDefinition> dataTypeOptional = dataTypeOperation.getDataTypeByUid(id);
186 dataTypeOptional.orElseThrow(() -> {
187 throw new OperationException(ActionStatus.DATA_TYPE_NOT_FOUND, String.format("Failed to find data type '%s'", id));
189 DataTypeDataDefinition dataType = dataTypeOptional.get();
190 String model = dataType.getModel();
191 Optional<DataTypeDataDefinition> propertyDataType = dataTypeOperation.getDataTypeByNameAndModel(propertyDefinitionDto.getType(), model);
192 if (propertyDataType.isEmpty()) {
193 if (StringUtils.isEmpty(model)) {
194 model = Constants.DEFAULT_MODEL_NAME;
196 throw new OperationException(ActionStatus.INVALID_MODEL,
197 String.format("Property model is not the same as the data type model. Must be '%s'", model));
199 if (StringUtils.isEmpty(dataType.getModel())) {
200 dataType.setModel(Constants.DEFAULT_MODEL_NAME);
202 final PropertyDefinitionDto property = dataTypeOperation.updateProperty(id, propertyDefinitionDto);
203 dataTypeOperation.updatePropertyInAdditionalTypeDataType(dataType, property, true);
204 dataTypeBusinessLogic.updateApplicationDataTypeCache(id);
205 return Response.status(Status.CREATED).entity(property).build();
209 @Path("{dataTypeName}/models")
210 @Consumes(MediaType.APPLICATION_JSON)
211 @Produces(MediaType.APPLICATION_JSON)
212 @Operation(description = "Get models for type", method = "GET", summary = "Returns list of models for type", responses = {
213 @ApiResponse(content = @Content(array = @ArraySchema(schema = @Schema(implementation = Response.class)))),
214 @ApiResponse(responseCode = "200", description = "dataTypeModels"), @ApiResponse(responseCode = "403", description = "Restricted operation"),
215 @ApiResponse(responseCode = "400", description = "Invalid content / Missing content"),
216 @ApiResponse(responseCode = "403", description = "Restricted operation"),
217 @ApiResponse(responseCode = "404", description = "Data type not found")})
218 public Response getDataTypeModels(@PathParam("dataTypeName") String dataTypeName) {
219 return buildOkResponse(getComponentsUtils().getResponseFormat(ActionStatus.OK),
220 gson.toJson(dataTypeOperation.getAllDataTypeModels(dataTypeName)));
224 @Path("{dataTypeId}/{propertyId}")
225 public Response deleteProperty(@Parameter(in = ParameterIn.PATH, required = true, description = "The data type id")
226 @PathParam("dataTypeId") final String dataTypeId,
227 @Parameter(in = ParameterIn.PATH, required = true, description = "The property id to delete")
228 @PathParam("propertyId") final String propertyId) {
229 final Optional<DataTypeDataDefinition> dataTypeOptional = dataTypeOperation.getDataTypeByUid(dataTypeId);
230 dataTypeOptional.orElseThrow(() -> {
231 throw new OperationException(ActionStatus.DATA_TYPE_NOT_FOUND, String.format("Failed to find data type '%s'", dataTypeId));
233 final DataTypeDataDefinition dataTypeDataDefinition = dataTypeOptional.get();
234 if (StringUtils.isEmpty(dataTypeDataDefinition.getModel())) {
235 dataTypeDataDefinition.setModel(Constants.DEFAULT_MODEL_NAME);
237 final PropertyDefinitionDto propertyDefinitionDto;
239 propertyDefinitionDto = dataTypeOperation.deleteProperty(dataTypeDataDefinition, propertyId);
240 dataTypeOperation.updatePropertyInAdditionalTypeDataType(dataTypeDataDefinition, propertyDefinitionDto, false);
241 } catch (OperationException e) {
242 final PropertyDefinitionDto dto = new PropertyDefinitionDto();
243 dto.setName(extractNameFromPropertyId(propertyId));
244 dataTypeOperation.updatePropertyInAdditionalTypeDataType(dataTypeDataDefinition, dto, false);
247 dataTypeBusinessLogic.updateApplicationDataTypeCache(dataTypeId);
249 return Response.status(Status.OK).entity(propertyDefinitionDto).build();
253 @Path("{dataTypeId}")
254 public Response deleteDatatype(@Parameter(in = ParameterIn.PATH, required = true, description = "The data type id")
255 @PathParam("dataTypeId") final String dataTypeId) {
256 final Optional<DataTypeDataDefinition> dataTypeOptional = dataTypeOperation.getDataTypeByUid(dataTypeId);
257 dataTypeOptional.orElseThrow(() -> {
258 throw new OperationException(ActionStatus.DATA_TYPE_NOT_FOUND, String.format("Failed to find data type '%s'", dataTypeId));
260 final DataTypeDataDefinition dataTypeDataDefinition = dataTypeOptional.get();
261 if (dataTypeDataDefinition.isNormative()) {
262 throw new OperationException(ActionStatus.CANNOT_DELETE_SYSTEM_DEPLOYED_RESOURCES, ElementTypeEnum.DATA_TYPE.getToscaEntryName(),
265 if (StringUtils.isEmpty(dataTypeDataDefinition.getModel())) {
266 dataTypeDataDefinition.setModel(Constants.DEFAULT_MODEL_NAME);
269 dataTypeOperation.deleteDataTypesByDataTypeId(dataTypeId);
270 dataTypeOperation.removeDataTypeFromAdditionalType(dataTypeDataDefinition);
271 } catch (Exception e) {
272 BeEcompErrorManager.getInstance().logBeRestApiGeneralError("Delete Datatype");
273 log.debug("delete datatype failed with exception ", e);
276 return buildOkResponse(getComponentsUtils().getResponseFormat(ActionStatus.NO_CONTENT), null);
279 private String extractNameFromPropertyId(final String propertyId) {
280 final String[] split = propertyId.split("\\.");
281 return split[split.length - 1];