a8eb1d63b93960db58a4e77c06c0176716f2971e
[portal.git] / ecomp-portal-BE-common / src / main / java / org / onap / portalapp / portal / controller / WebAnalyticsExtAppController.java
1 /*-
2  * ============LICENSE_START==========================================
3  * ONAP Portal
4  * ===================================================================
5  * Copyright (C) 2019 AT&T Intellectual Property. All rights reserved.
6  * ===================================================================
7  * Modifications Copyright (c) 2020 IBM
8  * ===================================================================
9  *
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
14  *
15  *             http://www.apache.org/licenses/LICENSE-2.0
16  *
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.
22  *
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
27  *
28  *             https://creativecommons.org/licenses/by/4.0/
29  *
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.
35  *
36  * ============LICENSE_END============================================
37  *
38  * 
39  */
40 package org.onap.portalapp.portal.controller;
41
42 import io.swagger.annotations.ApiOperation;
43 import java.io.IOException;
44 import java.io.InputStream;
45 import java.nio.charset.StandardCharsets;
46 import java.util.HashMap;
47 import java.util.Map;
48 import java.util.Objects;
49 import javax.servlet.http.HttpServletRequest;
50 import lombok.NoArgsConstructor;
51 import org.apache.commons.io.IOUtils;
52 import org.apache.commons.lang.StringUtils;
53 import org.onap.portalapp.controller.EPRestrictedRESTfulBaseController;
54 import org.onap.portalapp.portal.domain.EPApp;
55 import org.onap.portalapp.portal.domain.EcompAuditLog;
56 import org.onap.portalapp.portal.logging.aop.EPAuditLog;
57 import org.onap.portalapp.portal.logging.aop.EPEELFLoggerAdvice;
58 import org.onap.portalapp.portal.logging.logic.EPLogUtil;
59 import org.onap.portalapp.portal.service.AppsCacheService;
60 import org.onap.portalapp.portal.service.WidgetMService;
61 import org.onap.portalapp.portal.transport.Analytics;
62 import org.onap.portalapp.portal.utils.EPCommonSystemProperties;
63 import org.onap.portalapp.portal.utils.EcompPortalUtils;
64 import org.onap.portalapp.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;
68 import org.slf4j.MDC;
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.PostMapping;
83 import org.springframework.web.bind.annotation.GetMapping;
84 import org.springframework.web.bind.annotation.RequestMethod;
85 import org.springframework.web.bind.annotation.ResponseBody;
86 import org.springframework.web.bind.annotation.RestController;
87 import org.springframework.web.client.AsyncRestTemplate;
88
89 @RestController
90 @RequestMapping(PortalConstants.REST_AUX_API)
91 @Configuration
92 @EnableAspectJAutoProxy
93 @EPAuditLog
94 @NoArgsConstructor
95 public class WebAnalyticsExtAppController extends EPRestrictedRESTfulBaseController {
96         public static final String FEED_ML = "feed.ml";
97         private WidgetMService widgetMService;
98         private AppsCacheService appCacheService;
99
100         private static final String MACHINE_LEARNING_SERVICE_CTX = "/ml_api";
101         private static final String REGISTER_ACTION = MACHINE_LEARNING_SERVICE_CTX + "/" + "registerAction";
102         private static final String APP_KEY = "uebkey";
103         private static final String ERROR_MSG = " Error retrieving Application to capture app name for analytics; Proceeding with empty app name";
104         private final EELFLoggerDelegate logger = EELFLoggerDelegate.getLogger(WebAnalyticsExtAppController.class);
105         private final AsyncRestTemplate restTemplate = new AsyncRestTemplate();
106         private final SuccessCallback<ResponseEntity<String>> successCallback = arg -> logger.info(EELFLoggerDelegate.debugLogger, arg.getBody());
107         private final FailureCallback failureCallback = arg -> logger.error(EELFLoggerDelegate.errorLogger, "storeAuxAnalytics failed", arg);
108
109         @Autowired
110         public WebAnalyticsExtAppController(AppsCacheService appCacheService, WidgetMService consulHealthService) {
111                 this.appCacheService = appCacheService;
112                 this.widgetMService = consulHealthService;
113         }
114
115         /**
116          * Answers requests from partner applications for a file that is expected to
117          * contain javascript to support web analytics.
118          * 
119          * @param request
120          *            HttpServletRequest
121          * @return String
122          */
123         @ApiOperation(value = "Gets javascript with functions that support gathering and reporting web analytics.", response = String.class)
124         @GetMapping(value = { "/analytics" }, produces = "application/javascript")
125         public String getAnalyticsScript(HttpServletRequest request) {
126                 String responseText = "";
127                 EPApp app = null;
128                 String version = "";
129                 try {
130                         app = getApp(request);
131                 } catch (Exception e) {
132             logger.error(EELFLoggerDelegate.errorLogger,
133                     ERROR_MSG, e);
134                 }
135                 if (app != null) {
136                         String restEndPoint = app.getAppRestEndpoint();
137                         if(restEndPoint.indexOf("/api")!=-1) {
138                                 version = restEndPoint.substring(restEndPoint.indexOf("api"));
139                         }
140                 }
141                 String endPoint = "/storeAnalytics";
142                 if(StringUtils.isNotBlank(version)) {
143                         endPoint = version + "/storeAnalytics";
144                 }
145
146                 final String fileName = "analytics.txt";
147                 try (InputStream analyticsFileStream = this.getClass().getClassLoader().getResourceAsStream(fileName)) {
148                         responseText = IOUtils.toString(Objects.requireNonNull(analyticsFileStream), StandardCharsets.UTF_8.name());
149                 } catch (IOException e) {
150                         logger.error(EELFLoggerDelegate.errorLogger, "Error reading contents of the file " + fileName, e);
151                 }
152
153                 String feURLContext = SystemProperties.getProperty("frontend_url");
154                 String feURL = feURLContext.substring(0, feURLContext.lastIndexOf('/'));
155                 responseText = responseText.replace("PORTAL_ENV_URL", feURL);
156                 responseText = responseText.replace("$END_POINT", endPoint);
157                 return responseText;
158         }
159
160         /**
161          * Accepts data from partner applications with web analytics data.
162          * 
163          * @param request
164          *            HttpServletRequest
165          * @param analyticsMap
166          *            Analytics
167          * @return PortalAPIResponse
168          */
169         @PostMapping(value = { "/storeAnalytics" }, produces = "application/json")
170         @ResponseBody
171         @ApiOperation(value = "Accepts data from partner applications with web analytics data.", response = PortalAPIResponse.class)
172         public PortalAPIResponse storeAnalyticsScript(HttpServletRequest request, @RequestBody Analytics analyticsMap) {
173                 try {
174                         MDC.put(EPCommonSystemProperties.AUDITLOG_BEGIN_TIMESTAMP, EPEELFLoggerAdvice.getCurrentDateTimeUTC());
175                         String appName = "";
176                         try {
177                                 appName = getAppName(request, appName);
178                         } catch (Exception e) {
179                                 logger.error(EELFLoggerDelegate.errorLogger,
180                         ERROR_MSG, e);
181                         }
182
183                         try {
184                                 if(SystemProperties.containsProperty(FEED_ML) && 
185                                                 SystemProperties.getProperty(FEED_ML).equals("true")) {
186                                         storeAuxAnalytics(analyticsMap, appName);
187                                 }
188                                 
189                         } catch (Exception e) {
190                                 logger.error(EELFLoggerDelegate.errorLogger,
191                         ERROR_MSG, e);
192                         }
193
194                         MDC.put(EPCommonSystemProperties.AUDITLOG_END_TIMESTAMP, EPEELFLoggerAdvice.getCurrentDateTimeUTC());
195
196                         EcompPortalUtils.calculateDateTimeDifferenceForLog(
197                                         MDC.get(EPCommonSystemProperties.AUDITLOG_BEGIN_TIMESTAMP),
198                                         MDC.get(EPCommonSystemProperties.AUDITLOG_END_TIMESTAMP));
199                         logger.info(EELFLoggerDelegate.auditLogger,
200                                         EPLogUtil.formatStoreAnalyticsAuditLogMessage(analyticsMap.getUserid(), appName,
201                                                         "WebAnalyticsExtAppController.postWebAnalyticsData",
202                                                         EcompAuditLog.CD_ACTIVITY_STORE_ANALYTICS, analyticsMap.getAction(), analyticsMap.getPage(),
203                                                         analyticsMap.getFunction(), analyticsMap.getType()));
204
205                         MDC.remove(EPCommonSystemProperties.AUDITLOG_BEGIN_TIMESTAMP);
206                         MDC.remove(EPCommonSystemProperties.AUDITLOG_END_TIMESTAMP);
207                         MDC.remove(SystemProperties.MDC_TIMER);
208
209                         return new PortalAPIResponse(true, "success");
210                 } catch (Exception e) {
211                         logger.error(EELFLoggerDelegate.errorLogger, "storeAnalytics failed", e);
212                         return new PortalAPIResponse(true, "error");
213                 }
214         }
215
216         private String getAppName(HttpServletRequest request, String appName) {
217                 
218                 EPApp appRecord = getApp(request);
219                 if (appRecord != null) {
220                         appName = appRecord.getName();
221                 }
222                 return appName;
223         }
224         
225         private EPApp getApp(HttpServletRequest request) {
226                 String appKeyValue = request.getHeader(APP_KEY);
227                 EPApp appRecord = null;
228                 if (appKeyValue == null || appKeyValue.equals("")) {
229                         logger.error(EELFLoggerDelegate.errorLogger, " App Key unavailable; Proceeding with null app name");
230                 } else {
231                          appRecord = appCacheService.getAppFromUeb(appKeyValue);
232                 }
233                 return appRecord;
234         }
235
236         protected void storeAuxAnalytics(Analytics analyticsMap, String appName) {
237                 logger.info(EELFLoggerDelegate.debugLogger,
238                                 " Registering an action for recommendation: AppName/Function/UserId " + appName + "/"
239                                                 + analyticsMap.getFunction() + "/" + analyticsMap.getUserid());
240
241                 
242                 Map<String, String> requestMapping = new HashMap<>();
243                 requestMapping.put("id", analyticsMap.getUserid());
244                 requestMapping.put("action", appName + "|" + analyticsMap.getFunction());
245                 
246                 HttpHeaders headers = new HttpHeaders();
247                 headers.setContentType(MediaType.APPLICATION_JSON);
248
249                 // set your entity to send
250                 HttpEntity<Map<String, String>> entity = new HttpEntity<>(requestMapping, headers);
251
252                 // send it!
253                 ListenableFuture<ResponseEntity<String>> out = restTemplate.exchange(
254                                 EcompPortalUtils.widgetMLProtocol() + "://"
255                                                 + widgetMService.getMLServiceLocation()
256                                                 + REGISTER_ACTION,
257                                 HttpMethod.POST, entity, String.class);
258                 out.addCallback(successCallback, failureCallback);
259         }
260         
261 }