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