Te paso el código de ConexionBD.java
package Pconexion;
import java.io.Serializable;
import java.sql.Connection;
import java.sql.SQLException;
import javax.naming.InitialContext;
import javax.sql.DataSource;
import org.apache.log4j.Logger;
public class ConexionBD
implements Serializable
{
private ConexionBD()
{
oracle = null;
ds = null;
numConexiones = 0;
}
public static ConexionBD getConexionBD()
{
logger.debug("getConexionBD");
miConexion = new ConexionBD();
return miConexion;
}
public Connection getConexionSQL()
{
logger.debug("getConexionSQL");
if(ds == null)
try
{
initialContext = new InitialContext();
ds = (DataSource)initialContext.lookup("jdbc/ptoventaDS");
logger.debug("-------------se conecto con el ptoventaDS--------------" + nomBean);
}
catch(Exception e)
{
logger.error("Error Datasource ptoventa ", e);
}
if(oracle != null)
{
try
{
if(!oracle.isClosed())
{
Connection connection = oracle;
return connection;
} else
{
numConexiones++;
logger.debug("************ nueva conexion (ptoventa) ******" + numConexiones + nomBean);
oracle = ds.getConnection();
Connection connection1 = oracle;
return connection1;
}
}
catch(Exception e)
{
logger.error("Se produjo un error al obtener otra conexion para ptoventa) ", e);
}
oracle = null;
} else
{
try
{
oracle = ds.getConnection();
logger.debug("***************Conexion Exitosa (ptoventa)******************");
}
catch(Exception e)
{
logger.error("Se produjo un error al intentar conectar(ptoventa) ", e);
oracle = null;
Connection connection2 = null;
return connection2;
}
}
return oracle;
}
public void delConexionSQL()
{
logger.debug("delConexionSQL");
if(oracle == null)
return;
try
{
oracle.close();
logger.debug("/////////////////se cerro la conexion ptoventa: ->////////////////");
}
catch(Exception e)
{
logger.error("Se produjo un error al Cerrar la conexion(ptoventa) ", e);
}
oracle = null;
}
public void imprimeMensaje(String aMessage)
{
logger.info(aMessage);
}
public void imprimeMensajeError(String aMessage, Exception e)
{
logger.error(aMessage, e);
}
public void imprimeMensajeError(String aMessage)
{
logger.error(aMessage);
}
public void iniTransaccion()
{
try
{
getConexionSQL().setAutoCommit(false);
}
catch(SQLException e)
{
logger.error("No fue posible iniciar la transacci\363n. ", e);
}
}
public void commit()
{
try
{
getConexionSQL().commit();
getConexionSQL().setAutoCommit(true);
}
catch(SQLException e)
{
logger.error("No fue posible dar commit. ", e);
}
}
public void rollback()
{
try
{
getConexionSQL().rollback();
getConexionSQL().setAutoCommit(true);
}
catch(SQLException e)
{
logger.error("No fue posible dar rollback. ", e);
}
}
public void setNomBean(String nombre)
{
nomBean = nombre;
}
public boolean existeConexion()
{
if(oracle == null)
return false;
try
{
boolean flag = !oracle.isClosed();
return flag;
}
catch(SQLException e)
{
logger.error("Error en existeConexion " + nomBean, e);
}
boolean flag1 = false;
return flag1;
}
static Logger logger = Logger.getLogger(Class.forName("Pconexion.ConexionBD").getName());
private Connection oracle;
private InitialContext initialContext;
private DataSource ds;
private static ConexionBD miConexion;
private int numConexiones;
private String nomBean;
}
Y el código para obtener la sesión RMI
package Pconexion;
import Pactores.Estructuras.EstBuscaDatosUsuario;
import Pbean.Documentacion.*;
import Pcatalogos.SesionException;
import Pframes.SwingWorker;
import java.io.PrintStream;
import java.rmi.RemoteException;
import java.util.*;
import javax.ejb.EJBObject;
import javax.ejb.RemoveException;
import javax.naming.Context;
import javax.naming.InitialContext;
import javax.rmi.PortableRemoteObject;
import org.apache.log4j.Logger;
public class ConexionSADocumentacion
{
private static class ConexionTask
implements Runnable
{
public void run()
{
try
{
ConexionSADocumentacion.logger.debug("Conectando...");
initialContextTmp = new InitialContext(ConexionSADocumentacion.env);
ConexionSADocumentacion.logger.info("Conectado!");
b_initial = true;
ConexionSADocumentacion.threadMessage((String)ConexionSADocumentacion.env.get("java.naming.provider.url"));
}
catch(Exception e)
{
ConexionSADocumentacion.threadMessage("Error al intentar establecer la conexion!");
ConexionSADocumentacion.logger.error(e.getMessage(), e);
b_initial = false;
initialContextTmp = null;
}
}
public Context getContext()
{
return initialContextTmp;
}
public boolean isInicializado()
{
return b_initial;
}
private Context initialContextTmp;
private boolean b_initial;
ConexionTask()
{
initialContextTmp = null;
b_initial = false;
}
}
public ConexionSADocumentacion()
{
myRemoteNacionalInstance = null;
myRemoteOtrosInstance = null;
myRemoteRDDInstance = null;
}
public RemoteDocumentacionNacional getSesionNacional()
throws SesionException
{
return getSesionNacional(null);
}
public RemoteDocumentacionNacional getSesionNacional(EstBuscaDatosUsuario usuario)
{
if(myRemoteNacionalInstance != null)
try
{
if(!enableEcho)
{
RemoteDocumentacionNacional remotedocumentacionnacional = myRemoteNacionalInstance;
return remotedocumentacionnacional;
}
if("Documentacion Nacional".equals(myRemoteNacionalInstance.echoAlive("Documentacion Nacional")))
{
RemoteDocumentacionNacional remotedocumentacionnacional1 = myRemoteNacionalInstance;
return remotedocumentacionnacional1;
}
}
catch(RemoteException re)
{
if(enableEcho)
{
if("Session has timed out".indexOf(re.getMessage()) == -1)
logger.error("Sesion invalida" + re.getMessage(), re);
} else
{
try
{
myRemoteNacionalInstance.remove();
}
catch(RemoveException ree)
{
myRemoteNacionalInstance = null;
}
catch(RemoteException rme)
{
myRemoteNacionalInstance = null;
}
finally
{
myRemoteNacionalInstance = null;
}
}
logger.warn("Creando nuevamente la sesion...");
}
try
{
String name = "DocumentacionNacional";
initialContext = instanciaContexto(initialContext);
HomeDocumentacionNacional myHome = (HomeDocumentacionNacional)PortableRemoteObject.narrow(initialContext.lookup(serviceURL + name), Class.forName("Pbean.Documentacion.HomeDocumentacionNacional"));
logger.debug("Creando Sesion " + name + "...");
myRemoteNacionalInstance = myHome.create();
logger.debug("Sesion " + name + " creada");
myRemoteNacionalInstance.inicio(usuario);
myRemoteNacionalInstance.setNonBean("Nacional");
}
catch(Exception e)
{
logger.error("Error en ConexionSADocumentacion.getSesionNacional " + e.getMessage(), e);
myRemoteNacionalInstance = null;
}
return myRemoteNacionalInstance;
}
public static RemoteDocumentacionNacional getSesionNacionalStatic(EstBuscaDatosUsuario usuario)
{
if(myRemoteNacional != null)
try
{
if(!enableEcho)
{
RemoteDocumentacionNacional remotedocumentacionnacional = myRemoteNacional;
return remotedocumentacionnacional;
}
if("Documentacion Nacional".equals(myRemoteNacional.echoAlive("Documentacion Nacional")))
{
RemoteDocumentacionNacional remotedocumentacionnacional1 = myRemoteNacional;
return remotedocumentacionnacional1;
}
}
catch(RemoteException re)
{
if(enableEcho)
{
if("Session has timed out".indexOf(re.getMessage()) == -1)
logger.error("Sesion invalida" + re.getMessage(), re);
} else
{
try
{
myRemoteNacional.remove();
}
catch(RemoveException ree)
{
myRemoteNacional = null;
}
catch(RemoteException rme)
{
myRemoteNacional = null;
}
finally
{
myRemoteNacional = null;
}
}
logger.warn("Creando nuevamente la sesion...");
}
try
{
String name = "DocumentacionNacional";
initialContext = instanciaContexto(initialContext);
HomeDocumentacionNacional myHome = (HomeDocumentacionNacional)PortableRemoteObject.narrow(initialContext.lookup(serviceURL + name), Class.forName("Pbean.Documentacion.HomeDocumentacionNacional"));
logger.debug("Creando Sesion " + name + "...");
myRemoteNacional = myHome.create();
logger.debug("Sesion " + name + " creada");
myRemoteNacional.inicio(usuario);
myRemoteNacional.setNonBean("Nacional");
}
catch(Exception e)
{
logger.error("Error en ConexionSADocumentacion.getSesionNacional " + e.getMessage(), e);
myRemoteNacional = null;
}
return myRemoteNacional;
}
public RemoteDocumentacionOtros getSesionOtros()
throws SesionException
{
return getSesionOtros(null);
}
public RemoteDocumentacionOtros getSesionOtros(EstBuscaDatosUsuario usuario)
{
if(myRemoteOtrosInstance != null)
try
{
if(!enableEcho)
{
RemoteDocumentacionOtros remotedocumentacionotros = myRemoteOtrosInstance;
return remotedocumentacionotros;
}
if("Documentacion Otros".equals(myRemoteOtrosInstance.echoAlive("Documentacion Otros")))
{
RemoteDocumentacionOtros remotedocumentacionotros1 = myRemoteOtrosInstance;
return remotedocumentacionotros1;
}
}
catch(RemoteException re)
{
if(enableEcho)
{
if("Session has timed out".indexOf(re.getMessage()) == -1)
logger.error("Sesion invalida" + re.getMessage(), re);
} else
{
try
{
myRemoteOtrosInstance.remove();
}
catch(RemoveException ree)
{
myRemoteOtrosInstance = null;
}
catch(RemoteException rme)
{
myRemoteOtrosInstance = null;
}
finally
{
myRemoteOtrosInstance = null;
}
}
logger.warn("Creando nuevamente la sesion...");
}
try
{
String name = "DocumentacionOtros";
initialContext = instanciaContexto(initialContext);
HomeDocumentacionOtros myHome = (HomeDocumentacionOtros)PortableRemoteObject.narrow(initialContext.lookup(serviceURL + name), Class.forName("Pbean.Documentacion.HomeDocumentacionOtros"));
logger.debug("Creando Sesion " + name);
myRemoteOtrosInstance = myHome.create();
myRemoteOtrosInstance.inicio(usuario);
myRemoteOtrosInstance.setNonBean("Otros");
}
catch(Exception e)
{
logger.error("Error en ConexionSA.getSesionOtros " + e.getMessage(), e);
myRemoteOtrosInstance = null;
}
return myRemoteOtrosInstance;
}
public static RemoteDocumentacionOtros getSesionOtrosStatic(EstBuscaDatosUsuario usuario)
{
if(myRemoteOtros != null)
try
{
if(!enableEcho)
{
RemoteDocumentacionOtros remotedocumentacionotros = myRemoteOtros;
return remotedocumentacionotros;
}
if("Documentacion Otros".equals(myRemoteOtros.echoAlive("Documentacion Otros")))
{
RemoteDocumentacionOtros remotedocumentacionotros1 = myRemoteOtros;
return remotedocumentacionotros1;
}
}
catch(RemoteException re)
{
if(enableEcho)
{
if("Session has timed out".indexOf(re.getMessage()) == -1)
logger.error("Sesion invalida" + re.getMessage(), re);
} else
{
try
{
myRemoteOtros.remove();
}
catch(RemoveException ree)
{
myRemoteOtros = null;
}
catch(RemoteException rme)
{
myRemoteOtros = null;
}
finally
{
myRemoteOtros = null;
}
}
logger.warn("Creando nuevamente la sesion...");
}
try
{
String name = "DocumentacionOtros";
initialContext = instanciaContexto(initialContext);
HomeDocumentacionOtros myHome = (HomeDocumentacionOtros)PortableRemoteObject.narrow(initialContext.lookup(serviceURL + name), Class.forName("Pbean.Documentacion.HomeDocumentacionOtros"));
logger.debug("Creando Sesion " + name);
myRemoteOtros = myHome.create();
myRemoteOtros.inicio(usuario);
myRemoteOtros.setNonBean("Otros");
}
catch(Exception e)
{
logger.error("Error en ConexionSA.getSesionOtros " + e.getMessage(), e);
myRemoteOtros = null;
}
return myRemoteOtros;
}
public RemoteRDD getSesionRDD()
{
if(myRemoteRDDInstance != null)
try
{
if(!enableEcho)
{
RemoteRDD remoterdd = myRemoteRDDInstance;
return remoterdd;
}
if("RDD".equals(myRemoteRDDInstance.echoAlive("RDD")))
{
RemoteRDD remoterdd1 = myRemoteRDDInstance;
return remoterdd1;
}
}
catch(RemoteException re)
{
if(enableEcho)
{
if("Session has timed out".indexOf(re.getMessage()) == -1)
logger.error("Sesion invalida" + re.getMessage(), re);
} else
{
try
{
myRemoteRDDInstance.remove();
}
catch(RemoveException ree)
{
myRemoteRDDInstance = null;
}
catch(RemoteException rme)
{
myRemoteRDDInstance = null;
}
finally
{
myRemoteRDDInstance = null;
}
}
logger.warn("Creando nuevamente la sesion...");
}
try
{
String name = "SesionRDD";
initialContext = instanciaContexto(initialContext);
HomeRDD myHome = (HomeRDD)PortableRemoteObject.narrow(initialContext.lookup(serviceURL + name), Class.forName("Pbean.Documentacion.HomeRDD"));
logger.debug("Creando Sesion " + name);
myRemoteRDDInstance = myHome.create();
}
catch(Exception e)
{
logger.error("Error en ConexionSA.getSesionRDD " + e.getMessage(), e);
myRemoteRDDInstance = null;
}
return myRemoteRDDInstance;
}
public static RemoteRDD getSesionRDDStatic()
{
if(myRemoteRDD != null)
try
{
if(!enableEcho)
{
RemoteRDD remoterdd = myRemoteRDD;
return remoterdd;
}
if("RDD".equals(myRemoteRDD.echoAlive("RDD")))
{
RemoteRDD remoterdd1 = myRemoteRDD;
return remoterdd1;
}
}
catch(RemoteException re)
{
if(enableEcho)
{
if("Session has timed out".indexOf(re.getMessage()) == -1)
logger.error("Sesion invalida" + re.getMessage(), re);
} else
{
try
{
myRemoteRDD.remove();
}
catch(RemoveException ree)
{
myRemoteRDD = null;
}
catch(RemoteException rme)
{
myRemoteRDD = null;
}
finally
{
myRemoteRDD = null;
}
}
logger.warn("Creando nuevamente la sesion...");
}
try
{
String name = "SesionRDD";
initialContext = instanciaContexto(initialContext);
HomeRDD myHome = (HomeRDD)PortableRemoteObject.narrow(initialContext.lookup(serviceURL + name), Class.forName("Pbean.Documentacion.HomeRDD"));
logger.debug("Creando Sesion " + name);
myRemoteRDD = myHome.create();
}
catch(Exception e)
{
logger.error("Error en ConexionSA.getSesionRDD " + e.getMessage(), e);
myRemoteRDD = null;
}
return myRemoteRDD;
}
public void cierraSesiones()
{
logger.debug("cierraSesiones");
if(myRemoteNacionalInstance != null)
{
cierraSesion(myRemoteNacionalInstance);
myRemoteNacionalInstance = null;
}
if(myRemoteOtrosInstance != null)
{
cierraSesion(myRemoteOtrosInstance);
myRemoteOtrosInstance = null;
}
if(myRemoteRDDInstance != null)
{
cierraSesion(myRemoteRDDInstance);
myRemoteRDDInstance = null;
}
}
public void cierraSesionesStatic()
{
logger.debug("cierraSesiones");
if(myRemoteNacional != null)
{
cierraSesion(myRemoteNacional);
myRemoteNacional = null;
}
if(myRemoteOtros != null)
{
cierraSesion(myRemoteOtros);
myRemoteOtros = null;
}
if(myRemoteRDD != null)
{
cierraSesion(myRemoteRDD);
myRemoteRDD = null;
}
}
public static void cierraSesion(EJBObject sesion)
{
logger.debug("cierraSesion");
if(sesion == null)
return;
try
{
sesion.remove();
}
catch(RemoveException e)
{
logger.error("Error al cerrar la sesion. ", e);
}
catch(RemoteException re)
{
if(re.getMessage().indexOf("Session has timed out") <= -1)
logger.error("Error en el servidor. " + re);
}
finally
{
sesion = null;
}
}
public void finalize()
throws Throwable
{
logger.debug("finalize");
cierraSesiones();
super.finalize();
}
public static void setHostName(String aName)
{
hostName = aName;
}
public static String getHostName()
{
return hostName;
}
public static void removeSesion(EJBObject pSessionBean)
{
try
{
pSessionBean.remove();
}
catch(Exception e)
{
logger.error("Error en removeSesion:" + e.getMessage(), e);
}
}
private static Context instanciaContexto(Context contextoInicial)
throws Exception
{
if(contextoInicial != null)
return contextoInicial;
Context contexto = null;
String initialFactory = null;
hostName = getCadenaCompleta(hostName);
String usuario = null;
String password = null;
try
{
env = new Hashtable();
if(hostName != null && hostName.indexOf("localhost") == -1)
{
initialFactory = "com.evermind.server.ApplicationClientInitialContextFactory";
usuario = "appuser";
password = "app123";
} else
{
initialFactory = "com.evermind.server.rmi.RMIInitialContextFactory";
hostName = "ormi://localhost:23891/current-workspace-app";
usuario = "admin";
password = "welcome";
serviceURL = "";
}
env.put("java.naming.factory.initial", initialFactory);
env.put("java.naming.provider.url", hostName);
env.put("java.naming.security.principal", usuario);
env.put("java.naming.security.credentials", password);
long esperaMaxima = 9L;
int reintentos = 3;
long retardoEntreMensajeEspera = 3L;
threadMessage("Iniciando Tarea de Conexion");
int intento = 0;
ConexionTask tareaConexion = null;
do
{
long startTime = System.currentTimeMillis();
if(hostName.indexOf(',') == -1)
{
if(!logger.isDebugEnabled())
System.out.println("url: " + env.get("java.naming.provider.url") + "/" + serviceURL);
else
logger.debug("url: " + env.get("java.naming.provider.url") + "/" + serviceURL);
} else
if(!logger.isDebugEnabled())
System.out.println("url: " + env.get("java.naming.provider.url") + " - " + serviceURL);
else
logger.debug("url: " + env.get("java.naming.provider.url") + " - " + serviceURL);
tareaConexion = new ConexionTask();
Thread t = new Thread(tareaConexion);
threadMessage("Esperando una conexion valida...");
t.start();
threadMessage("Esperando una conexion valida...");
do
{
if(!t.isAlive() || t.isInterrupted())
break;
logger.info("Esperando respuesta conexion... ");
t.join(retardoEntreMensajeEspera * (long)1000);
if(System.currentTimeMillis() - startTime > esperaMaxima * (long)1000 && t.isAlive())
{
threadMessage("Tiempo de espera excedido!");
t.interrupt();
logger.debug("Espera de conexion excedio el tiempo limite.");
}
} while(true);
threadMessage("Finalizada!");
intento++;
b_initial = tareaConexion.isInicializado();
if(b_initial)
{
threadMessage("Conexion Establecida!");
contexto = tareaConexion.getContext();
logger.error("Tiempo Conexion: " + (System.currentTimeMillis() - startTime));
} else
{
logger.debug("Estableciendo nueva cadena de conexion...");
env.put("java.naming.provider.url", suffleServers((String)env.get("java.naming.provider.url")));
}
} while(intento < reintentos && !b_initial);
if(!b_initial)
logger.warn("No se puedo obtener una conexion valida!");
}
catch(Exception e)
{
logger.error(e.getMessage(), e);
throw new Exception("Error al inicializar el contexto. " + e.getMessage());
}
return contexto;
}
static String getCadenaCompleta(String hostName)
{
String cadena = "";
int indiceInicio = 0;
do
{
int indiceFin = hostName.indexOf(',', indiceInicio + 1);
if(indiceFin == -1)
{
cadena = cadena + (hostName.substring(indiceInicio) + "Documentacion");
break;
}
cadena = cadena + (hostName.substring(indiceInicio, indiceFin) + "Documentacion");
indiceInicio = indiceFin;
} while(true);
return cadena;
}
private static String suffleServers(String url)
{
logger.debug("suffleServers");
if(url == null)
return null;
boolean lookupEnable = false;
if(url.indexOf("lookup:") > -1)
lookupEnable = true;
if(lookupEnable)
url = url.substring(url.indexOf("lookup:") + "lookup:".length(), url.length());
Vector servidores = new Vector();
String servidor;
for(; url.indexOf(",") > -1 || url.length() > 0; servidores.add(servidor))
{
servidor = "";
if(url.indexOf(",") > -1)
{
servidor = url.substring(0, url.indexOf(","));
url = url.substring(url.indexOf(",") + 1, url.length());
} else
{
servidor = url;
url = "";
}
}
Random ran = new Random();
do
{
int seleccion = ran.nextInt(servidores.size());
if(seleccion < servidores.size())
{
if(url.length() == 0)
{
if(lookupEnable)
url = "lookup:";
url = url + (String)servidores.get(seleccion);
} else
{
url = url + ("," + (String)servidores.get(seleccion));
}
servidores.remove(seleccion);
}
} while(servidores.size() > 0);
logger.debug("new URL: " + url);
return url;
}
static void threadMessage(String message)
{
String threadName = Thread.currentThread().getName();
logger.debug(threadName + " : " + message);
}
static Logger logger = Logger.getLogger(Class.forName("Pconexion.ConexionSADocumentacion").getName());
protected static String hostName = "";
protected static String serviceURL = "java:comp/env/ejb/";
protected static Context initialContext = null;
private RemoteDocumentacionNacional myRemoteNacionalInstance;
private RemoteDocumentacionOtros myRemoteOtrosInstance;
private RemoteRDD myRemoteRDDInstance;
private static RemoteDocumentacionNacional myRemoteNacional = null;
private static RemoteDocumentacionOtros myRemoteOtros = null;
private static RemoteRDD myRemoteRDD = null;
private static boolean enableEcho = true;
private static boolean b_initial = false;
protected static SwingWorker worker = null;
protected static Hashtable env = null;
}