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.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;
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;
55 import java.util.Map.Entry;
56 import java.util.function.Supplier;
58 public class BeGenericServlet extends BasicServlet {
61 protected HttpServletRequest servletRequest;
63 private static final Logger log = Logger.getLogger(BeGenericServlet.class);
65 /******************** New error response mechanism
66 * @param requestErrorWrapper **************/
68 protected Response buildErrorResponse(ResponseFormat requestErrorWrapper) {
69 return Response.status(requestErrorWrapper.getStatus()).entity(gson.toJson(requestErrorWrapper.getRequestError())).build();
72 protected Response buildGeneralErrorResponse() {
73 return buildErrorResponse(getComponentsUtils().getResponseFormat(ActionStatus.GENERAL_ERROR));
76 protected Response buildOkResponse(Object entity) {
77 return buildOkResponseStatic(entity);
80 private static Response buildOkResponseStatic(Object entity) {
81 return Response.status(Response.Status.OK)
86 protected Response buildOkResponse(ResponseFormat errorResponseWrapper, Object entity) {
87 return buildOkResponse(errorResponseWrapper, entity, null);
90 protected Response buildOkResponse(ResponseFormat errorResponseWrapper, Object entity, Map<String, String> additionalHeaders) {
91 int status = errorResponseWrapper.getStatus();
92 ResponseBuilder responseBuilder = Response.status(status);
94 if (log.isTraceEnabled())
95 log.trace("returned entity is {}", entity.toString());
96 responseBuilder = responseBuilder.entity(entity);
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);
107 return responseBuilder.build();
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);
118 getComponentsUtils().auditResource(errorResponse, user, "", AuditingActionEnum.CHECKOUT_RESOURCE);
119 return Either.right(errorResponse);
121 return Either.left(eitherCreator.left().value());
125 UserBusinessLogic getUserAdminManager(ServletContext context) {
126 return getClassFromWebAppContext(context, () -> UserBusinessLogic.class);
129 protected ResourceBusinessLogic getResourceBL(ServletContext context) {
130 return getClassFromWebAppContext(context, () -> ResourceBusinessLogic.class);
133 protected InterfaceOperationBusinessLogic getInterfaceOperationBL(ServletContext context) {
134 return getClassFromWebAppContext(context, () -> InterfaceOperationBusinessLogic.class);
137 ComponentsCleanBusinessLogic getComponentCleanerBL(ServletContext context) {
138 return getClassFromWebAppContext(context, () -> ComponentsCleanBusinessLogic.class);
141 protected ServiceBusinessLogic getServiceBL(ServletContext context) {
142 return getClassFromWebAppContext(context, () -> ServiceBusinessLogic.class);
145 ProductBusinessLogic getProductBL(ServletContext context) {
146 return getClassFromWebAppContext(context, () -> ProductBusinessLogic.class);
149 protected ArtifactsBusinessLogic getArtifactBL(ServletContext context) {
150 return getClassFromWebAppContext(context, () -> ArtifactsBusinessLogic.class);
152 protected UpgradeBusinessLogic getUpgradeBL(ServletContext context) {
153 return getClassFromWebAppContext(context, () -> UpgradeBusinessLogic.class);
156 protected ElementBusinessLogic getElementBL(ServletContext context) {
157 return getClassFromWebAppContext(context, () -> ElementBusinessLogic.class);
160 MonitoringBusinessLogic getMonitoringBL(ServletContext context) {
161 return getClassFromWebAppContext(context, () -> MonitoringBusinessLogic.class);
164 protected AssetMetadataConverter getAssetUtils(ServletContext context) {
165 return getClassFromWebAppContext(context, () -> AssetMetadataConverter.class);
168 protected LifecycleBusinessLogic getLifecycleBL(ServletContext context) {
169 return getClassFromWebAppContext(context, () -> LifecycleBusinessLogic.class);
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());
178 GroupBusinessLogic getGroupBL(ServletContext context) {
180 WebAppContextWrapper webApplicationContextWrapper = (WebAppContextWrapper) context.getAttribute(Constants.WEB_APPLICATION_CONTEXT_WRAPPER_ATTR);
181 WebApplicationContext webApplicationContext = webApplicationContextWrapper.getWebAppContext(context);
182 return webApplicationContext.getBean(GroupBusinessLogic.class);
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);
191 protected ComponentsUtils getComponentsUtils() {
192 ServletContext context = this.servletRequest.getSession().getServletContext();
194 WebAppContextWrapper webApplicationContextWrapper = (WebAppContextWrapper) context.getAttribute(Constants.WEB_APPLICATION_CONTEXT_WRAPPER_ATTR);
195 WebApplicationContext webApplicationContext = webApplicationContextWrapper.getWebAppContext(context);
196 return webApplicationContext.getBean(ComponentsUtils.class);
200 * Used to support Unit Test.<br>
201 * Header Params are not supported in Unit Tests
205 String initHeaderParam(String headerValue, HttpServletRequest request, String headerName) {
207 if (headerValue != null) {
208 retValue = headerValue;
210 retValue = request.getHeader(headerName);
215 protected String getContentDispositionValue(String artifactFileName) {
216 return new StringBuilder().append("attachment; filename=\"").append(artifactFileName).append("\"").toString();
221 protected ComponentBusinessLogic getComponentBL(ComponentTypeEnum componentTypeEnum, ServletContext context) {
222 ComponentBusinessLogic businessLogic;
223 switch (componentTypeEnum) {
225 businessLogic = getResourceBL(context);
228 businessLogic = getServiceBL(context);
231 businessLogic = getProductBL(context);
233 case RESOURCE_INSTANCE:
234 businessLogic = getResourceBL(context);
237 BeEcompErrorManager.getInstance().logBeSystemError("getComponentBL");
238 throw new IllegalArgumentException("Illegal component type:" + componentTypeEnum.getValue());
240 return businessLogic;
243 <T> void convertJsonToObjectOfClass(String json, Wrapper<T> policyWrapper, Class<T> clazz, Wrapper<Response> errorWrapper) {
245 ObjectMapper mapper = new ObjectMapper()
246 .configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false)
247 .configure(DeserializationFeature.ACCEPT_SINGLE_VALUE_AS_ARRAY, true);
249 log.trace("Starting to convert json to object. Json=\n{}", json);
251 SimpleModule module = new SimpleModule("customDeserializationModule");
252 module.addDeserializer(PropertyConstraint.class, new PropertyConstraintJacksonDeserializer());
253 mapper.registerModule(module);
255 object = mapper.readValue(json, clazz);
256 if (object != null) {
257 policyWrapper.setInnerElement(object);
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)));
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)));