44a5dcdf2d87791ebf0c761ebb5b2755c58f81f0
[portal.git] / ecomp-portal-BE-common / src / main / java / org / openecomp / portalapp / portal / controller / WebAnalyticsExtAppController.java
1 /*-
2  * ================================================================================
3  * ECOMP Portal
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
10  * 
11  *      http://www.apache.org/licenses/LICENSE-2.0
12  * 
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  * ================================================================================
19  */
20 package org.openecomp.portalapp.portal.controller;
21
22 import java.io.InputStream;
23 import java.nio.charset.StandardCharsets;
24 import java.util.HashMap;
25 import java.util.Map;
26
27 import javax.servlet.http.HttpServletRequest;
28
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;
46 import org.slf4j.MDC;
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;
64
65 import io.swagger.annotations.ApiOperation;
66
67 @RestController
68 @RequestMapping(PortalConstants.REST_AUX_API)
69 @Configuration
70 @EnableAspectJAutoProxy
71 @EPAuditLog
72 public class WebAnalyticsExtAppController extends EPRestrictedRESTfulBaseController {
73
74         @Autowired
75         private ConsulHealthService consulHealthService;
76
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 APP_KEY = "uebkey";
81         private EELFLoggerDelegate logger = EELFLoggerDelegate.getLogger(WebAnalyticsExtAppController.class);
82         private AsyncRestTemplate restTemplate = new AsyncRestTemplate();
83
84
85         @Autowired
86         AuditService auditService;
87
88         @Autowired
89         AppsCacheService appCacheService;
90
91         SuccessCallback<ResponseEntity<String>> successCallback = new SuccessCallback<ResponseEntity<String>>() {
92                 @Override
93                 public void onSuccess(ResponseEntity<String> arg) {
94                         logger.info(EELFLoggerDelegate.debugLogger, arg.getBody());
95                 }
96         };
97
98         FailureCallback failureCallback = new FailureCallback() {
99                 @Override
100                 public void onFailure(Throwable arg) {
101                         logger.error(EELFLoggerDelegate.errorLogger, "storeAuxAnalytics failed", arg);
102                 }
103         };
104
105         protected boolean isAuxRESTfulCall() {
106                 return true;
107         }
108
109         /**
110          * Answers requests from partner applications for a file that is expected to
111          * contain javascript to support web analytics.
112          * 
113          * @param request
114          *            HttpServletRequest
115          * @return String
116          * @throws Exception
117          *             on failure
118          */
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) throws Exception {
122                 String responseText = "";
123                 final String fileName = "analytics.txt";
124                 InputStream analyticsFileStream = null;
125                 try {
126                         analyticsFileStream = this.getClass().getClassLoader().getResourceAsStream(fileName);
127                         responseText = IOUtils.toString(analyticsFileStream, StandardCharsets.UTF_8.name());
128                 } catch (Exception e) {
129                         logger.error(EELFLoggerDelegate.errorLogger, "Error reading contents of the file " + fileName, e);
130                 } finally {
131                         if (analyticsFileStream != null)
132                                 analyticsFileStream.close();
133                 }
134
135                 String feURLContext = SystemProperties.getProperty("frontend_url");
136                 String feURL = feURLContext.substring(0, feURLContext.lastIndexOf('/'));
137
138                 responseText = responseText.replace("PORTAL_ENV_URL", feURL);
139                 return responseText;
140         }
141
142         /**
143          * Accepts data from partner applications with web analytics data.
144          * 
145          * @param request
146          *            HttpServletRequest
147          * @param analyticsMap
148          *            Analytics
149          * @return PortalAPIResponse
150          * @throws Exception
151          *             on failure
152          */
153         @RequestMapping(value = { "/storeAnalytics" }, method = RequestMethod.POST, produces = "application/json")
154         @ResponseBody
155         @ApiOperation(value = "Accepts data from partner applications with web analytics data.", response = PortalAPIResponse.class)
156         public PortalAPIResponse storeAnalyticsScript(HttpServletRequest request, @RequestBody Analytics analyticsMap)
157                         throws Exception {
158                 try {
159                         MDC.put(EPCommonSystemProperties.AUDITLOG_BEGIN_TIMESTAMP, EPEELFLoggerAdvice.getCurrentDateTimeUTC());
160                         String appName = "";
161                         try {
162                                 appName = getAppName(request, appName);
163                         } catch (Exception e) {
164                                 logger.error(EELFLoggerDelegate.errorLogger,
165                                                 " Error retrieving Application to capture app name for analytics; Proceeding with empty app name");
166                         }
167
168                         try {
169                                 storeAuxAnalytics(analyticsMap, appName);
170                         } catch (Exception e) {
171                                 logger.error(EELFLoggerDelegate.errorLogger,
172                                                 " Error retrieving Application to capture app name for analytics; Proceeding with empty app name");
173                         }
174
175                         MDC.put(EPCommonSystemProperties.AUDITLOG_END_TIMESTAMP, EPEELFLoggerAdvice.getCurrentDateTimeUTC());
176
177                         EcompPortalUtils.calculateDateTimeDifferenceForLog(
178                                         MDC.get(EPCommonSystemProperties.AUDITLOG_BEGIN_TIMESTAMP),
179                                         MDC.get(EPCommonSystemProperties.AUDITLOG_END_TIMESTAMP));
180                         logger.info(EELFLoggerDelegate.auditLogger,
181                                         EPLogUtil.formatStoreAnalyticsAuditLogMessage(analyticsMap.getUserid(), appName,
182                                                         "WebAnalyticsExtAppController.postWebAnalyticsData",
183                                                         EcompAuditLog.CD_ACTIVITY_STORE_ANALYTICS, analyticsMap.getAction(), analyticsMap.getPage(),
184                                                         analyticsMap.getFunction(), analyticsMap.getType()));
185
186                         MDC.remove(EPCommonSystemProperties.AUDITLOG_BEGIN_TIMESTAMP);
187                         MDC.remove(EPCommonSystemProperties.AUDITLOG_END_TIMESTAMP);
188                         MDC.remove(SystemProperties.MDC_TIMER);
189
190                         PortalAPIResponse response = new PortalAPIResponse(true, "success");
191                         return response;
192                 } catch (Exception e) {
193                         logger.error(EELFLoggerDelegate.errorLogger, "storeAnalytics failed", e);
194                         PortalAPIResponse response = new PortalAPIResponse(true, "error");
195                         return response;
196                 }
197         }
198
199         protected String getAppName(HttpServletRequest request, String appName) {
200                 String appKeyValue = request.getHeader(APP_KEY);
201                 if (appKeyValue == null || appKeyValue.equals("")) {
202                         logger.error(EELFLoggerDelegate.errorLogger, " App Key unavailable; Proceeding with null app name");
203                 } else {
204                         EPApp appRecord = appCacheService.getAppForAnalytics(appKeyValue);
205                         if (appRecord == null) {
206                                 logger.error(EELFLoggerDelegate.errorLogger, " App could not be found for the key " + appKeyValue);
207                         } else
208                                 appName = appRecord.getName();
209
210                 }
211                 return appName;
212         }
213
214         protected void storeAuxAnalytics(Analytics analyticsMap, String appName) {
215                 logger.info(EELFLoggerDelegate.debugLogger,
216                                 " Registering an action for recommendation: AppName/Function/UserId " + appName + "/"
217                                                 + analyticsMap.getFunction() + "/" + analyticsMap.getUserid());
218
219                 Map<String, String> requestMapping = new HashMap<String, String>();
220                 requestMapping.put("id", analyticsMap.getUserid());
221                 requestMapping.put("action", appName + "|" + analyticsMap.getFunction());
222
223                 HttpHeaders headers = new HttpHeaders();
224                 headers.setContentType(MediaType.APPLICATION_JSON);
225
226                 // set your entity to send
227                 HttpEntity<Map<String, String>> entity = new HttpEntity<Map<String, String>>(requestMapping, headers);
228
229                 // send it!
230                 ListenableFuture<ResponseEntity<String>> out = restTemplate.exchange(
231                                 EcompPortalUtils.widgetMsProtocol() + "://"
232                                                 + consulHealthService.getServiceLocation(CONSUL_ML_SERVICE_ID,
233                                                                 SystemProperties.getProperty("microservices.m-learn.local.port"))
234                                                 + REGISTER_ACTION,
235                                 HttpMethod.POST, entity, String.class);
236                 out.addCallback(successCallback, failureCallback);
237         }
238
239 }