catalog-be servlets refactoring
[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 javax.inject.Inject;
26 import org.glassfish.jersey.media.multipart.FormDataContentDisposition;
27 import org.glassfish.jersey.media.multipart.FormDataParam;
28 import org.openecomp.sdc.be.components.impl.ComponentInstanceBusinessLogic;
29 import org.openecomp.sdc.be.components.impl.GroupBusinessLogic;
30 import org.openecomp.sdc.be.components.impl.ResourceImportManager;
31 import org.openecomp.sdc.be.config.BeEcompErrorManager;
32 import org.openecomp.sdc.be.dao.api.ActionStatus;
33 import org.openecomp.sdc.be.impl.ComponentsUtils;
34 import org.openecomp.sdc.be.impl.ServletUtils;
35 import org.openecomp.sdc.be.model.UploadResourceInfo;
36 import org.openecomp.sdc.be.model.User;
37 import org.openecomp.sdc.be.user.UserBusinessLogic;
38 import org.openecomp.sdc.common.api.Constants;
39 import org.openecomp.sdc.common.datastructure.Wrapper;
40 import org.openecomp.sdc.common.log.wrappers.Logger;
41
42 import javax.inject.Singleton;
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 = Logger.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     @Inject
66     public ResourceUploadServlet(UserBusinessLogic userBusinessLogic,
67         ComponentInstanceBusinessLogic componentInstanceBL,
68         ComponentsUtils componentsUtils, ServletUtils servletUtils,
69         ResourceImportManager resourceImportManager) {
70         super(userBusinessLogic, componentInstanceBL, componentsUtils, servletUtils, resourceImportManager);
71     }
72
73     public enum ResourceAuthorityTypeEnum {
74         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);
75
76         private String urlPath;
77         private boolean isBackEndImport, isUserTypeResource;
78
79         public static ResourceAuthorityTypeEnum findByUrlPath(String urlPath) {
80             ResourceAuthorityTypeEnum found = null;
81             for (ResourceAuthorityTypeEnum curr : ResourceAuthorityTypeEnum.values()) {
82                 if (curr.getUrlPath().equals(urlPath)) {
83                     found = curr;
84                     break;
85                 }
86             }
87             return found;
88         }
89
90         private ResourceAuthorityTypeEnum(String urlPath, boolean isBackEndImport, boolean isUserTypeResource) {
91             this.urlPath = urlPath;
92             this.isBackEndImport = isBackEndImport;
93             this.isUserTypeResource = isUserTypeResource;
94         }
95
96         public String getUrlPath() {
97             return urlPath;
98         }
99
100         public boolean isBackEndImport() {
101             return isBackEndImport;
102         }
103
104         public boolean isUserTypeResource() {
105             return isUserTypeResource;
106         }
107     }
108
109     @POST
110     @Path("/{resourceAuthority}")
111     @Consumes(MediaType.MULTIPART_FORM_DATA)
112     @Produces(MediaType.APPLICATION_JSON)
113     @ApiOperation(value = "Create Resource from yaml", httpMethod = "POST", notes = "Returns created resource", response = Response.class)
114     @ApiResponses(value = { @ApiResponse(code = 201, message = "Resource created"), @ApiResponse(code = 403, message = "Restricted operation"), @ApiResponse(code = 400, message = "Invalid content / Missing content"),
115             @ApiResponse(code = 409, message = "Resource already exist") })
116     public Response uploadMultipart(
117             @ApiParam(value = "validValues: normative-resource / user-resource", allowableValues = NORMATIVE_TYPE_RESOURCE + "," + USER_TYPE_RESOURCE + ","
118                     + USER_TYPE_RESOURCE_UI_IMPORT) @PathParam(value = "resourceAuthority") final String resourceAuthority,
119             @ApiParam("FileInputStream") @FormDataParam("resourceZip") File file, @ApiParam("ContentDisposition") @FormDataParam("resourceZip") FormDataContentDisposition contentDispositionHeader,
120             @ApiParam("resourceMetadata") @FormDataParam("resourceMetadata") String resourceInfoJsonString, @Context final HttpServletRequest request, @HeaderParam(value = Constants.USER_ID_HEADER) String userId,
121             // updateResourse Query Parameter if false checks if already exist
122             @DefaultValue("true") @QueryParam("createNewVersion") boolean createNewVersion) {
123
124         try {
125
126             Wrapper<Response> responseWrapper = new Wrapper<>();
127             Wrapper<User> userWrapper = new Wrapper<>();
128             Wrapper<UploadResourceInfo> uploadResourceInfoWrapper = new Wrapper<>();
129             Wrapper<String> yamlStringWrapper = new Wrapper<>();
130
131             String url = request.getMethod() + " " + request.getRequestURI();
132             log.debug("Start handle request of {}", url);
133
134             // When we get an errorResponse it will be filled into the
135             // responseWrapper
136             validateAuthorityType(responseWrapper, resourceAuthority);
137
138             ResourceAuthorityTypeEnum resourceAuthorityEnum = ResourceAuthorityTypeEnum.findByUrlPath(resourceAuthority);
139
140             commonGeneralValidations(responseWrapper, userWrapper, uploadResourceInfoWrapper, resourceAuthorityEnum, userId, resourceInfoJsonString);
141
142             fillPayload(responseWrapper, uploadResourceInfoWrapper, yamlStringWrapper, userWrapper.getInnerElement(), resourceInfoJsonString, resourceAuthorityEnum, file);
143
144             // PayLoad Validations
145             if(!resourceAuthorityEnum.equals(ResourceAuthorityTypeEnum.CSAR_TYPE_BE)){
146                 commonPayloadValidations(responseWrapper, yamlStringWrapper, userWrapper.getInnerElement(), uploadResourceInfoWrapper.getInnerElement());
147
148                 specificResourceAuthorityValidations(responseWrapper, uploadResourceInfoWrapper, yamlStringWrapper, userWrapper.getInnerElement(), request, resourceInfoJsonString, resourceAuthorityEnum);
149             }
150
151             if (responseWrapper.isEmpty()) {
152                 handleImport(responseWrapper, userWrapper.getInnerElement(), uploadResourceInfoWrapper.getInnerElement(), yamlStringWrapper.getInnerElement(), resourceAuthorityEnum, createNewVersion, null);
153             }
154
155             return responseWrapper.getInnerElement();
156
157         } catch (Exception e) {
158             BeEcompErrorManager.getInstance().logBeRestApiGeneralError("Upload Resource");
159             log.debug("upload resource failed with exception", e);
160             return buildErrorResponse(getComponentsUtils().getResponseFormat(ActionStatus.GENERAL_ERROR));
161         }
162     }
163
164     /********************************************************************************************************************/
165 }