Hello Tomcat world users. This is the reply for all people who replies me. 
Thank you all. My apologies if the english i write sounds "rude", but i am not 
very good with english or Tomcat neither :D
---------------------
I speak spanish, so don't be mad with me, specially Antonio Petrelli.
----------------------
Answering to Hassan Schroeder: Thanks for your answer Hassan.
Specifying when and how Tomcat doesn't work for me:

1) The servlet loading problem happens when I startup Tomcat, manually, as I 
always do, showing the exception:

java.lang.NoClassDefFoundError: javax/servlet/http/HttpServlet
    java.lang.ClassLoader.defineClass1(Native Method)
    java.lang.ClassLoader.defineClass(ClassLoader.java:620)

    java.security.SecureClassLoader.defineClass(SecureClassLoader.java:124)
    java.net.URLClassLoader.defineClass(URLClassLoader.java:260)
    java.net.URLClassLoader.access$000(URLClassLoader.java:56)
    java.net.URLClassLoader$1.run(URLClassLoader.java:195)

    java.security.AccessController.doPrivileged(Native Method)
    java.net.URLClassLoader.findClass(URLClassLoader.java:188)
    java.lang.ClassLoader.loadClass(ClassLoader.java:306)
    sun.misc.Launcher$AppClassLoader.loadClass(Launcher.java:276)

    java.lang.ClassLoader.loadClass(ClassLoader.java:251)
    
org.apache.catalina.loader.WebappClassLoader.loadClass(WebappClassLoader.java:1273)
    
org.apache.catalina.loader.WebappClassLoader.loadClass(WebappClassLoader.java:1204)

    
org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:102)
    org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:263)
    org.apache.coyote.http11.Http11Processor.process(Http11Processor.java:844)

    
org.apache.coyote.http11.Http11Protocol$Http11ConnectionHandler.process(Http11Protocol.java:584)
    org.apache.tomcat.util.net.JIoEndpoint$Worker.run(JIoEndpoint.java:447)
    java.lang.Thread.run(Thread.java:619)

And when I shutdown Tomcat and then startup it again, only sometimes my servlet 
is loaded. In other times, Tomcat load my servlet perfectly, just doing the 
same.

2) When the first problem does not happen, the http session works unproperly, 
and some attributes of the session are made null, in this case, Tomcat throws 
the NullPointerException, but if I reload the jsp everything is ok.

Files with the source code of the servlet (Login.java), a jsp and the 
connection class (works in a package called peerca) are attached.
---------------------------------
Answering now to Matthew Chamber, and giving thanks for the reply:
1) About the web.xml: I include the web.xml file in the attachments. 
2) About an earlier Tomcat: I just downloaded the 6.0.18 version and 
catalina.sh it's running ok (but I have not put my webapp there yet). 
3) About the db2 jdbc driver, well, it is allocated in many paths... 

JAVA_HOME/jdk/jre/lib/ext/db2jcc.jar
CATALINA_HOME/lib/db2jcc.jar
CATALINA_HOME/webapps/cqaex/db2jcc.jar
CATALINA_HOME/webapps/peerca/WEB-INF/lib/db2jcc.jar
DB2_HOME/V9.5/java/db2jcc.jar

¿Can this cause troubles? Where exactly I need to put this file, taking into 
account I need driver be avalaible for other java aplications, not only for 
tomcat webapps?

4) About using war file: I am not using any war file, I just use the folder 
with the name of the app put it into webapps.
5) About running Tomcat as root user: can this cause troubles too? Do I need to 
running it as the common user? What kind of properties (chmod) does the 
CATALINA_HOME need to work in many users without running as a root?
----------------------------------------------------

Answering David Smith: thanks for the reply. I am using the binary version 
6.0.14 available on Tomcat website, but Matthew recommended me to use an 
earlier one, the 6.0.18. This one I will use from now go on. I am not using any 
Eclipse, I just write manually my codes and the follow the folder structure of 
a webapp into webapps folder. Servlet api is where you said, as always does: 
into CATALINA_HOME/lib.

About the nulls: yes, I already check for null values before use it, but is 
like the session delete it from nowhere, without reasons. 

---------------------------------------

Now I just try with the 6.0.18 and I will put my webapp there. The only error 
is with DB2 connections, although the session has the connection, this is not 
null but when i tried to list the tables some error happens:
------------------
com.ibm.db2.jcc.b.nm: DB2 SQL Error: SQLCODE=-204, SQLSTATE=42704, 
SQLERRMC=DB2INST1.AM_BASE_TASKS, DRIVER=3.50.152
        at com.ibm.db2.jcc.b.wc.a(wc.java:579)
        at com.ibm.db2.jcc.b.wc.a(wc.java:57)
        at com.ibm.db2.jcc.b.wc.a(wc.java:126)
        at com.ibm.db2.jcc.b.tk.c(tk.java:1901)
        at com.ibm.db2.jcc.b.tk.d(tk.java:1889)
        at com.ibm.db2.jcc.b.tk.a(tk.java:1416)
        at com.ibm.db2.jcc.t4.db.g(db.java:138)
        at com.ibm.db2.jcc.t4.db.a(db.java:38)
        at com.ibm.db2.jcc.t4.t.a(t.java:32)
        at com.ibm.db2.jcc.t4.sb.h(sb.java:141)
        at com.ibm.db2.jcc.b.tk.N(tk.java:1387)
        at com.ibm.db2.jcc.b.tk.a(tk.java:2215)
        at com.ibm.db2.jcc.b.tk.e(tk.java:866)
        at com.ibm.db2.jcc.b.tk.execute(tk.java:850)
        at peerca.Conexion.setResultado(Conexion.java:354)
        at peerca.Conexion.getTablas(Conexion.java:802)
        at org.apache.jsp.peericadd_jsp._jspService(peericadd_jsp.java:160)
        at org.apache.jasper.runtime.HttpJspBase.service(HttpJspBase.java:70)
        at javax.servlet.http.HttpServlet.service(HttpServlet.java:717)
        at 
