Add Support for creating model type
[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.util.Arrays;
32 import javax.inject.Inject;
33 import javax.validation.Valid;
34 import javax.validation.constraints.NotNull;
35 import javax.ws.rs.Consumes;
36 import javax.ws.rs.HeaderParam;
37 import javax.ws.rs.POST;
38 import javax.ws.rs.Path;
39 import javax.ws.rs.Produces;
40 import javax.ws.rs.core.MediaType;
41 import javax.ws.rs.core.Response;
42 import org.openecomp.sdc.be.components.impl.ComponentInstanceBusinessLogic;
43 import org.openecomp.sdc.be.components.impl.ModelBusinessLogic;
44 import org.openecomp.sdc.be.components.impl.ResourceImportManager;
45 import org.openecomp.sdc.be.components.impl.aaf.AafPermission;
46 import org.openecomp.sdc.be.components.impl.aaf.PermissionAllowed;
47 import org.openecomp.sdc.be.components.validation.UserValidations;
48 import org.openecomp.sdc.be.config.BeEcompErrorManager;
49 import org.openecomp.sdc.be.dao.api.ActionStatus;
50 import org.openecomp.sdc.be.exception.BusinessException;
51 import org.openecomp.sdc.be.impl.ComponentsUtils;
52 import org.openecomp.sdc.be.impl.ServletUtils;
53 import org.openecomp.sdc.be.model.Model;
54 import org.openecomp.sdc.be.ui.model.ModelCreateRequest;
55 import org.openecomp.sdc.be.user.Role;
56 import org.openecomp.sdc.be.user.UserBusinessLogic;
57 import org.openecomp.sdc.common.api.Constants;
58 import org.slf4j.Logger;
59 import org.slf4j.LoggerFactory;
60 import org.springframework.stereotype.Controller;
61 import org.springframework.web.bind.annotation.RequestBody;
62
63 /**
64  * Root resource (exposed at "/" path)
65  */
66 @Loggable(prepend = true, value = Loggable.DEBUG, trim = false)
67 @Path("/v1/catalog")
68 @Tag(name = "SDCE-2 APIs")
69 @Server(url = "/sdc2/rest")
70 @Controller
71 public class ModelServlet extends AbstractValidationsServlet {
72
73     private static final Logger log = LoggerFactory.getLogger(ModelServlet.class);
74     private final ModelBusinessLogic modelBusinessLogic;
75     private final UserValidations userValidations;
76
77     @Inject
78     public ModelServlet(final UserBusinessLogic userBusinessLogic, final ComponentInstanceBusinessLogic componentInstanceBL,
79                         final ComponentsUtils componentsUtils, final ServletUtils servletUtils, final ResourceImportManager resourceImportManager,
80                         final ModelBusinessLogic modelBusinessLogic, final UserValidations userValidations) {
81         super(userBusinessLogic, componentInstanceBL, componentsUtils, servletUtils, resourceImportManager);
82         this.modelBusinessLogic = modelBusinessLogic;
83         this.userValidations = userValidations;
84     }
85
86     @POST
87     @Path("/model")
88     @Consumes(MediaType.APPLICATION_JSON)
89     @Produces(MediaType.APPLICATION_JSON)
90     @Operation(description = "Create model", method = "POST", summary = "Returns created model", responses = {
91         @ApiResponse(content = @Content(array = @ArraySchema(schema = @Schema(implementation = Response.class)))),
92         @ApiResponse(responseCode = "201", description = "Model created"),
93         @ApiResponse(responseCode = "403", description = "Restricted operation"),
94         @ApiResponse(responseCode = "400", description = "Invalid content / Missing content"),
95         @ApiResponse(responseCode = "409", description = "Resource already exists")})
96     @PermissionAllowed(AafPermission.PermNames.INTERNAL_ALL_VALUE)
97     public Response createModel(@Parameter(description = "model to be created", required = true)
98                                     @Valid @RequestBody @NotNull final ModelCreateRequest modelCreateRequest,
99                                 @HeaderParam(value = Constants.USER_ID_HEADER) String userId) {
100
101         validateUser(userId);
102         try {
103             final Model modelCreateResponse = modelBusinessLogic
104                 .createModel(new JMapper<>(Model.class, ModelCreateRequest.class).getDestination(modelCreateRequest));
105             return buildOkResponse(getComponentsUtils().getResponseFormat(ActionStatus.CREATED),
106                 RepresentationUtils.toRepresentation(modelCreateResponse));
107         } catch (final BusinessException e) {
108             throw e;
109         } catch (final Exception e) {
110             var errorMsg = String
111                 .format("Unexpected error while creating model '%s'", modelCreateRequest.getName());
112             BeEcompErrorManager.getInstance().logBeRestApiGeneralError(errorMsg);
113             log.error(errorMsg, e);
114             return buildErrorResponse(getComponentsUtils().getResponseFormat(ActionStatus.GENERAL_ERROR));
115         }
116     }
117
118     private void validateUser(final String userId) {
119         userValidations.validateUserRole(userValidations.validateUserExists(userId), Arrays.asList(Role.DESIGNER, Role.ADMIN));
120     }
121
122 }