Initial OpenECOMP SDC commit
[sdc.git] / catalog-be / src / main / java / org / openecomp / sdc / be / servlets / ResourceUploadServlet.java
1 /*-
2  * ============LICENSE_START=======================================================
3  * SDC
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
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 java.io.File;
24
25 import javax.annotation.Resource;
26 import javax.inject.Singleton;
27 import javax.servlet.ServletContext;
28 import javax.servlet.http.HttpServletRequest;
29 import javax.ws.rs.Consumes;
30 import javax.ws.rs.DefaultValue;
31 import javax.ws.rs.HeaderParam;
32 import javax.ws.rs.POST;
33 import javax.ws.rs.Path;
34 import javax.ws.rs.PathParam;
35 import javax.ws.rs.Produces;
36 import javax.ws.rs.QueryParam;
37 import javax.ws.rs.core.Context;
38 import javax.ws.rs.core.MediaType;
39 import javax.ws.rs.core.Response;
40
41 import org.glassfish.jersey.media.multipart.FormDataContentDisposition;
42 import org.glassfish.jersey.media.multipart.FormDataParam;
43 import org.openecomp.sdc.be.components.impl.ResourceImportManager;
44 import org.openecomp.sdc.be.config.BeEcompErrorManager;
45 import org.openecomp.sdc.be.dao.api.ActionStatus;
46 import org.openecomp.sdc.be.impl.WebAppContextWrapper;
47 import org.openecomp.sdc.be.model.UploadResourceInfo;
48 import org.openecomp.sdc.be.model.User;
49 import org.openecomp.sdc.common.api.Constants;
50 import org.openecomp.sdc.common.config.EcompErrorName;
51 import org.openecomp.sdc.common.datastructure.Wrapper;
52 import org.slf4j.Logger;
53 import org.slf4j.LoggerFactory;
54 import org.springframework.web.context.WebApplicationContext;
55
56 import com.jcabi.aspects.Loggable;
57 import com.wordnik.swagger.annotations.Api;
58 import com.wordnik.swagger.annotations.ApiOperation;
59 import com.wordnik.swagger.annotations.ApiParam;
60 import com.wordnik.swagger.annotations.ApiResponse;
61 import com.wordnik.swagger.annotations.ApiResponses;
62
63 /**
64  * Root resource (exposed at "/" path)
65  */
66 @Loggable(prepend = true, value = Loggable.DEBUG, trim = false)
67 @Path("/v1/catalog/upload")
68 @Api(value = "Resources Catalog Upload", description = "Upload resource yaml")
69 @Singleton
70 public class ResourceUploadServlet extends AbstractValidationsServlet {
71
72         private static Logger log = LoggerFactory.getLogger(ResourceUploadServlet.class.getName());
73         public static final String NORMATIVE_TYPE_RESOURCE = "multipart";
74         public static final String USER_TYPE_RESOURCE = "user-resource";
75         public static final String USER_TYPE_RESOURCE_UI_IMPORT = "user-resource-ui-import";
76
77         public enum ResourceAuthorityTypeEnum {
78                 NORMATIVE_TYPE_BE(NORMATIVE_TYPE_RESOURCE, true, false), USER_TYPE_BE(USER_TYPE_RESOURCE, true, true), USER_TYPE_UI(USER_TYPE_RESOURCE_UI_IMPORT, false, true);
79
80                 private String urlPath;
81                 private boolean isBackEndImport, isUserTypeResource;
82
83                 public static ResourceAuthorityTypeEnum findByUrlPath(String urlPath) {
84                         ResourceAuthorityTypeEnum found = null;
85                         for (ResourceAuthorityTypeEnum curr : ResourceAuthorityTypeEnum.values()) {
86                                 if (curr.getUrlPath().equals(urlPath)) {
87                                         found = curr;
88                                         break;
89                                 }
90                         }
91                         return found;
92                 }
93
94                 private ResourceAuthorityTypeEnum(String urlPath, boolean isBackEndImport, boolean isUserTypeResource) {
95                         this.urlPath = urlPath;
96                         this.isBackEndImport = isBackEndImport;
97                         this.isUserTypeResource = isUserTypeResource;
98                 }
99
100                 public String getUrlPath() {
101                         return urlPath;
102                 }
103
104                 public boolean isBackEndImport() {
105                         return isBackEndImport;
106                 }
107
108                 public boolean isUserTypeResource() {
109                         return isUserTypeResource;
110                 }
111         }
112
113         @Resource
114         private ResourceImportManager resourceImportManager;
115
116         @POST
117         @Path("/{resourceAuthority}")
118         @Consumes(MediaType.MULTIPART_FORM_DATA)
119         @Produces(MediaType.APPLICATION_JSON)
120         @ApiOperation(value = "Create Resource from yaml", httpMethod = "POST", notes = "Returns created resource", response = Response.class)
121         @ApiResponses(value = { @ApiResponse(code = 201, message = "Resource created"), @ApiResponse(code = 403, message = "Restricted operation"), @ApiResponse(code = 400, message = "Invalid content / Missing content"),
122                         @ApiResponse(code = 409, message = "Resource already exist") })
123         public Response uploadMultipart(
124                         @ApiParam(value = "validValues: normative-resource / user-resource", allowableValues = NORMATIVE_TYPE_RESOURCE + "," + USER_TYPE_RESOURCE + ","
125                                         + USER_TYPE_RESOURCE_UI_IMPORT) @PathParam(value = "resourceAuthority") final String resourceAuthority,
126                         @ApiParam("FileInputStream") @FormDataParam("resourceZip") File file, @ApiParam("ContentDisposition") @FormDataParam("resourceZip") FormDataContentDisposition contentDispositionHeader,
127                         @ApiParam("resourceMetadata") @FormDataParam("resourceMetadata") String resourceInfoJsonString, @Context final HttpServletRequest request, @HeaderParam(value = Constants.USER_ID_HEADER) String userId,
128                         // updateResourse Query Parameter if false checks if already exist
129                         @DefaultValue("true") @QueryParam("createNewVersion") boolean createNewVersion) {
130
131                 init(request.getSession().getServletContext());
132                 try {
133
134                         Wrapper<Response> responseWrapper = new Wrapper<>();
135                         Wrapper<User> userWrapper = new Wrapper<>();
136                         Wrapper<UploadResourceInfo> uploadResourceInfoWrapper = new Wrapper<>();
137                         Wrapper<String> yamlStringWrapper = new Wrapper<>();
138
139                         String url = request.getMethod() + " " + request.getRequestURI();
140                         log.debug("Start handle request of {}", url);
141
142                         // When we get an errorResponse it will be filled into the
143                         // responseWrapper
144                         validateAuthorityType(responseWrapper, resourceAuthority);
145
146                         ResourceAuthorityTypeEnum resourceAuthorityEnum = ResourceAuthorityTypeEnum.findByUrlPath(resourceAuthority);
147
148                         commonGeneralValidations(responseWrapper, userWrapper, uploadResourceInfoWrapper, resourceAuthorityEnum, userId, resourceInfoJsonString);
149
150                         fillPayload(responseWrapper, uploadResourceInfoWrapper, yamlStringWrapper, userWrapper.getInnerElement(), resourceInfoJsonString, resourceAuthorityEnum, file);
151
152                         // PayLoad Validations
153                         commonPayloadValidations(responseWrapper, yamlStringWrapper, userWrapper.getInnerElement(), uploadResourceInfoWrapper.getInnerElement());
154
155                         specificResourceAuthorityValidations(responseWrapper, uploadResourceInfoWrapper, yamlStringWrapper, userWrapper.getInnerElement(), request, resourceInfoJsonString, resourceAuthorityEnum);
156
157                         if (responseWrapper.isEmpty()) {
158                                 handleImport(responseWrapper, userWrapper.getInnerElement(), uploadResourceInfoWrapper.getInnerElement(), yamlStringWrapper.getInnerElement(), resourceAuthorityEnum, createNewVersion, null);
159                         }
160
161                         return responseWrapper.getInnerElement();
162
163                 } catch (Exception e) {
164                         BeEcompErrorManager.getInstance().processEcompError(EcompErrorName.BeRestApiGeneralError, "Upload Resource");
165                         BeEcompErrorManager.getInstance().logBeRestApiGeneralError("Upload Resource");
166                         log.debug("upload resource failed with exception", e);
167                         return buildErrorResponse(getComponentsUtils().getResponseFormat(ActionStatus.GENERAL_ERROR));
168                 }
169         }
170
171         /********************************************************************************************************************/
172
173         private void init(ServletContext context) {
174                 init(log);
175                 WebAppContextWrapper webApplicationContextWrapper = (WebAppContextWrapper) context.getAttribute(Constants.WEB_APPLICATION_CONTEXT_WRAPPER_ATTR);
176                 WebApplicationContext webApplicationContext = webApplicationContextWrapper.getWebAppContext(context);
177                 resourceImportManager = webApplicationContext.getBean(ResourceImportManager.class);
178                 resourceImportManager.init(context);
179         }
180 }