2 * ============LICENSE_START==========================================
4 * ===================================================================
5 * Copyright (C) 2017-2018 AT&T Intellectual Property. All rights reserved.
6 * ===================================================================
8 * Unless otherwise specified, all software contained herein is licensed
9 * under the Apache License, Version 2.0 (the "License");
10 * you may not use this software except in compliance with the License.
11 * You may obtain a copy of the License at
13 * http://www.apache.org/licenses/LICENSE-2.0
15 * Unless required by applicable law or agreed to in writing, software
16 * distributed under the License is distributed on an "AS IS" BASIS,
17 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
18 * See the License for the specific language governing permissions and
19 * limitations under the License.
21 * Unless otherwise specified, all documentation contained herein is licensed
22 * under the Creative Commons License, Attribution 4.0 Intl. (the "License");
23 * you may not use this documentation except in compliance with the License.
24 * You may obtain a copy of the License at
26 * https://creativecommons.org/licenses/by/4.0/
28 * Unless required by applicable law or agreed to in writing, documentation
29 * distributed under the License is distributed on an "AS IS" BASIS,
30 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
31 * See the License for the specific language governing permissions and
32 * limitations under the License.
34 * ============LICENSE_END============================================
38 package org.onap.portalapp.portal.controller;
40 import java.io.InputStream;
41 import java.nio.charset.StandardCharsets;
42 import java.util.HashMap;
45 import javax.servlet.http.HttpServletRequest;
47 import org.apache.commons.io.IOUtils;
48 import org.apache.commons.lang.StringUtils;
49 import org.onap.portalapp.controller.EPRestrictedRESTfulBaseController;
50 import org.onap.portalapp.portal.domain.EPApp;
51 import org.onap.portalapp.portal.domain.EcompAuditLog;
52 import org.onap.portalapp.portal.logging.aop.EPAuditLog;
53 import org.onap.portalapp.portal.logging.aop.EPEELFLoggerAdvice;
54 import org.onap.portalapp.portal.logging.logic.EPLogUtil;
55 import org.onap.portalapp.portal.service.AppsCacheService;
56 import org.onap.portalapp.portal.service.ConsulHealthService;
57 import org.onap.portalapp.portal.transport.Analytics;
58 import org.onap.portalapp.portal.utils.EPCommonSystemProperties;
59 import org.onap.portalapp.portal.utils.EcompPortalUtils;
60 import org.onap.portalapp.portal.utils.PortalConstants;
61 import org.onap.portalsdk.core.logging.logic.EELFLoggerDelegate;
62 import org.onap.portalsdk.core.onboarding.crossapi.PortalAPIResponse;
63 import org.onap.portalsdk.core.service.AuditService;
64 import org.onap.portalsdk.core.util.SystemProperties;
66 import org.springframework.beans.factory.annotation.Autowired;
67 import org.springframework.context.annotation.Configuration;
68 import org.springframework.context.annotation.EnableAspectJAutoProxy;
69 import org.springframework.http.HttpEntity;
70 import org.springframework.http.HttpHeaders;
71 import org.springframework.http.HttpMethod;
72 import org.springframework.http.MediaType;
73 import org.springframework.http.ResponseEntity;
74 import org.springframework.util.concurrent.FailureCallback;
75 import org.springframework.util.concurrent.ListenableFuture;
76 import org.springframework.util.concurrent.SuccessCallback;
77 import org.springframework.web.bind.annotation.RequestBody;
78 import org.springframework.web.bind.annotation.RequestMapping;
79 import org.springframework.web.bind.annotation.RequestMethod;
80 import org.springframework.web.bind.annotation.ResponseBody;
81 import org.springframework.web.bind.annotation.RestController;
82 import org.springframework.web.client.AsyncRestTemplate;
84 import io.swagger.annotations.ApiOperation;
87 @RequestMapping(PortalConstants.REST_AUX_API)
89 @EnableAspectJAutoProxy
91 public class WebAnalyticsExtAppController extends EPRestrictedRESTfulBaseController {
94 private ConsulHealthService consulHealthService;
96 private static final String MACHINE_LEARNING_SERVICE_CTX = "/ml_api";
97 private static final String REGISTER_ACTION = MACHINE_LEARNING_SERVICE_CTX + "/" + "registerAction";
98 private static final String CONSUL_ML_SERVICE_ID = "machine-learning";
99 private static final String APP_KEY = "uebkey";
100 private EELFLoggerDelegate logger = EELFLoggerDelegate.getLogger(WebAnalyticsExtAppController.class);
101 private AsyncRestTemplate restTemplate = new AsyncRestTemplate();
105 AuditService auditService;
108 AppsCacheService appCacheService;
110 SuccessCallback<ResponseEntity<String>> successCallback = new SuccessCallback<ResponseEntity<String>>() {
112 public void onSuccess(ResponseEntity<String> arg) {
113 logger.info(EELFLoggerDelegate.debugLogger, arg.getBody());
117 FailureCallback failureCallback = new FailureCallback() {
119 public void onFailure(Throwable arg) {
120 logger.error(EELFLoggerDelegate.errorLogger, "storeAuxAnalytics failed", arg);
124 protected boolean isAuxRESTfulCall() {
129 * Answers requests from partner applications for a file that is expected to
130 * contain javascript to support web analytics.
138 @ApiOperation(value = "Gets javascript with functions that support gathering and reporting web analytics.", response = String.class)
139 @RequestMapping(value = { "/analytics" }, method = RequestMethod.GET, produces = "application/javascript")
140 public String getAnalyticsScript(HttpServletRequest request) throws Exception {
141 String responseText = "";
145 app = getApp(request);
146 } catch (Exception e) {
147 logger.error(EELFLoggerDelegate.errorLogger,
148 " Error retrieving Application to capture app name for analytics; Proceeding with empty app name");
151 String restEndPoint = app.getAppRestEndpoint();
152 if(restEndPoint.indexOf("/api")!=-1) {
153 version = restEndPoint.substring(restEndPoint.indexOf("/api")+4);
156 String END_POINT = "/storeAnalytics";
157 if(StringUtils.isNotBlank(version)) {
158 END_POINT = version + "/storeAnalytics";
161 final String fileName = "analytics.txt";
162 InputStream analyticsFileStream = null;
164 analyticsFileStream = this.getClass().getClassLoader().getResourceAsStream(fileName);
165 responseText = IOUtils.toString(analyticsFileStream, StandardCharsets.UTF_8.name());
166 } catch (Exception e) {
167 logger.error(EELFLoggerDelegate.errorLogger, "Error reading contents of the file " + fileName, e);
169 if (analyticsFileStream != null)
170 analyticsFileStream.close();
173 String feURLContext = SystemProperties.getProperty("frontend_url");
174 String feURL = feURLContext.substring(0, feURLContext.lastIndexOf('/'));
175 responseText = responseText.replace("PORTAL_ENV_URL", feURL);
176 responseText = responseText.replace("$END_POINT", END_POINT);
181 * Accepts data from partner applications with web analytics data.
185 * @param analyticsMap
187 * @return PortalAPIResponse
191 @RequestMapping(value = { "/storeAnalytics" }, method = RequestMethod.POST, produces = "application/json")
193 @ApiOperation(value = "Accepts data from partner applications with web analytics data.", response = PortalAPIResponse.class)
194 public PortalAPIResponse storeAnalyticsScript(HttpServletRequest request, @RequestBody Analytics analyticsMap)
197 MDC.put(EPCommonSystemProperties.AUDITLOG_BEGIN_TIMESTAMP, EPEELFLoggerAdvice.getCurrentDateTimeUTC());
200 appName = getAppName(request, appName);
201 } catch (Exception e) {
202 logger.error(EELFLoggerDelegate.errorLogger,
203 " Error retrieving Application to capture app name for analytics; Proceeding with empty app name");
207 storeAuxAnalytics(analyticsMap, appName);
208 } catch (Exception e) {
209 logger.error(EELFLoggerDelegate.errorLogger,
210 " Error retrieving Application to capture app name for analytics; Proceeding with empty app name");
213 MDC.put(EPCommonSystemProperties.AUDITLOG_END_TIMESTAMP, EPEELFLoggerAdvice.getCurrentDateTimeUTC());
215 EcompPortalUtils.calculateDateTimeDifferenceForLog(
216 MDC.get(EPCommonSystemProperties.AUDITLOG_BEGIN_TIMESTAMP),
217 MDC.get(EPCommonSystemProperties.AUDITLOG_END_TIMESTAMP));
218 logger.info(EELFLoggerDelegate.auditLogger,
219 EPLogUtil.formatStoreAnalyticsAuditLogMessage(analyticsMap.getUserid(), appName,
220 "WebAnalyticsExtAppController.postWebAnalyticsData",
221 EcompAuditLog.CD_ACTIVITY_STORE_ANALYTICS, analyticsMap.getAction(), analyticsMap.getPage(),
222 analyticsMap.getFunction(), analyticsMap.getType()));
224 MDC.remove(EPCommonSystemProperties.AUDITLOG_BEGIN_TIMESTAMP);
225 MDC.remove(EPCommonSystemProperties.AUDITLOG_END_TIMESTAMP);
226 MDC.remove(SystemProperties.MDC_TIMER);
228 PortalAPIResponse response = new PortalAPIResponse(true, "success");
230 } catch (Exception e) {
231 logger.error(EELFLoggerDelegate.errorLogger, "storeAnalytics failed", e);
232 PortalAPIResponse response = new PortalAPIResponse(true, "error");
237 protected String getAppName(HttpServletRequest request, String appName) {
239 EPApp appRecord = getApp(request);
240 if (appRecord != null) {
241 appName = appRecord.getName();
246 protected EPApp getApp(HttpServletRequest request) {
247 String appKeyValue = request.getHeader(APP_KEY);
248 EPApp appRecord = null;
249 if (appKeyValue == null || appKeyValue.equals("")) {
250 logger.error(EELFLoggerDelegate.errorLogger, " App Key unavailable; Proceeding with null app name");
252 appRecord = appCacheService.getAppFromUeb(appKeyValue);
257 protected void storeAuxAnalytics(Analytics analyticsMap, String appName) {
258 logger.info(EELFLoggerDelegate.debugLogger,
259 " Registering an action for recommendation: AppName/Function/UserId " + appName + "/"
260 + analyticsMap.getFunction() + "/" + analyticsMap.getUserid());
262 Map<String, String> requestMapping = new HashMap<String, String>();
263 requestMapping.put("id", analyticsMap.getUserid());
264 requestMapping.put("action", appName + "|" + analyticsMap.getFunction());
266 HttpHeaders headers = new HttpHeaders();
267 headers.setContentType(MediaType.APPLICATION_JSON);
269 // set your entity to send
270 HttpEntity<Map<String, String>> entity = new HttpEntity<Map<String, String>>(requestMapping, headers);
273 ListenableFuture<ResponseEntity<String>> out = restTemplate.exchange(
274 EcompPortalUtils.widgetMsProtocol() + "://"
275 + consulHealthService.getServiceLocation(CONSUL_ML_SERVICE_ID,
276 SystemProperties.getProperty("microservices.m-learn.local.port"))
278 HttpMethod.POST, entity, String.class);
279 out.addCallback(successCallback, failureCallback);