4c67429bfad9d7dff4b3e3de67ea9fff869cf257
[portal.git] / ecomp-portal-BE-common / src / main / java / org / onap / portalapp / portal / logging / aop / EPEELFLoggerAdvice.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.logging.aop;
39
40 import java.net.InetAddress;
41 import java.text.SimpleDateFormat;
42 import java.util.Date;
43 import java.util.UUID;
44
45 import javax.servlet.http.HttpServletRequest;
46
47 import org.onap.portalapp.portal.domain.EPApp;
48 import org.onap.portalapp.portal.domain.EPUser;
49 import org.onap.portalapp.portal.service.AppsCacheService;
50 import org.onap.portalapp.portal.utils.EPCommonSystemProperties;
51 import org.onap.portalapp.portal.utils.EcompPortalUtils;
52 import org.onap.portalapp.util.EPUserUtils;
53 import org.onap.portalsdk.core.exception.SessionExpiredException;
54 import org.onap.portalsdk.core.logging.format.AlarmSeverityEnum;
55 import org.onap.portalsdk.core.logging.format.AuditLogFormatter;
56 import org.onap.portalsdk.core.logging.logic.EELFLoggerDelegate;
57 import org.onap.portalsdk.core.util.SystemProperties;
58 import org.onap.portalsdk.core.util.SystemProperties.SecurityEventTypeEnum;
59 import org.onap.portalsdk.core.web.support.UserUtils;
60 import org.slf4j.MDC;
61 import org.springframework.beans.factory.annotation.Autowired;
62
63 import com.att.eelf.configuration.Configuration;
64
65 @org.springframework.context.annotation.Configuration
66 public class EPEELFLoggerAdvice {
67
68         private EELFLoggerDelegate adviceLogger = EELFLoggerDelegate.getLogger(EPEELFLoggerAdvice.class);
69         
70         @Autowired
71         AppsCacheService appCacheService;
72
73         /**
74          * DateTime Format according to the ONAP Application Logging Guidelines.
75          */
76
77         /**
78          * @return Current date and time in the format specified by the ONAP
79          *         Application Logging Guidelines.
80          */
81         public static String getCurrentDateTimeUTC() {
82                 SimpleDateFormat ecompLogDateFormat = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSSXXX");
83                 String currentDateTime = ecompLogDateFormat.format(new Date());
84                 return currentDateTime;
85         }
86
87         /**
88          * Sets logging context with values from HttpServletRequest object.
89          * 
90          * @param req
91          *            HttpServletRequest
92          * @param securityEventType
93          *            SecurityEventTypeEnum
94          */
95         public void loadServletRequestBasedDefaults(HttpServletRequest req, SecurityEventTypeEnum securityEventType) {
96                 try {
97                         setHttpRequestBasedDefaultsIntoGlobalLoggingContext(req, securityEventType, req.getServletPath());
98                 } catch (Exception e) {
99                         adviceLogger.error(EELFLoggerDelegate.errorLogger, "loadServletRequestBasedDefaults failed", e);
100                 }
101         }
102
103         /**
104          * 
105          * @param securityEventType
106          * @param args
107          * @param passOnArgs
108          * @return Object array
109          */
110         public Object[] before(SecurityEventTypeEnum securityEventType, Object[] args, Object[] passOnArgs) {
111                 String className = "";
112                 if (passOnArgs.length > 0 && passOnArgs[0] != null)
113                         className = passOnArgs[0].toString();
114                 String methodName = EPCommonSystemProperties.ECOMP_PORTAL_BE;
115                 if (passOnArgs.length > 1 && passOnArgs[1] != null)
116                         methodName = passOnArgs[1].toString();
117
118                 // Initialize Request defaults only for controller methods.
119                 MDC.put(className + methodName + EPCommonSystemProperties.METRICSLOG_BEGIN_TIMESTAMP, getCurrentDateTimeUTC());
120                 MDC.put(EPCommonSystemProperties.TARGET_ENTITY, EPCommonSystemProperties.ECOMP_PORTAL_BE);
121                 MDC.put(EPCommonSystemProperties.TARGET_SERVICE_NAME, methodName);
122                 if (MDC.get(Configuration.MDC_KEY_REQUEST_ID) == null||MDC.get(Configuration.MDC_KEY_REQUEST_ID).isEmpty()){
123                         String requestId = UUID.randomUUID().toString();
124                         MDC.put(Configuration.MDC_KEY_REQUEST_ID, requestId);
125                 }
126                 MDC.put(EPCommonSystemProperties.PARTNER_NAME, "Unknown");
127                 MDC.put(Configuration.MDC_SERVICE_NAME, EPCommonSystemProperties.ECOMP_PORTAL_BE);
128
129                 if (securityEventType != null) {
130                         MDC.put(className + methodName + EPCommonSystemProperties.AUDITLOG_BEGIN_TIMESTAMP,
131                                         getCurrentDateTimeUTC());
132                         HttpServletRequest req = null;
133                         if (args.length > 0 && args[0] != null && args[0] instanceof HttpServletRequest) {
134                                 req = (HttpServletRequest) args[0];
135                                 this.setHttpRequestBasedDefaultsIntoGlobalLoggingContext(req, securityEventType, methodName);
136                         }
137                 }
138
139                 EELFLoggerDelegate logger = EELFLoggerDelegate.getLogger(className);
140                 logger.debug(EELFLoggerDelegate.debugLogger, "EPEELFLoggerAdvice#after: finished {}", methodName);
141                 // add the metrics log
142                 logger.info(EELFLoggerDelegate.metricsLogger,  methodName + " operation is completed.");
143
144                 // Log security message, if necessary
145                 if (securityEventType != null) {
146                         MDC.put(EPCommonSystemProperties.AUDITLOG_BEGIN_TIMESTAMP,getCurrentDateTimeUTC());
147                         MDC.put(EPCommonSystemProperties.AUDITLOG_END_TIMESTAMP, getCurrentDateTimeUTC());
148                         this.calculateDateTimeDifference(MDC.get(EPCommonSystemProperties.AUDITLOG_BEGIN_TIMESTAMP),MDC.get(EPCommonSystemProperties.AUDITLOG_END_TIMESTAMP));
149                         MDC.put(EPCommonSystemProperties.STATUS_CODE, "INPROGRESS");
150                         MDC.put("CustomField1", "ENTRY");
151                         MDC.put("CustomField2", "InvocationID="+MDC.get(Configuration.MDC_KEY_REQUEST_ID));
152                         try {
153                                 MDC.put(Configuration.MDC_SERVER_FQDN, InetAddress.getLocalHost().getCanonicalHostName());
154                         } catch (Exception e) {
155                                 adviceLogger.error(EELFLoggerDelegate.errorLogger,
156                                                 " while setting the IP address ", e);
157                         }
158                         this.logSecurityMessage(logger, securityEventType, methodName);
159
160                         // Outgoing & LDAP messages are part of Incoming requests so,
161                         // keep "RequestId", "PartnerName", "ServiceName", "LoginId" &
162                         // "ResponseCode" etc. in memory and remove it only when
163                         // finished processing the parent incoming message.
164                         if (securityEventType != SecurityEventTypeEnum.OUTGOING_REST_MESSAGE
165                                         && securityEventType != SecurityEventTypeEnum.LDAP_PHONEBOOK_USER_SEARCH) {
166                                 MDC.remove(Configuration.MDC_KEY_REQUEST_ID);
167                                 MDC.remove(EPCommonSystemProperties.PARTNER_NAME);
168                                 MDC.remove(Configuration.MDC_SERVICE_NAME);
169                                 MDC.remove(EPCommonSystemProperties.MDC_LOGIN_ID);
170                                 MDC.remove(EPCommonSystemProperties.EXTERNAL_API_RESPONSE_CODE);
171                         }else{
172                                 MDC.remove(Configuration.MDC_KEY_REQUEST_ID);
173                                 MDC.remove(EPCommonSystemProperties.PARTNER_NAME);
174                                 MDC.remove(Configuration.MDC_SERVICE_NAME);
175                         }
176                         
177                         MDC.remove(Configuration.MDC_SERVER_FQDN);
178                 }
179                 logger.debug(EELFLoggerDelegate.debugLogger, "EPEELFLoggerAdvice#before: entering {}", methodName);
180                 return new Object[] { "" };
181         }
182
183         /**
184          * 
185          * @param securityEventType
186          * @param statusCode
187          * @param responseCode
188          * @param args
189          * @param returnArgs
190          * @param passOnArgs
191          */
192         public void after(SecurityEventTypeEnum securityEventType, String statusCode, String responseCode, Object[] args,
193                         Object[] returnArgs, Object[] passOnArgs) {
194                 String className = "";
195                 if (passOnArgs.length > 0 && passOnArgs[0] != null)
196                         className = passOnArgs[0].toString();
197                 // Method Name
198                 String methodName =  EPCommonSystemProperties.ECOMP_PORTAL_BE;
199                 if (passOnArgs.length > 1 && passOnArgs[1] != null)
200                         methodName = passOnArgs[1].toString();
201
202                 if (MDC.get(EPCommonSystemProperties.TARGET_SERVICE_NAME) == null
203                                 || MDC.get(EPCommonSystemProperties.TARGET_SERVICE_NAME) == "")
204                         MDC.put(EPCommonSystemProperties.TARGET_SERVICE_NAME, methodName);
205
206                 if (MDC.get(EPCommonSystemProperties.TARGET_ENTITY) == null
207                                 || MDC.get(EPCommonSystemProperties.TARGET_ENTITY) == "")
208                         MDC.put(EPCommonSystemProperties.TARGET_ENTITY, EPCommonSystemProperties.ECOMP_PORTAL_BE);
209                 
210                 if (MDC.get(Configuration.MDC_KEY_REQUEST_ID) == null||MDC.get(Configuration.MDC_KEY_REQUEST_ID).isEmpty()){
211                         String requestId = UUID.randomUUID().toString();
212                         MDC.put(Configuration.MDC_KEY_REQUEST_ID, requestId);
213                 }
214
215                 if (MDC.get(EPCommonSystemProperties.PARTNER_NAME) == null|| MDC.get(EPCommonSystemProperties.PARTNER_NAME).isEmpty()){
216                         MDC.put(EPCommonSystemProperties.PARTNER_NAME, "Unknown");
217                 }
218                 
219                 MDC.put(Configuration.MDC_SERVICE_NAME, EPCommonSystemProperties.ECOMP_PORTAL_BE);
220
221
222                 MDC.put(EPCommonSystemProperties.METRICSLOG_BEGIN_TIMESTAMP,
223                                 MDC.get(className + methodName + EPCommonSystemProperties.METRICSLOG_BEGIN_TIMESTAMP));
224                 MDC.put(EPCommonSystemProperties.METRICSLOG_END_TIMESTAMP, getCurrentDateTimeUTC());
225                 this.calculateDateTimeDifference(MDC.get(EPCommonSystemProperties.METRICSLOG_BEGIN_TIMESTAMP),
226                                 MDC.get(EPCommonSystemProperties.METRICSLOG_END_TIMESTAMP));
227
228                 // Making sure to reload the INCOMING request MDC defaults if they have
229                 // been wiped out by either Outgoing or LDAP Phone book search
230                 // operations.
231                 if (securityEventType != null && args.length > 0 && args[0] != null && args[0] instanceof HttpServletRequest
232                                 && securityEventType == SecurityEventTypeEnum.INCOMING_REST_MESSAGE
233                                 && (MDC.get(EPCommonSystemProperties.FULL_URL) == null
234                                                 || MDC.get(EPCommonSystemProperties.FULL_URL).isEmpty())) {
235                         HttpServletRequest req = (HttpServletRequest) args[0];
236                         this.setHttpRequestBasedDefaultsIntoGlobalLoggingContext(req, securityEventType, methodName);
237                 }
238
239                 // Use external API response code in case if it resulted in an error.
240                 String externalAPIResponseCode = MDC.get(EPCommonSystemProperties.EXTERNAL_API_RESPONSE_CODE);
241                 if (externalAPIResponseCode == null || externalAPIResponseCode == ""
242                                 || externalAPIResponseCode.trim().equalsIgnoreCase("200")) {
243                         MDC.put(EPCommonSystemProperties.RESPONSE_CODE, responseCode);
244                         MDC.put(EPCommonSystemProperties.STATUS_CODE, statusCode);
245                 } else {
246                         MDC.put(EPCommonSystemProperties.RESPONSE_CODE, externalAPIResponseCode);
247                         MDC.put(EPCommonSystemProperties.STATUS_CODE, "ERROR");
248                 }
249
250                 EELFLoggerDelegate logger = EELFLoggerDelegate.getLogger(className);
251                 logger.debug(EELFLoggerDelegate.debugLogger, "EPEELFLoggerAdvice#after: finished {}", methodName);
252                 // add the metrics log
253                 logger.info(EELFLoggerDelegate.metricsLogger,  methodName + " operation is completed.");
254
255                 // Log security message, if necessary
256                 if (securityEventType != null) {
257                         MDC.put(EPCommonSystemProperties.AUDITLOG_BEGIN_TIMESTAMP,
258                                         MDC.get(className + methodName + EPCommonSystemProperties.AUDITLOG_BEGIN_TIMESTAMP));
259                         MDC.put(EPCommonSystemProperties.AUDITLOG_END_TIMESTAMP, getCurrentDateTimeUTC());
260                         this.calculateDateTimeDifference(MDC.get(EPCommonSystemProperties.AUDITLOG_BEGIN_TIMESTAMP),
261                                         MDC.get(EPCommonSystemProperties.AUDITLOG_END_TIMESTAMP));
262                         MDC.put("CustomField1", "EXIT");
263                         MDC.put("CustomField2", "InvocationID="+MDC.get(Configuration.MDC_KEY_REQUEST_ID));
264                         try {
265                                 MDC.put(Configuration.MDC_SERVER_FQDN, InetAddress.getLocalHost().getCanonicalHostName());
266                         } catch (Exception e) {
267                                 adviceLogger.error(EELFLoggerDelegate.errorLogger,
268                                                 " while setting the IP address ", e);
269                         }
270                         this.logSecurityMessage(logger, securityEventType, methodName);
271
272                         // Outgoing & LDAP messages are part of Incoming requests so,
273                         // keep "RequestId", "PartnerName", "ServiceName", "LoginId" &
274                         // "ResponseCode" etc. in memory and remove it only when
275                         // finished processing the parent incoming message.
276                         if (securityEventType != SecurityEventTypeEnum.OUTGOING_REST_MESSAGE
277                                         && securityEventType != SecurityEventTypeEnum.LDAP_PHONEBOOK_USER_SEARCH) {
278                                 MDC.remove(Configuration.MDC_KEY_REQUEST_ID);
279                                 MDC.remove(EPCommonSystemProperties.PARTNER_NAME);
280                                 MDC.remove(Configuration.MDC_SERVICE_NAME);
281                                 MDC.remove(EPCommonSystemProperties.MDC_LOGIN_ID);
282                                 MDC.remove(EPCommonSystemProperties.EXTERNAL_API_RESPONSE_CODE);
283                         }else{
284                                 MDC.remove(Configuration.MDC_KEY_REQUEST_ID);
285                                 MDC.remove(EPCommonSystemProperties.PARTNER_NAME);
286                                 MDC.remove(Configuration.MDC_SERVICE_NAME);
287                         }
288
289                         // clear when finishes audit logging
290                         MDC.remove(Configuration.MDC_SERVER_FQDN);
291                         MDC.remove(EPCommonSystemProperties.FULL_URL);
292                         MDC.remove(EPCommonSystemProperties.PROTOCOL);
293                         MDC.remove(EPCommonSystemProperties.STATUS_CODE);
294                         MDC.remove(className + methodName + EPCommonSystemProperties.AUDITLOG_BEGIN_TIMESTAMP);
295                         MDC.remove(EPCommonSystemProperties.AUDITLOG_BEGIN_TIMESTAMP);
296                         MDC.remove(EPCommonSystemProperties.AUDITLOG_END_TIMESTAMP);
297                         MDC.remove(EPCommonSystemProperties.RESPONSE_CODE);
298                         
299                 }
300                 MDC.remove("CustomField1");
301                 MDC.remove("CustomField2");
302                 MDC.remove(className + methodName + EPCommonSystemProperties.METRICSLOG_BEGIN_TIMESTAMP);
303                 MDC.remove(EPCommonSystemProperties.METRICSLOG_BEGIN_TIMESTAMP);
304                 MDC.remove(EPCommonSystemProperties.METRICSLOG_END_TIMESTAMP);
305                 MDC.remove(EPCommonSystemProperties.MDC_TIMER);
306                 MDC.remove(EPCommonSystemProperties.TARGET_ENTITY);
307                 MDC.remove(EPCommonSystemProperties.TARGET_SERVICE_NAME);
308         
309         }
310
311         /**
312          * 
313          * @param logger
314          * @param securityEventType
315          * @param restMethod
316          */
317         private void logSecurityMessage(EELFLoggerDelegate logger, SecurityEventTypeEnum securityEventType,
318                         String restMethod) {
319                 StringBuilder additionalInfoAppender = new StringBuilder();
320                 String auditMessage = "";
321
322                 if (securityEventType == SecurityEventTypeEnum.OUTGOING_REST_MESSAGE) {
323                         additionalInfoAppender.append(String.format("%s '%s' request was initiated.", restMethod,
324                                         MDC.get(EPCommonSystemProperties.TARGET_SERVICE_NAME)));
325                 } else if (securityEventType == SecurityEventTypeEnum.LDAP_PHONEBOOK_USER_SEARCH) {
326                         additionalInfoAppender.append("LDAP Phonebook search operation is performed.");
327                 } else {
328                         additionalInfoAppender.append(String.format("%s request was received.", restMethod));
329
330                         if (securityEventType == SecurityEventTypeEnum.FE_LOGIN_ATTEMPT) {
331                                 String loginId = "";
332                                 String additionalMessage = " Successfully authenticated.";
333                                 loginId = MDC.get(EPCommonSystemProperties.MDC_LOGIN_ID);
334                                 if (loginId == null || loginId == "" || loginId == EPCommonSystemProperties.UNKNOWN) {
335                                         additionalMessage = " No cookies are found.";
336                                 }
337                                 additionalInfoAppender.append(additionalMessage);
338                         } else if (securityEventType == SecurityEventTypeEnum.FE_LOGOUT) {
339                                 additionalInfoAppender.append(" User has been successfully logged out.");
340                         }
341                 }
342
343                 String fullURL = MDC.get(EPCommonSystemProperties.FULL_URL);
344                 if (fullURL != null && fullURL != "") {
345                         additionalInfoAppender.append(" Request-URL:" + MDC.get(EPCommonSystemProperties.FULL_URL));
346                 }
347
348                 auditMessage = AuditLogFormatter.getInstance().createMessage(MDC.get(EPCommonSystemProperties.PROTOCOL),
349                                 securityEventType.name(), MDC.get(EPCommonSystemProperties.MDC_LOGIN_ID),
350                                 additionalInfoAppender.toString());
351
352                 logger.info(EELFLoggerDelegate.auditLogger, auditMessage);
353         }
354
355         /**
356          * 
357          * @param req
358          * @param securityEventType
359          * @param restMethod
360          */
361         private void setHttpRequestBasedDefaultsIntoGlobalLoggingContext(HttpServletRequest req,
362                         SecurityEventTypeEnum securityEventType, String restMethod) {
363                 /**
364                  * No need to load the request based defaults for the following security
365                  * messages since either they are initiated by the Portal BE or not Http
366                  * request based.
367                  */
368                 if (req != null) {
369                         if (securityEventType != SecurityEventTypeEnum.OUTGOING_REST_MESSAGE
370                                         && securityEventType != SecurityEventTypeEnum.LDAP_PHONEBOOK_USER_SEARCH
371                                         && securityEventType != SecurityEventTypeEnum.INCOMING_UEB_MESSAGE) {
372                                 // Load the RequestID (aka TrasactionId) into MDC context.
373                                 loadRequestId(req);
374                                 
375                                 loadPartnerName(req);
376
377                                 loadLoginId(req);
378
379                                 loadUrlProtocol(req);
380
381                                 loadServicePath(req, restMethod);
382
383                                 loadClientAddress(req);
384                                 
385                         } else if (securityEventType == SecurityEventTypeEnum.LDAP_PHONEBOOK_USER_SEARCH) {
386                                 MDC.put(EPCommonSystemProperties.TARGET_ENTITY, "Phonebook");
387                                 MDC.put(EPCommonSystemProperties.TARGET_SERVICE_NAME, "search");
388                         }
389                 } else {
390                         MDC.put(Configuration.MDC_SERVICE_NAME, restMethod);
391                         MDC.put(EPCommonSystemProperties.PARTNER_NAME, EPCommonSystemProperties.ECOMP_PORTAL_FE);
392                 }
393
394                 MDC.put(Configuration.MDC_SERVICE_INSTANCE_ID, "");
395                 MDC.put(Configuration.MDC_ALERT_SEVERITY, AlarmSeverityEnum.INFORMATIONAL.severity());
396                 try {
397                         MDC.put(Configuration.MDC_SERVER_FQDN, InetAddress.getLocalHost().getCanonicalHostName());
398                         MDC.put(Configuration.MDC_SERVER_IP_ADDRESS, InetAddress.getLocalHost().getHostAddress());
399                         MDC.put(Configuration.MDC_INSTANCE_UUID, SystemProperties.getProperty(SystemProperties.INSTANCE_UUID));
400                 } catch (Exception e) {
401                         adviceLogger.error(EELFLoggerDelegate.errorLogger,
402                                         "setHttpRequestBasedDefaultsIntoGlobalLoggingContext failed", e);
403                 }
404         }
405
406         private void loadClientAddress(HttpServletRequest req) {
407                 // Client IPAddress i.e. IPAddress of the remote host who is
408                 // making this request.
409                 String clientIPAddress = "";
410                 clientIPAddress = req.getHeader("X-FORWARDED-FOR");
411                 if (clientIPAddress == null) {
412                         clientIPAddress = req.getRemoteAddr();
413                 }
414                 MDC.put(EPCommonSystemProperties.CLIENT_IP_ADDRESS, clientIPAddress);
415         }
416
417         private void loadServicePath(HttpServletRequest req, String restMethod) {
418                 // Rest Path
419                 MDC.put(Configuration.MDC_SERVICE_NAME, restMethod);
420                 String restPath = req.getServletPath();
421                 //if (restPath != null && restPath != "") {
422                 if (restPath != null && restPath.trim().length()>0) {
423
424                         MDC.put(Configuration.MDC_SERVICE_NAME, restPath);
425                 }
426         }
427
428         private void loadUrlProtocol(HttpServletRequest req) {
429                 // Rest URL & Protocol
430                 String restURL = "";
431                 MDC.put(EPCommonSystemProperties.FULL_URL, EPCommonSystemProperties.UNKNOWN);
432                 MDC.put(EPCommonSystemProperties.PROTOCOL, EPCommonSystemProperties.HTTP);
433                 restURL = UserUtils.getFullURL(req);
434                 //if (restURL != null && restURL != "") {
435                 if (restURL != null && restURL.trim().length()>0) {
436                         MDC.put(EPCommonSystemProperties.FULL_URL, restURL);
437                         if (restURL.toLowerCase().contains("https")) {
438                                 MDC.put(EPCommonSystemProperties.PROTOCOL, EPCommonSystemProperties.HTTPS);
439                         }
440                 }
441         }
442
443         private void loadRequestId(HttpServletRequest req) {
444                 String requestId = UserUtils.getRequestId(req);
445                 if (requestId == null||requestId.trim().length()==0) {
446                         requestId = UUID.randomUUID().toString();
447                 }
448                 MDC.put(Configuration.MDC_KEY_REQUEST_ID, requestId);
449         }
450
451         private void loadLoginId(HttpServletRequest req) {
452                 // Load loginId into MDC context.
453                 String loginId = "NoUser";
454
455                 try {
456                         EPUser user = EPUserUtils.getUserSession(req);
457                         loginId = (user != null ? user.getOrgUserId(): loginId);
458                 } catch (SessionExpiredException se) {
459                         adviceLogger.debug(EELFLoggerDelegate.debugLogger,
460                                         "setHttpRequestBasedDefaultsIntoGlobalLoggingContext: No user found in session");
461                 }
462                 
463                 // try fetching from username in header
464                 final String nameHeader = req.getHeader(EPCommonSystemProperties.USERNAME);
465                 if (nameHeader != null) {
466                         loginId = nameHeader;
467                 }
468                 
469                 // try fetching from BasicAuth info
470                 final String authHeader = req.getHeader(EPCommonSystemProperties.AUTHORIZATION);
471                 if (authHeader != null) {
472                         String[] accountNamePassword = EcompPortalUtils.getUserNamePassword(authHeader);
473                         if (accountNamePassword != null && accountNamePassword.length == 2) {
474                                 loginId = accountNamePassword[0];
475                         }
476
477                 }
478                 
479                 MDC.put(EPCommonSystemProperties.MDC_LOGIN_ID, loginId );
480
481         }
482
483         private void loadPartnerName(HttpServletRequest req) {
484                 
485
486                 // Load user agent into MDC context, if available.
487                 String accessingClient = req.getHeader(SystemProperties.USERAGENT_NAME);
488                 accessingClient = (accessingClient == null || accessingClient.trim().length()==0)?"Unknown":accessingClient;
489                 if (accessingClient != null && accessingClient.trim().length()==0 && (accessingClient.contains("Mozilla")
490                                 || accessingClient.contains("Chrome") || accessingClient.contains("Safari"))) {
491                         accessingClient = EPCommonSystemProperties.ECOMP_PORTAL_FE;
492                 }
493                 MDC.put(EPCommonSystemProperties.PARTNER_NAME, accessingClient);
494                 
495                 // try get the Partner name from uebkey
496                 String uebVal = req.getHeader(EPCommonSystemProperties.UEB_KEY);
497                 if(uebVal != null) {
498                         EPApp appRecord = appCacheService.getAppFromUeb(uebVal);
499                         MDC.put(EPCommonSystemProperties.PARTNER_NAME, appRecord.getName());
500                 }
501                 
502                 
503         }
504
505         /**
506          * 
507          * @param beginDateTime
508          * @param endDateTime
509          */
510         private void calculateDateTimeDifference(String beginDateTime, String endDateTime) {
511                 if (beginDateTime != null && endDateTime != null && !beginDateTime.isEmpty()&&!endDateTime.isEmpty()) {
512                         try {
513                                 SimpleDateFormat ecompLogDateFormat = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSSXXX");
514                                 Date beginDate = ecompLogDateFormat.parse(beginDateTime);
515                                 Date endDate = ecompLogDateFormat.parse(endDateTime);
516                                 String timeDifference = String.format("%d", endDate.getTime() - beginDate.getTime());
517                                 MDC.put(SystemProperties.MDC_TIMER, timeDifference);
518                         } catch (Exception e) {
519                                 adviceLogger.error(EELFLoggerDelegate.errorLogger, "calculateDateTimeDifference failed", e);
520                         }
521                 }
522         }
523
524         public String getInternalResponseCode() {
525                 return MDC.get(EPCommonSystemProperties.RESPONSE_CODE);
526         }
527
528 }