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