re base code
[sdc.git] / catalog-be / src / main / java / org / openecomp / sdc / be / servlets / BeGenericServlet.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.fasterxml.jackson.databind.DeserializationFeature;
24 import com.fasterxml.jackson.databind.ObjectMapper;
25 import com.fasterxml.jackson.databind.module.SimpleModule;
26 import fj.data.Either;
27 import org.openecomp.sdc.be.components.impl.*;
28 import org.openecomp.sdc.be.components.lifecycle.LifecycleBusinessLogic;
29 import org.openecomp.sdc.be.components.scheduledtasks.ComponentsCleanBusinessLogic;
30 import org.openecomp.sdc.be.components.upgrade.UpgradeBusinessLogic;
31 import org.openecomp.sdc.be.config.BeEcompErrorManager;
32 import org.openecomp.sdc.be.dao.api.ActionStatus;
33 import org.openecomp.sdc.be.datatypes.enums.ComponentTypeEnum;
34 import org.openecomp.sdc.be.ecomp.converters.AssetMetadataConverter;
35 import org.openecomp.sdc.be.impl.ComponentsUtils;
36 import org.openecomp.sdc.be.impl.WebAppContextWrapper;
37 import org.openecomp.sdc.be.model.PropertyConstraint;
38 import org.openecomp.sdc.be.model.User;
39 import org.openecomp.sdc.be.model.operations.impl.PropertyOperation.PropertyConstraintJacksonDeserializer;
40 import org.openecomp.sdc.be.resources.data.auditing.AuditingActionEnum;
41 import org.openecomp.sdc.be.user.UserBusinessLogic;
42 import org.openecomp.sdc.common.api.Constants;
43 import org.openecomp.sdc.common.datastructure.Wrapper;
44 import org.openecomp.sdc.common.log.wrappers.Logger;
45 import org.openecomp.sdc.common.servlets.BasicServlet;
46 import org.openecomp.sdc.exception.ResponseFormat;
47 import org.springframework.web.context.WebApplicationContext;
48
49 import javax.servlet.ServletContext;
50 import javax.servlet.http.HttpServletRequest;
51 import javax.ws.rs.core.Context;
52 import javax.ws.rs.core.Response;
53 import javax.ws.rs.core.Response.ResponseBuilder;
54 import java.util.Map;
55 import java.util.Map.Entry;
56 import java.util.function.Supplier;
57
58 public class BeGenericServlet extends BasicServlet {
59
60     @Context
61     protected HttpServletRequest servletRequest;
62
63     private static final Logger log = Logger.getLogger(BeGenericServlet.class);
64
65     /******************** New error response mechanism
66      * @param requestErrorWrapper **************/
67
68     protected Response buildErrorResponse(ResponseFormat requestErrorWrapper) {
69         return Response.status(requestErrorWrapper.getStatus()).entity(gson.toJson(requestErrorWrapper.getRequestError())).build();
70     }
71
72     protected Response buildGeneralErrorResponse() {
73         return buildErrorResponse(getComponentsUtils().getResponseFormat(ActionStatus.GENERAL_ERROR));
74     }
75
76     protected Response buildOkResponse(Object entity) {
77         return buildOkResponseStatic(entity);
78     }
79
80     private static Response buildOkResponseStatic(Object entity) {
81         return Response.status(Response.Status.OK)
82                 .entity(entity)
83                 .build();
84     }
85
86     protected Response buildOkResponse(ResponseFormat errorResponseWrapper, Object entity) {
87         return buildOkResponse(errorResponseWrapper, entity, null);
88     }
89
90     protected Response buildOkResponse(ResponseFormat errorResponseWrapper, Object entity, Map<String, String> additionalHeaders) {
91         int status = errorResponseWrapper.getStatus();
92         ResponseBuilder responseBuilder = Response.status(status);
93         if (entity != null) {
94             if (log.isTraceEnabled())
95                 log.trace("returned entity is {}", entity.toString());
96             responseBuilder = responseBuilder.entity(entity);
97         }
98         if (additionalHeaders != null) {
99             for (Entry<String, String> additionalHeader : additionalHeaders.entrySet()) {
100                 String headerName = additionalHeader.getKey();
101                 String headerValue = additionalHeader.getValue();
102                 if (log.isTraceEnabled())
103                     log.trace("Adding header {} with value {} to the response", headerName, headerValue);
104                 responseBuilder.header(headerName, headerValue);
105             }
106         }
107         return responseBuilder.build();
108     }
109
110     /*******************************************************************************************************/
111     protected Either<User, ResponseFormat> getUser(final HttpServletRequest request, String userId) {
112         Either<User, ActionStatus> eitherCreator = getUserAdminManager(request.getSession().getServletContext()).getUser(userId, false);
113         if (eitherCreator.isRight()) {
114             log.info("createResource method - user is not listed. userId= {}", userId);
115             ResponseFormat errorResponse = getComponentsUtils().getResponseFormat(ActionStatus.MISSING_INFORMATION);
116             User user = new User("", "", userId, "", null, null);
117
118             getComponentsUtils().auditResource(errorResponse, user, "", AuditingActionEnum.CHECKOUT_RESOURCE);
119             return Either.right(errorResponse);
120         }
121         return Either.left(eitherCreator.left().value());
122
123     }
124
125     UserBusinessLogic getUserAdminManager(ServletContext context) {
126         return getClassFromWebAppContext(context, () -> UserBusinessLogic.class);
127     }
128
129     protected ResourceBusinessLogic getResourceBL(ServletContext context) {
130         return getClassFromWebAppContext(context, () -> ResourceBusinessLogic.class);
131     }
132
133     protected InterfaceOperationBusinessLogic getInterfaceOperationBL(ServletContext context) {
134         return getClassFromWebAppContext(context, () -> InterfaceOperationBusinessLogic.class);
135     }
136
137     ComponentsCleanBusinessLogic getComponentCleanerBL(ServletContext context) {
138         return getClassFromWebAppContext(context, () -> ComponentsCleanBusinessLogic.class);
139     }
140
141     protected ServiceBusinessLogic getServiceBL(ServletContext context) {
142         return getClassFromWebAppContext(context, () -> ServiceBusinessLogic.class);
143     }
144
145     ProductBusinessLogic getProductBL(ServletContext context) {
146         return getClassFromWebAppContext(context, () -> ProductBusinessLogic.class);
147     }
148
149     protected ArtifactsBusinessLogic getArtifactBL(ServletContext context) {
150         return getClassFromWebAppContext(context, () -> ArtifactsBusinessLogic.class);
151     }
152     protected UpgradeBusinessLogic getUpgradeBL(ServletContext context) {
153         return getClassFromWebAppContext(context, () -> UpgradeBusinessLogic.class);
154     }
155
156     protected ElementBusinessLogic getElementBL(ServletContext context) {
157         return getClassFromWebAppContext(context, () -> ElementBusinessLogic.class);
158     }
159
160     MonitoringBusinessLogic getMonitoringBL(ServletContext context) {
161         return getClassFromWebAppContext(context, () -> MonitoringBusinessLogic.class);
162     }
163
164     protected AssetMetadataConverter getAssetUtils(ServletContext context) {
165         return getClassFromWebAppContext(context, () -> AssetMetadataConverter.class);
166     }
167
168     protected LifecycleBusinessLogic getLifecycleBL(ServletContext context) {
169         return getClassFromWebAppContext(context, () -> LifecycleBusinessLogic.class);
170     }
171
172     <T> T getClassFromWebAppContext(ServletContext context, Supplier<Class<T>> businessLogicClassGen) {
173         WebAppContextWrapper webApplicationContextWrapper = (WebAppContextWrapper) context.getAttribute(Constants.WEB_APPLICATION_CONTEXT_WRAPPER_ATTR);
174         WebApplicationContext webApplicationContext = webApplicationContextWrapper.getWebAppContext(context);
175         return webApplicationContext.getBean(businessLogicClassGen.get());
176     }
177
178     GroupBusinessLogic getGroupBL(ServletContext context) {
179
180         WebAppContextWrapper webApplicationContextWrapper = (WebAppContextWrapper) context.getAttribute(Constants.WEB_APPLICATION_CONTEXT_WRAPPER_ATTR);
181         WebApplicationContext webApplicationContext = webApplicationContextWrapper.getWebAppContext(context);
182         return webApplicationContext.getBean(GroupBusinessLogic.class);
183     }
184
185     protected ComponentInstanceBusinessLogic getComponentInstanceBL(ServletContext context) {
186         WebAppContextWrapper webApplicationContextWrapper = (WebAppContextWrapper) context.getAttribute(Constants.WEB_APPLICATION_CONTEXT_WRAPPER_ATTR);
187         WebApplicationContext webApplicationContext = webApplicationContextWrapper.getWebAppContext(context);
188         return webApplicationContext.getBean(ComponentInstanceBusinessLogic.class);
189     }
190
191     protected ComponentsUtils getComponentsUtils() {
192         ServletContext context = this.servletRequest.getSession().getServletContext();
193
194         WebAppContextWrapper webApplicationContextWrapper = (WebAppContextWrapper) context.getAttribute(Constants.WEB_APPLICATION_CONTEXT_WRAPPER_ATTR);
195         WebApplicationContext webApplicationContext = webApplicationContextWrapper.getWebAppContext(context);
196         return webApplicationContext.getBean(ComponentsUtils.class);
197     }
198
199     /**
200      * Used to support Unit Test.<br>
201      * Header Params are not supported in Unit Tests
202      *
203      * @return
204      */
205     String initHeaderParam(String headerValue, HttpServletRequest request, String headerName) {
206         String retValue;
207         if (headerValue != null) {
208             retValue = headerValue;
209         } else {
210             retValue = request.getHeader(headerName);
211         }
212         return retValue;
213     }
214
215     protected String getContentDispositionValue(String artifactFileName) {
216         return new StringBuilder().append("attachment; filename=\"").append(artifactFileName).append("\"").toString();
217     }
218     
219     
220
221     protected ComponentBusinessLogic getComponentBL(ComponentTypeEnum componentTypeEnum, ServletContext context) {
222         ComponentBusinessLogic businessLogic;
223         switch (componentTypeEnum) {
224             case RESOURCE:
225                 businessLogic = getResourceBL(context);
226                 break;
227             case SERVICE:
228                 businessLogic = getServiceBL(context);
229                 break;
230             case PRODUCT:
231                 businessLogic = getProductBL(context);
232                 break;
233             case RESOURCE_INSTANCE:
234                 businessLogic = getResourceBL(context);
235                 break;
236             default:
237                 BeEcompErrorManager.getInstance().logBeSystemError("getComponentBL");
238                 throw new IllegalArgumentException("Illegal component type:" + componentTypeEnum.getValue());
239         }
240         return businessLogic;
241     }
242
243     <T> void convertJsonToObjectOfClass(String json, Wrapper<T> policyWrapper, Class<T> clazz, Wrapper<Response> errorWrapper) {
244         T object = null;
245         ObjectMapper mapper = new ObjectMapper()
246                 .configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false)
247                 .configure(DeserializationFeature.ACCEPT_SINGLE_VALUE_AS_ARRAY, true);
248         try {
249             log.trace("Starting to convert json to object. Json=\n{}", json);
250
251             SimpleModule module = new SimpleModule("customDeserializationModule");
252             module.addDeserializer(PropertyConstraint.class, new PropertyConstraintJacksonDeserializer());
253             mapper.registerModule(module);
254
255             object = mapper.readValue(json, clazz);
256             if (object != null) {
257                 policyWrapper.setInnerElement(object);
258             } else {
259                 BeEcompErrorManager.getInstance().logBeInvalidJsonInput("convertJsonToObject");
260                 log.debug("The object of class {} is null after converting from json. ", clazz);
261                 errorWrapper.setInnerElement(buildErrorResponse(getComponentsUtils().getResponseFormat(ActionStatus.INVALID_CONTENT)));
262             }
263         } catch (Exception e) {
264             BeEcompErrorManager.getInstance().logBeInvalidJsonInput("convertJsonToObject");
265             log.debug("The exception {} occured upon json to object convertation. Json=\n{}", e, json);
266             errorWrapper.setInnerElement(buildErrorResponse(getComponentsUtils().getResponseFormat(ActionStatus.INVALID_CONTENT)));
267         }
268     }
269 }