org.apache.jasper.servlet.JspServletWrapper.service(JspServletWrapper.java:374)
        at 
org.apache.jasper.servlet.JspServlet.serviceJspFile(JspServlet.java:342)
        at org.apache.jasper.servlet.JspServlet.service(JspServlet.java:267)
        at javax.servlet.http.HttpServlet.service(HttpServlet.java:717)
        at 
org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:290)
        at 
org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:206)
        at 
org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:233)
        at 
org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:191)
        at 
org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:128)
        at 
org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:102)
        at 
org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:109)
        at 
org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:286)
        at 
org.apache.coyote.http11.Http11Processor.process(Http11Processor.java:845)
        at 
org.apache.coyote.http11.Http11Protocol$Http11ConnectionHandler.process(Http11Protocol.java:583)
        at 
org.apache.tomcat.util.net.JIoEndpoint$Worker.run(JIoEndpoint.java:447)
        at java.lang.Thread.run(Thread.java:619)
-----------
and this error did not happen in the older version... any ideas? Where the 
db2jcc.jar needs to be, to be available for all my applications in java (not 
only in Tomcat).


The idea I have is to create a pool of connections. I read the concept but now 
I need to implement it. Is Tomcat deal with the pool or I need to ask help in 
DB2 forums ?
If anybody know how to create a pooling, please reply.

Thanks for all your help. Best regards,

Ariela



      Premios MTV 2008¡En exclusiva! Fotos, nominados, videos, y mucho más! 
Mira aquí http://mtvla.yahoo.com/
import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;
import peerca.Conexion;
import java.sql.SQLException;
import java.lang.InstantiationException;
import java.lang.IllegalAccessException;
import java.util.Enumeration;


public class Login extends HttpServlet {
	private static final int DESCONOCIDO = -2;
	private static final int POSTGRESQL =7; 
	private String database = null; //Nombre de la base de datos;
	private String ip = null; //Direccion ip de la base de datos;
	private String user=null; 	//Usuario de la base de datos;
	private String pass=null;	//Clave del usuario
	private int typedb=DESCONOCIDO;	//Tipo de SGBD
	private static final int ADMINISTRADOR = 1;
	private static final int CONSULTOR = 2;
	private Conexion miConector = null; //Clase Conexion
	private String pagina = null;
	public HttpSession session;
			
	/** Inicializacion
	 * 
	 */
	public void init(ServletConfig config) throws ServletException {
		super.init(config);
	}

	/** Inicializacion
	 *  Cuando llenan el formulario y envian peticion
	 *  Procesa peticion POST
	 */
	public void doPost (HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException, IllegalStateException{
		try{
			//Obtiene Datos de formulario
			if(obtenerDatos(request)){	
				//Realiza conexion y guarda datos en la sesion
				if(hacerConexion(request))
					reenvia(request,response, pagina);	//Redirige a la siguiente pagina
				else 
					reenvia(request, response, "error.jsp");  //Redirige a la pagina de error
			}
			else
				reenvia(request,response,"error.jsp"); //Redirige a la pagina de error
		}
		catch(NullPointerException np){np.printStackTrace();throw np;}
		catch(IOException io){io.printStackTrace();throw io;}
		catch(IllegalStateException ie){ie.printStackTrace();throw ie;}
	}
	
	/** Por si quieren ir a la direccion directamente
	 *  Procesa peticion GET
	 */
	
	public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException{
		RequestDispatcher dispatcher = null;
		HttpSession session = request.getSession(false);
		if(session == null) session.invalidate();
		else session = request.getSession(true);
		dispatcher = request.getRequestDispatcher("index.html");
		if (dispatcher != null) dispatcher.forward(request, response);
	}

	/** Obtiene Datos de formulario "index.html"
	 */
	private boolean obtenerDatos(HttpServletRequest request){
		database=request.getParameter("database");
		ip=request.getParameter("ip");
		user=request.getParameter("user");
		pass=request.getParameter("pass");
		if(((database!=null) && (ip!=null)) && ((user!=null) && (pass!=null))){
			if((database.equals("peerca") && ip.equals("localhost")) && (user.equals("postgres") && pass.equals("postgres"))){
				//Si se conecta a la bd del sw mismo, entonces es el admin
				typedb = POSTGRESQL; //y su tipo de SGBD es el tipo 1, que corresponde a DB2
				pagina = "admin.html";
			}
			else {
				//typedb = DESCONOCIDO , quiere decir que tengo q buscar que tipo de SGBD
				//es el que ha hecho la conexion (el usuario no sabe q tipo es, el se conecta no mas)
				//y en este caso por pregunto con el tipo -2.
				typedb = DESCONOCIDO;
				pagina = "user.html";
			}
			return true;
		}
		else
			return false;
	}

	// Almacena datos de conexion según tipo de usuario
	private boolean hacerConexion(HttpServletRequest request) {
		try{
			session = request.getSession(true);  //Crea u obtiene sesion
			//Establece Conexion con el servidor DB2
			miConector = new Conexion();  //Crea Bean de Conexion
			miConector.setConector(database, ip, user, pass, typedb);			
			session.setAttribute("con", miConector);		
		}
		catch(IllegalStateException e){ return false;}
		catch(ClassNotFoundException e){ return false;}
		catch(SQLException e){return false;}
		catch(InstantiationException e){return false;}
		catch(IllegalAccessException e){return false;}
		return true;
	}

	private void reenvia(HttpServletRequest request, HttpServletResponse response, String pagina) throws ServletException,IOException, IllegalStateException{
		RequestDispatcher dispatcher = null;
		//session = request.getSession(true);
		dispatcher = request.getRequestDispatcher(pagina);
		if (dispatcher != null) dispatcher.forward(request, response);
		/*
		response.setContentType("text/html");
		PrintWriter out = response.getWriter();
		String title = "Reading All Request Parameters";
		out.println("<H1 ALIGN=CENTER>" + title + "</H1>\n" +
					"<TABLE BORDER=1 ALIGN=CENTER>\n" +
					"<TR BGCOLOR=\"#FFAD00\">\n" +
					"<TH>Parameter Name<TH>Parameter Value(s)");
		Enumeration paramNames = request.getParameterNames();
		while(paramNames.hasMoreElements()) {
		  String paramName = (String)paramNames.nextElement();
		  out.println("<TR><TD>" + paramName + "\n<TD>");
		  String[] paramValues = request.getParameterValues(paramName);
		  if (paramValues.length == 1) {
			String paramValue = paramValues[0];
			if (paramValue.length() == 0)
			  out.print("<I>No Value</I>");
			else
			  out.print(paramValue);
		  } else {
			out.println("<UL>");
			for(int i=0; i<paramValues.length; i++) {
			  out.println("<LI>" + paramValues[i]);
			}
			out.println("</UL>");
		  }
		}
		out.println("</TABLE>\n</BODY></HTML>");*/
	}
}
package peerca;

import java.util.*;
import java.sql.DriverManager;
import java.sql.Connection;
import java.sql.Statement;
import java.sql.ResultSet;
import java.sql.ResultSetMetaData;
import java.sql.DatabaseMetaData;
import java.sql.SQLException;
import java.lang.InstantiationException;
import java.lang.IllegalAccessException;

/**********************************************************************
			Conexion.java - Copyright ariela
* @autor Ariela Carrera Clavería
* @date Mayo 2008
* @filename Conexion.java
* 
**********************************************************************/

/**
 * Class Conexion
 */
public class Conexion {

