2 * ============LICENSE_START==========================================
4 * ===================================================================
5 * Copyright (C) 2019 AT&T Intellectual Property. All rights reserved.
6 * ===================================================================
7 * Modifications Copyright (c) 2019 Samsung
8 * ===================================================================
10 * Unless otherwise specified, all software contained herein is licensed
11 * under the Apache License, Version 2.0 (the "License");
12 * you may not use this software except in compliance with the License.
13 * You may obtain a copy of the License at
15 * http://www.apache.org/licenses/LICENSE-2.0
17 * Unless required by applicable law or agreed to in writing, software
18 * distributed under the License is distributed on an "AS IS" BASIS,
19 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
20 * See the License for the specific language governing permissions and
21 * limitations under the License.
23 * Unless otherwise specified, all documentation contained herein is licensed
24 * under the Creative Commons License, Attribution 4.0 Intl. (the "License");
25 * you may not use this documentation except in compliance with the License.
26 * You may obtain a copy of the License at
28 * https://creativecommons.org/licenses/by/4.0/
30 * Unless required by applicable law or agreed to in writing, documentation
31 * distributed under the License is distributed on an "AS IS" BASIS,
32 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
33 * See the License for the specific language governing permissions and
34 * limitations under the License.
36 * ============LICENSE_END============================================
41 package org.onap.portal.controller;
43 import io.swagger.annotations.ApiOperation;
44 import java.io.IOException;
45 import java.io.InputStream;
46 import java.nio.charset.StandardCharsets;
47 import java.util.HashMap;
49 import java.util.Objects;
50 import javax.servlet.http.HttpServletRequest;
51 import lombok.NoArgsConstructor;
52 import org.apache.commons.io.IOUtils;
53 import org.apache.commons.lang.StringUtils;
54 import org.onap.portal.domain.db.fn.FnApp;
55 import org.onap.portal.domain.dto.ecomp.EcompAuditLog;
56 import org.onap.portal.domain.dto.transport.Analytics;
57 import org.onap.portal.logging.aop.EPAuditLog;
58 import org.onap.portal.logging.aop.EPEELFLoggerAdvice;
59 import org.onap.portal.logging.logic.EPLogUtil;
60 import org.onap.portal.service.WidgetMService;
61 import org.onap.portal.service.fn.old.AppsCacheService;
62 import org.onap.portal.utils.EPCommonSystemProperties;
63 import org.onap.portal.utils.EcompPortalUtils;
64 import org.onap.portal.utils.PortalConstants;
65 import org.onap.portalsdk.core.logging.logic.EELFLoggerDelegate;
66 import org.onap.portalsdk.core.onboarding.crossapi.PortalAPIResponse;
67 import org.onap.portalsdk.core.util.SystemProperties;
69 import org.springframework.beans.factory.annotation.Autowired;
70 import org.springframework.context.annotation.Configuration;
71 import org.springframework.context.annotation.EnableAspectJAutoProxy;
72 import org.springframework.http.HttpEntity;
73 import org.springframework.http.HttpHeaders;
74 import org.springframework.http.HttpMethod;
75 import org.springframework.http.MediaType;
76 import org.springframework.http.ResponseEntity;
77 import org.springframework.util.concurrent.FailureCallback;
78 import org.springframework.util.concurrent.ListenableFuture;
79 import org.springframework.util.concurrent.SuccessCallback;
80 import org.springframework.web.bind.annotation.RequestBody;
81 import org.springframework.web.bind.annotation.RequestMapping;
82 import org.springframework.web.bind.annotation.RequestMethod;
83 import org.springframework.web.bind.annotation.ResponseBody;
84 import org.springframework.web.bind.annotation.RestController;
85 import org.springframework.web.client.AsyncRestTemplate;
88 @RequestMapping(PortalConstants.REST_AUX_API)
90 @EnableAspectJAutoProxy
93 public class WebAnalyticsExtAppController {
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 final EELFLoggerDelegate logger = EELFLoggerDelegate.getLogger(WebAnalyticsExtAppController.class);
100 private final AsyncRestTemplate restTemplate = new AsyncRestTemplate();
101 private final SuccessCallback<ResponseEntity<String>> successCallback = arg -> logger.info(EELFLoggerDelegate.debugLogger, arg.getBody());
102 private final FailureCallback failureCallback = arg -> logger.error(EELFLoggerDelegate.errorLogger, "storeAuxAnalytics failed", arg);
104 private WidgetMService widgetMService;
105 private AppsCacheService appCacheService;
108 public WebAnalyticsExtAppController(final WidgetMService widgetMService,
109 final AppsCacheService appCacheService) {
110 this.widgetMService = widgetMService;
111 this.appCacheService = appCacheService;
115 * Answers requests from partner applications for a file that is expected to
116 * contain javascript to support web analytics.
122 @ApiOperation(value = "Gets javascript with functions that support gathering and reporting web analytics.", response = String.class)
123 @RequestMapping(value = { "/analytics" }, method = RequestMethod.GET, produces = "application/javascript")
124 public String getAnalyticsScript(HttpServletRequest request) {
125 String responseText = "";
129 app = getApp(request);
130 } catch (Exception e) {
131 logger.error(EELFLoggerDelegate.errorLogger,
132 " Error retrieving Application to capture app name for analytics; Proceeding with empty app name");
135 String restEndPoint = app.getAppRestEndpoint();
136 if(restEndPoint.indexOf("/api")!=-1) {
137 version = restEndPoint.substring(restEndPoint.indexOf("api"));
140 String endPoint = "/storeAnalytics";
141 if(StringUtils.isNotBlank(version)) {
142 endPoint = version + "/storeAnalytics";
145 final String fileName = "analytics.txt";
146 try (InputStream analyticsFileStream = this.getClass().getClassLoader().getResourceAsStream(fileName)) {
147 responseText = IOUtils.toString(Objects.requireNonNull(analyticsFileStream), StandardCharsets.UTF_8.name());
148 } catch (IOException e) {
149 logger.error(EELFLoggerDelegate.errorLogger, "Error reading contents of the file " + fileName, e);
152 String feURLContext = SystemProperties.getProperty("frontend_url");
153 String feURL = feURLContext.substring(0, feURLContext.lastIndexOf('/'));
154 responseText = responseText.replace("PORTAL_ENV_URL", feURL);
155 responseText = responseText.replace("$END_POINT", endPoint);
160 * Accepts data from partner applications with web analytics data.
164 * @param analyticsMap
166 * @return PortalAPIResponse
168 @RequestMapping(value = { "/storeAnalytics" }, method = RequestMethod.POST, produces = "application/json")
170 @ApiOperation(value = "Accepts data from partner applications with web analytics data.", response = PortalAPIResponse.class)
171 public PortalAPIResponse storeAnalyticsScript(HttpServletRequest request, @RequestBody Analytics analyticsMap) {
173 MDC.put(EPCommonSystemProperties.AUDITLOG_BEGIN_TIMESTAMP, EPEELFLoggerAdvice.getCurrentDateTimeUTC());
176 appName = getAppName(request, appName);
177 } catch (Exception e) {
178 logger.error(EELFLoggerDelegate.errorLogger,
179 " Error retrieving Application to capture app name for analytics; Proceeding with empty app name");
183 storeAuxAnalytics(analyticsMap, appName);
184 } catch (Exception e) {
185 logger.error(EELFLoggerDelegate.errorLogger,
186 " Error retrieving Application to capture app name for analytics; Proceeding with empty app name");
189 MDC.put(EPCommonSystemProperties.AUDITLOG_END_TIMESTAMP, EPEELFLoggerAdvice.getCurrentDateTimeUTC());
191 EcompPortalUtils.calculateDateTimeDifferenceForLog(
192 MDC.get(EPCommonSystemProperties.AUDITLOG_BEGIN_TIMESTAMP),
193 MDC.get(EPCommonSystemProperties.AUDITLOG_END_TIMESTAMP));
194 logger.info(EELFLoggerDelegate.auditLogger,
195 EPLogUtil.formatStoreAnalyticsAuditLogMessage(analyticsMap.getUserid(), appName,
196 "WebAnalyticsExtAppController.postWebAnalyticsData",
197 EcompAuditLog.CD_ACTIVITY_STORE_ANALYTICS, analyticsMap.getAction(), analyticsMap.getPage(),
198 analyticsMap.getFunction(), analyticsMap.getType()));
200 MDC.remove(EPCommonSystemProperties.AUDITLOG_BEGIN_TIMESTAMP);
201 MDC.remove(EPCommonSystemProperties.AUDITLOG_END_TIMESTAMP);
202 MDC.remove(SystemProperties.MDC_TIMER);
204 return new PortalAPIResponse(true, "success");
205 } catch (Exception e) {
206 logger.error(EELFLoggerDelegate.errorLogger, "storeAnalytics failed", e);
207 return new PortalAPIResponse(true, "error");
211 private String getAppName(HttpServletRequest request, String appName) {
213 FnApp appRecord = getApp(request);
214 if (appRecord != null) {
215 appName = appRecord.getAppName();
220 private FnApp getApp(HttpServletRequest request) {
221 String appKeyValue = request.getHeader(APP_KEY);
222 FnApp appRecord = null;
223 if (appKeyValue == null || appKeyValue.equals("")) {
224 logger.error(EELFLoggerDelegate.errorLogger, " App Key unavailable; Proceeding with null app name");
226 appRecord = appCacheService.getAppFromUeb(appKeyValue);
231 private void storeAuxAnalytics(Analytics analyticsMap, String appName) {
232 logger.info(EELFLoggerDelegate.debugLogger,
233 " Registering an action for recommendation: AppName/Function/UserId " + appName + "/"
234 + analyticsMap.getFunction() + "/" + analyticsMap.getUserid());
236 Map<String, String> requestMapping = new HashMap<>();
237 requestMapping.put("id", analyticsMap.getUserid());
238 requestMapping.put("action", appName + "|" + analyticsMap.getFunction());
240 HttpHeaders headers = new HttpHeaders();
241 headers.setContentType(MediaType.APPLICATION_JSON);
243 // set your entity to send
244 HttpEntity<Map<String, String>> entity = new HttpEntity<>(requestMapping, headers);
247 ListenableFuture<ResponseEntity<String>> out = restTemplate.exchange(
248 EcompPortalUtils.widgetMsProtocol() + "://"
249 + widgetMService.getServiceLocation(CONSUL_ML_SERVICE_ID,
250 SystemProperties.getProperty("microservices.m-learn.local.port"))
252 HttpMethod.POST, entity, String.class);
253 out.addCallback(successCallback, failureCallback);