2 * ============LICENSE_START=======================================================
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
11 * http://www.apache.org/licenses/LICENSE-2.0
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=========================================================
21 package org.openecomp.sdc.be.servlets;
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;
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;
67 import java.util.Map.Entry;
68 import java.util.function.Supplier;
70 public class BeGenericServlet extends BasicServlet {
73 protected HttpServletRequest servletRequest;
75 private static final Logger log = LoggerFactory.getLogger(BeGenericServlet.class);
77 /******************** New error response mechanism
78 * @param requestErrorWrapper **************/
80 protected Response buildErrorResponse(ResponseFormat requestErrorWrapper) {
81 return Response.status(requestErrorWrapper.getStatus()).entity(gson.toJson(requestErrorWrapper.getRequestError())).build();
84 protected Response buildGeneralErrorResponse() {
85 return buildErrorResponse(getComponentsUtils().getResponseFormat(ActionStatus.GENERAL_ERROR));
88 protected Response buildOkResponse(Object entity) {
89 return buildOkResponseStatic(entity);
92 static public Response buildOkResponseStatic(Object entity) {
93 return Response.status(Response.Status.OK)
98 protected Response buildOkResponse(ResponseFormat errorResponseWrapper, Object entity) {
99 return buildOkResponse(errorResponseWrapper, entity, null);
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);
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);
119 return responseBuilder.build();
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);
130 getComponentsUtils().auditResource(errorResponse, user, "", AuditingActionEnum.CHECKOUT_RESOURCE);
131 return Either.right(errorResponse);
133 return Either.left(eitherCreator.left().value());
137 protected PolicyTypeBusinessLogic getPolicyTypeBL(ServletContext context) {
138 return getClassFromWebAppContext(context, () -> PolicyTypeBusinessLogic.class);
141 protected UserBusinessLogic getUserAdminManager(ServletContext context) {
142 return getClassFromWebAppContext(context, () -> UserBusinessLogic.class);
145 protected ResourceBusinessLogic getResourceBL(ServletContext context) {
146 return getClassFromWebAppContext(context, () -> ResourceBusinessLogic.class);
149 protected ComponentsCleanBusinessLogic getComponentCleanerBL(ServletContext context) {
150 return getClassFromWebAppContext(context, () -> ComponentsCleanBusinessLogic.class);
153 protected ServiceBusinessLogic getServiceBL(ServletContext context) {
154 return getClassFromWebAppContext(context, () -> ServiceBusinessLogic.class);
157 protected ProductBusinessLogic getProductBL(ServletContext context) {
158 return getClassFromWebAppContext(context, () -> ProductBusinessLogic.class);
161 protected ArtifactsBusinessLogic getArtifactBL(ServletContext context) {
162 return getClassFromWebAppContext(context, () -> ArtifactsBusinessLogic.class);
165 protected ElementBusinessLogic getElementBL(ServletContext context) {
166 return getClassFromWebAppContext(context, () -> ElementBusinessLogic.class);
169 protected MonitoringBusinessLogic getMonitoringBL(ServletContext context) {
170 return getClassFromWebAppContext(context, () -> MonitoringBusinessLogic.class);
173 protected AssetMetadataConverter getAssetUtils(ServletContext context) {
174 return getClassFromWebAppContext(context, () -> AssetMetadataConverter.class);
177 protected LifecycleBusinessLogic getLifecycleBL(ServletContext context) {
178 return getClassFromWebAppContext(context, () -> LifecycleBusinessLogic.class);
181 protected PolicyBusinessLogic getPolicyBL(ServletContext context) {
182 return getClassFromWebAppContext(context, () -> PolicyBusinessLogic.class);
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());
191 protected GroupBusinessLogic getGroupBL(ServletContext context) {
193 WebAppContextWrapper webApplicationContextWrapper = (WebAppContextWrapper) context.getAttribute(Constants.WEB_APPLICATION_CONTEXT_WRAPPER_ATTR);
194 WebApplicationContext webApplicationContext = webApplicationContextWrapper.getWebAppContext(context);
195 return webApplicationContext.getBean(GroupBusinessLogic.class);
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);
204 protected IElementDAO getElementDao(Class<? extends IElementDAO> clazz, ServletContext context) {
205 WebAppContextWrapper webApplicationContextWrapper = (WebAppContextWrapper) context.getAttribute(Constants.WEB_APPLICATION_CONTEXT_WRAPPER_ATTR);
207 WebApplicationContext webApplicationContext = webApplicationContextWrapper.getWebAppContext(context);
209 return webApplicationContext.getBean(clazz);
212 protected ComponentsUtils getComponentsUtils() {
213 ServletContext context = this.servletRequest.getSession().getServletContext();
215 WebAppContextWrapper webApplicationContextWrapper = (WebAppContextWrapper) context.getAttribute(Constants.WEB_APPLICATION_CONTEXT_WRAPPER_ATTR);
216 WebApplicationContext webApplicationContext = webApplicationContextWrapper.getWebAppContext(context);
217 return webApplicationContext.getBean(ComponentsUtils.class);
221 * Used to support Unit Test.<br>
222 * Header Params are not supported in Unit Tests
226 protected String initHeaderParam(String headerValue, HttpServletRequest request, String headerName) {
228 if (headerValue != null) {
229 retValue = headerValue;
231 retValue = request.getHeader(headerName);
236 protected String getContentDispositionValue(String artifactFileName) {
237 return new StringBuilder().append("attachment; filename=\"").append(artifactFileName).append("\"").toString();
240 protected ComponentBusinessLogic getComponentBL(ComponentTypeEnum componentTypeEnum, ServletContext context) {
241 ComponentBusinessLogic businessLogic;
242 switch (componentTypeEnum) {
244 businessLogic = getResourceBL(context);
247 businessLogic = getServiceBL(context);
250 businessLogic = getProductBL(context);
252 case RESOURCE_INSTANCE:
253 businessLogic = getResourceBL(context);
256 BeEcompErrorManager.getInstance().logBeSystemError("getComponentBL");
257 throw new IllegalArgumentException("Illegal component type:" + componentTypeEnum.getValue());
259 return businessLogic;
262 protected <T> void convertJsonToObjectOfClass(String json, Wrapper<T> policyWrapper, Class<T> clazz, Wrapper<Response> errorWrapper) {
264 ObjectMapper mapper = new ObjectMapper()
265 .configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false)
266 .configure(DeserializationFeature.ACCEPT_SINGLE_VALUE_AS_ARRAY, true);
268 log.trace("Starting to convert json to object. Json=\n{}", json);
270 SimpleModule module = new SimpleModule("customDeserializationModule");
271 module.addDeserializer(PropertyConstraint.class, new PropertyConstraintJacksonDeserializer());
272 mapper.registerModule(module);
274 object = mapper.readValue(json, clazz);
275 if (object != null) {
276 policyWrapper.setInnerElement(object);
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)));
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)));