2 * ================================================================================
4 * ================================================================================
5 * Copyright (C) 2017 AT&T Intellectual Property
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 * ================================================================================
20 package org.openecomp.portalapp.portal.controller;
22 import java.io.InputStream;
23 import java.nio.charset.StandardCharsets;
24 import java.util.HashMap;
27 import javax.servlet.http.HttpServletRequest;
29 import org.apache.commons.io.IOUtils;
30 import org.openecomp.portalapp.controller.EPRestrictedRESTfulBaseController;
31 import org.openecomp.portalapp.portal.domain.EPApp;
32 import org.openecomp.portalapp.portal.domain.EcompAuditLog;
33 import org.openecomp.portalapp.portal.logging.aop.EPAuditLog;
34 import org.openecomp.portalapp.portal.logging.aop.EPEELFLoggerAdvice;
35 import org.openecomp.portalapp.portal.logging.logic.EPLogUtil;
36 import org.openecomp.portalapp.portal.service.AppsCacheService;
37 import org.openecomp.portalapp.portal.service.ConsulHealthService;
38 import org.openecomp.portalapp.portal.transport.Analytics;
39 import org.openecomp.portalapp.portal.utils.EPCommonSystemProperties;
40 import org.openecomp.portalapp.portal.utils.EcompPortalUtils;
41 import org.openecomp.portalapp.portal.utils.PortalConstants;
42 import org.openecomp.portalsdk.core.logging.logic.EELFLoggerDelegate;
43 import org.openecomp.portalsdk.core.onboarding.crossapi.PortalAPIResponse;
44 import org.openecomp.portalsdk.core.service.AuditService;
45 import org.openecomp.portalsdk.core.util.SystemProperties;
47 import org.springframework.beans.factory.annotation.Autowired;
48 import org.springframework.context.annotation.Configuration;
49 import org.springframework.context.annotation.EnableAspectJAutoProxy;
50 import org.springframework.http.HttpEntity;
51 import org.springframework.http.HttpHeaders;
52 import org.springframework.http.HttpMethod;
53 import org.springframework.http.MediaType;
54 import org.springframework.http.ResponseEntity;
55 import org.springframework.util.concurrent.FailureCallback;
56 import org.springframework.util.concurrent.ListenableFuture;
57 import org.springframework.util.concurrent.SuccessCallback;
58 import org.springframework.web.bind.annotation.RequestBody;
59 import org.springframework.web.bind.annotation.RequestMapping;
60 import org.springframework.web.bind.annotation.RequestMethod;
61 import org.springframework.web.bind.annotation.ResponseBody;
62 import org.springframework.web.bind.annotation.RestController;
63 import org.springframework.web.client.AsyncRestTemplate;
65 import io.swagger.annotations.ApiOperation;
68 @RequestMapping(PortalConstants.REST_AUX_API)
70 @EnableAspectJAutoProxy
72 public class WebAnalyticsExtAppController extends EPRestrictedRESTfulBaseController {
75 private ConsulHealthService consulHealthService;
77 private static final String MACHINE_LEARNING_SERVICE_CTX = "/ml_api";
78 private static final String REGISTER_ACTION = MACHINE_LEARNING_SERVICE_CTX + "/" + "registerAction";
79 private static final String CONSUL_ML_SERVICE_ID = "machine-learning";
80 private static final String APP_KEY = "uebkey";
81 private EELFLoggerDelegate logger = EELFLoggerDelegate.getLogger(WebAnalyticsExtAppController.class);
82 private AsyncRestTemplate restTemplate = new AsyncRestTemplate();
86 AuditService auditService;
89 AppsCacheService appCacheService;
91 SuccessCallback<ResponseEntity<String>> successCallback = new SuccessCallback<ResponseEntity<String>>() {
93 public void onSuccess(ResponseEntity<String> arg) {
94 logger.info(EELFLoggerDelegate.debugLogger, arg.getBody());
98 FailureCallback failureCallback = new FailureCallback() {
100 public void onFailure(Throwable arg) {
101 logger.error(EELFLoggerDelegate.errorLogger, "storeAuxAnalytics failed", arg);
105 protected boolean isAuxRESTfulCall() {
110 * Answers requests from partner applications for a file that is expected to
111 * contain javascript to support web analytics.
119 @ApiOperation(value = "Gets javascript with functions that support gathering and reporting web analytics.", response = String.class)
120 @RequestMapping(value = { "/analytics" }, method = RequestMethod.GET, produces = "application/javascript")
121 public String getAnalyticsScript(HttpServletRequest request) throws Exception {
122 String responseText = "";
123 final String fileName = "analytics.txt";
124 InputStream analyticsFileStream = null;
126 analyticsFileStream = this.getClass().getClassLoader().getResourceAsStream(fileName);
127 responseText = IOUtils.toString(analyticsFileStream, StandardCharsets.UTF_8.name());
128 } catch (Exception e) {
129 logger.error(EELFLoggerDelegate.errorLogger, "Error reading contents of the file " + fileName, e);
131 if (analyticsFileStream != null)
132 analyticsFileStream.close();
135 String feURLContext = SystemProperties.getProperty("frontend_url");
136 String feURL = feURLContext.substring(0, feURLContext.lastIndexOf('/'));
138 responseText = responseText.replace("PORTAL_ENV_URL", feURL);
143 * Accepts data from partner applications with web analytics data.
147 * @param analyticsMap
149 * @return PortalAPIResponse
153 @RequestMapping(value = { "/storeAnalytics" }, method = RequestMethod.POST, produces = "application/json")
155 @ApiOperation(value = "Accepts data from partner applications with web analytics data.", response = PortalAPIResponse.class)
156 public PortalAPIResponse storeAnalyticsScript(HttpServletRequest request, @RequestBody Analytics analyticsMap)
159 MDC.put(EPCommonSystemProperties.AUDITLOG_BEGIN_TIMESTAMP, EPEELFLoggerAdvice.getCurrentDateTimeUTC());
162 appName = getAppName(request, appName);
163 } catch (Exception e) {
164 logger.error(EELFLoggerDelegate.errorLogger,
165 " Error retrieving Application to capture app name for analytics; Proceeding with empty app name");
169 storeAuxAnalytics(analyticsMap, appName);
170 } catch (Exception e) {
171 logger.error(EELFLoggerDelegate.errorLogger,
172 " Error retrieving Application to capture app name for analytics; Proceeding with empty app name");
175 MDC.put(EPCommonSystemProperties.AUDITLOG_END_TIMESTAMP, EPEELFLoggerAdvice.getCurrentDateTimeUTC());
177 EcompPortalUtils.calculateDateTimeDifferenceForLog(
178 MDC.get(EPCommonSystemProperties.AUDITLOG_BEGIN_TIMESTAMP),
179 MDC.get(EPCommonSystemProperties.AUDITLOG_END_TIMESTAMP));
180 logger.info(EELFLoggerDelegate.auditLogger,
181 EPLogUtil.formatStoreAnalyticsAuditLogMessage(analyticsMap.getUserId(), appName,
182 "WebAnalyticsExtAppController.postWebAnalyticsData",
183 EcompAuditLog.CD_ACTIVITY_STORE_ANALYTICS, analyticsMap.getAction(), analyticsMap.getPage(),
184 analyticsMap.getFunction(), analyticsMap.getType()));
186 MDC.remove(EPCommonSystemProperties.AUDITLOG_BEGIN_TIMESTAMP);
187 MDC.remove(EPCommonSystemProperties.AUDITLOG_END_TIMESTAMP);
188 MDC.remove(SystemProperties.MDC_TIMER);
190 PortalAPIResponse response = new PortalAPIResponse(true, "success");
192 } catch (Exception e) {
193 logger.error(EELFLoggerDelegate.errorLogger, "storeAnalytics failed", e);
194 PortalAPIResponse response = new PortalAPIResponse(true, "error");
199 protected String getAppName(HttpServletRequest request, String appName) {
200 String appKeyValue = request.getHeader(APP_KEY);
201 if (appKeyValue == null || appKeyValue.equals("")) {
202 logger.error(EELFLoggerDelegate.errorLogger, " App Key unavailable; Proceeding with null app name");
204 EPApp appRecord = appCacheService.getAppForAnalytics(appKeyValue);
205 if (appRecord == null) {
206 logger.error(EELFLoggerDelegate.errorLogger, " App could not be found for the key " + appKeyValue);
208 appName = appRecord.getName();
214 protected void storeAuxAnalytics(Analytics analyticsMap, String appName) {
215 logger.info(EELFLoggerDelegate.debugLogger,
216 " Registering an action for recommendation: AppName/Function/UserId " + appName + "/"
217 + analyticsMap.getFunction() + "/" + analyticsMap.getUserId());
219 Map<String, String> requestMapping = new HashMap<String, String>();
220 requestMapping.put("id", analyticsMap.getUserId());
221 requestMapping.put("action", appName + "|" + analyticsMap.getFunction());
223 HttpHeaders headers = new HttpHeaders();
224 headers.setContentType(MediaType.APPLICATION_JSON);
226 // set your entity to send
227 HttpEntity<Map<String, String>> entity = new HttpEntity<Map<String, String>>(requestMapping, headers);
230 ListenableFuture<ResponseEntity<String>> out = restTemplate.exchange(
231 EcompPortalUtils.widgetMsProtocol() + "://"
232 + consulHealthService.getServiceLocation(CONSUL_ML_SERVICE_ID,
233 SystemProperties.getProperty("microservices.m-learn.local.port"))
235 HttpMethod.POST, entity, String.class);
236 out.addCallback(successCallback, failureCallback);