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/27 07:24:45 UTC

Getting the client IP address

Hi All

We have a requirement that all calls to our back-end systems must include the user's IP address for auditing purposes. Some of these calls occur before the portlet is rendered, so there are limits on the possible solutions. The code needs to work for both authenticated and unauthenticated pages.

In Jetspeed 2.1 I could obtain the user's IP with a short section of code that was not JSR 168 compliant, but worked. Surprisingly it worked without modification on IBM Websphere portal server as well.

But it breaks on Jetspeed 2.2. Before I start hacking, has anyone got an existing solution?

Regards

Ron

Re: Getting the client IP address - Solved

Posted by Ron McNulty <rm...@xtra.co.nz>.
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