Constraints in data type view
[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.apache.commons.lang3.StringUtils;
49 import org.openecomp.sdc.be.components.impl.DataTypeBusinessLogic;
50 import org.openecomp.sdc.be.components.impl.aaf.AafPermission;
51 import org.openecomp.sdc.be.components.impl.aaf.PermissionAllowed;
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.operations.impl.DataTypeOperation;
61 import org.openecomp.sdc.common.api.Constants;
62 import org.openecomp.sdc.common.log.enums.EcompLoggerErrorCode;
63 import org.openecomp.sdc.common.log.wrappers.Logger;
64 import org.springframework.stereotype.Controller;
65 import org.apache.commons.lang3.StringUtils;
66
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")
71 @Controller
72 public class DataTypeServlet extends BeGenericServlet {
73
74     private static final Logger log = Logger.getLogger(DataTypeServlet.class);
75     private final DataTypeOperation dataTypeOperation;
76     private final DataTypeBusinessLogic dataTypeBusinessLogic;
77
78     public DataTypeServlet(final ComponentsUtils componentsUtils,
79                            final DataTypeOperation dataTypeOperation, DataTypeBusinessLogic dataTypeBusinessLogic) {
80         super(componentsUtils);
81         this.dataTypeOperation = dataTypeOperation;
82         this.dataTypeBusinessLogic = dataTypeBusinessLogic;
83     }
84
85     @GET
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     @PermissionAllowed(AafPermission.PermNames.INTERNAL_ALL_VALUE)
96     public Response fetchDataType(@Context final HttpServletRequest request,
97                                   @HeaderParam(value = Constants.USER_ID_HEADER) String userId,
98                                   @PathParam("dataTypeUid") String dataTypeUid) {
99         final String url = request.getMethod() + " " + request.getRequestURI();
100         log.debug("Start handle request of {} - modifier id is {}", url, userId);
101         final Optional<DataTypeDataDefinition> dataTypeFoundOptional;
102         try {
103             dataTypeFoundOptional = dataTypeOperation.getDataTypeByUid(dataTypeUid);
104         } catch (final BusinessException e) {
105             throw e;
106         } catch (final Exception ex) {
107             final String errorMsg = "Unexpected error while listing the Tosca DataType";
108             BeEcompErrorManager.getInstance().logBeRestApiGeneralError(errorMsg);
109             log.error(EcompLoggerErrorCode.UNKNOWN_ERROR, this.getClass().getName(), errorMsg, ex);
110             return buildErrorResponse(getComponentsUtils().getResponseFormat(ActionStatus.GENERAL_ERROR));
111         }
112         var dataType = dataTypeFoundOptional.orElseThrow(() -> new OperationException(ActionStatus.DATA_TYPE_NOT_FOUND, dataTypeUid));
113         return buildOkResponse(getComponentsUtils().getResponseFormat(ActionStatus.OK), dataType);
114     }
115
116     @GET
117     @Path("{id}/properties")
118     @Consumes(MediaType.APPLICATION_JSON)
119     @Produces(MediaType.APPLICATION_JSON)
120     @Operation(description = "Get a data type properties", method = "GET", summary = "Returns the data type properties", responses = {
121         @ApiResponse(content = @Content(array = @ArraySchema(schema = @Schema(implementation = PropertyDefinition.class)))),
122         @ApiResponse(responseCode = "200", description = "Data type found, properties may be empty"),
123         @ApiResponse(responseCode = "403", description = "Restricted operation"),
124         @ApiResponse(responseCode = "404", description = "Data type not found")})
125     @PermissionAllowed(AafPermission.PermNames.INTERNAL_ALL_VALUE)
126     public Response fetchProperties(@Parameter(in = ParameterIn.PATH, required = true, description = "The data type id")
127                                     @PathParam("id") final String id) {
128         final List<PropertyDefinition> allProperties = dataTypeOperation.findAllProperties(id);
129         return buildOkResponse(allProperties);
130     }
131
132     @POST
133     @Path("{id}/properties")
134     @Consumes(MediaType.APPLICATION_JSON)
135     @Produces(MediaType.APPLICATION_JSON)
136     @Operation(summary = "Create a property in the given data type", method = "POST", description = "Create a property in the given data type",
137         responses = {
138             @ApiResponse(content = @Content(schema = @Schema(implementation = PropertyDefinitionDto.class))),
139             @ApiResponse(responseCode = "201", description = "Property created in the data type"),
140             @ApiResponse(responseCode = "400", description = "Invalid payload"),
141             @ApiResponse(responseCode = "409", description = "Property already exists in the data type"),
142             @ApiResponse(responseCode = "403", description = "Restricted operation"),
143             @ApiResponse(responseCode = "404", description = "Data type not found")
144         })
145     @PermissionAllowed(AafPermission.PermNames.INTERNAL_ALL_VALUE)
146     public Response createProperty(@Parameter(in = ParameterIn.PATH, required = true, description = "The data type id")
147                                    @PathParam("id") final String id,
148                                    @RequestBody(description = "Property to add", required = true) final PropertyDefinitionDto propertyDefinitionDto) {
149         Optional<DataTypeDataDefinition> dataTypeOptional = dataTypeOperation.getDataTypeByUid(id);
150         dataTypeOptional.orElseThrow(() -> {
151             throw new OperationException(ActionStatus.DATA_TYPE_NOT_FOUND, String.format("Failed to find data type '%s'", id));
152         });
153         DataTypeDataDefinition dataType = dataTypeOptional.get();
154         String model = dataType.getModel();
155         Optional<DataTypeDataDefinition> propertyDataType = dataTypeOperation.getDataTypeByNameAndModel(propertyDefinitionDto.getType(), model);
156         if (propertyDataType.isEmpty()) {
157             if (StringUtils.isEmpty(model)) {
158                 model = Constants.DEFAULT_MODEL_NAME;
159             }
160             throw new OperationException(ActionStatus.INVALID_MODEL,
161                 String.format("Property model is not the same as the data type model. Must be '%s'", model));
162         }
163         if (StringUtils.isEmpty(dataType.getModel())) {
164             dataType.setModel("SDC AID");
165         }
166         final PropertyDefinitionDto property = dataTypeOperation.createProperty(id, propertyDefinitionDto);
167         dataTypeOperation.addPropertyToAdditionalTypeDataType(dataType, property);
168         dataTypeBusinessLogic.updateApplicationDataTypeCache(id);
169         return Response.status(Status.CREATED).entity(property).build();
170     }
171
172     @GET
173     @Path("{dataTypeName}/models")
174     @Consumes(MediaType.APPLICATION_JSON)
175     @Produces(MediaType.APPLICATION_JSON)
176     @Operation(description = "Get models for type", method = "GET", summary = "Returns list of models for type", responses = {
177         @ApiResponse(content = @Content(array = @ArraySchema(schema = @Schema(implementation = Response.class)))),
178         @ApiResponse(responseCode = "200", description = "dataTypeModels"), @ApiResponse(responseCode = "403", description = "Restricted operation"),
179         @ApiResponse(responseCode = "400", description = "Invalid content / Missing content"),
180         @ApiResponse(responseCode = "403", description = "Restricted operation"),
181         @ApiResponse(responseCode = "404", description = "Data type not found")})
182     @PermissionAllowed(AafPermission.PermNames.INTERNAL_ALL_VALUE)
183     public Response getDataTypeModels(@PathParam("dataTypeName") String dataTypeName) {
184         return buildOkResponse(getComponentsUtils().getResponseFormat(ActionStatus.OK),
185             gson.toJson(dataTypeOperation.getAllDataTypeModels(dataTypeName)));
186     }
187 }