	//
	// Fields
	//
	private static final int DESCONOCIDO = -2;
	private static final int OCULTA = 0;
	private static final int DB2 =1; 
	private static final int MSSQLSERVER2000 =2;
	private static final int MSSQLSERVER2005 =3;
	private static final int MYSQL =4;
	private static final int ORACLETHINCLIENT =5; 
	private static final int ORACLEOCI = 6;
	private static final int POSTGRESQL =7;	
	private String baseDeDatos;
	private String clave;
	private int columnas;
	private Connection conector;
	private String consulta;
	private ResultSetMetaData datos;
	private String direccionIP; 
	private int filas;
	private DatabaseMetaData metadatos;
	private ResultSet resultado;
	private Statement sentencia; 
	private int tipoSGBD;
	private String usuario;

	//
	// Methods
	//


	//
	// Accessor methods
	//

	public int setActualizacion (String q, boolean administrador){
		int respuesta=-1;
		if(administrador){
			try{
				this.setConsulta(q);
				this.setSentencia();
				if(this.sentencia != null){		
					System.out.println("SETACTUALIZACION:   sentencia no es nulo");
					
					respuesta = this.sentencia.executeUpdate(q);
					if(respuesta >= 0){
						System.out.println("SETACTUALIZACION:   filas afectadas="+respuesta);						
					}
					else{
						System.out.println("SETACTUALIZACION:   SIN FILAS afectadas="+respuesta);						
					}
				}
				else{
					System.out.println("SETACTUALIZACION:   Sentencia SI ERA NULO");					
				}
			}
			catch(SQLException e){
					respuesta = -4;
			}
		}
		else{
			Conexion oculta = new Conexion();
			System.out.println("SETACTUALIZACION:   QUERY q no es nulo");
			try{
				System.out.println("SETACTUALIZACION:  entro al try");
				oculta.setConector();
				oculta.setConsulta(q);
				oculta.setSentencia();
				if(oculta.sentencia != null){		
					System.out.println("SETACTUALIZACION:   sentencia no es nulo");
					respuesta = oculta.sentencia.executeUpdate(q);
					if(respuesta >= 0){
						System.out.println("SETACTUALIZACION:   filas afectadas="+respuesta);						
					}
					else{
						System.out.println("SETACTUALIZACION:   SIN FILAS afectadas="+respuesta);						
					}			
				}
				else{
					System.out.println("SETACTUALIZACION:   Sentencia SI ERA NULO");					
				}
				oculta.sentencia.close();
				oculta.conector.close();
			}
			catch(SQLException e){
				System.out.println("SETACTUALIZACION:   Sqlexception");
				e.printStackTrace();
				respuesta = -2;
				return respuesta;
			}
			catch(ClassNotFoundException e){
				System.out.println("SETACTUALIZACION:   class not found exception");
				e.printStackTrace();
				respuesta = -2;
				return respuesta;
			}
		}
		
		return respuesta;
	}
	
	/**
	 * Configura el valor del atributo baseDeDatos
	 * @param newVar the new value of baseDeDatos
	 */
	  public void setBaseDeDatos ( String value ) {
			baseDeDatos = value;
	  }

	/**
	 * Configura el valor del atributo clave
	 * @param newVar the new value of clave
	 */
	  public void setClave ( String value ) {
			clave = value;
	  }	

	/**
	 * Configura el valor del atributo columnas
	 * @param ResultSetMetaData d 
	 */
	  public void setColumnas (ResultSetMetaData d ) {
			try{
				this.columnas = d.getColumnCount();
			}
			catch(SQLException e){
				System.out.println("EXCEPTION: "+ e.getMessage());
				e.printStackTrace();
			}
	  }
	  
