sexta-feira, 10 de outubro de 2008

Exemplo de ServiceLocator

import java.util.Properties;
import javax.naming.Context;
import javax.naming.InitialContext;
import javax.naming.NamingException;

/**
*
* @author Administrador
*/
public class ServiceLocator {

private InitialContext initialContext;
private static ServiceLocator locator;

/** Creates a new instance of ServiceLocator */
public ServiceLocator() throws Exception {
try {
Properties prop = new Properties();
prop.put(Context.INITIAL_CONTEXT_FACTORY, "org.jnp.interfaces.NamingContextFactory");
prop.put(Context.URL_PKG_PREFIXES, "org.jboss.naming:org.jnp.interfaces");
prop.put(Context.PROVIDER_URL, "localhost");

initialContext = new InitialContext(prop);

} catch (Exception e) {
e.printStackTrace();
}
}

public ServiceLocator(String url) throws Exception {
try {
Properties prop = new Properties();
prop.put(Context.INITIAL_CONTEXT_FACTORY, "org.jnp.interfaces.NamingContextFactory");
prop.put(Context.URL_PKG_PREFIXES, "org.jboss.naming:org.jnp.interfaces");
prop.put(Context.PROVIDER_URL, url);

initialContext = new InitialContext(prop);

} catch (Exception e) {
e.printStackTrace();
}
}

public static ServiceLocator getInstance() throws Exception {
if (locator == null) {
locator = new ServiceLocator();
}
return locator;
}

protected Object clone() throws CloneNotSupportedException {
throw new CloneNotSupportedException("Não é possível clonar o Service Locator");
}

public Object get(String jndiName) throws Exception {
try {
Object result = null;
result = initialContext.lookup(jndiName);

if (result == null) {
throw new NamingException("Erro ao se comunicar com serviço EJB!");
}

return result;

} catch (NamingException ne) {
ne.printStackTrace();
}

return null;
}
}


Vc usa assim:

Object ref = ServiceLocator.getInstance().get("SuaClasseBean/remote");
seuBeanRemote = (SuaInterfaceRemote) PortableRemoteObject.narrow(ref, SuaInterfaceRemote.class);

seuBeanRemote.seuMetodo();

Nenhum comentário: