tomcat-users mailing list archives

Site index · List index
Message view « Date » · « Thread »
Top « Date » · « Thread »
From Christopher Schultz <ch...@christopherschultz.net>
Subject Re: How do I create and re-create an object for the entire application?
Date Thu, 20 Jul 2006 21:42:39 GMT
To whom it may concern,

> ClientServices cs =
> com.mycompany.searchapp.ClientServicesFactory.getInstance("RMI",
> parms); // Get the ClientServices
> cs.Login(strDomain, strUser, strPassword); // Login

I assume you put this thing into the application scope, so that your
code can get to it at some point, yes?

> But, the login will expire after 30 minutes and I cannot change that.
> 
> How do I recreate the login after it expires?

What is the usage pattern for this object? Do you fetch it, and then do
something to it (like query it for information)? Assuming that is the
case, you could wrap your object in a helper object that does something
like this:

public synchronized Object getSomeData(...)
{
    if(!cs.isConnected())
    {
         // Do whatever needs to be done to re-connect
    }

    return cs.getSomeData();
}

This is even easier if ClientServices is an interface, 'cause you can
create a new class that implements that interface and wraps an object of
the same type:

public class ClientServicesWrapper
    implements ClientServices
{
    private ClientServices _cs;

    public ClientServicesWrapper(ClientServices cs)
    {
        _cs = cs;
    }

    public synchronized Object getSomeData(...)
    {
        if(!_cs.isConnected())
        {
             // Do whatever needs to be done to re-connect
        }

        return _cs.getSomeData();
    }

    // Implement the remaining methods in a similar way
}

But the Coup de Gras is using Java's Proxy stuff to save typing and look
like a 1337 h4x0r in front of all your friends:

import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Proxy;

// ...

ClientServices cs = // get from RMI
ClientServices wrapper = (ClientServices)Proxy.newProxyInstance(
                 ClientServices.class.getClassLoader(),
                 new Class[] { ClientServices.class },
                 new ClientServicesWrapper(cs)
                 );

// ...

public class ClientServicesWrapper
    implements InvocationHandler
{
    private ClientServices _cs;

    public ClientServicesWrapper(ClientServices cs)
    {
        _cs = cs;
    }

    public Object invoke(Object proxy, Method method, Object[] args)
        throws Throwable
    {
        if(!_cs.isConnected())
        {
            // reconnect the _cs object
        }

        method.invoke(_cs, args);
    }
}

How sexy is /that/?

Hope that helps. At least it was a pretty good example of using Java
proxies ;)

-chris


Mime
View raw message