	/**
	 * Prepara parametros para realizar una conexion
	 *  @param Sin parametros. Pensado para conectarse por debajo con la aplicacion.
	 *  @return Nada.
	 */
	public void setConector()throws ClassNotFoundException, SQLException{
		System.out.println("SETCONNECTION (NO PARAMS)   Entró");
		String datosConexion = null;
		
		try{
			System.out.println("SET CONNECTION (NO PARAMS)   ...Entro al TRY");
			Class.forName("org.postgresql.Driver");
			datosConexion="jdbc:postgresql://localhost:5432/peerca";
			System.out.println("SET CONNECTION (NO PARAMS)   ....Datos de conexion "+datosConexion);
			/* Establece conexion con servidor de base de datos */
			conector = DriverManager.getConnection(datosConexion,"postgres", "postgres");
			/* Configura los parametros de conexion */
			baseDeDatos = "peerca";			//Almacena DAtabase
			direccionIP = "localhost";		//Almacena IP
			usuario = "postgres";			//Almacena User name
			clave = "postgres";				//Almacena Password
			tipoSGBD = OCULTA;				//Almacena tipo conexion OCULTA
		}
		catch (ClassNotFoundException cnfe){
		  cnfe.printStackTrace();
		  throw cnfe;
		}
		catch (SQLException sqle){
		  sqle.printStackTrace();
		  sqle.getCause();
		  throw sqle;
		}
		System.out.println("SET CONNECTION (NO PARAMS)  ....Saliendo");
	}
	
	/**
	 * Prepara parametros para realizar una conexion
	 * @param bd Nombre de la base de datos.
	 * @param ip Direccion ip de la base de datos.
	 * @param user Nombre de usuario.
	 * @param pass Clave de usuario.
	 */
	public void setConector(String db, String ip, String user, String pw, int type) throws ClassNotFoundException, SQLException, InstantiationException, IllegalAccessException{
		String datosConexion = null;
		int tipo;
		System.out.println("SETCONNECTION FULL          ....Entró ");
		System.out.println("SETCONNECTION FULL     ....VALOR DB : " + db+ ".");
		System.out.println("SETCONNECTION FULL     ....VALOR IP : " + ip+ ".");
		System.out.println("SETCONNECTION FULL   ....VALOR USER : " + user+ ".");
		System.out.println("SETCONNECTION FULL   ....VALOR PASS : " + pw + ".");
		System.out.println("SETCONNECTION FULL   ....VALOR TIPO : " + type+ ".");
		if(type == DESCONOCIDO)
			type = getTipoSGBD(db,ip,user,pw);
		tipo = type;
		System.out.println("SETCONNECTION FULL   ...Respuesta TIPO : " + type+ ".");
			try{
				System.out.println("SETCONNECTION  FULL  ....Entró al TRY");
				// Carga Driver según tipo
				switch(tipo){
					case DB2:
						Class.forName("com.ibm.db2.jcc.DB2Driver").newInstance();
						System.out.println("SETCONNECTION FULL   ....Entró al CASE DB2");
						datosConexion="jdbc:db2://"+ip+":50000"+"/"+db;
						System.out.println("SETCONNECTION FULL   ....DatosConexion :" +datosConexion);
						break;
					case MSSQLSERVER2000:
						Class.forName("com.microsoft.jdbc.sqlserver.SQLServerDriver");
						datosConexion="jdbc:microsoft:sqlserver://"+ip+":1433;DatabaseName="+db;
						break;
					case MSSQLSERVER2005:
						Class.forName("com.microsoft.sqlserver.jdbc.SQLServerDriver");
						datosConexion="jdbc:sqlserver://"+ip+":1433;databaseName="+db;
						break;			
					case MYSQL:
						Class.forName("com.mysql.jdbc.Driver");
						datosConexion="jdbc:mysql://"+ip+":3306/"+db;
						break;
					case OCULTA:
						Class.forName("com.ibm.db2.jcc.DB2Driver");
						datosConexion="jdbc:db2://"+ip+":50000"+"/"+db;
						break;					
					case ORACLETHINCLIENT:
						Class.forName("oracle.jdbc.OracleDriver");
						datosConexion="jdbc:oracle:thin://"+ip+":1521/"+db;
						break;
					case ORACLEOCI:
						Class.forName("oracle.jdbc.OracleDriver");
						datosConexion="jdbc:oracle:oci://"+ip+":1521/"+db;
						break;					
					case POSTGRESQL:
						Class.forName("org.postgresql.Driver");
						System.out.println("SETCONNECTION FULL   ....Entró al CASE POSTGRES");
						datosConexion="jdbc:postgresql://"+ip+":5432/"+db;
						break;
				}
				System.out.println("SETCONNECTION FULL      .....Salió del SWITCH");
				System.out.println("SETCONNECTION FULL       ....USER     :"+user);
				System.out.println("SETCONNECTION FULL       ....PASSWORD :"+pw);
				
			/* Establece conexion con servidor de base de datos */
			conector = DriverManager.getConnection(datosConexion,user,pw);			
			/* Configura los parametros de conexion */			
			baseDeDatos = db;
			direccionIP = ip;
			usuario = user;
			clave = pw;
			tipoSGBD = tipo;
		}
		catch (ClassNotFoundException cnfe){
		  	cnfe.printStackTrace();
		  	throw cnfe;
		}
		catch (SQLException sqle){
		  	System.out.println("SETCONNECTION: "+sqle.getMessage());
		  	System.out.println("SETCONNECTION" + sqle.getErrorCode());
		  	sqle.printStackTrace();
		  	sqle.getCause();
		  	throw sqle;
		}	
		catch (InstantiationException ie){
		  	ie.printStackTrace();
		  	throw ie;
		}
		catch (IllegalAccessException iae){
		  	iae.printStackTrace();
		  	throw iae;
		}
	}		

	/**
	 * Configura el valor del atributo consulta
	 * @param newVar the new value of consulta
	 */
	  public void setConsulta ( String value ) {
			consulta = value;
	  }
	  
	/**
	 * Configura el valor del atributo datos
	 * @param ResultSet rs the new value of datos
	 */
	  public void setDatos (ResultSet rs ) {
			try{
				datos = rs.getMetaData();
			}
			catch(SQLException e){
				System.out.println("EXCEPTION: "+ e.getMessage());
				e.printStackTrace();
			}
	  }
	
