ComponentBaseTest.java enhancement and
[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 io.swagger.annotations.Api;
58 import io.swagger.annotations.ApiOperation;
59 import io.swagger.annotations.ApiParam;
60 import io.swagger.annotations.ApiResponse;
61 import io.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 CSAR_TYPE_RESOURCE = "csar";
75         public static final String USER_TYPE_RESOURCE = "user-resource";
76         public static final String USER_TYPE_RESOURCE_UI_IMPORT = "user-resource-ui-import";
77
78         public enum ResourceAuthorityTypeEnum {
79                 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), CSAR_TYPE_BE(CSAR_TYPE_RESOURCE, true, true);
80
81                 private String urlPath;
82                 private boolean isBackEndImport, isUserTypeResource;
83
84                 public static ResourceAuthorityTypeEnum findByUrlPath(String urlPath) {
85                         ResourceAuthorityTypeEnum found = null;
86                         for (ResourceAuthorityTypeEnum curr : ResourceAuthorityTypeEnum.values()) {
87                                 if (curr.getUrlPath().equals(urlPath)) {
88                                         found = curr;
89                                         break;
90                                 }
91                         }
92                         return found;
93                 }
94
95                 private ResourceAuthorityTypeEnum(String urlPath, boolean isBackEndImport, boolean isUserTypeResource) {
96                         this.urlPath = urlPath;
97                         this.isBackEndImport = isBackEndImport;
98                         this.isUserTypeResource = isUserTypeResource;
99                 }
100
101                 public String getUrlPath() {
102                         return urlPath;
103                 }
104
105                 public boolean isBackEndImport() {
106                         return isBackEndImport;
107                 }
108
109                 public boolean isUserTypeResource() {
110                         return isUserTypeResource;
111                 }
112         }
113
114         @Resource
115         private ResourceImportManager resourceImportManager;
116
117         @POST
118         @Path("/{resourceAuthority}")
119         @Consumes(MediaType.MULTIPART_FORM_DATA)
120         @Produces(MediaType.APPLICATION_JSON)
121         @ApiOperation(value = "Create Resource from yaml", httpMethod = "POST", notes = "Returns created resource", response = Response.class)
122         @ApiResponses(value = { @ApiResponse(code = 201, message = "Resource created"), @ApiResponse(code = 403, message = "Restricted operation"), @ApiResponse(code = 400, message = "Invalid content / Missing content"),
123                         @ApiResponse(code = 409, message = "Resource already exist") })
124         public Response uploadMultipart(
125                         @ApiParam(value = "validValues: normative-resource / user-resource", allowableValues = NORMATIVE_TYPE_RESOURCE + "," + USER_TYPE_RESOURCE + ","
126                                         + USER_TYPE_RESOURCE_UI_IMPORT) @PathParam(value = "resourceAuthority") final String resourceAuthority,
127                         @ApiParam("FileInputStream") @FormDataParam("resourceZip") File file, @ApiParam("ContentDisposition") @FormDataParam("resourceZip") FormDataContentDisposition contentDispositionHeader,
128                         @ApiParam("resourceMetadata") @FormDataParam("resourceMetadata") String resourceInfoJsonString, @Context final HttpServletRequest request, @HeaderParam(value = Constants.USER_ID_HEADER) String userId,
129                         // updateResourse Query Parameter if false checks if already exist
130                         @DefaultValue("true") @QueryParam("createNewVersion") boolean createNewVersion) {
131
132                 init(request.getSession().getServletContext());
133                 try {
134
135                         Wrapper<Response> responseWrapper = new Wrapper<>();
136                         Wrapper<User> userWrapper = new Wrapper<>();
137                         Wrapper<UploadResourceInfo> uploadResourceInfoWrapper = new Wrapper<>();
138                         Wrapper<String> yamlStringWrapper = new Wrapper<>();
139
140                         String url = request.getMethod() + " " + request.getRequestURI();
141                         log.debug("Start handle request of {}", url);
142
143                         // When we get an errorResponse it will be filled into the
144                         // responseWrapper
145                         validateAuthorityType(responseWrapper, resourceAuthority);
146
147                         ResourceAuthorityTypeEnum resourceAuthorityEnum = ResourceAuthorityTypeEnum.findByUrlPath(resourceAuthority);
148
149                         commonGeneralValidations(responseWrapper, userWrapper, uploadResourceInfoWrapper, resourceAuthorityEnum, userId, resourceInfoJsonString);
150
151                         fillPayload(responseWrapper, uploadResourceInfoWrapper, yamlStringWrapper, userWrapper.getInnerElement(), resourceInfoJsonString, resourceAuthorityEnum, file);
152
153                         // PayLoad Validations
154                         if(!resourceAuthorityEnum.equals(ResourceAuthorityTypeEnum.CSAR_TYPE_BE)){
155                                 commonPayloadValidations(responseWrapper, yamlStringWrapper, userWrapper.getInnerElement(), uploadResourceInfoWrapper.getInnerElement());
156
157                                 specificResourceAuthorityValidations(responseWrapper, uploadResourceInfoWrapper, yamlStringWrapper, userWrapper.getInnerElement(), request, resourceInfoJsonString, resourceAuthorityEnum);
158                         }
159
160                         if (responseWrapper.isEmpty()) {
161                                 handleImport(responseWrapper, userWrapper.getInnerElement(), uploadResourceInfoWrapper.getInnerElement(), yamlStringWrapper.getInnerElement(), resourceAuthorityEnum, createNewVersion, null);
162                         }
163
164                         return responseWrapper.getInnerElement();
165
166                 } catch (Exception e) {
167                         BeEcompErrorManager.getInstance().processEcompError(EcompErrorName.BeRestApiGeneralError, "Upload Resource");
168                         BeEcompErrorManager.getInstance().logBeRestApiGeneralError("Upload Resource");
169                         log.debug("upload resource failed with exception", e);
170                         return buildErrorResponse(getComponentsUtils().getResponseFormat(ActionStatus.GENERAL_ERROR));
171                 }
172         }
173
174         /********************************************************************************************************************/
175
176         private void init(ServletContext context) {
177                 init(log);
178                 WebAppContextWrapper webApplicationContextWrapper = (WebAppContextWrapper) context.getAttribute(Constants.WEB_APPLICATION_CONTEXT_WRAPPER_ATTR);
179                 WebApplicationContext webApplicationContext = webApplicationContextWrapper.getWebAppContext(context);
180                 resourceImportManager = webApplicationContext.getBean(ResourceImportManager.class);
181                 resourceImportManager.init(context);
182         }
183 }