You are viewing a plain text version of this content. The canonical link for it is here.
Posted to jetspeed-user@portals.apache.org by Ron McNulty <rm...@xtra.co.nz> on 2009/06/29 06:50:16 UTC

Re: Getting the client IP address - Solved

Hi All

The following code gets the client IP address using reflection. Not very 
pretty, but it works fine unless you install a security manager. It will 
also break if the Jetspeed implementation undergoes a major revision. But 
for now, in the absence of anything more elegant, it works.

 public static void printRemoteAddr(RenderRequest request) {
  try {
     String remoteAddr = (String) findField(request, 
"requestContext.servletRequest.request.request.remoteAddr");
     System.out.println("Remote addr: " + remoteAddr);
  } catch (Exception e) {
     e.printStackTrace();
  }
 }

 /**
  * Find the value of a field that you normally do not have access to using 
reflection.
  * The field may have a protected, package or private access modifier.
  *
  * @param obj The object instance to start with
  * @param fieldName The name of the field in "request.remoteAddr" format
  * @return The field value
  * @throws IllegalArgumentException Field does not exist
  * @throws IllegalAccessException Security manager threw you out
  */
 public static Object findField(Object obj, String fieldName)
  throws IllegalArgumentException, IllegalAccessException {
    // Step through the path to the field
   String[] tokens = fieldName.split("\\.");
    for (String token : tokens) {
       // Iterate up the inheritance hierarchy
       boolean found = false;
       Class<?> clazz = obj.getClass();
       while (clazz != null && !found) {
       try {
          Field field = clazz.getDeclaredField(token);
          found = true;
          field.setAccessible(true);
          obj = field.get(obj);
      } catch (NoSuchFieldException nsfex) {
        clazz = clazz.getSuperclass();
      }
    }
    if (!found)
     throw new IllegalArgumentException(token + " is not a field in class " 
+ obj.getClass().getName());
  }
   return obj;
 }



---------------------------------------------------------------------
To unsubscribe, e-mail: jetspeed-user-unsubscribe@portals.apache.org
For additional commands, e-mail: jetspeed-user-help@portals.apache.org