	/**
	 * Configura el valor del atributo direccionIP
	 * @param newVar the new value of direccionIP
	 */
	  public void setDireccionIP ( String value ) {
			direccionIP = value;
	  }

	public void setFilas(ResultSet rs) {
		System.out.println("SETFILAS:  ... Entro");
		System.out.println("SETFILAS:  ... Filas inicial : "+this.filas);
    	this.filas = -1;
    	try{
    		if(filas == -1) filas = 0;
    		while(rs.next())
  				this.filas++;
  			rs.beforeFirst();
		}
		catch(SQLException e){
			e.printStackTrace();
			System.out.println("SETFILAS : SqlException : " + e.getMessage());
		}
		System.out.println("SETFILAS:  ... Filas final : "+this.filas);
	}
	
	public void setMetadatos (){
		try{
			metadatos = conector.getMetaData();
		}
		catch(SQLException e){
			e.printStackTrace();	
		}
	}
	/**
	 * Configura el valor del atributo respuesta
	 * @param String q Consulta en sql.
	 */	
	public void setResultado (String q) throws SQLException, NullPointerException{
		System.out.println("SETRESPUESTA:          ENTRO");
		System.out.println("SETRESPUESTA:  CONSULTA VALE : "+q);
		System.out.println("SETRESPUESTA:  Sentencia vale : [" +this.sentencia+"]");
		if((q != null) && (this.sentencia != null)){
			System.out.println("SETRESPUESTA:   dentro del IF");
			try{
				System.out.println("SETRESPUESTA:   dentro del TRY");
				boolean so = this.sentencia.execute(q);
				if(so){
					this.resultado = this.sentencia.getResultSet();
					System.out.println("SETRESPUESTA: EL RESULTADO NO ES NULO!");
					this.setDatos(resultado);
					System.out.println("SETRESPUESTA:     ....Datos : "+this.datos);
					this.setColumnas(datos);
					System.out.println("SETRESPUESTA:  ....Columnas : "+this.columnas);
					this.setFilas(this.resultado);
					System.out.println("SETRESPUESTA:     ....Filas : "+this.getFilas());
				}
				else
					System.out.println("SETRESPUESTA: EL RESULTADO SIIIII ES NULO!");
			}
			catch(SQLException e){
					e.printStackTrace();
					throw e;
			}
		}
		else{
			throw new NullPointerException();	
		}
		System.out.println("SALIO DE SETRESPUESTA");
	}

	/**
	 * setSentencia
	 * 
	 */
	public void setSentencia() throws SQLException{
		System.out.println("SETSENTENCIA:   Dentrando");
		try{
			this.sentencia = this.conector.createStatement(ResultSet.TYPE_SCROLL_SENSITIVE, ResultSet.CONCUR_READ_ONLY);
			System.out.println("SETSENTENCIA:   Creo el Statement");	
		}
		catch(SQLException e){
			e.printStackTrace();
			throw e;
		}
		System.out.println("SETSENTENCIA:   Salio de aca");
	}


	/**
	 * Configura el valor del atributo tipoSGBD
	 * @param newVar the new value of tipoSGBD
	 */
	  public void setTipoSGBD ( int value ) {
			tipoSGBD = value;
	  }

	/**
	 * Configura el valor del atributo usuario
	 * @param newVar the new value of usuario
	 */
	  public void setUsuario ( String value ) {
			usuario = value;
	  }
  
	/**
	 * Obtiene el valor del atributo baseDeDatos
	 * @return the value of baseDeDatos
	 */
	  public String getBaseDeDatos ( ) {
			return baseDeDatos;
	  }
	  
	/**
	 * Obtiene el valor del atributo clave
	 * @return the value of clave
	 */
	  public String getClave ( ) {
			return clave;
	  }


	public int getColumnas(){
		return columnas;	
	}
	
	/**
	 * Obtiene la conexion
	 * @return Connection
	 */
	public Connection getConector() {
		return conector;
	}
	
	/**
	 * Obtiene el valor del atributo consulta
	 * @return the value of consulta
	 */
	  public String getConsulta( ) {
			return consulta;
	  }
	
	/**
	 * Obtiene el valor del atributo consulta
	 * @return the value of consulta
	 */
	  public ResultSetMetaData getDatos( ) {
			return datos;
	  }
	/**
	 * Obtiene el valor del atributo direccionIP
	 * @return the value of direccionIP
	 */
	  public String getDireccionIP ( ) {
			return direccionIP;
	  }
	public int getFilas(){
		return filas;	
	}
		  	
