2 * ============LICENSE_START==========================================
4 * ===================================================================
5 * Copyright (C) 2019 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 io.swagger.annotations.ApiOperation;
41 import java.io.IOException;
42 import java.io.InputStream;
43 import java.nio.charset.StandardCharsets;
44 import java.util.HashMap;
46 import java.util.Objects;
47 import javax.servlet.http.HttpServletRequest;
48 import lombok.NoArgsConstructor;
49 import org.apache.commons.io.IOUtils;
50 import org.apache.commons.lang.StringUtils;
51 import org.onap.portalapp.controller.EPRestrictedRESTfulBaseController;
52 import org.onap.portalapp.portal.domain.EPApp;
53 import org.onap.portalapp.portal.domain.EcompAuditLog;
54 import org.onap.portalapp.portal.logging.aop.EPAuditLog;
55 import org.onap.portalapp.portal.logging.aop.EPEELFLoggerAdvice;
56 import org.onap.portalapp.portal.logging.logic.EPLogUtil;
57 import org.onap.portalapp.portal.service.AppsCacheService;
58 import org.onap.portalapp.portal.service.WidgetMService;
59 import org.onap.portalapp.portal.transport.Analytics;
60 import org.onap.portalapp.portal.utils.EPCommonSystemProperties;
61 import org.onap.portalapp.portal.utils.EcompPortalUtils;
62 import org.onap.portalapp.portal.utils.PortalConstants;
63 import org.onap.portalsdk.core.logging.logic.EELFLoggerDelegate;
64 import org.onap.portalsdk.core.onboarding.crossapi.PortalAPIResponse;
65 import org.onap.portalsdk.core.util.SystemProperties;
67 import org.springframework.beans.factory.annotation.Autowired;
68 import org.springframework.context.annotation.Configuration;
69 import org.springframework.context.annotation.EnableAspectJAutoProxy;
70 import org.springframework.http.HttpEntity;
71 import org.springframework.http.HttpHeaders;
72 import org.springframework.http.HttpMethod;
73 import org.springframework.http.MediaType;
74 import org.springframework.http.ResponseEntity;
75 import org.springframework.util.concurrent.FailureCallback;
76 import org.springframework.util.concurrent.ListenableFuture;
77 import org.springframework.util.concurrent.SuccessCallback;
78 import org.springframework.web.bind.annotation.RequestBody;
79 import org.springframework.web.bind.annotation.RequestMapping;
80 import org.springframework.web.bind.annotation.RequestMethod;
81 import org.springframework.web.bind.annotation.ResponseBody;
82 import org.springframework.web.bind.annotation.RestController;
83 import org.springframework.web.client.AsyncRestTemplate;
86 @RequestMapping(PortalConstants.REST_AUX_API)
88 @EnableAspectJAutoProxy
91 public class WebAnalyticsExtAppController extends EPRestrictedRESTfulBaseController {
92 public static final String FEED_ML = "feed.ml";
93 private WidgetMService widgetMService;
94 private AppsCacheService appCacheService;
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 APP_KEY = "uebkey";
99 private static final String ERROR_MSG = " Error retrieving Application to capture app name for analytics; Proceeding with empty app name";
100 private final EELFLoggerDelegate logger = EELFLoggerDelegate.getLogger(WebAnalyticsExtAppController.class);
101 private final AsyncRestTemplate restTemplate = new AsyncRestTemplate();
102 private final SuccessCallback<ResponseEntity<String>> successCallback = arg -> logger.info(EELFLoggerDelegate.debugLogger, arg.getBody());
103 private final FailureCallback failureCallback = arg -> logger.error(EELFLoggerDelegate.errorLogger, "storeAuxAnalytics failed", arg);
106 public WebAnalyticsExtAppController(AppsCacheService appCacheService, WidgetMService consulHealthService) {
107 this.appCacheService = appCacheService;
108 this.widgetMService = consulHealthService;
112 * Answers requests from partner applications for a file that is expected to
113 * 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) {
122 String responseText = "";
126 app = getApp(request);
127 } catch (Exception e) {
128 logger.error(EELFLoggerDelegate.errorLogger,
132 String restEndPoint = app.getAppRestEndpoint();
133 if(restEndPoint.indexOf("/api")!=-1) {
134 version = restEndPoint.substring(restEndPoint.indexOf("api"));
137 String endPoint = "/storeAnalytics";
138 if(StringUtils.isNotBlank(version)) {
139 endPoint = version + "/storeAnalytics";
142 final String fileName = "analytics.txt";
143 try (InputStream analyticsFileStream = this.getClass().getClassLoader().getResourceAsStream(fileName)) {
144 responseText = IOUtils.toString(Objects.requireNonNull(analyticsFileStream), StandardCharsets.UTF_8.name());
145 } catch (IOException e) {
146 logger.error(EELFLoggerDelegate.errorLogger, "Error reading contents of the file " + fileName, e);
149 String feURLContext = SystemProperties.getProperty("frontend_url");
150 String feURL = feURLContext.substring(0, feURLContext.lastIndexOf('/'));
151 responseText = responseText.replace("PORTAL_ENV_URL", feURL);
152 responseText = responseText.replace("$END_POINT", endPoint);
157 * Accepts data from partner applications with web analytics data.
161 * @param analyticsMap
163 * @return PortalAPIResponse
165 @RequestMapping(value = { "/storeAnalytics" }, method = RequestMethod.POST, produces = "application/json")
167 @ApiOperation(value = "Accepts data from partner applications with web analytics data.", response = PortalAPIResponse.class)
168 public PortalAPIResponse storeAnalyticsScript(HttpServletRequest request, @RequestBody Analytics analyticsMap) {
170 MDC.put(EPCommonSystemProperties.AUDITLOG_BEGIN_TIMESTAMP, EPEELFLoggerAdvice.getCurrentDateTimeUTC());
173 appName = getAppName(request, appName);
174 } catch (Exception e) {
175 logger.error(EELFLoggerDelegate.errorLogger,
180 if(SystemProperties.containsProperty(FEED_ML) &&
181 SystemProperties.getProperty(FEED_ML).equals("true")) {
182 storeAuxAnalytics(analyticsMap, appName);
185 } catch (Exception e) {
186 logger.error(EELFLoggerDelegate.errorLogger,
190 MDC.put(EPCommonSystemProperties.AUDITLOG_END_TIMESTAMP, EPEELFLoggerAdvice.getCurrentDateTimeUTC());
192 EcompPortalUtils.calculateDateTimeDifferenceForLog(
193 MDC.get(EPCommonSystemProperties.AUDITLOG_BEGIN_TIMESTAMP),
194 MDC.get(EPCommonSystemProperties.AUDITLOG_END_TIMESTAMP));
195 logger.info(EELFLoggerDelegate.auditLogger,
196 EPLogUtil.formatStoreAnalyticsAuditLogMessage(analyticsMap.getUserid(), appName,
197 "WebAnalyticsExtAppController.postWebAnalyticsData",
198 EcompAuditLog.CD_ACTIVITY_STORE_ANALYTICS, analyticsMap.getAction(), analyticsMap.getPage(),
199 analyticsMap.getFunction(), analyticsMap.getType()));
201 MDC.remove(EPCommonSystemProperties.AUDITLOG_BEGIN_TIMESTAMP);
202 MDC.remove(EPCommonSystemProperties.AUDITLOG_END_TIMESTAMP);
203 MDC.remove(SystemProperties.MDC_TIMER);
205 return new PortalAPIResponse(true, "success");
206 } catch (Exception e) {
207 logger.error(EELFLoggerDelegate.errorLogger, "storeAnalytics failed", e);
208 return new PortalAPIResponse(true, "error");
212 private String getAppName(HttpServletRequest request, String appName) {
214 EPApp appRecord = getApp(request);
215 if (appRecord != null) {
216 appName = appRecord.getName();
221 private EPApp getApp(HttpServletRequest request) {
222 String appKeyValue = request.getHeader(APP_KEY);
223 EPApp appRecord = null;
224 if (appKeyValue == null || appKeyValue.equals("")) {
225 logger.error(EELFLoggerDelegate.errorLogger, " App Key unavailable; Proceeding with null app name");
227 appRecord = appCacheService.getAppFromUeb(appKeyValue);
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());
238 Map<String, String> requestMapping = new HashMap<>();
239 requestMapping.put("id", analyticsMap.getUserid());
240 requestMapping.put("action", appName + "|" + analyticsMap.getFunction());
242 HttpHeaders headers = new HttpHeaders();
243 headers.setContentType(MediaType.APPLICATION_JSON);
245 // set your entity to send
246 HttpEntity<Map<String, String>> entity = new HttpEntity<>(requestMapping, headers);
249 ListenableFuture<ResponseEntity<String>> out = restTemplate.exchange(
250 EcompPortalUtils.widgetMLProtocol() + "://"
251 + widgetMService.getMLServiceLocation()
253 HttpMethod.POST, entity, String.class);
254 out.addCallback(successCallback, failureCallback);