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.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;
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")
74 public class DataTypeServlet extends BeGenericServlet {
76 private static final Logger log = Logger.getLogger(DataTypeServlet.class);
77 private final DataTypeOperation dataTypeOperation;
78 private final DataTypeBusinessLogic dataTypeBusinessLogic;
80 public DataTypeServlet(final ComponentsUtils componentsUtils,
81 final DataTypeOperation dataTypeOperation, DataTypeBusinessLogic dataTypeBusinessLogic) {
82 super(componentsUtils);
83 this.dataTypeOperation = dataTypeOperation;
84 this.dataTypeBusinessLogic = dataTypeBusinessLogic;
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;
105 dataTypeFoundOptional = dataTypeOperation.getDataTypeByUid(dataTypeUid);
106 } catch (final BusinessException 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));
114 var dataType = dataTypeFoundOptional.orElseThrow(() -> new OperationException(ActionStatus.DATA_TYPE_NOT_FOUND, dataTypeUid));
115 return buildOkResponse(getComponentsUtils().getResponseFormat(ActionStatus.OK), dataType);
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);
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",
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")
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));
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;
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));
165 if (StringUtils.isEmpty(dataType.getModel())) {
166 dataType.setModel(Constants.DEFAULT_MODEL_NAME);
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();
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",
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")
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));
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;
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));
205 if (StringUtils.isEmpty(dataType.getModel())) {
206 dataType.setModel(Constants.DEFAULT_MODEL_NAME);
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();
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)));
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));
240 final DataTypeDataDefinition dataTypeDataDefinition = dataTypeOptional.get();
241 if (StringUtils.isEmpty(dataTypeDataDefinition.getModel())) {
242 dataTypeDataDefinition.setModel(Constants.DEFAULT_MODEL_NAME);
244 final PropertyDefinitionDto propertyDefinitionDto;
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);
254 dataTypeBusinessLogic.updateApplicationDataTypeCache(dataTypeId);
256 return Response.status(Status.OK).entity(propertyDefinitionDto).build();
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));
267 final DataTypeDataDefinition dataTypeDataDefinition = dataTypeOptional.get();
268 if (dataTypeDataDefinition.isNormative()) {
269 throw new OperationException(ActionStatus.CANNOT_DELETE_SYSTEM_DEPLOYED_RESOURCES, ElementTypeEnum.DATA_TYPE.getToscaEntryName(),
272 if (StringUtils.isEmpty(dataTypeDataDefinition.getModel())) {
273 dataTypeDataDefinition.setModel(Constants.DEFAULT_MODEL_NAME);
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);
283 return buildOkResponse(getComponentsUtils().getResponseFormat(ActionStatus.NO_CONTENT), null);
286 private String extractNameFromPropertyId(final String propertyId) {
287 final String[] split = propertyId.split("\\.");
288 return split[split.length - 1];