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 SERVICE_PROTOCOL = "http";
81 private static final String APP_KEY = "uebkey";
84 AuditService auditService;
87 AppsCacheService appCacheService;
89 private EELFLoggerDelegate logger = EELFLoggerDelegate.getLogger(WebAnalyticsExtAppController.class);
91 private AsyncRestTemplate restTemplate = new AsyncRestTemplate();
93 SuccessCallback<ResponseEntity<String>> successCallback = new SuccessCallback<ResponseEntity<String>>() {
95 public void onSuccess(ResponseEntity<String> arg) {
96 logger.info(EELFLoggerDelegate.debugLogger, arg.getBody());
100 FailureCallback failureCallback = new FailureCallback() {
102 public void onFailure(Throwable arg) {
103 logger.error(EELFLoggerDelegate.errorLogger, "storeAuxAnalytics failed", arg);
107 protected boolean isAuxRESTfulCall() {
112 * Answers requests from partner applications for a file that is expected to
113 * contain javascript to support web analytics.
121 @ApiOperation(value = "Gets javascript with functions that support gathering and reporting web analytics.", response = String.class)
122 @RequestMapping(value = { "/analytics" }, method = RequestMethod.GET, produces = "application/javascript")
123 public String getAnalyticsScript(HttpServletRequest request) throws Exception {
124 String responseText = "";
125 final String fileName = "analytics.txt";
126 InputStream analyticsFileStream = null;
128 analyticsFileStream = this.getClass().getClassLoader().getResourceAsStream(fileName);
129 responseText = IOUtils.toString(analyticsFileStream, StandardCharsets.UTF_8.name());
130 } catch (Exception e) {
131 logger.error(EELFLoggerDelegate.errorLogger, "Error reading contents of the file " + fileName, e);
133 if (analyticsFileStream != null)
134 analyticsFileStream.close();
137 String feURLContext = SystemProperties.getProperty("frontend_url");
138 String feURL = feURLContext.substring(0, feURLContext.lastIndexOf('/'));
140 responseText = responseText.replace("PORTAL_ENV_URL", feURL);
145 * Accepts data from partner applications with web analytics data.
149 * @param analyticsMap
151 * @return PortalAPIResponse
155 @RequestMapping(value = { "/storeAnalytics" }, method = RequestMethod.POST, produces = "application/json")
157 @ApiOperation(value = "Accepts data from partner applications with web analytics data.", response = PortalAPIResponse.class)
158 public PortalAPIResponse storeAnalyticsScript(HttpServletRequest request, @RequestBody Analytics analyticsMap)
161 MDC.put(EPCommonSystemProperties.AUDITLOG_BEGIN_TIMESTAMP, EPEELFLoggerAdvice.getCurrentDateTimeUTC());
164 appName = getAppName(request, appName);
165 } catch (Exception e) {
166 logger.error(EELFLoggerDelegate.errorLogger,
167 " Error retrieving Application to capture app name for analytics; Proceeding with empty app name");
171 storeAuxAnalytics(analyticsMap, appName);
172 } catch (Exception e) {
173 logger.error(EELFLoggerDelegate.errorLogger,
174 " Error retrieving Application to capture app name for analytics; Proceeding with empty app name");
177 MDC.put(EPCommonSystemProperties.AUDITLOG_END_TIMESTAMP, EPEELFLoggerAdvice.getCurrentDateTimeUTC());
179 EcompPortalUtils.calculateDateTimeDifferenceForLog(
180 MDC.get(EPCommonSystemProperties.AUDITLOG_BEGIN_TIMESTAMP),
181 MDC.get(EPCommonSystemProperties.AUDITLOG_END_TIMESTAMP));
182 logger.info(EELFLoggerDelegate.auditLogger,
183 EPLogUtil.formatStoreAnalyticsAuditLogMessage(analyticsMap.getUserId(), appName,
184 "WebAnalyticsExtAppController.postWebAnalyticsData",
185 EcompAuditLog.CD_ACTIVITY_STORE_ANALYTICS, analyticsMap.getAction(), analyticsMap.getPage(),
186 analyticsMap.getFunction(), analyticsMap.getType()));
188 MDC.remove(EPCommonSystemProperties.AUDITLOG_BEGIN_TIMESTAMP);
189 MDC.remove(EPCommonSystemProperties.AUDITLOG_END_TIMESTAMP);
190 MDC.remove(SystemProperties.MDC_TIMER);
192 PortalAPIResponse response = new PortalAPIResponse(true, "success");
194 } catch (Exception e) {
195 logger.error(EELFLoggerDelegate.errorLogger, "storeAnalytics failed", e);
196 PortalAPIResponse response = new PortalAPIResponse(true, "error");
201 protected String getAppName(HttpServletRequest request, String appName) {
202 String appKeyValue = request.getHeader(APP_KEY);
203 if (appKeyValue == null || appKeyValue.equals("")) {
204 logger.error(EELFLoggerDelegate.errorLogger, " App Key unavailable; Proceeding with null app name");
206 EPApp appRecord = appCacheService.getAppForAnalytics(appKeyValue);
207 if (appRecord == null) {
208 logger.error(EELFLoggerDelegate.errorLogger, " App could not be found for the key " + appKeyValue);
210 appName = appRecord.getName();
216 protected void storeAuxAnalytics(Analytics analyticsMap, String appName) {
217 logger.info(EELFLoggerDelegate.debugLogger,
218 " Registering an action for recommendation: AppName/Function/UserId " + appName + "/"
219 + analyticsMap.getFunction() + "/" + analyticsMap.getUserId());
221 Map<String, String> requestMapping = new HashMap<String, String>();
222 requestMapping.put("id", analyticsMap.getUserId());
223 requestMapping.put("action", appName + "|" + analyticsMap.getFunction());
225 HttpHeaders headers = new HttpHeaders();
226 headers.setContentType(MediaType.APPLICATION_JSON);
228 // set your entity to send
229 HttpEntity<Map<String, String>> entity = new HttpEntity<Map<String, String>>(requestMapping, headers);
232 ListenableFuture<ResponseEntity<String>> out = restTemplate.exchange(
233 SERVICE_PROTOCOL + "://"
234 + consulHealthService.getServiceLocation(CONSUL_ML_SERVICE_ID,
235 SystemProperties.getProperty("microservices.m-learn.local.port"))
237 HttpMethod.POST, entity, String.class);
238 out.addCallback(successCallback, failureCallback);