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