2 * ============LICENSE_START=======================================================
4 * ================================================================================
5 * Copyright (C) 2017 AT&T Intellectual Property. 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
11 * http://www.apache.org/licenses/LICENSE-2.0
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=========================================================
20 package org.openecomp.sdc.be.servlets;
22 import com.jcabi.aspects.Loggable;
23 import fj.data.Either;
24 import io.swagger.v3.oas.annotations.Operation;
25 import io.swagger.v3.oas.annotations.Parameter;
26 import io.swagger.v3.oas.annotations.media.ArraySchema;
27 import io.swagger.v3.oas.annotations.media.Content;
28 import io.swagger.v3.oas.annotations.media.Schema;
29 import io.swagger.v3.oas.annotations.responses.ApiResponse;
30 import io.swagger.v3.oas.annotations.servers.Server;
31 import io.swagger.v3.oas.annotations.tags.Tag;
33 import java.io.IOException;
34 import java.io.InputStream;
35 import java.nio.charset.StandardCharsets;
36 import javax.inject.Inject;
37 import javax.servlet.http.HttpServletRequest;
38 import javax.validation.constraints.NotNull;
39 import javax.ws.rs.Consumes;
40 import javax.ws.rs.DefaultValue;
41 import javax.ws.rs.HeaderParam;
42 import javax.ws.rs.POST;
43 import javax.ws.rs.Path;
44 import javax.ws.rs.PathParam;
45 import javax.ws.rs.Produces;
46 import javax.ws.rs.QueryParam;
47 import javax.ws.rs.core.Context;
48 import javax.ws.rs.core.MediaType;
49 import javax.ws.rs.core.Response;
50 import org.glassfish.jersey.media.multipart.FormDataContentDisposition;
51 import org.glassfish.jersey.media.multipart.FormDataParam;
52 import org.openecomp.sdc.be.components.impl.ComponentInstanceBusinessLogic;
53 import org.openecomp.sdc.be.components.impl.ModelBusinessLogic;
54 import org.openecomp.sdc.be.components.impl.ResourceImportManager;
55 import org.openecomp.sdc.be.config.BeEcompErrorManager;
56 import org.openecomp.sdc.be.dao.api.ActionStatus;
57 import org.openecomp.sdc.be.exception.BusinessException;
58 import org.openecomp.sdc.be.impl.ComponentsUtils;
59 import org.openecomp.sdc.be.impl.ServletUtils;
60 import org.openecomp.sdc.be.model.NodeTypesMetadataList;
61 import org.openecomp.sdc.be.model.UploadResourceInfo;
62 import org.openecomp.sdc.be.model.User;
63 import org.openecomp.sdc.be.model.jsonjanusgraph.operations.exception.ModelOperationExceptionSupplier;
64 import org.openecomp.sdc.common.api.Constants;
65 import org.openecomp.sdc.common.datastructure.Wrapper;
66 import org.openecomp.sdc.common.util.ValidationUtils;
67 import org.openecomp.sdc.exception.ResponseFormat;
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)
76 @Path("/v1/catalog/upload")
77 @Tag(name = "SDCE-2 APIs")
78 @Server(url = "/sdc2/rest")
80 public class ResourceUploadServlet extends AbstractValidationsServlet {
82 public static final String NORMATIVE_TYPE_RESOURCE = "multipart";
83 public static final String CSAR_TYPE_RESOURCE = "csar";
84 public static final String USER_TYPE_RESOURCE = "user-resource";
85 public static final String USER_TYPE_RESOURCE_UI_IMPORT = "user-resource-ui-import";
86 private static final Logger log = LoggerFactory.getLogger(ResourceUploadServlet.class);
88 private final ModelBusinessLogic modelBusinessLogic;
91 public ResourceUploadServlet(ComponentInstanceBusinessLogic componentInstanceBL,
92 ComponentsUtils componentsUtils, ServletUtils servletUtils, ResourceImportManager resourceImportManager,
93 ModelBusinessLogic modelBusinessLogic) {
94 super(componentInstanceBL, componentsUtils, servletUtils, resourceImportManager);
95 this.modelBusinessLogic = modelBusinessLogic;
99 @Path("/{resourceAuthority}")
100 @Consumes(MediaType.MULTIPART_FORM_DATA)
101 @Produces(MediaType.APPLICATION_JSON)
102 @Operation(description = "Create Resource from yaml", method = "POST", summary = "Returns created resource", responses = {
103 @ApiResponse(content = @Content(array = @ArraySchema(schema = @Schema(implementation = Response.class)))),
104 @ApiResponse(responseCode = "201", description = "Resource created"),
105 @ApiResponse(responseCode = "403", description = "Restricted operation"),
106 @ApiResponse(responseCode = "400", description = "Invalid content / Missing content"),
107 @ApiResponse(responseCode = "409", description = "Resource already exist")})
108 public Response uploadMultipart(
109 @Parameter(description = "validValues: normative-resource / user-resource", schema = @Schema(allowableValues = {NORMATIVE_TYPE_RESOURCE,
110 USER_TYPE_RESOURCE, USER_TYPE_RESOURCE_UI_IMPORT})) @PathParam(value = "resourceAuthority") final String resourceAuthority,
111 @Parameter(description = "FileInputStream") @FormDataParam("resourceZip") File file,
112 @Parameter(description = "ContentDisposition") @FormDataParam("resourceZip") FormDataContentDisposition contentDispositionHeader,
113 @Parameter(description = "resourceMetadata") @FormDataParam("resourceMetadata") String resourceInfoJsonString,
114 @Context final HttpServletRequest request, @HeaderParam(value = Constants.USER_ID_HEADER) String userId,
115 // updateResource Query Parameter if false checks if already exist
116 @DefaultValue("true") @QueryParam("createNewVersion") boolean createNewVersion) {
118 Wrapper<Response> responseWrapper = new Wrapper<>();
119 Wrapper<User> userWrapper = new Wrapper<>();
120 Wrapper<UploadResourceInfo> uploadResourceInfoWrapper = new Wrapper<>();
121 Wrapper<String> yamlStringWrapper = new Wrapper<>();
122 String url = request.getMethod() + " " + request.getRequestURI();
123 log.debug("Start handle request of {}", url);
124 // When we get an errorResponse it will be filled into the responseWrapper
125 validateAuthorityType(responseWrapper, resourceAuthority);
126 ResourceAuthorityTypeEnum resourceAuthorityEnum = ResourceAuthorityTypeEnum.findByUrlPath(resourceAuthority);
127 commonGeneralValidations(responseWrapper, userWrapper, uploadResourceInfoWrapper, resourceAuthorityEnum, userId, resourceInfoJsonString);
128 final String modelNameToBeAssociated = uploadResourceInfoWrapper.getInnerElement().getModel();
129 if (modelNameToBeAssociated != null) {
130 log.debug("Model Name to be validated {}", modelNameToBeAssociated);
131 validateModel(modelNameToBeAssociated);
133 fillPayload(responseWrapper, uploadResourceInfoWrapper, yamlStringWrapper, userWrapper.getInnerElement(), resourceInfoJsonString,
134 resourceAuthorityEnum, file);
135 // PayLoad Validations
136 if (resourceAuthorityEnum != ResourceAuthorityTypeEnum.CSAR_TYPE_BE) {
137 commonPayloadValidations(responseWrapper, yamlStringWrapper, userWrapper.getInnerElement(),
138 uploadResourceInfoWrapper.getInnerElement());
139 specificResourceAuthorityValidations(responseWrapper, uploadResourceInfoWrapper, yamlStringWrapper, userWrapper.getInnerElement(),
140 request, resourceInfoJsonString, resourceAuthorityEnum);
142 if (responseWrapper.isEmpty()) {
143 handleImport(responseWrapper, userWrapper.getInnerElement(), uploadResourceInfoWrapper.getInnerElement(),
144 yamlStringWrapper.getInnerElement(), resourceAuthorityEnum, createNewVersion, null);
146 return responseWrapper.getInnerElement();
147 } catch (final BusinessException e) {
149 } catch (final Exception e) {
150 var errorMsg = String.format("Unexpected error while uploading Resource '%s'", resourceInfoJsonString);
151 BeEcompErrorManager.getInstance().logBeRestApiGeneralError(errorMsg);
152 log.error(errorMsg, e);
153 return buildErrorResponse(getComponentsUtils().getResponseFormat(ActionStatus.GENERAL_ERROR));
158 @Path("/resource/import")
159 @Consumes(MediaType.MULTIPART_FORM_DATA)
160 @Produces(MediaType.APPLICATION_JSON)
161 @Operation(description = "Import node types from a TOSCA yaml, along with the types metadata", method = "POST",
162 summary = "Creates node types from a TOSCA yaml file", responses = {
163 @ApiResponse(content = @Content(array = @ArraySchema(schema = @Schema(implementation = Response.class)))),
164 @ApiResponse(responseCode = "201", description = "Resources created"),
165 @ApiResponse(responseCode = "400", description = "Invalid content / Missing content"),
166 @ApiResponse(responseCode = "403", description = "Restricted operation"),
167 @ApiResponse(responseCode = "409", description = "One of the resources already exists")}
169 public Response bulkImport(@Parameter(description = "The nodes metadata JSON", required = true)
170 @NotNull @FormDataParam("nodeTypeMetadataJson") final NodeTypesMetadataList nodeTypeMetadata,
171 @Parameter(description = "The node types TOSCA definition yaml", required = true)
172 @NotNull @FormDataParam("nodeTypesYaml") final InputStream nodeTypesYamlInputStream,
173 @Parameter(description = "The model name to associate the node types to")
174 @DefaultValue("true") @FormDataParam("createNewVersion") boolean createNewVersion,
175 @HeaderParam(value = Constants.USER_ID_HEADER) String userId,
176 @Context final HttpServletRequest request) {
177 userId = ValidationUtils.sanitizeInputString(userId);
178 final Either<User, ResponseFormat> userEither = getUser(request, userId);
179 if (userEither.isRight()) {
180 return buildErrorResponse(userEither.right().value());
183 final User user = userEither.left().value();
185 final String nodeTypesYamlString;
187 nodeTypesYamlString = new String(nodeTypesYamlInputStream.readAllBytes(), StandardCharsets.UTF_8);
188 } catch (final IOException e) {
189 var errorMsg = "Could not read the given node types yaml";
190 BeEcompErrorManager.getInstance().logBeRestApiGeneralError(errorMsg);
191 log.error(errorMsg, e);
192 return buildErrorResponse(getComponentsUtils().getResponseFormat(ActionStatus.INVALID_NODE_TYPES_YAML));
196 resourceImportManager.importAllNormativeResource(nodeTypesYamlString, nodeTypeMetadata, user, createNewVersion, false);
197 return buildOkResponse(getComponentsUtils().getResponseFormat(ActionStatus.CREATED), null);
198 } catch (final BusinessException e) {
200 } catch (final Exception e) {
201 var errorMsg = "Unexpected error while importing the node types";
202 BeEcompErrorManager.getInstance().logBeRestApiGeneralError(errorMsg);
203 log.error(errorMsg, e);
204 return buildErrorResponse(getComponentsUtils().getResponseFormat(ActionStatus.GENERAL_ERROR));
209 * The Model field is an optional entry when uploading a resource. If the field is present, it validates if the Model name exists.
211 * @param modelName Model names declared on the resource json representation
213 private void validateModel(final String modelName) {
214 if (modelBusinessLogic.findModel(modelName).isEmpty()) {
215 log.error("Could not find model name {}", modelName);
216 throw ModelOperationExceptionSupplier.invalidModel(modelName).get();
220 public enum ResourceAuthorityTypeEnum {
222 NORMATIVE_TYPE_BE(NORMATIVE_TYPE_RESOURCE, true, false),
223 USER_TYPE_BE(USER_TYPE_RESOURCE, true, true),
224 USER_TYPE_UI(USER_TYPE_RESOURCE_UI_IMPORT, false, true),
225 CSAR_TYPE_BE(CSAR_TYPE_RESOURCE, true, true);
228 private String urlPath;
229 private boolean isBackEndImport;
230 private boolean isUserTypeResource;
232 public static ResourceAuthorityTypeEnum findByUrlPath(String urlPath) {
233 ResourceAuthorityTypeEnum found = null;
234 for (ResourceAuthorityTypeEnum curr : ResourceAuthorityTypeEnum.values()) {
235 if (curr.getUrlPath().equals(urlPath)) {
243 ResourceAuthorityTypeEnum(String urlPath, boolean isBackEndImport, boolean isUserTypeResource) {
244 this.urlPath = urlPath;
245 this.isBackEndImport = isBackEndImport;
246 this.isUserTypeResource = isUserTypeResource;
249 public String getUrlPath() {
253 public boolean isBackEndImport() {
254 return isBackEndImport;
257 public boolean isUserTypeResource() {
258 return isUserTypeResource;