[PORTAL-16 PORTAL-18] Widget ms; staging
[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 SERVICE_PROTOCOL = "http";
81         private static final String APP_KEY = "uebkey";
82
83         @Autowired
84         AuditService auditService;
85
86         @Autowired
87         AppsCacheService appCacheService;
88
89         private EELFLoggerDelegate logger = EELFLoggerDelegate.getLogger(WebAnalyticsExtAppController.class);
90
91         private AsyncRestTemplate restTemplate = new AsyncRestTemplate();
92
93         SuccessCallback<ResponseEntity<String>> successCallback = new SuccessCallback<ResponseEntity<String>>() {
94                 @Override
95                 public void onSuccess(ResponseEntity<String> arg) {
96                         logger.info(EELFLoggerDelegate.debugLogger, arg.getBody());
97                 }
98         };
99
100         FailureCallback failureCallback = new FailureCallback() {
101                 @Override
102                 public void onFailure(Throwable arg) {
103                         logger.error(EELFLoggerDelegate.errorLogger, "storeAuxAnalytics failed", arg);
104                 }
105         };
106
107         protected boolean isAuxRESTfulCall() {
108                 return true;
109         }
110
111         /**
112          * Answers requests from partner applications for a file that is expected to
113          * contain javascript to support web analytics.
114          * 
115          * @param request
116          *            HttpServletRequest
117          * @return String
118          * @throws Exception
119          *             on failure
120          */
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;
127                 try {
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);
132                 } finally {
133                         if (analyticsFileStream != null)
134                                 analyticsFileStream.close();
135                 }
136
137                 String feURLContext = SystemProperties.getProperty("frontend_url");
138                 String feURL = feURLContext.substring(0, feURLContext.lastIndexOf('/'));
139
140                 responseText = responseText.replace("PORTAL_ENV_URL", feURL);
141                 return responseText;
142         }
143
144         /**
145          * Accepts data from partner applications with web analytics data.
146          * 
147          * @param request
148          *            HttpServletRequest
149          * @param analyticsMap
150          *            Analytics
151          * @return PortalAPIResponse
152          * @throws Exception
153          *             on failure
154          */
155         @RequestMapping(value = { "/storeAnalytics" }, method = RequestMethod.POST, produces = "application/json")
156         @ResponseBody
157         @ApiOperation(value = "Accepts data from partner applications with web analytics data.", response = PortalAPIResponse.class)
158         public PortalAPIResponse storeAnalyticsScript(HttpServletRequest request, @RequestBody Analytics analyticsMap)
159                         throws Exception {
160                 try {
161                         MDC.put(EPCommonSystemProperties.AUDITLOG_BEGIN_TIMESTAMP, EPEELFLoggerAdvice.getCurrentDateTimeUTC());
162                         String appName = "";
163                         try {
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");
168                         }
169
170                         try {
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");
175                         }
176
177                         MDC.put(EPCommonSystemProperties.AUDITLOG_END_TIMESTAMP, EPEELFLoggerAdvice.getCurrentDateTimeUTC());
178
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()));
187
188                         MDC.remove(EPCommonSystemProperties.AUDITLOG_BEGIN_TIMESTAMP);
189                         MDC.remove(EPCommonSystemProperties.AUDITLOG_END_TIMESTAMP);
190                         MDC.remove(SystemProperties.MDC_TIMER);
191
192                         PortalAPIResponse response = new PortalAPIResponse(true, "success");
193                         return response;
194                 } catch (Exception e) {
195                         logger.error(EELFLoggerDelegate.errorLogger, "storeAnalytics failed", e);
196                         PortalAPIResponse response = new PortalAPIResponse(true, "error");
197                         return response;
198                 }
199         }
200
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");
205                 } else {
206                         EPApp appRecord = appCacheService.getAppForAnalytics(appKeyValue);
207                         if (appRecord == null) {
208                                 logger.error(EELFLoggerDelegate.errorLogger, " App could not be found for the key " + appKeyValue);
209                         } else
210                                 appName = appRecord.getName();
211
212                 }
213                 return appName;
214         }
215
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());
220
221                 Map<String, String> requestMapping = new HashMap<String, String>();
222                 requestMapping.put("id", analyticsMap.getUserId());
223                 requestMapping.put("action", appName + "|" + analyticsMap.getFunction());
224
225                 HttpHeaders headers = new HttpHeaders();
226                 headers.setContentType(MediaType.APPLICATION_JSON);
227
228                 // set your entity to send
229                 HttpEntity<Map<String, String>> entity = new HttpEntity<Map<String, String>>(requestMapping, headers);
230
231                 // send it!
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"))
236                                                 + REGISTER_ACTION,
237                                 HttpMethod.POST, entity, String.class);
238                 out.addCallback(successCallback, failureCallback);
239         }
240
241 }