	/**
	 * Obtiene el valor del atributo tipoSGBD
	 * Para buscar tipoSGBD se requieren establecer conexiones ocultas.
	 * @param bd Nombre de la base de datos.
	 * @param ip Direccion ip de la base de datos.
	 * @param user Nombre de usuario.
	 * @param pass Clave de usuario.
	 * @return el valor de tipoSGBD
	 */
	public int getIdNodo(){
		
		Conexion oculta= new Conexion();
		int id = -1;
		try{
			oculta.setConector(); //Conexion oculta con la aplicacion
			oculta.setConsulta("select idnodo from nodo where nombrenodo = '"+this.baseDeDatos+"' and direccionip ='"+this.direccionIP+"' and tiponodo ="+this.getTipoSGBD(this.baseDeDatos, this.direccionIP, this.usuario, this.clave));
			System.out.println("GETIDNODO   .... La consulta es : ");
			System.out.println("GETIDNODO :  "+oculta.getConsulta());
			oculta.setSentencia();
			oculta.setResultado(oculta.getConsulta());
			System.out.println("GETIDNODO  .... Antes de entrar al WHILE");
			System.out.println("GETIDNODO  .... getRespuesta(): "+oculta.getResultado());
			while(oculta.getResultado().next()){
				System.out.println("GETIDNODO  ....Entro al WHILE");
				id = oculta.getResultado().getInt("idnodo");
			}
			System.out.println("GETIDNODO  .... Fuera del WHILE");
			oculta.getResultado().close();
			oculta.conector.close();		
		}
		catch(ClassNotFoundException e){return -1;} 
		catch(NullPointerException e){return -1;}
		catch(SQLException e){ return -1;}
		System.out.println("GETIDNODO  Saliendo casi. Respuesta: ["+id+"]");
		return id;
	}

public int getIdUsuario(){
		
		Conexion oculta= new Conexion();
		int respuesta = 0;
		try{
			oculta.setConector(); //Conexion oculta con la aplicacion
			oculta.setConsulta("select idusuario from usuario where nombreusuario = '"+this.usuario+"' and basededatos = '"+this.baseDeDatos+"' and direccionip ='"+this.direccionIP+"' and claveusuario ='"+this.clave+"'");
			System.out.println("GETIDUSUARIO   .... La consulta es : ");
			System.out.println("GETIDUSUARIO:  "+oculta.getConsulta());
			oculta.setSentencia();
			oculta.setResultado(oculta.getConsulta());
			System.out.println("GETIDUSUARIO  .... Antes de entrar al WHILE");
			System.out.println("GETIDUSUARIO  .... getRespuesta(): "+oculta.getResultado());
			oculta.setFilas(oculta.getResultado());
			while(oculta.getResultado().next()){
				System.out.println("GETIDUSUARIO  ....Entro al WHILE de ya estar en la bd");
				respuesta = oculta.getResultado().getInt("idusuario");
			}
			
			if(oculta.getFilas() == 0) {
				int aux = oculta.setActualizacion("insert into usuario values ( DEFAULT, '"+this.usuario+"', '"+this.direccionIP+"', '"+this.clave+"', '"+this.baseDeDatos+"'", true);	
				if(aux == 1) {
					oculta.setSentencia();
					oculta.setConsulta("select idusuario from usuario where nombreusuario = '"+this.usuario+"' and basededatos = '"+this.baseDeDatos+"' and direccionip ='"+this.direccionIP+"' and claveusuario ='"+this.clave+"'");
					oculta.setResultado(oculta.getConsulta());
					oculta.setFilas(oculta.getResultado());
					while(oculta.getResultado().next()){
						System.out.println("GETIDUSUARIO  ....Entro al WHILE de insertar y consultar si esta");
						respuesta = oculta.getResultado().getInt("idusuario");
					}
					if(oculta.getFilas() > 1) respuesta = -2;
					else if(oculta.getFilas() < 1) respuesta = -2;					
				}
				else respuesta = -2;							
			}
			oculta.getResultado().close();
			oculta.conector.close();			
		}
		catch(ClassNotFoundException e){respuesta = -1;} 
		catch(NullPointerException e){respuesta = -1;}
		catch(SQLException e){ respuesta = -1;}
		System.out.println("GETIDNODO  Saliendo casi. Respuesta: ["+respuesta+"]");
		return respuesta;
	}


	public DatabaseMetaData getMetadatos(){
		return metadatos;	
	}
	/**
	 * Obtiene el valor del atributo respuesta
	 * @return the value of respuesta
	 */
	public ResultSet getResultado () {
		return resultado;			
	}
			

	public Statement getSentencia(){
		return sentencia;
	}
	
	/**
	 * Obtiene el valor del atributo tipoSGBD
	 * Para buscar tipoSGBD se requieren establecer conexiones ocultas.
	 * @param bd Nombre de la base de datos.
	 * @param ip Direccion ip de la base de datos.
	 * @param user Nombre de usuario.
	 * @param pass Clave de usuario.
	 * @return el valor de tipoSGBD
	 */
	public int getTipoSGBD(String db, String ip, String user, String pass){
		
		System.out.println("BUSCARTIPOSGBD         ENTRO");
		System.out.println("BUSCARTIPOSGBD      VALOR DB : " + db+ ".");
		System.out.println("BUSCARTIPOSGBD      VALOR IP : " + ip+ ".");
		System.out.println("BUSCARTIPOSGBD    VALOR USER : " + user+ ".");
		System.out.println("BUSCARTIPOSGBD    VALOR PASS : " + pass + ".");
		
		Conexion oculta= new Conexion();
		tipoSGBD = -1;
		try{
			oculta.setConector(); //Conexion oculta con la aplicacion
			oculta.setConsulta("select tiponodo from nodo where nombrenodo = '"+db+"' and direccionip ='"+ip+"'");
			System.out.println("BUSCARTIPOSGBD   .... La consulta es : ");
			System.out.println(oculta.getConsulta());
			oculta.setSentencia();
			oculta.setResultado(oculta.getConsulta());
			System.out.println("BUSCARTIPOSGBD  .... Antes de entrar al WHILE");
			System.out.println("BUSCARTIPOSGBD  .... getRespuesta(): "+oculta.getResultado());
			while(oculta.getResultado().next()){
				System.out.println("BUSCARTIPOSGBD  ....Entro al WHILE");
				tipoSGBD = oculta.getResultado().getInt("tiponodo");
			}
			System.out.println("BUSCARTIPOSGBD  .... Fuera del WHILE");
			oculta.getResultado().close();
			oculta.conector.close();		
		}
		catch(ClassNotFoundException e){return -1;} 
		catch(NullPointerException e){return -1;}
		catch(SQLException e){ return -1;}
		System.out.println("BUSCARTIPOSGBD  Saliendo casi. Respuesta: ["+tipoSGBD+"]");
		return tipoSGBD;
	}
		
	/**
	 * Obtiene el valor del atributo usuario
	 * @return the value of usuario
	 */
	  public String getUsuario ( ) {
			return usuario;
	  }
	  
