2 * ============LICENSE_START=======================================================
3 * Copyright (C) 2021 Nordix Foundation
4 * ================================================================================
5 * Licensed under the Apache License, Version 2.0 (the "License");
6 * you may not use this file except in compliance with the License.
7 * You may obtain a copy of the License at
9 * http://www.apache.org/licenses/LICENSE-2.0
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
16 * SPDX-License-Identifier: Apache-2.0
17 * ============LICENSE_END=========================================================
19 package org.openecomp.sdc.be.servlets;
21 import com.googlecode.jmapper.JMapper;
22 import com.jcabi.aspects.Loggable;
23 import io.swagger.v3.oas.annotations.Operation;
24 import io.swagger.v3.oas.annotations.Parameter;
25 import io.swagger.v3.oas.annotations.media.ArraySchema;
26 import io.swagger.v3.oas.annotations.media.Content;
27 import io.swagger.v3.oas.annotations.media.Schema;
28 import io.swagger.v3.oas.annotations.responses.ApiResponse;
29 import io.swagger.v3.oas.annotations.servers.Server;
30 import io.swagger.v3.oas.annotations.tags.Tag;
31 import java.io.InputStream;
32 import java.util.Arrays;
33 import java.util.List;
34 import javax.inject.Inject;
35 import javax.validation.Valid;
36 import javax.validation.constraints.NotNull;
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.Produces;
44 import javax.ws.rs.QueryParam;
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.glassfish.jersey.media.multipart.FormDataParam;
50 import org.openecomp.sdc.be.components.impl.ComponentInstanceBusinessLogic;
51 import org.openecomp.sdc.be.components.impl.ModelBusinessLogic;
52 import org.openecomp.sdc.be.components.impl.ResourceImportManager;
53 import org.openecomp.sdc.be.components.impl.aaf.AafPermission;
54 import org.openecomp.sdc.be.components.impl.aaf.PermissionAllowed;
55 import org.openecomp.sdc.be.components.validation.UserValidations;
56 import org.openecomp.sdc.be.config.BeEcompErrorManager;
57 import org.openecomp.sdc.be.dao.api.ActionStatus;
58 import org.openecomp.sdc.be.datatypes.enums.ModelTypeEnum;
59 import org.openecomp.sdc.be.exception.BusinessException;
60 import org.openecomp.sdc.be.impl.ComponentsUtils;
61 import org.openecomp.sdc.be.impl.ServletUtils;
62 import org.openecomp.sdc.be.model.Model;
63 import org.openecomp.sdc.be.model.jsonjanusgraph.operations.exception.ModelOperationExceptionSupplier;
64 import org.openecomp.sdc.be.ui.model.ModelCreateRequest;
65 import org.openecomp.sdc.be.user.Role;
66 import org.openecomp.sdc.common.api.Constants;
67 import org.openecomp.sdc.common.util.ValidationUtils;
68 import org.slf4j.Logger;
69 import org.slf4j.LoggerFactory;
70 import org.springframework.stereotype.Controller;
73 * Root resource (exposed at "/" path)
75 @Loggable(prepend = true, value = Loggable.DEBUG, trim = false)
77 @Tag(name = "SDCE-2 APIs")
78 @Server(url = "/sdc2/rest")
80 public class ModelServlet extends AbstractValidationsServlet {
82 private static final Logger log = LoggerFactory.getLogger(ModelServlet.class);
83 private final ModelBusinessLogic modelBusinessLogic;
84 private final UserValidations userValidations;
87 public ModelServlet(final ComponentInstanceBusinessLogic componentInstanceBL,
88 final ComponentsUtils componentsUtils, final ServletUtils servletUtils, final ResourceImportManager resourceImportManager,
89 final ModelBusinessLogic modelBusinessLogic, final UserValidations userValidations) {
90 super(componentInstanceBL, componentsUtils, servletUtils, resourceImportManager);
91 this.modelBusinessLogic = modelBusinessLogic;
92 this.userValidations = userValidations;
97 @Consumes(MediaType.MULTIPART_FORM_DATA)
98 @Produces(MediaType.APPLICATION_JSON)
99 @PermissionAllowed(AafPermission.PermNames.INTERNAL_ALL_VALUE)
100 @Operation(description = "Create a TOSCA model, along with its imports files", method = "POST", summary = "Create a TOSCA model", responses = {
101 @ApiResponse(content = @Content(array = @ArraySchema(schema = @Schema(implementation = Response.class)))),
102 @ApiResponse(responseCode = "201", description = "Model created"),
103 @ApiResponse(responseCode = "400", description = "Invalid content / Missing content"),
104 @ApiResponse(responseCode = "403", description = "Restricted operation"),
105 @ApiResponse(responseCode = "409", description = "Model already exists")})
106 public Response createModel(@Parameter(description = "model to be created", required = true)
107 @NotNull @Valid @FormDataParam("model") final ModelCreateRequest modelCreateRequest,
108 @Parameter(description = "the model TOSCA imports zipped", required = true)
109 @NotNull @FormDataParam("modelImportsZip") final InputStream modelImportsZip,
110 @HeaderParam(value = Constants.USER_ID_HEADER) final String userId) {
111 validateUser(ValidationUtils.sanitizeInputString(userId));
112 final var modelName = ValidationUtils.sanitizeInputString(modelCreateRequest.getName().trim());
114 final Model createdModel = modelBusinessLogic
115 .createModel(new JMapper<>(Model.class, ModelCreateRequest.class).getDestination(modelCreateRequest));
116 modelBusinessLogic.createModelImports(modelName, modelImportsZip);
117 return buildOkResponse(getComponentsUtils().getResponseFormat(ActionStatus.CREATED),
118 RepresentationUtils.toRepresentation(createdModel));
119 } catch (final BusinessException e) {
121 } catch (final Exception e) {
122 var errorMsg = String.format("Unexpected error while creating model '%s' imports", modelName);
123 BeEcompErrorManager.getInstance().logBeRestApiGeneralError(errorMsg);
124 log.error(errorMsg, e);
125 return buildErrorResponse(getComponentsUtils().getResponseFormat(ActionStatus.GENERAL_ERROR));
131 @Produces(MediaType.APPLICATION_JSON)
132 @PermissionAllowed(AafPermission.PermNames.INTERNAL_ALL_VALUE)
133 @Operation(method = "GET", summary = "List TOSCA models", description = "List all the existing TOSCA models",
135 @ApiResponse(content = @Content(array = @ArraySchema(schema = @Schema(implementation = Model.class)))),
136 @ApiResponse(responseCode = "200", description = "Listing successful"),
137 @ApiResponse(responseCode = "403", description = "Restricted operation")
140 public Response listModels(@HeaderParam(value = Constants.USER_ID_HEADER) final String userId, @QueryParam("modelType") final String modelType) {
141 validateUser(ValidationUtils.sanitizeInputString(userId));
143 final List<Model> modelList =
144 StringUtils.isEmpty(modelType) ? modelBusinessLogic.listModels() : modelBusinessLogic.listModels(getModelTypeEnum(modelType));
145 return buildOkResponse(getComponentsUtils().getResponseFormat(ActionStatus.OK), RepresentationUtils.toRepresentation(modelList));
146 } catch (final BusinessException e) {
148 } catch (final Exception e) {
149 var errorMsg = "Unexpected error while listing the models";
150 BeEcompErrorManager.getInstance().logBeRestApiGeneralError(errorMsg);
151 log.error(errorMsg, e);
152 return buildErrorResponse(getComponentsUtils().getResponseFormat(ActionStatus.GENERAL_ERROR));
156 private ModelTypeEnum getModelTypeEnum(final String modelType) {
157 final ModelTypeEnum modelTypeEnum = ModelTypeEnum.valueOf(modelType.toUpperCase());
158 if (modelTypeEnum == null) {
159 throw ModelOperationExceptionSupplier.unknownModelType(modelType).get();
161 return modelTypeEnum;
165 @Path("/model/imports")
166 @Consumes(MediaType.MULTIPART_FORM_DATA)
167 @Produces(MediaType.APPLICATION_JSON)
168 @PermissionAllowed(AafPermission.PermNames.INTERNAL_ALL_VALUE)
169 @Operation(description = "Update a model TOSCA imports", method = "PUT", summary = "Update a model TOSCA imports", responses = {
170 @ApiResponse(content = @Content(array = @ArraySchema(schema = @Schema(implementation = Response.class)))),
171 @ApiResponse(responseCode = "204", description = "Model imports updated"),
172 @ApiResponse(responseCode = "400", description = "Invalid content / Missing content"),
173 @ApiResponse(responseCode = "403", description = "Restricted operation"),
174 @ApiResponse(responseCode = "404", description = "Model not found")})
175 public Response updateModelImports(@Parameter(description = "model to be created", required = true)
176 @NotNull @FormDataParam("modelName") String modelName,
177 @Parameter(description = "the model TOSCA imports zipped", required = true)
178 @NotNull @FormDataParam("modelImportsZip") final InputStream modelImportsZip,
179 @HeaderParam(value = Constants.USER_ID_HEADER) final String userId) {
180 validateUser(ValidationUtils.sanitizeInputString(userId));
181 modelName = ValidationUtils.sanitizeInputString(modelName);
183 modelBusinessLogic.createModelImports(modelName, modelImportsZip);
184 } catch (final BusinessException e) {
186 } catch (final Exception e) {
187 var errorMsg = String.format("Unexpected error while creating model '%s' imports", modelName);
188 BeEcompErrorManager.getInstance().logBeRestApiGeneralError(errorMsg);
189 log.error(errorMsg, e);
190 return buildErrorResponse(getComponentsUtils().getResponseFormat(ActionStatus.GENERAL_ERROR));
192 return Response.status(Status.NO_CONTENT).build();
195 private void validateUser(final String userId) {
196 userValidations.validateUserRole(userValidations.validateUserExists(userId), Arrays.asList(Role.DESIGNER, Role.ADMIN));