CADI AAF Integration and merging the code
[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.apache.commons.lang.StringUtils;
49 import org.onap.portalapp.controller.EPRestrictedRESTfulBaseController;
50 import org.onap.portalapp.portal.domain.EPApp;
51 import org.onap.portalapp.portal.domain.EcompAuditLog;
52 import org.onap.portalapp.portal.logging.aop.EPAuditLog;
53 import org.onap.portalapp.portal.logging.aop.EPEELFLoggerAdvice;
54 import org.onap.portalapp.portal.logging.logic.EPLogUtil;
55 import org.onap.portalapp.portal.service.AppsCacheService;
56 import org.onap.portalapp.portal.service.ConsulHealthService;
57 import org.onap.portalapp.portal.transport.Analytics;
58 import org.onap.portalapp.portal.utils.EPCommonSystemProperties;
59 import org.onap.portalapp.portal.utils.EcompPortalUtils;
60 import org.onap.portalapp.portal.utils.PortalConstants;
61 import org.onap.portalsdk.core.logging.logic.EELFLoggerDelegate;
62 import org.onap.portalsdk.core.onboarding.crossapi.PortalAPIResponse;
63 import org.onap.portalsdk.core.service.AuditService;
64 import org.onap.portalsdk.core.util.SystemProperties;
65 import org.slf4j.MDC;
66 import org.springframework.beans.factory.annotation.Autowired;
67 import org.springframework.context.annotation.Configuration;
68 import org.springframework.context.annotation.EnableAspectJAutoProxy;
69 import org.springframework.http.HttpEntity;
70 import org.springframework.http.HttpHeaders;
71 import org.springframework.http.HttpMethod;
72 import org.springframework.http.MediaType;
73 import org.springframework.http.ResponseEntity;
74 import org.springframework.util.concurrent.FailureCallback;
75 import org.springframework.util.concurrent.ListenableFuture;
76 import org.springframework.util.concurrent.SuccessCallback;
77 import org.springframework.web.bind.annotation.RequestBody;
78 import org.springframework.web.bind.annotation.RequestMapping;
79 import org.springframework.web.bind.annotation.RequestMethod;
80 import org.springframework.web.bind.annotation.ResponseBody;
81 import org.springframework.web.bind.annotation.RestController;
82 import org.springframework.web.client.AsyncRestTemplate;
83
84 import io.swagger.annotations.ApiOperation;
85
86 @RestController
87 @RequestMapping(PortalConstants.REST_AUX_API)
88 @Configuration
89 @EnableAspectJAutoProxy
90 @EPAuditLog
91 public class WebAnalyticsExtAppController extends EPRestrictedRESTfulBaseController {
92
93         @Autowired
94         private ConsulHealthService consulHealthService;
95
96         private static final String MACHINE_LEARNING_SERVICE_CTX = "/ml_api";
97         private static final String REGISTER_ACTION = MACHINE_LEARNING_SERVICE_CTX + "/" + "registerAction";
98         private static final String CONSUL_ML_SERVICE_ID = "machine-learning";
99         private static final String APP_KEY = "uebkey";
100         private EELFLoggerDelegate logger = EELFLoggerDelegate.getLogger(WebAnalyticsExtAppController.class);
101         private AsyncRestTemplate restTemplate = new AsyncRestTemplate();
102
103
104         @Autowired
105         AuditService auditService;
106
107         @Autowired
108         AppsCacheService appCacheService;
109
110         SuccessCallback<ResponseEntity<String>> successCallback = new SuccessCallback<ResponseEntity<String>>() {
111                 @Override
112                 public void onSuccess(ResponseEntity<String> arg) {
113                         logger.info(EELFLoggerDelegate.debugLogger, arg.getBody());
114                 }
115         };
116
117         FailureCallback failureCallback = new FailureCallback() {
118                 @Override
119                 public void onFailure(Throwable arg) {
120                         logger.error(EELFLoggerDelegate.errorLogger, "storeAuxAnalytics failed", arg);
121                 }
122         };
123
124         protected boolean isAuxRESTfulCall() {
125                 return true;
126         }
127
128         /**
129          * Answers requests from partner applications for a file that is expected to
130          * contain javascript to support web analytics.
131          * 
132          * @param request
133          *            HttpServletRequest
134          * @return String
135          * @throws Exception
136          *             on failure
137          */
138         @ApiOperation(value = "Gets javascript with functions that support gathering and reporting web analytics.", response = String.class)
139         @RequestMapping(value = { "/analytics" }, method = RequestMethod.GET, produces = "application/javascript")
140         public String getAnalyticsScript(HttpServletRequest request) throws Exception {
141                 String responseText = "";
142                 EPApp app = null;
143                 String version = "";
144                 try {
145                         app = getApp(request);
146                 } catch (Exception e) {
147                         logger.error(EELFLoggerDelegate.errorLogger,
148                                         " Error retrieving Application to capture app name for analytics; Proceeding with empty app name");
149                 }
150                 if (app != null) {
151                         String restEndPoint = app.getAppRestEndpoint();
152                         if(restEndPoint.indexOf("/api")!=-1) {
153                                 version = restEndPoint.substring(restEndPoint.indexOf("/api")+4);
154                         }
155                 }
156                 String END_POINT = "/storeAnalytics";
157                 if(StringUtils.isNotBlank(version)) {
158                         END_POINT = version + "/storeAnalytics";
159                 }
160
161                 final String fileName = "analytics.txt";
162                 InputStream analyticsFileStream = null;
163                 try {
164                         analyticsFileStream = this.getClass().getClassLoader().getResourceAsStream(fileName);
165                         responseText = IOUtils.toString(analyticsFileStream, StandardCharsets.UTF_8.name());
166                 } catch (Exception e) {
167                         logger.error(EELFLoggerDelegate.errorLogger, "Error reading contents of the file " + fileName, e);
168                 } finally {
169                         if (analyticsFileStream != null)
170                                 analyticsFileStream.close();
171                 }
172
173                 String feURLContext = SystemProperties.getProperty("frontend_url");
174                 String feURL = feURLContext.substring(0, feURLContext.lastIndexOf('/'));
175                 responseText = responseText.replace("PORTAL_ENV_URL", feURL);
176                 responseText = responseText.replace("$END_POINT", END_POINT);
177                 return responseText;
178         }
179
180         /**
181          * Accepts data from partner applications with web analytics data.
182          * 
183          * @param request
184          *            HttpServletRequest
185          * @param analyticsMap
186          *            Analytics
187          * @return PortalAPIResponse
188          * @throws Exception
189          *             on failure
190          */
191         @RequestMapping(value = { "/storeAnalytics" }, method = RequestMethod.POST, produces = "application/json")
192         @ResponseBody
193         @ApiOperation(value = "Accepts data from partner applications with web analytics data.", response = PortalAPIResponse.class)
194         public PortalAPIResponse storeAnalyticsScript(HttpServletRequest request, @RequestBody Analytics analyticsMap)
195                         throws Exception {
196                 try {
197                         MDC.put(EPCommonSystemProperties.AUDITLOG_BEGIN_TIMESTAMP, EPEELFLoggerAdvice.getCurrentDateTimeUTC());
198                         String appName = "";
199                         try {
200                                 appName = getAppName(request, appName);
201                         } catch (Exception e) {
202                                 logger.error(EELFLoggerDelegate.errorLogger,
203                                                 " Error retrieving Application to capture app name for analytics; Proceeding with empty app name");
204                         }
205
206                         try {
207                                 storeAuxAnalytics(analyticsMap, appName);
208                         } catch (Exception e) {
209                                 logger.error(EELFLoggerDelegate.errorLogger,
210                                                 " Error retrieving Application to capture app name for analytics; Proceeding with empty app name");
211                         }
212
213                         MDC.put(EPCommonSystemProperties.AUDITLOG_END_TIMESTAMP, EPEELFLoggerAdvice.getCurrentDateTimeUTC());
214
215                         EcompPortalUtils.calculateDateTimeDifferenceForLog(
216                                         MDC.get(EPCommonSystemProperties.AUDITLOG_BEGIN_TIMESTAMP),
217                                         MDC.get(EPCommonSystemProperties.AUDITLOG_END_TIMESTAMP));
218                         logger.info(EELFLoggerDelegate.auditLogger,
219                                         EPLogUtil.formatStoreAnalyticsAuditLogMessage(analyticsMap.getUserid(), appName,
220                                                         "WebAnalyticsExtAppController.postWebAnalyticsData",
221                                                         EcompAuditLog.CD_ACTIVITY_STORE_ANALYTICS, analyticsMap.getAction(), analyticsMap.getPage(),
222                                                         analyticsMap.getFunction(), analyticsMap.getType()));
223
224                         MDC.remove(EPCommonSystemProperties.AUDITLOG_BEGIN_TIMESTAMP);
225                         MDC.remove(EPCommonSystemProperties.AUDITLOG_END_TIMESTAMP);
226                         MDC.remove(SystemProperties.MDC_TIMER);
227
228                         PortalAPIResponse response = new PortalAPIResponse(true, "success");
229                         return response;
230                 } catch (Exception e) {
231                         logger.error(EELFLoggerDelegate.errorLogger, "storeAnalytics failed", e);
232                         PortalAPIResponse response = new PortalAPIResponse(true, "error");
233                         return response;
234                 }
235         }
236
237         protected String getAppName(HttpServletRequest request, String appName) {
238                 
239                 EPApp appRecord = getApp(request);
240                 if (appRecord != null) {
241                         appName = appRecord.getName();
242                 }
243                 return appName;
244         }
245         
246         protected EPApp getApp(HttpServletRequest request) {
247                 String appKeyValue = request.getHeader(APP_KEY);
248                 EPApp appRecord = null;
249                 if (appKeyValue == null || appKeyValue.equals("")) {
250                         logger.error(EELFLoggerDelegate.errorLogger, " App Key unavailable; Proceeding with null app name");
251                 } else {
252                          appRecord = appCacheService.getAppFromUeb(appKeyValue);
253                 }
254                 return appRecord;
255         }
256
257         protected void storeAuxAnalytics(Analytics analyticsMap, String appName) {
258                 logger.info(EELFLoggerDelegate.debugLogger,
259                                 " Registering an action for recommendation: AppName/Function/UserId " + appName + "/"
260                                                 + analyticsMap.getFunction() + "/" + analyticsMap.getUserid());
261
262                 Map<String, String> requestMapping = new HashMap<String, String>();
263                 requestMapping.put("id", analyticsMap.getUserid());
264                 requestMapping.put("action", appName + "|" + analyticsMap.getFunction());
265
266                 HttpHeaders headers = new HttpHeaders();
267                 headers.setContentType(MediaType.APPLICATION_JSON);
268
269                 // set your entity to send
270                 HttpEntity<Map<String, String>> entity = new HttpEntity<Map<String, String>>(requestMapping, headers);
271
272                 // send it!
273                 ListenableFuture<ResponseEntity<String>> out = restTemplate.exchange(
274                                 EcompPortalUtils.widgetMsProtocol() + "://"
275                                                 + consulHealthService.getServiceLocation(CONSUL_ML_SERVICE_ID,
276                                                                 SystemProperties.getProperty("microservices.m-learn.local.port"))
277                                                 + REGISTER_ACTION,
278                                 HttpMethod.POST, entity, String.class);
279                 out.addCallback(successCallback, failureCallback);
280         }
281         
282 }