	public Vector getPredicados(String relacion){
		int aridad;
	  	int i=0;
	  	String predicado=null;
	  	Vector <String> v = new Vector<String>();
	  	try {
	  		this.setSentencia();			
			this.setResultado("SELECT * FROM "+relacion);
			ResultSet rs= this.getResultado();
			aridad = this.getColumnas();
			for(i=1; i<=aridad; i++){
				predicado=null;
				predicado=this.datos.getColumnLabel(i);//getMetaData is a java method
				v.addElement(predicado);
			}			
		} 
		catch (SQLException sqle){
		  sqle.printStackTrace();
		  return null;	
		}
		return v;
	}
	  
	/**
	 * Obtiene un vector con todas las tablas de un nodo.
	 * @return Vector tablas
	 */
	  public Vector getTablas(String user, int maxColum){
	  	int i=0;
	  	Vector <String> v = new Vector<String>();
	  	ResultSet rs = null;
	  	String[] s = new String[1];
	  	s[0] = "TABLE";
	  	
	  	try{			
			this.setMetadatos();
			this.setSentencia();
			rs = metadatos.getTables(null,null,"%", s);
			try{
				this.setSentencia();
				while(rs.next()){					
					this.setConsulta("select * from "+rs.getString(3));
					System.out.println("Consulta : "+this.getConsulta());
					this.setResultado(this.getConsulta());
					this.setDatos(this.getResultado());
					this.setColumnas(this.getDatos());
					this.setFilas(this.getResultado());
					if((this.getColumnas() <= maxColum)&&(this.getColumnas()>0))
						if(this.getFilas()>=0)
							if((rs.getString(2).equalsIgnoreCase(user))||(rs.getString(2).equalsIgnoreCase("public")))
							v.addElement(rs.getString(3));
				}
				rs.close();
			}					
			catch(Throwable e){
				System.out.println(e.getCause());
				v =null;
			}			
		} 
		catch (SQLException sqle){
		  sqle.printStackTrace();
		  v = null;
		}
		
		return v;
	}
	
	/**
	 * Obtiene un vector con todas las tablas de un nodo.
	 * @return Vector tablas
	 */
	  public Vector getTablas(String user){
	  	int i=0;
	  	Vector <String> v = new Vector<String>();
	  	ResultSet rs = null;
	  	String[] s = new String[1];
	  	s[0] = "TABLE";
	  	
	  	try{			
			this.setMetadatos();
			this.setSentencia();
			rs = metadatos.getTables(null,null,"%", s);
			try{
				this.setSentencia();
				while(rs.next()){					
					this.setConsulta("select * from "+rs.getString(3));
					System.out.println("Consulta : "+this.getConsulta());
					this.setResultado(this.getConsulta());
					this.setDatos(this.getResultado());
					this.setColumnas(this.getDatos());
					this.setFilas(this.getResultado());
					if(this.getColumnas()>0)
						if(this.getFilas()>=0)
							if((rs.getString(2).equalsIgnoreCase(user))||(rs.getString(2).equalsIgnoreCase("public")))
								v.addElement(rs.getString(3));
				}
				rs.close();
			}		
			catch(Throwable e){
				System.out.println(e.getCause());
				v =null;
			}			
		} 
		catch (SQLException sqle){
		  sqle.printStackTrace();
		  v = null;
		}		
		return v;
	}
	
	
	/**
	 * Obtiene un vector con todas las tablas de un nodo.
	 * @return Vector tablas
	 * boolean caso es true si se exige el maximo de columnas
	 * boolean caso es falso si se exige el minimo de columnas
	 */
	  public Vector getTablas(int maxColum, boolean caso){
	  	int i=0;
	  	Vector <String> v = new Vector<String>();
	  	ResultSet rs = null;
	  	String[] s = new String[1];
	  	s[0] = "TABLE";
	  	
	  	try{			
			this.setMetadatos();
			this.setSentencia();
			rs = metadatos.getTables(null,null,"%", s);
			try{				
				this.setSentencia();
				while(rs.next()){					
					this.setConsulta("select * from "+rs.getString(3));
					System.out.println("Consulta : "+this.getConsulta());
					this.setResultado(this.getConsulta());
					this.setDatos(this.getResultado());
					this.setColumnas(this.getDatos());
					this.setFilas(this.getResultado());
					if(caso == true){
						if((this.getColumnas() <= maxColum)&&(this.getColumnas()>0))
							if(this.getFilas()>=0)						
								v.addElement(rs.getString(3));
					}
					else{
						if((this.getColumnas() >= maxColum)&&(this.getColumnas()>0))
							if(this.getFilas()>=0)	
								v.addElement(rs.getString(3));
					}						
				}
				rs.close();
			}			
			catch(Throwable e){
				System.out.println(e.getCause());
				v =null;
			}			
		} 
		catch (SQLException sqle){
		  sqle.printStackTrace();
		  v = null;
		}
		
		return v;
	}
	
	  
	/**
	 * Obtiene un vector con todas las tablas de un nodo.
	 * @return Vector tablas
	 */
	  public Vector getTablas(){
	  	int i=0;
	  	Vector <String> v = new Vector<String>();
	  	ResultSet rs = null;
	  	String[] s = new String[1];
	  	s[0] = "TABLE";
	  	
	  	try{			
			this.setMetadatos();
			this.setSentencia();
			rs = metadatos.getTables(null,null,"%", s);
			try{
				this.setSentencia();
				while(rs.next()){					
					this.setConsulta("select * from "+rs.getString(3));
					System.out.println("Consulta : "+this.getConsulta());
					this.setResultado(this.getConsulta());
					this.setDatos(this.getResultado());
					this.setColumnas(this.getDatos());
					this.setFilas(this.getResultado());
					if(this.getColumnas()>0)
						if(this.getFilas()>=0)
							v.addElement(rs.getString(3));
				}
				rs.close();
			}			
			catch(Throwable e){
				System.out.println(e.getCause());
				v =null;
			}			
		} 
		catch (SQLException sqle){
		  sqle.printStackTrace();
		  v = null;
		}
		
		return v;
	}
		
