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.onap.portalapp.controller.EPRestrictedRESTfulBaseController;
49 import org.onap.portalapp.portal.domain.EPApp;
50 import org.onap.portalapp.portal.domain.EcompAuditLog;
51 import org.onap.portalapp.portal.logging.aop.EPAuditLog;
52 import org.onap.portalapp.portal.logging.aop.EPEELFLoggerAdvice;
53 import org.onap.portalapp.portal.logging.logic.EPLogUtil;
54 import org.onap.portalapp.portal.service.AppsCacheService;
55 import org.onap.portalapp.portal.service.ConsulHealthService;
56 import org.onap.portalapp.portal.transport.Analytics;
57 import org.onap.portalapp.portal.utils.EPCommonSystemProperties;
58 import org.onap.portalapp.portal.utils.EcompPortalUtils;
59 import org.onap.portalapp.portal.utils.PortalConstants;
60 import org.onap.portalsdk.core.logging.logic.EELFLoggerDelegate;
61 import org.onap.portalsdk.core.onboarding.crossapi.PortalAPIResponse;
62 import org.onap.portalsdk.core.service.AuditService;
63 import org.onap.portalsdk.core.util.SystemProperties;
65 import org.springframework.beans.factory.annotation.Autowired;
66 import org.springframework.context.annotation.Configuration;
67 import org.springframework.context.annotation.EnableAspectJAutoProxy;
68 import org.springframework.http.HttpEntity;
69 import org.springframework.http.HttpHeaders;
70 import org.springframework.http.HttpMethod;
71 import org.springframework.http.MediaType;
72 import org.springframework.http.ResponseEntity;
73 import org.springframework.util.concurrent.FailureCallback;
74 import org.springframework.util.concurrent.ListenableFuture;
75 import org.springframework.util.concurrent.SuccessCallback;
76 import org.springframework.web.bind.annotation.RequestBody;
77 import org.springframework.web.bind.annotation.RequestMapping;
78 import org.springframework.web.bind.annotation.RequestMethod;
79 import org.springframework.web.bind.annotation.ResponseBody;
80 import org.springframework.web.bind.annotation.RestController;
81 import org.springframework.web.client.AsyncRestTemplate;
83 import io.swagger.annotations.ApiOperation;
86 @RequestMapping(PortalConstants.REST_AUX_API)
88 @EnableAspectJAutoProxy
90 public class WebAnalyticsExtAppController extends EPRestrictedRESTfulBaseController {
93 private ConsulHealthService consulHealthService;
95 private static final String MACHINE_LEARNING_SERVICE_CTX = "/ml_api";
96 private static final String REGISTER_ACTION = MACHINE_LEARNING_SERVICE_CTX + "/" + "registerAction";
97 private static final String CONSUL_ML_SERVICE_ID = "machine-learning";
98 private static final String APP_KEY = "uebkey";
99 private EELFLoggerDelegate logger = EELFLoggerDelegate.getLogger(WebAnalyticsExtAppController.class);
100 private AsyncRestTemplate restTemplate = new AsyncRestTemplate();
104 AuditService auditService;
107 AppsCacheService appCacheService;
109 SuccessCallback<ResponseEntity<String>> successCallback = new SuccessCallback<ResponseEntity<String>>() {
111 public void onSuccess(ResponseEntity<String> arg) {
112 logger.info(EELFLoggerDelegate.debugLogger, arg.getBody());
116 FailureCallback failureCallback = new FailureCallback() {
118 public void onFailure(Throwable arg) {
119 logger.error(EELFLoggerDelegate.errorLogger, "storeAuxAnalytics failed", arg);
123 protected boolean isAuxRESTfulCall() {
128 * Answers requests from partner applications for a file that is expected to
129 * contain javascript to support web analytics.
137 @ApiOperation(value = "Gets javascript with functions that support gathering and reporting web analytics.", response = String.class)
138 @RequestMapping(value = { "/analytics" }, method = RequestMethod.GET, produces = "application/javascript")
139 public String getAnalyticsScript(HttpServletRequest request) throws Exception {
140 String responseText = "";
141 final String fileName = "analytics.txt";
142 InputStream analyticsFileStream = null;
144 analyticsFileStream = this.getClass().getClassLoader().getResourceAsStream(fileName);
145 responseText = IOUtils.toString(analyticsFileStream, StandardCharsets.UTF_8.name());
146 } catch (Exception e) {
147 logger.error(EELFLoggerDelegate.errorLogger, "Error reading contents of the file " + fileName, e);
149 if (analyticsFileStream != null)
150 analyticsFileStream.close();
153 String feURLContext = SystemProperties.getProperty("frontend_url");
154 String feURL = feURLContext.substring(0, feURLContext.lastIndexOf('/'));
156 responseText = responseText.replace("PORTAL_ENV_URL", feURL);
161 * Accepts data from partner applications with web analytics data.
165 * @param analyticsMap
167 * @return PortalAPIResponse
171 @RequestMapping(value = { "/storeAnalytics" }, method = RequestMethod.POST, produces = "application/json")
173 @ApiOperation(value = "Accepts data from partner applications with web analytics data.", response = PortalAPIResponse.class)
174 public PortalAPIResponse storeAnalyticsScript(HttpServletRequest request, @RequestBody Analytics analyticsMap)
177 MDC.put(EPCommonSystemProperties.AUDITLOG_BEGIN_TIMESTAMP, EPEELFLoggerAdvice.getCurrentDateTimeUTC());
180 appName = getAppName(request, appName);
181 } catch (Exception e) {
182 logger.error(EELFLoggerDelegate.errorLogger,
183 " Error retrieving Application to capture app name for analytics; Proceeding with empty app name");
187 storeAuxAnalytics(analyticsMap, appName);
188 } catch (Exception e) {
189 logger.error(EELFLoggerDelegate.errorLogger,
190 " Error retrieving Application to capture app name for analytics; Proceeding with empty app name");
193 MDC.put(EPCommonSystemProperties.AUDITLOG_END_TIMESTAMP, EPEELFLoggerAdvice.getCurrentDateTimeUTC());
195 EcompPortalUtils.calculateDateTimeDifferenceForLog(
196 MDC.get(EPCommonSystemProperties.AUDITLOG_BEGIN_TIMESTAMP),
197 MDC.get(EPCommonSystemProperties.AUDITLOG_END_TIMESTAMP));
198 logger.info(EELFLoggerDelegate.auditLogger,
199 EPLogUtil.formatStoreAnalyticsAuditLogMessage(analyticsMap.getUserid(), appName,
200 "WebAnalyticsExtAppController.postWebAnalyticsData",
201 EcompAuditLog.CD_ACTIVITY_STORE_ANALYTICS, analyticsMap.getAction(), analyticsMap.getPage(),
202 analyticsMap.getFunction(), analyticsMap.getType()));
204 MDC.remove(EPCommonSystemProperties.AUDITLOG_BEGIN_TIMESTAMP);
205 MDC.remove(EPCommonSystemProperties.AUDITLOG_END_TIMESTAMP);
206 MDC.remove(SystemProperties.MDC_TIMER);
208 PortalAPIResponse response = new PortalAPIResponse(true, "success");
210 } catch (Exception e) {
211 logger.error(EELFLoggerDelegate.errorLogger, "storeAnalytics failed", e);
212 PortalAPIResponse response = new PortalAPIResponse(true, "error");
217 protected String getAppName(HttpServletRequest request, String appName) {
218 String appKeyValue = request.getHeader(APP_KEY);
219 if (appKeyValue == null || appKeyValue.equals("")) {
220 logger.error(EELFLoggerDelegate.errorLogger, " App Key unavailable; Proceeding with null app name");
222 EPApp appRecord = appCacheService.getAppFromUeb(appKeyValue);
223 if (appRecord == null) {
224 logger.error(EELFLoggerDelegate.errorLogger, " App could not be found for the key " + appKeyValue);
226 appName = appRecord.getName();
232 protected void storeAuxAnalytics(Analytics analyticsMap, String appName) {
233 logger.info(EELFLoggerDelegate.debugLogger,
234 " Registering an action for recommendation: AppName/Function/UserId " + appName + "/"
235 + analyticsMap.getFunction() + "/" + analyticsMap.getUserid());
237 Map<String, String> requestMapping = new HashMap<String, String>();
238 requestMapping.put("id", analyticsMap.getUserid());
239 requestMapping.put("action", appName + "|" + analyticsMap.getFunction());
241 HttpHeaders headers = new HttpHeaders();
242 headers.setContentType(MediaType.APPLICATION_JSON);
244 // set your entity to send
245 HttpEntity<Map<String, String>> entity = new HttpEntity<Map<String, String>>(requestMapping, headers);
248 ListenableFuture<ResponseEntity<String>> out = restTemplate.exchange(
249 EcompPortalUtils.widgetMsProtocol() + "://"
250 + consulHealthService.getServiceLocation(CONSUL_ML_SERVICE_ID,
251 SystemProperties.getProperty("microservices.m-learn.local.port"))
253 HttpMethod.POST, entity, String.class);
254 out.addCallback(successCallback, failureCallback);