afde8bc57aca5c7d3a20d41fc9c85668fcdd9b8a
[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) 2017-2018 AT&T Intellectual Property. All rights reserved.
6  * ===================================================================
7  *
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
12  *
13  *             http://www.apache.org/licenses/LICENSE-2.0
14  *
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.
20  *
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
25  *
26  *             https://creativecommons.org/licenses/by/4.0/
27  *
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.
33  *
34  * ============LICENSE_END============================================
35  *
36  * 
37  */
38 package org.onap.portalapp.portal.controller;
39
40 import java.io.InputStream;
41 import java.nio.charset.StandardCharsets;
42 import java.util.HashMap;
43 import java.util.Map;
44
45 import javax.servlet.http.HttpServletRequest;
46
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;
64 import org.slf4j.MDC;
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;
82
83 import io.swagger.annotations.ApiOperation;
84
85 @RestController
86 @RequestMapping(PortalConstants.REST_AUX_API)
87 @Configuration
88 @EnableAspectJAutoProxy
89 @EPAuditLog
90 public class WebAnalyticsExtAppController extends EPRestrictedRESTfulBaseController {
91
92         @Autowired
93         private ConsulHealthService consulHealthService;
94
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();
101
102
103         @Autowired
104         AuditService auditService;
105
106         @Autowired
107         AppsCacheService appCacheService;
108
109         SuccessCallback<ResponseEntity<String>> successCallback = new SuccessCallback<ResponseEntity<String>>() {
110                 @Override
111                 public void onSuccess(ResponseEntity<String> arg) {
112                         logger.info(EELFLoggerDelegate.debugLogger, arg.getBody());
113                 }
114         };
115
116         FailureCallback failureCallback = new FailureCallback() {
117                 @Override
118                 public void onFailure(Throwable arg) {
119                         logger.error(EELFLoggerDelegate.errorLogger, "storeAuxAnalytics failed", arg);
120                 }
121         };
122
123         protected boolean isAuxRESTfulCall() {
124                 return true;
125         }
126
127         /**
128          * Answers requests from partner applications for a file that is expected to
129          * contain javascript to support web analytics.
130          * 
131          * @param request
132          *            HttpServletRequest
133          * @return String
134          * @throws Exception
135          *             on failure
136          */
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;
143                 try {
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);
148                 } finally {
149                         if (analyticsFileStream != null)
150                                 analyticsFileStream.close();
151                 }
152
153                 String feURLContext = SystemProperties.getProperty("frontend_url");
154                 String feURL = feURLContext.substring(0, feURLContext.lastIndexOf('/'));
155
156                 responseText = responseText.replace("PORTAL_ENV_URL", feURL);
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          * @throws Exception
169          *             on failure
170          */
171         @RequestMapping(value = { "/storeAnalytics" }, method = RequestMethod.POST, produces = "application/json")
172         @ResponseBody
173         @ApiOperation(value = "Accepts data from partner applications with web analytics data.", response = PortalAPIResponse.class)
174         public PortalAPIResponse storeAnalyticsScript(HttpServletRequest request, @RequestBody Analytics analyticsMap)
175                         throws Exception {
176                 try {
177                         MDC.put(EPCommonSystemProperties.AUDITLOG_BEGIN_TIMESTAMP, EPEELFLoggerAdvice.getCurrentDateTimeUTC());
178                         String appName = "";
179                         try {
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");
184                         }
185
186                         try {
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");
191                         }
192
193                         MDC.put(EPCommonSystemProperties.AUDITLOG_END_TIMESTAMP, EPEELFLoggerAdvice.getCurrentDateTimeUTC());
194
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()));
203
204                         MDC.remove(EPCommonSystemProperties.AUDITLOG_BEGIN_TIMESTAMP);
205                         MDC.remove(EPCommonSystemProperties.AUDITLOG_END_TIMESTAMP);
206                         MDC.remove(SystemProperties.MDC_TIMER);
207
208                         PortalAPIResponse response = new PortalAPIResponse(true, "success");
209                         return response;
210                 } catch (Exception e) {
211                         logger.error(EELFLoggerDelegate.errorLogger, "storeAnalytics failed", e);
212                         PortalAPIResponse response = new PortalAPIResponse(true, "error");
213                         return response;
214                 }
215         }
216
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");
221                 } else {
222                         EPApp appRecord = appCacheService.getAppFromUeb(appKeyValue);
223                         if (appRecord == null) {
224                                 logger.error(EELFLoggerDelegate.errorLogger, " App could not be found for the key " + appKeyValue);
225                         } else
226                                 appName = appRecord.getName();
227
228                 }
229                 return appName;
230         }
231
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());
236
237                 Map<String, String> requestMapping = new HashMap<String, String>();
238                 requestMapping.put("id", analyticsMap.getUserid());
239                 requestMapping.put("action", appName + "|" + analyticsMap.getFunction());
240
241                 HttpHeaders headers = new HttpHeaders();
242                 headers.setContentType(MediaType.APPLICATION_JSON);
243
244                 // set your entity to send
245                 HttpEntity<Map<String, String>> entity = new HttpEntity<Map<String, String>>(requestMapping, headers);
246
247                 // send it!
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"))
252                                                 + REGISTER_ACTION,
253                                 HttpMethod.POST, entity, String.class);
254                 out.addCallback(successCallback, failureCallback);
255         }
256
257 }