Fix model init
[sdc.git] / catalog-be / src / main / java / org / openecomp / sdc / be / servlets / ModelServlet.java
1 /*
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
8  *
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.
15  *
16  *  SPDX-License-Identifier: Apache-2.0
17  *  ============LICENSE_END=========================================================
18  */
19 package org.openecomp.sdc.be.servlets;
20
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.be.user.UserBusinessLogic;
67 import org.openecomp.sdc.common.api.Constants;
68 import org.openecomp.sdc.common.util.ValidationUtils;
69 import org.slf4j.Logger;
70 import org.slf4j.LoggerFactory;
71 import org.springframework.stereotype.Controller;
72
73 /**
74  * Root resource (exposed at "/" path)
75  */
76 @Loggable(prepend = true, value = Loggable.DEBUG, trim = false)
77 @Path("/v1/catalog")
78 @Tag(name = "SDCE-2 APIs")
79 @Server(url = "/sdc2/rest")
80 @Controller
81 public class ModelServlet extends AbstractValidationsServlet {
82
83     private static final Logger log = LoggerFactory.getLogger(ModelServlet.class);
84     private final ModelBusinessLogic modelBusinessLogic;
85     private final UserValidations userValidations;
86
87     @Inject
88     public ModelServlet(final UserBusinessLogic userBusinessLogic, final ComponentInstanceBusinessLogic componentInstanceBL,
89                         final ComponentsUtils componentsUtils, final ServletUtils servletUtils, final ResourceImportManager resourceImportManager,
90                         final ModelBusinessLogic modelBusinessLogic, final UserValidations userValidations) {
91         super(userBusinessLogic, componentInstanceBL, componentsUtils, servletUtils, resourceImportManager);
92         this.modelBusinessLogic = modelBusinessLogic;
93         this.userValidations = userValidations;
94     }
95
96     @POST
97     @Path("/model")
98     @Consumes(MediaType.MULTIPART_FORM_DATA)
99     @Produces(MediaType.APPLICATION_JSON)
100     @PermissionAllowed(AafPermission.PermNames.INTERNAL_ALL_VALUE)
101     @Operation(description = "Create a TOSCA model, along with its imports files", method = "POST", summary = "Create a TOSCA model", responses = {
102         @ApiResponse(content = @Content(array = @ArraySchema(schema = @Schema(implementation = Response.class)))),
103         @ApiResponse(responseCode = "201", description = "Model created"),
104         @ApiResponse(responseCode = "400", description = "Invalid content / Missing content"),
105         @ApiResponse(responseCode = "403", description = "Restricted operation"),
106         @ApiResponse(responseCode = "409", description = "Model already exists")})
107     public Response createModel(@Parameter(description = "model to be created", required = true)
108                                     @NotNull @Valid @FormDataParam("model") final ModelCreateRequest modelCreateRequest,
109                                 @Parameter(description = "the model TOSCA imports zipped", required = true)
110                                     @NotNull @FormDataParam("modelImportsZip") final InputStream modelImportsZip,
111                                 @HeaderParam(value = Constants.USER_ID_HEADER) final String userId) {
112         validateUser(ValidationUtils.sanitizeInputString(userId));
113         final var modelName = ValidationUtils.sanitizeInputString(modelCreateRequest.getName().trim());
114         try {
115             final Model createdModel = modelBusinessLogic
116                 .createModel(new JMapper<>(Model.class, ModelCreateRequest.class).getDestination(modelCreateRequest));
117             modelBusinessLogic.createModelImports(modelName, modelImportsZip);
118             return buildOkResponse(getComponentsUtils().getResponseFormat(ActionStatus.CREATED),
119                 RepresentationUtils.toRepresentation(createdModel));
120         } catch (final BusinessException e) {
121             throw e;
122         } catch (final Exception e) {
123             var errorMsg = String.format("Unexpected error while creating model '%s' imports", modelName);
124             BeEcompErrorManager.getInstance().logBeRestApiGeneralError(errorMsg);
125             log.error(errorMsg, e);
126             return buildErrorResponse(getComponentsUtils().getResponseFormat(ActionStatus.GENERAL_ERROR));
127         }
128     }
129
130     @GET
131     @Path("/model")
132     @Produces(MediaType.APPLICATION_JSON)
133     @PermissionAllowed(AafPermission.PermNames.INTERNAL_ALL_VALUE)
134     @Operation(method = "GET", summary = "List TOSCA models", description = "List all the existing TOSCA models",
135         responses = {
136             @ApiResponse(content = @Content(array = @ArraySchema(schema = @Schema(implementation = Model.class)))),
137             @ApiResponse(responseCode = "200", description = "Listing successful"),
138             @ApiResponse(responseCode = "403", description = "Restricted operation")
139         }
140     )
141     public Response listModels(@HeaderParam(value = Constants.USER_ID_HEADER) final String userId, @QueryParam("modelType") final String modelType) {
142         validateUser(ValidationUtils.sanitizeInputString(userId));
143         try {
144             final List<Model> modelList = StringUtils.isEmpty(modelType)? modelBusinessLogic.listModels() : modelBusinessLogic.listModels(getModelTypeEnum(modelType));
145             return buildOkResponse(getComponentsUtils().getResponseFormat(ActionStatus.OK), RepresentationUtils.toRepresentation(modelList));
146         } catch (final BusinessException e) {
147             throw 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));
153         }
154     }
155     
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();
160         }
161         return modelTypeEnum;
162     }
163
164     @PUT
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);
182         try {
183             modelBusinessLogic.createModelImports(modelName, modelImportsZip);
184         } catch (final BusinessException e) {
185             throw 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));
191         }
192         return Response.status(Status.NO_CONTENT).build();
193     }
194
195     private void validateUser(final String userId) {
196         userValidations.validateUserRole(userValidations.validateUserExists(userId), Arrays.asList(Role.DESIGNER, Role.ADMIN));
197     }
198
199 }