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