Edit properties of non-normative data types
[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.PUT;
42 import javax.ws.rs.Path;
43 import javax.ws.rs.PathParam;
44 import javax.ws.rs.Produces;
45 import javax.ws.rs.core.Context;
46 import javax.ws.rs.core.MediaType;
47 import javax.ws.rs.core.Response;
48 import javax.ws.rs.core.Response.Status;
49 import org.apache.commons.lang3.StringUtils;
50 import org.openecomp.sdc.be.components.impl.DataTypeBusinessLogic;
51 import org.openecomp.sdc.be.components.impl.aaf.AafPermission;
52 import org.openecomp.sdc.be.components.impl.aaf.PermissionAllowed;
53 import org.openecomp.sdc.be.config.BeEcompErrorManager;
54 import org.openecomp.sdc.be.dao.api.ActionStatus;
55 import org.openecomp.sdc.be.datatypes.elements.DataTypeDataDefinition;
56 import org.openecomp.sdc.be.exception.BusinessException;
57 import org.openecomp.sdc.be.impl.ComponentsUtils;
58 import org.openecomp.sdc.be.model.PropertyDefinition;
59 import org.openecomp.sdc.be.model.dto.PropertyDefinitionDto;
60 import org.openecomp.sdc.be.model.jsonjanusgraph.operations.exception.OperationException;
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;
66 import org.apache.commons.lang3.StringUtils;
67
68 @Loggable(prepend = true, value = Loggable.DEBUG, trim = false)
69 @Path("/v1/catalog/data-types")
70 @Tag(name = "SDCE-2 APIs")
71 @Server(url = "/sdc2/rest")
72 @Controller
73 public class DataTypeServlet extends BeGenericServlet {
74
75     private static final Logger log = Logger.getLogger(DataTypeServlet.class);
76     private final DataTypeOperation dataTypeOperation;
77     private final DataTypeBusinessLogic dataTypeBusinessLogic;
78
79     public DataTypeServlet(final ComponentsUtils componentsUtils,
80                            final DataTypeOperation dataTypeOperation, DataTypeBusinessLogic dataTypeBusinessLogic) {
81         super(componentsUtils);
82         this.dataTypeOperation = dataTypeOperation;
83         this.dataTypeBusinessLogic = dataTypeBusinessLogic;
84     }
85
86     @GET
87     @Path("{dataTypeUid}")
88     @Consumes(MediaType.APPLICATION_JSON)
89     @Produces(MediaType.APPLICATION_JSON)
90     @Operation(description = "Get data types", method = "GET", summary = "Returns data types", responses = {
91         @ApiResponse(content = @Content(schema = @Schema(implementation = DataTypeDataDefinition.class))),
92         @ApiResponse(responseCode = "200", description = "Data type found"),
93         @ApiResponse(responseCode = "403", description = "Restricted operation"),
94         @ApiResponse(responseCode = "400", description = "Invalid content / Missing content"),
95         @ApiResponse(responseCode = "404", description = "Data types not found")})
96     @PermissionAllowed(AafPermission.PermNames.INTERNAL_ALL_VALUE)
97     public Response fetchDataType(@Context final HttpServletRequest request,
98                                   @HeaderParam(value = Constants.USER_ID_HEADER) String userId,
99                                   @PathParam("dataTypeUid") String dataTypeUid) {
100         final String url = request.getMethod() + " " + request.getRequestURI();
101         log.debug("Start handle request of {} - modifier id is {}", url, userId);
102         final Optional<DataTypeDataDefinition> dataTypeFoundOptional;
103         try {
104             dataTypeFoundOptional = dataTypeOperation.getDataTypeByUid(dataTypeUid);
105         } catch (final BusinessException e) {
106             throw e;
107         } catch (final Exception ex) {
108             final String errorMsg = "Unexpected error while listing the Tosca DataType";
109             BeEcompErrorManager.getInstance().logBeRestApiGeneralError(errorMsg);
110             log.error(EcompLoggerErrorCode.UNKNOWN_ERROR, this.getClass().getName(), errorMsg, ex);
111             return buildErrorResponse(getComponentsUtils().getResponseFormat(ActionStatus.GENERAL_ERROR));
112         }
113         var dataType = dataTypeFoundOptional.orElseThrow(() -> new OperationException(ActionStatus.DATA_TYPE_NOT_FOUND, dataTypeUid));
114         return buildOkResponse(getComponentsUtils().getResponseFormat(ActionStatus.OK), dataType);
115     }
116
117     @GET
118     @Path("{id}/properties")
119     @Consumes(MediaType.APPLICATION_JSON)
120     @Produces(MediaType.APPLICATION_JSON)
121     @Operation(description = "Get a data type properties", method = "GET", summary = "Returns the data type properties", responses = {
122         @ApiResponse(content = @Content(array = @ArraySchema(schema = @Schema(implementation = PropertyDefinition.class)))),
123         @ApiResponse(responseCode = "200", description = "Data type found, properties may be empty"),
124         @ApiResponse(responseCode = "403", description = "Restricted operation"),
125         @ApiResponse(responseCode = "404", description = "Data type not found")})
126     @PermissionAllowed(AafPermission.PermNames.INTERNAL_ALL_VALUE)
127     public Response fetchProperties(@Parameter(in = ParameterIn.PATH, required = true, description = "The data type id")
128                                     @PathParam("id") final String id) {
129         final List<PropertyDefinition> allProperties = dataTypeOperation.findAllProperties(id);
130         return buildOkResponse(allProperties);
131     }
132
133     @POST
134     @Path("{id}/properties")
135     @Consumes(MediaType.APPLICATION_JSON)
136     @Produces(MediaType.APPLICATION_JSON)
137     @Operation(summary = "Create a property in the given data type", method = "POST", description = "Create a property in the given data type",
138         responses = {
139             @ApiResponse(content = @Content(schema = @Schema(implementation = PropertyDefinitionDto.class))),
140             @ApiResponse(responseCode = "201", description = "Property created in the data type"),
141             @ApiResponse(responseCode = "400", description = "Invalid payload"),
142             @ApiResponse(responseCode = "409", description = "Property already exists in the data type"),
143             @ApiResponse(responseCode = "403", description = "Restricted operation"),
144             @ApiResponse(responseCode = "404", description = "Data type not found")
145         })
146     @PermissionAllowed(AafPermission.PermNames.INTERNAL_ALL_VALUE)
147     public Response createProperty(@Parameter(in = ParameterIn.PATH, required = true, description = "The data type id")
148                                    @PathParam("id") final String id,
149                                    @RequestBody(description = "Property to add", required = true) final PropertyDefinitionDto propertyDefinitionDto) {
150         Optional<DataTypeDataDefinition> dataTypeOptional = dataTypeOperation.getDataTypeByUid(id);
151         dataTypeOptional.orElseThrow(() -> {
152             throw new OperationException(ActionStatus.DATA_TYPE_NOT_FOUND, String.format("Failed to find data type '%s'", id));
153         });
154         DataTypeDataDefinition dataType = dataTypeOptional.get();
155         String model = dataType.getModel();
156         Optional<DataTypeDataDefinition> propertyDataType = dataTypeOperation.getDataTypeByNameAndModel(propertyDefinitionDto.getType(), model);
157         if (propertyDataType.isEmpty()) {
158             if (StringUtils.isEmpty(model)) {
159                 model = Constants.DEFAULT_MODEL_NAME;
160             }
161             throw new OperationException(ActionStatus.INVALID_MODEL,
162                 String.format("Property model is not the same as the data type model. Must be '%s'", model));
163         }
164         if (StringUtils.isEmpty(dataType.getModel())) {
165             dataType.setModel("SDC AID");
166         }
167         final PropertyDefinitionDto property = dataTypeOperation.createProperty(id, propertyDefinitionDto);
168         dataTypeOperation.addPropertyToAdditionalTypeDataType(dataType, property);
169         dataTypeBusinessLogic.updateApplicationDataTypeCache(id);
170         return Response.status(Status.CREATED).entity(property).build();
171     }
172
173     @PUT
174     @Path("{id}/properties")
175     @Consumes(MediaType.APPLICATION_JSON)
176     @Produces(MediaType.APPLICATION_JSON)
177     @Operation(summary = "Update a property in the given data type", method = "POST", description = "Update a property in the given data type",
178         responses = {
179             @ApiResponse(content = @Content(schema = @Schema(implementation = PropertyDefinitionDto.class))),
180             @ApiResponse(responseCode = "201", description = "Property updated in the data type"),
181             @ApiResponse(responseCode = "400", description = "Invalid payload"),
182             @ApiResponse(responseCode = "403", description = "Restricted operation"),
183             @ApiResponse(responseCode = "404", description = "Data type not found")
184         })
185     @PermissionAllowed(AafPermission.PermNames.INTERNAL_ALL_VALUE)
186     public Response updateProperty(@Parameter(in = ParameterIn.PATH, required = true, description = "The data type id")
187                                    @PathParam("id") final String id,
188                                    @RequestBody(description = "Property to update", required = true) final PropertyDefinitionDto propertyDefinitionDto) {
189         Optional<DataTypeDataDefinition> dataTypeOptional = dataTypeOperation.getDataTypeByUid(id);
190         dataTypeOptional.orElseThrow(() -> {
191             throw new OperationException(ActionStatus.DATA_TYPE_NOT_FOUND, String.format("Failed to find data type '%s'", id));
192         });
193         DataTypeDataDefinition dataType = dataTypeOptional.get();
194         String model = dataType.getModel();
195         Optional<DataTypeDataDefinition> propertyDataType = dataTypeOperation.getDataTypeByNameAndModel(propertyDefinitionDto.getType(), model);
196         if (propertyDataType.isEmpty()) {
197             if (StringUtils.isEmpty(model)) {
198                 model = Constants.DEFAULT_MODEL_NAME;
199             }
200             throw new OperationException(ActionStatus.INVALID_MODEL,
201                 String.format("Property model is not the same as the data type model. Must be '%s'", model));
202         }
203         if (StringUtils.isEmpty(dataType.getModel())) {
204             dataType.setModel(Constants.DEFAULT_MODEL_NAME);
205         }
206         final PropertyDefinitionDto property = dataTypeOperation.updateProperty(id, propertyDefinitionDto);
207         dataTypeOperation.addPropertyToAdditionalTypeDataType(dataType, property);
208         dataTypeBusinessLogic.updateApplicationDataTypeCache(id);
209         return Response.status(Status.CREATED).entity(property).build();
210     }
211
212     @GET
213     @Path("{dataTypeName}/models")
214     @Consumes(MediaType.APPLICATION_JSON)
215     @Produces(MediaType.APPLICATION_JSON)
216     @Operation(description = "Get models for type", method = "GET", summary = "Returns list of models for type", responses = {
217         @ApiResponse(content = @Content(array = @ArraySchema(schema = @Schema(implementation = Response.class)))),
218         @ApiResponse(responseCode = "200", description = "dataTypeModels"), @ApiResponse(responseCode = "403", description = "Restricted operation"),
219         @ApiResponse(responseCode = "400", description = "Invalid content / Missing content"),
220         @ApiResponse(responseCode = "403", description = "Restricted operation"),
221         @ApiResponse(responseCode = "404", description = "Data type not found")})
222     @PermissionAllowed(AafPermission.PermNames.INTERNAL_ALL_VALUE)
223     public Response getDataTypeModels(@PathParam("dataTypeName") String dataTypeName) {
224         return buildOkResponse(getComponentsUtils().getResponseFormat(ActionStatus.OK),
225             gson.toJson(dataTypeOperation.getAllDataTypeModels(dataTypeName)));
226     }
227 }