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