	public ResultSet getConsultas(int idnodo, int idusuario){
		System.out.println("GETCONSULTAS ::  entro");
		System.out.println("GETCONSULTAS ::  usuario es ="+this.usuario);
		String lista = null;
		ResultSet rs = null;
		
		if((this.usuario != null) &&(idnodo > 0 )){
			Conexion oculta = new Conexion();
			try {
				System.out.println("GETCONSULTAS ::  entro al try!");
				oculta.setConector();
				oculta.setSentencia();
				lista = "select consulta.* from consulta, usuario where idnodo = '"+idnodo+"' and idusuario = '"+idusuario+"'";
				System.out.println("GETCONSULTAS ::  lista = "+lista);
				oculta.setResultado(lista);
				rs = oculta.getResultado();
				//oculta.setFilas(rs);
				//largo = oculta.getFilas();
				if(rs != null){
					System.out.println("GETCONSULTAS ::  entro al if: RS esta bien!");
					while(rs.next()){
						System.out.println("GETCONSULTAS ::  entro al while!");
						System.out.println("GETCONSULTAS ::  cabezaconsulta = "+rs.getString("cabezacon"));
						System.out.println("GETCONSULTAS ::  cuerpoconsulta = "+rs.getString("cuerpocon"));					
					}
				}
				else{
						System.out.println("GETCONSULTAS ::  entro al else: RS ES NULO!");
				}				
			}
			catch(ClassNotFoundException e){
				System.out.println("GETCONSULTAS :: Fallo la conexion :( "); 

				rs = null;
			}
			catch(SQLException e){

				rs= null;
				System.out.println("GETCONSULTAS ::  entro al catch :(  nulo !");
			}
		}
	  	System.out.println("GETCONSULTAS ::  casi saliendo");	  	
	  	return rs;
	}
	
	public boolean esTabla(String tabla) throws NullPointerException{
		boolean respuesta = false;
		if(this.getAridad(tabla) > 0)
			respuesta = true;	
		return respuesta;
	}
	
	public int getAridad(String tabla){
		ResultSet rs;	
		int respuesta = 0;
		try {
			System.out.println("GETARIDAD ::  entro al try!");
			this.setSentencia();
			String q = "select * from "+tabla;
			this.setConsulta(q);
			System.out.println("GETARIDAD ::  Consulta ="+ q);
			this.setResultado(q);
			rs = this.getResultado();
			if(rs != null){
				this.setColumnas(rs.getMetaData());
				respuesta = this.getColumnas();
			}
			else respuesta = -1;
		}		
		catch(SQLException e){
			respuesta = -1;
			System.out.println("GETARIDAD ::  entro al catch :(  nulo !");
		}
		System.out.println("GETARIDAD ::  Saliendo casi.\n RESPUESTA ="+ respuesta);
		return respuesta;
	}
	
	public String getColumna(String tabla, int posicion){
		ResultSet rs;	
		String respuesta = null;
		int cols = 0;
		try {
			System.out.println("GETCOLUMNA ::  entro al try!");
			this.setSentencia();
			String q = "select * from "+tabla;
			this.setConsulta(q);
			System.out.println("GETARIDAD ::  Consulta ="+ q);
			this.setResultado(q);
			rs = this.getResultado();
			if(rs != null){
				this.setColumnas(rs.getMetaData());
				cols = this.getColumnas();
				if((posicion > cols)||(posicion < 1)) respuesta = null;
				else{
					respuesta = this.datos.getColumnLabel(posicion);
				}
			}
			else respuesta = null;
		}		
		catch(SQLException e){
			respuesta = null;
			System.out.println("GETARIDAD ::  entro al catch :(  nulo !");
		}
		System.out.println("GETARIDAD ::  Saliendo casi.\n RESPUESTA ="+ respuesta);
		return respuesta;
	}
}
<?xml version="1.0" encoding="ISO-8859-1"?>
<web-app xmlns="http://java.sun.com/xml/ns/j2ee"; 
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"; 
    xsi:schemaLocation="http://java.sun.com/xml/ns/j2ee 
    http://java.sun.com/xml/ns/j2ee/web-app_2_4.xsd"; version="2.4">

	<display-name>PeerCA Peer Consistent Answers</display-name>
    <servlet>
        <servlet-name>Login</servlet-name>
        <servlet-class>Login</servlet-class>
    </servlet>
    <servlet-mapping>
        <servlet-name>Login</servlet-name>
        <url-pattern>/Login</url-pattern>
    </servlet-mapping>
    <welcome-file-list>
		<welcome-file>index.html</welcome-file>
	</welcome-file-list>
	<error-page>
		<exception-type>IOException</exception-type>
    	<location>/error.jsp</location>
	</error-page>
	<error-page>
		<exception-type>ServletException</exception-type>		
    	<location>/error.jsp</location>
	</error-page>
	<error-page>
		<exception-type>ClassNotFoundException</exception-type>		
    	<location>/error.jsp</location>
	</error-page>
	<error-page>
		<exception-type>IllegalStateException</exception-type>				
    	<location>/401.jsp</location>
	</error-page>
	<error-page>
		<exception-type>SQLException</exception-type>	
    	<location>/error.jsp</location>
	</error-page>
	<error-page>		
		<exception-type>NullPointerException</exception-type>		
    	<location>/error.jsp</location>
	</error-page>
</web-app>
---------------------------------------------------------------------
To start a new topic, e-mail: users@tomcat.apache.org
To unsubscribe, e-mail: [EMAIL PROTECTED]
For additional commands, e-mail: [EMAIL PROTECTED]

Reply via email to