Created
March 1, 2017 15:27
-
-
Save svaponi/aa4d077f00e9217024f1c040b21debd6 to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
package it.miriade.commons.web.utils; | |
import java.util.Arrays; | |
import java.util.Enumeration; | |
import java.util.HashSet; | |
import java.util.Set; | |
import javax.servlet.http.HttpServletRequest; | |
import org.apache.commons.lang3.StringUtils; | |
public class DetectClientInfoUtil { | |
public static final String[] CLIENT_IP_HEADERS = { "X-FORWARDED-FOR", "VIA", "PROXY-CLIENT-IP", "WL-PROXY-CLIENT-IP", "HTTP_X_FORWARDED_FOR", "HTTP_X_FORWARDED", "HTTP_X_CLUSTER_CLIENT_IP", "HTTP_CLIENT_IP", "HTTP_FORWARDED_FOR", | |
"HTTP_FORWARDED", "HTTP_VIA", "REMOTE_ADDR" }; | |
private static final Set<String> LOCALHOST_IPs = new HashSet<String>(Arrays.asList(new String[] { "0:0:0:0:0:0:0:1", "127.0.0.1" })); | |
public static final String COOKIE_HEADER = "cookie"; | |
public static final String COOKIE_HEADER_JSESSIONID = "JSESSIONID"; | |
/** | |
* Ritorna IP address del client | |
* | |
* @param request | |
* @return | |
*/ | |
public static String getClientIpAddress(HttpServletRequest request) { | |
String ip; | |
for (String header : CLIENT_IP_HEADERS) { | |
ip = request.getHeader(header); | |
if (StringUtils.isNotBlank(ip) && !"unknown".equalsIgnoreCase(ip)) { | |
return ip; | |
} | |
} | |
ip = request.getRemoteAddr(); | |
if (LOCALHOST_IPs.contains(ip)) | |
ip = request.getServerName(); | |
return ip; | |
} | |
/** | |
* Ritorna un ID identificativo della sessione | |
* | |
* @param request | |
* @return | |
*/ | |
public static String getClientId(HttpServletRequest request) { | |
String id = request.getRequestedSessionId(); | |
if (StringUtils.isNotBlank(id)) | |
return id; | |
id = getCookieJSessionID(request); | |
if (StringUtils.isNotBlank(id)) | |
return id; | |
return ""; | |
} | |
/** | |
* Ritorna un ID identificativo della sessione prendendolo dai cookies | |
* | |
* @param request | |
* @return | |
*/ | |
public static String getCookieJSessionID(HttpServletRequest request) { | |
Enumeration<String> enumeration = request.getHeaderNames(); | |
while (enumeration.hasMoreElements()) { | |
String temp = enumeration.nextElement(); | |
String header = request.getHeader(temp); | |
if (COOKIE_HEADER.equalsIgnoreCase(temp)) | |
try { | |
for (String cookie : header.split(";")) | |
if (cookie.split("=")[0].trim().equalsIgnoreCase(COOKIE_HEADER_JSESSIONID)) | |
return cookie.split("=")[1]; | |
} catch (Exception e) { | |
} | |
} | |
return ""; | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment