practica2.doc - Servidor Jano - Universidad del Cauca

outstandingmaskΔιαχείριση Δεδομένων

29 Νοε 2012 (πριν από 4 χρόνια και 11 μήνες)

400 εμφανίσεις

Universidad del Cauca


FIET


Depart
amento de Telemática.

Sistemas Distribuidos.



GUIA Nº 2:
JAVA Y EL LENGUAJE DE DEFINICIÓN DE INTERFACES (IDL)


Objetivo:
Aplicar los conceptos adquiridos, relacionados con el IDL y las herramientas
que proporciona la plataforma Java para implementar aplicaciones distribuidas basadas
en una arquitectur
a CORBA.



Descripción:
En esta práctica se desarrolla una aplicación basada en la arquitectura
CORBA, que haciendo uso del ORB que viene con el J2SDK permite a un cliente
conectarse y realizar operaciones sobre una base de datos de manera distribuida.


De
sarrollo de la práctica:

1.

Directorio de trabajo




En el entorno de desarrollo de Eclipse 3.1 entremos en el WorkSpace “distribuidos”.



En el directorio (C:
\
desarrollo
\
distribuidos) creemos un proyecto de nombre

BancoServer_IDL.






Universidad del Cauca


FIET


Depart
amento de Telemática.

Sistemas Distribuidos.






Agreguemos el archivo
po
stgresql
-
8.0.309.jdbc3.jar

al path de nuestro proyecto
.
Este archivo se puede encontrar en la carpeta jdbc de postgresql y es necesario para
comunicarnos con la base de datos.

(Proyect
-
>Java Build Path
-
>Libraries
-
>)



2.

Crear el
archivo IDL.



En el block de notas (u otro editor de texto) copiar el siguiente código:

module interfaces{


struct User{


long id;


string name,login;



};


interface IUser{


User searchUser(in long id);



boolean updateUser(in long id,in string name,in string log);


boolean delUser(in long id);


boolean addUser(in long id,in string name,in string log);


};

};


Universidad del Cauca


FIET


Depart
amento de Telemática.

Sistemas Distribuidos.





Guardarlo con el nombre
“IUser.idl”

en el directorio

del proyecto.

3.

C
ompilar el archivo.



Crear un archivo con
extensión

.bat

(
IDLtoJava.bat
)

en
el directorio

del
proyecto con el siguiente contenido:

C:
\
Archiv~1
\
Java
\
jdk1.5.0
\
bin
\
idlj
-
fall IUser.idl

pause




Al ejecutar el archivo, se generará una carpeta llamada interfaces c
on archivos
.java generados a partir de la
idl
.




Copiemos o importemos estos archivos en un paquete interfaces creado dentro
del proyecto en Eclipse. (No olvidemos refrescar el proyecto después de copiar
los archivos).




9 archivos son generados, pero p
or
el momento, prestemos especial atención
al

archivo
User.java.


/**

* interfaces/User.java .

* Generated by the IDL
-
to
-
Java compiler (portable), version "3.2"

* from IUser.idl

* miércoles 12 de octubre de 2005 17H15' GMT
-
05:00

*/


public final class User im
plements org.omg.CORBA.portable.IDLEntity

{


public int id = (int)0;


public String name = null;


public String login = null;



public User ()


{


} // ctor



public User (int _id, String _name, String _login)


{


id = _id;


name = _name;



login = _login;


} // ctor


} // class User


Utilizaremos este archivo como nuestro valueObject del modelo. (Esto con el fin de
aprovechar la estructura generada por el compilador). Modifiquemos entonces este
archivo copiándole el siguiente fragmento de
código antes del último corchete
que
cierra la clase:

Universidad del Cauca


FIET


Depart
amento de Telemática.

Sistemas Distribuidos.





/**


* Get
-

and Set
-
methods for persistent variables. The default


* behaviour does not make any checks against malformed data,


* so these might require some manual additions.


*/



public

int getId() {



return this.id;


}




public void setId(int idIn) {


this.id = idIn;


}




public String getName() {


return this.name;


}


public void setName(String nameIn) {


this.name = nameIn;


}



public String getLog
in() {


return this.login;


}


public void setLogin(String loginIn) {


this.login = loginIn;


}





/**


* setAll allows to set all persistent variables in one method call.


* This is useful, when all data is available and it is need
ed to


* set the initial state of this object. Note that this method will


* directly modify instance variales, without going trough the


* individual set
-
methods.


*/



public void setAll(int cedulaIn,


String nameIn,


String logi
nIn) {


this.id = cedulaIn;


this.name = nameIn;


this.login = loginIn;


}




/**


* hasEqualMapping
-
method will compare two Usuario instances


* and return true if they contain same values in all persistent
instance


* varia
bles. If hasEqualMapping returns true, it does not mean the
objects


* are the same instance. However it does mean that in that moment,
they


* are mapped to the same row in database.


*/


public boolean hasEqualMapping(User valueObject) {


Universidad del Cauca


FIET


Depart
amento de Telemática.

Sistemas Distribuidos.





if (valueObject.getId() != this.id) {


return(false);


}


if (this.name == null) {


if (valueObject.getName() != null)


return(false);


} else if (!this.name.equals(
valueObject.getName())) {


return(false);


}


if (this.login == null) {


if (valueObject.getLogin() != null)


return(false);


} else if (!this.login.equals(valueObject.getLogin(
))) {


return(false);


}



return true;


}





/**


* toString will return String object representing the state of this


* valueObject. This is useful during application development, and


* possibly when application

is writing object states in textlog.


*/


public String toString() {


StringBuffer out = new StringBuffer(this.getDaogenVersion());


out.append("
\
nclass Tbl_usuario, mapping to table banco
\
n");


out.append("Persistent attributes:
\
n");


out.append("cédula = " + this.id + "
\
n");


out.append("nombre = " + this.name + "
\
n");


out.append("login = " + this.login + "
\
n");


return out.toString();


}




/**


* Clone will return identical deep copy of this valueObject.


* Note, that this method is different than the clone() which


* is defined in java.lang.Object. Here, the retuned cloned object


* will also have all its attributes cloned.


*/


public Object clone() {


User cloned = new User();


cloned
.setId(this.id);


cloned.setName(new String(this.name));


cloned.setLogin(new String(this.login));


return cloned;


}





/**


* getDaogenVersion will return information about


* generator which created these sources.


*/


publi
c String getDaogenVersion() {


return "DaoGen version 2.2.2";


}


Universidad del Cauca


FIET


Depart
amento de Telemática.

Sistemas Distribuidos.






Por último eliminemos los
parámetros

_login y _user

del
constructor

de laclase,

ya que no los utilizaremos en esta
ocasión. Este es el archivo modificado User.java que nos debe
quedar
:






package interfaces;



/**

* interfaces/User.java .

* Generated by the IDL
-
to
-
Java compiler (portable), version "3.2"

* from IUser.idl

* martes 11 de octubre de 2005 11:19:41 PM GMT
-
05:00

*/


public final class User implements org.omg.CORBA.portable.
IDLEntity

{


public int id = (int)0;


public String name = null;


public String login = null;



public User ()


{


} // ctor



public User (int _id)


{


id = _id;


} // ctor




/**


* Get
-

and Set
-
methods for persistent variables. The defa
ult


* behaviour does not make any checks against malformed data,


* so these might require some manual additions.


*/



public int getId() {



return this.id;


}




public void setId(int idIn) {


this.id = idIn;


}




public String ge
tName() {


return this.name;


}


public void setName(String nameIn) {


this.name = nameIn;


}



public String getLogin() {


return this.login;


}


public void setLogin(String loginIn) {


this.login = loginIn;

Universidad del Cauca


FIET


Depart
amento de Telemática.

Sistemas Distribuidos.




}





/**


* setAll allows to set all persistent variables in one method call.


* This is useful, when all data is available and it is needed to


* set the initial state of this object. Note that this method will


* directly modify instance variales, witho
ut going trough the


* individual set
-
methods.


*/



public void setAll(int cedulaIn,


String nameIn,


String loginIn) {


this.id = cedulaIn;


this.name = nameIn;


this.login = loginIn;


}




/**


* hasEqualMap
ping
-
method will compare two Usuario instances


* and return true if they contain same values in all persistent
instance


* variables. If hasEqualMapping returns true, it does not mean the
objects


* are the same instance. However it does mean that
in that moment,
they


* are mapped to the same row in database.


*/


public boolean hasEqualMapping(User valueObject) {



if (valueObject.getId() != this.id) {


return(false);


}


if (this.name == null
) {


if (valueObject.getName() != null)


return(false);


} else if (!this.name.equals(valueObject.getName())) {


return(false);


}


if (this.login == null) {


i
f (valueObject.getLogin() != null)


return(false);


} else if (!this.login.equals(valueObject.getLogin())) {


return(false);


}



return true;


}





/**


* toString will return String objec
t representing the state of this


* valueObject. This is useful during application development, and


* possibly when application is writing object states in textlog.


*/


public String toString() {


StringBuffer out = new StringBuffer(this.ge
tDaogenVersion());

Universidad del Cauca


FIET


Depart
amento de Telemática.

Sistemas Distribuidos.




out.append("
\
nclass Tbl_usuario, mapping to table banco
\
n");


out.append("Persistent attributes:
\
n");


out.append("cédula = " + this.id + "
\
n");


out.append("nombre = " + this.name + "
\
n");


out.append("logi
n = " + this.login + "
\
n");


return out.toString();


}




/**


* Clone will return identical deep copy of this valueObject.


* Note, that this method is different than the clone() which


* is defined in java.lang.Object. Here, the retuned clo
ned object


* will also have all its attributes cloned.


*/


public Object clone() {


User cloned = new User();


cloned.setId(this.id);


cloned.setName(new String(this.name));


cloned.setLogin(new String(this.login));


retu
rn cloned;


}





/**


* getDaogenVersion will return information about


* generator which created these sources.


*/


public String getDaogenVersion() {


return "DaoGen version 2.2.2";


}


} // class User




Los demás archivos deben quedar t
al como fueron generados.


4.

Clase que implementa la interfaz.




En el directorio del proyecto (
BancoServer_IDL
), c
reemos un paquete
logic

y una
clase de nombre
Impl_User
, con el siguiente código

package logic;




import interfaces.IUserPOA;

import interface
s.User;


import java.rmi.RemoteException;

import java.sql.Connection;

import java.sql.DriverManager;

import java.sql.SQLException;

import org.omg.CORBA.ORB;


import persistence.NotFoundException;

import persistence.UserDao;


public class Impl_User extends
IUserPOA {


private ORB orb;

Universidad del Cauca


FIET


Depart
amento de Telemática.

Sistemas Distribuidos.






public Impl_User() throws RemoteException {



super();



// TODO Auto
-
generated constructor stub


}





public void setORB(ORB orb_val) {



orb = orb_val;



}




public User searchUser(int id){



//crear el value objec
t a retornar



User u=new User(id);



//crear los DAO a manipular



UserDao user= new UserDao();





try{




user.load(getConnection(),u);



}



catch(SQLException e){




u=null;




e.printStackTrace();



} catch (NotFoun
dException e) {




u=null;




e.printStackTrace();



}



return u;


}



public boolean updateUser(int id, String name, String log){



boolean update=true;



//crear el value object a actualizar



User u=new User();



u.setAll(id,name,log);



//crear los

DAO a manipular



UserDao user= new UserDao();





try{




user.save(getConnection(),u);



}



catch(SQLException e){




update=false;




e.printStackTrace();




} catch (NotFoundException e) {




// TODO Auto
-
generated
catch block




update=false;




e.printStackTrace();







}



return update;


}



public boolean delUser(int id){



boolean del=true;



//crear el value object a eliminar



User u=new User(id);



//crear los DAO a manipular



UserDao user= new

UserDao();





try{

Universidad del Cauca


FIET


Depart
amento de Telemática.

Sistemas Distribuidos.






user.delete(getConnection(),u);



}



catch(SQLException e){




del=false;




e.printStackTrace();



} catch (NotFoundException e) {




// TODO Auto
-
generated catch block




del=false;




e.prin
tStackTrace();



}



return del;


}



public boolean addUser(int id, String name, String log) {



boolean add = true;




// crear el value object de user



User u = new User(id);



u.setLogin(log);



u.setName(name);




// crear el DAO a manipular



Use
rDao user = new UserDao();






try {




user.create(getConnection(),u);



} catch (SQLException e) {




add = false;




e.printStackTrace();



}



return add;


}




private Connection getConnection(){



Connection conn=null;



try{


//registrar

la clase del driver


Class.forName("org.postgresql.Driver");


//obtener el objeto de conexion


conn=DriverManager.getConnection("jdbc:postgresql://localhost/banco","
postgres","omcaicedo");


}


catch(ClassNotF
oundException e){


e.printStackTrace();


}


catch(SQLException e){



e.printStackTrace();


}


return conn;




}

}



5.

Creación de las clases de persistencia
.




Crea
r un paquete de nombre
persistence

con las clases

UserDAO

y
NotFoundException.


Universidad del Cauca


FIET


Depart
amento de Telemática.

Sistemas Distribuidos.



Código de UserDAO (UserDao.java).


package persistence;



import java.sql.Connection;

import java.sql.PreparedStatement;

import java.sql.ResultSet;

import java.sql.SQLException;

import java.util.List;

import java.util.Vector;




/**


* Usuario Data Access Object (DAO).


* This class contains all database handling that is needed to


* permanently store and retrieve Usuario object instances.


*/



/**


* This sourcecode has been generated by FREE DaoGen generator version
2.2.2.


* The usage of generated code is restricted to OpenSource software projects


* only. DaoGen is available in http://titaniclinux.net/daogen/


* It has been programmed by Tuomo Lukka, Tuomo.Lukka@iki.fi


*


* DaoGen license: The following DaoGen

generated source code is licensed


* under the terms of GNU GPL license. The full text for license is available


* in GNU project's pages: http://www.gnu.org/copyleft/gpl.html


*


* If you wish to use the DaoGen generator to produce code for closed
-
so
urce


* commercial applications, you must pay the lisence fee. The price is


* 5 USD or 5 Eur for each database table, you are generating code for.


* (That includes unlimited amount of iterations with all supported languages


* for each database table

you are paying for.) Send mail to


* "Tuomo.Lukka@iki.fi" for more information. Thank you!


*/



public class UserDao {



// Cache contents:


private boolean cacheOk;


private List cacheData;




/**


* Constructor for Dao. This construct
or will only reset cache.


* If extended Dao classes are generated, it is important to


* make sure resetCache() will be called in constructor.


*/


public UserDao() {


resetCache();


}



/**


* resetCache
-
method. This is im
portant method when caching is used


* to keep data in Dao instance. This method must be called whenever


* the data in table has been changed. This method will mark current


* cache to be outdated and next time when cacheable data will be



* retrieved from database, the cache will be rebuilt. Please note


* that using Dao
-
cache can have remarkable performace boost or it may


* not help at all. It all depends on the amount of data and the rate


* that data is being changed.


*/


public void resetCache() {


cacheOk = false;


cacheData = null;

Universidad del Cauca


FIET


Depart
amento de Telemática.

Sistemas Distribuidos.




}




/**


* load
-
method. This will load valueObject contents from database using


* Primary
-
Key as identifier. Upper layer should use this so that
valueObje
ct


* instance is created and only primary
-
key should be specified. Then call


* this method to complete other persistent information. This method will


* overwrite all other fields except primary
-
key and possible runtime
variables.


* If l
oad can not find matching row, NotFoundException will be thrown.


*


* @param conn This method requires working database connection.


* @param valueObject This parameter contains the class instance to be
loaded.


*

Primary
-
key field must be set for this to work
properly.


*/


public void load(Connection conn, User valueObject) throws
NotFoundException, SQLException {



String sql = "SELECT * FROM tbl_usuario WHERE (USU_CEDULA = ? )";


Pr
eparedStatement stmt = null;



try {


stmt = conn.prepareStatement(sql);


stmt.setInt(1, valueObject.getId());



singleQuery(conn, stmt, valueObject);



} finally {


if (stmt != null
)


stmt.close();


}


}




/**


* LoadAll
-
method. This will read all contents from database table and


* build an Vector containing valueObjects. Please note, that this method


* will consume huge amounts of resou
rces if table has lot's of rows.


* This should only be used when target tables have only small amounts


* of data.


*


* @param conn This method requires working database connection.


*/


public List loadAll(Connection conn
) throws SQLException {



// Check the cache status and use Cache if possible.


if (cacheOk) {


return cacheData;


}



String sql = "SELECT * FROM tbl_usuario";


List searchResults = listQuery(conn,

conn.prepareStatement(sql));



// Update cache and mark it ready.


cacheData = searchResults;


cacheOk = true;



return searchResults;


}





/**

Universidad del Cauca


FIET


Depart
amento de Telemática.

Sistemas Distribuidos.




* create
-
method. This will create new row in database accordin
g to
supplied


* valueObject contents. Make sure that values for all NOT NULL columns
are


* correctly specified. Also, if this table does not use automatic
surrogate
-
keys


* the primary
-
key must be specified. After INSERT command this method
w
ill


* read the generated primary
-
key back to valueObject if automatic
surrogate
-
keys


* were used.


*


* @param conn This method requires working database connection.


* @param valueObject This parameter contains the class i
nstance to be
created.


* If automatic surrogate
-
keys are not used the
Primary
-
key


* field must be set for this to work properly.


*/


public synchronized void create(Connection conn, User valueObjec
t) throws
SQLException {



String sql = "";


PreparedStatement stmt = null;




try {


sql = "INSERT INTO tbl_usuario
(USU_NOMBRE,USU_CEDULA,USU_LOGIN) VALUES(?, ?, ?) ";


stmt = conn.prepareSt
atement(sql);


stmt.setString(1, valueObject.getName());


stmt.setInt(2, valueObject.getId());


stmt.setString(3, valueObject.getLogin());



int rowcount = databaseUpdate(conn, stmt);



if (rowcount != 1) {


//System.out.println("PrimaryKey Error when updating
DB!");


throw new SQLException("PrimaryKey Error when updating
DB!");


}



} finally {


if (stmt != null)


stmt.close();


}




}




/**


* save
-
method. This method will save the current state of valueObject to
database.


* Save can not be used to create new instances in database, so upper
layer must


* make sure that

the primary
-
key is correctly specified. Primary
-
key will
indicate


* which instance is going to be updated in database. If save can not find
matching


* row, NotFoundException will be thrown.


*


* @param conn This method requires

working database connection.


* @param valueObject This parameter contains the class instance to be
saved.


* Primary
-
key field must be set for this to work
properly.


*/


public void save(Connection conn, User valueObj
ect)

Universidad del Cauca


FIET


Depart
amento de Telemática.

Sistemas Distribuidos.




throws NotFoundException, SQLException {



String sql = "UPDATE tbl_usuario SET USU_NOMBRE = ?, USU_LOGIN = ?
WHERE (USU_CEDULA = ? ) ";


PreparedStatement stmt = null;



try {


stmt = conn.prepareSta
tement(sql);


stmt.setString(1, valueObject.getName());


stmt.setString(2, valueObject.getLogin());


stmt.setInt(3, valueObject.getId());



int rowcount = databaseUpdate(conn, stmt);


if (
rowcount == 0) {


//System.out.println("Object could not be saved!
(PrimaryKey not found)");


throw new NotFoundException("Object could not be saved!
(PrimaryKey not found)");


}


if (rowcount >

1) {


//System.out.println("PrimaryKey Error when updating DB!
(Many objects were affected!)");


throw new SQLException("PrimaryKey Error when updating DB!
(Many objects were affected!)");


}


} fi
nally {


if (stmt != null)


stmt.close();


}


}




/**


* delete
-
method. This method will remove the information from database as
identified by


* by primary
-
key in supplied valueObject. Once valueObject

has been
deleted it can not


* be restored by calling save. Restoring can only be done using create
method but if


* database is using automatic surrogate
-
keys, the resulting object will
have different


* primary
-
key than what it was in the

deleted object. If delete can not
find matching row,


* NotFoundException will be thrown.


*


* @param conn This method requires working database connection.


* @param valueObject This parameter contains the class instance to be
d
eleted.


* Primary
-
key field must be set for this to work
properly.


*/


public void delete(Connection conn, User valueObject)


throws NotFoundException, SQLException {



String sql = "DELETE FROM tbl_usuar
io WHERE (USU_CEDULA = ? ) ";


PreparedStatement stmt = null;



try {


stmt = conn.prepareStatement(sql);


stmt.setInt(1, valueObject.getId());



int rowcount = databaseUpdate(conn, stmt);



if (rowcount == 0) {


//System.out.println("Object could not be deleted
(PrimaryKey not found)");


throw new NotFoundException("Object could not be deleted!
(PrimaryKey not found)");


}

Universidad del Cauca


FIET


Depart
amento de Telemática.

Sistemas Distribuidos.




if

(rowcount > 1) {


//System.out.println("PrimaryKey Error when updating DB!
(Many objects were deleted!)");


throw new SQLException("PrimaryKey Error when updating DB!
(Many objects were deleted!)");


}



} finally {


if (stmt != null)


stmt.close();


}


}




/**


* deleteAll
-
method. This method will remove all information from the
table that matches


* this Dao and ValueObject couple. This should b
e the most efficient way
to clear table.


* Once deleteAll has been called, no valueObject that has been created
before can be


* restored by calling save. Restoring can only be done using create
method but if database


* is using automatic s
urrogate
-
keys, the resulting object will have
different primary
-
key


* than what it was in the deleted object. (Note, the implementation of
this method should


* be different with different DB backends.)


*


* @param conn This meth
od requires working database connection.


*/


public void deleteAll(Connection conn) throws SQLException {



String sql = "DELETE FROM tbl_usuario";


PreparedStatement stmt = null;



try {


stmt = conn.prepare
Statement(sql);


databaseUpdate(conn, stmt);


} finally {


if (stmt != null)


stmt.close();


}


}




/**


* coutAll
-
method. This method will return the number of all rows from
table tha
t matches


* this Dao. The implementation will simply execute "select
count(primarykey) from table".


* If table is empty, the return value is 0. This method should be used
before calling


* loadAll, to make sure table has not too many rows.



*


* @param conn This method requires working database connection.


*/


public int countAll(Connection conn) throws SQLException {



// Check the cache status and use Cache if possible.


if (cacheOk) {


return cacheData.size();


}




String sql = "SELECT count(*) FROM tbl_usuario";


PreparedStatement stmt = null;


ResultSet result = null;


int allRows = 0;

Universidad del Cauca


FIET


Depart
amento de Telemática.

Sistemas Distribuidos.





try {


stmt = conn.prepareState
ment(sql);


result = stmt.executeQuery();



if (result.next())


allRows = result.getInt(1);


} finally {


if (result != null)


result.close();


if (stmt != null)


stmt.close();


}


return allRows;


}




/**


* searchMatching
-
Method. This method provides searching capability to


* get matching valueObjects from database. It works by searching all


* objects th
at match permanent instance variables of given object.


* Upper layer should use this by setting some parameters in valueObject


* and then call searchMatching. The result will be 0
-
N objects in
vector,


* all matching those criteria you spec
ified. Those instance
-
variables
that


* have NULL values are excluded in search
-
criteria.


*


* @param conn This method requires working database connection.


* @param valueObject This parameter contains the class instance where
se
arch will be based.


* Primary
-
key field should not be set.


*/


public List searchMatching(Connection conn, User valueObject) throws
SQLException {



List searchResults;



boolean first = true;


St
ringBuffer sql = new StringBuffer("SELECT * FROM tbl_usuario WHERE
1=1 ");



if (valueObject.getId() != 0) {


if (first) { first = false; }


sql.append("AND USU_CEDULA =
").append(valueObject.getId()).append(" ");



}


if (valueObject.getName() != null) {


if (first) { first = false; }


sql.append("AND USU_NOMBRE LIKE
'").append(valueObject.getName()).append("%' ");


}


if (valueObject.getLogin() != null) {



if (first) { first = false; }


sql.append("AND USU_LOGIN LIKE
'").append(valueObject.getLogin()).append("%' ");


}




sql.append("ORDER BY USU_CEDULA ASC ");



// Prevent accidential full table results.



// Use loadAll if all rows must be returned.


if (first)


searchResults = new Vector();


else


searchResults = listQuery(conn,
conn.prepareStatement(sql.toString()));

Universidad del Cauca


FIET


Depart
amento de Telemática.

Sistemas Distribuidos.





return searchResults;



}




/**


* getDaogenVersion will return information about


* generator which created these sources.


*/


public String getDaogenVersion() {


return "DaoGen version 2.2.2";


}




/**


* databaseUpdate
-
method. This metho
d is a helper method for internal use.
It will execute


* all database handling that will change the information in tables.
SELECT queries will


* not be executed here however. The return value indicates how many rows
were affected.


* This met
hod will also make sure that if cache is used, it will reset
when data changes.


*


* @param conn This method requires working database connection.


* @param stmt This parameter contains the SQL statement to be
excuted.


*/


protected int databaseUpdate(Connection conn, PreparedStatement stmt)
throws SQLException {



int result = stmt.executeUpdate();



resetCache();



return result;


}





/**


* databaseQuery
-
method. This method is a
helper method for internal use.
It will execute


* all database queries that will return only one row. The resultset will
be converted


* to valueObject. If no rows were found, NotFoundException will be
thrown.


*


* @param conn Thi
s method requires working database connection.


* @param stmt This parameter contains the SQL statement to be
excuted.


* @param valueObject Class
-
instance where resulting data will be stored.


*/


protected void singleQuery(Connect
ion conn, PreparedStatement stmt, User
valueObject)


throws NotFoundException, SQLException {



ResultSet result = null;



try {


result = stmt.executeQuery();



if (result.next()) {




valueObject.setId(result.getInt("USU_CEDULA"));


valueObject.setName(result.getString("USU_NOMBRE"));


valueObject.setLogin(result.getString("USU_LOGIN"));


Universidad del Cauca


FIET


Depart
amento de Telemática.

Sistemas Distribuidos.




} else {


//System.out.pri
ntln("Tbl_usuario Object Not Found!");


throw new NotFoundException("Tbl_usuario Object Not
Found!");


}


} finally {


if (result != null)


result.close();


if (stmt != nul
l)


stmt.close();


}


}




/**


* databaseQuery
-
method. This method is a helper method for internal use.
It will execute


* all database queries that will return multiple rows. The resultset will
be converted


*
to the List of valueObjects. If no rows were found, an empty List will
be returned.


*


* @param conn This method requires working database connection.


* @param stmt This parameter contains the SQL statement to be
excuted.



*/


protected List listQuery(Connection conn, PreparedStatement stmt) throws
SQLException {



Vector searchResults = new Vector();


ResultSet result = null;



try {


result = stmt.executeQuery();



w
hile (result.next()) {


User temp = new User();



temp.setId(result.getInt("USU_CEDULA"));


temp.setName(result.getString("USU_NOMBRE"));


temp.setLogin(result.getString("USU_LOGIN")
);



searchResults.add(temp);


}



} finally {


if (result != null)


result.close();


if (stmt != null)


stmt.close();


}



return (List)s
earchResults;


}



}


Código de la clase NotFoundException (NotFoundException.java)

package persistence;


/**


* NotFoundException exception. This exception will be thrown from


* Dao object if load, update or delete for one object fails to find the


* correct row.


*


* NOTE: You will need only one instance of this class to use multiple

Universidad del Cauca


FIET


Depart
amento de Telemática.

Sistemas Distribuidos.




* DaoGen generated objects.


*/



/**


* This sourcecode has been generated by FREE DaoGen generator version 2.2.2.


* The usage of generated code is restrict
ed to OpenSource software projects


* only. DaoGen is available in http://titaniclinux.net/daogen/


* It has been programmed by Tuomo Lukka, Tuomo.Lukka@iki.fi


*


* DaoGen license: The following DaoGen generated source code is licensed


* under the t
erms of GNU GPL license. The full text for license is available


* in GNU project's pages: http://www.gnu.org/copyleft/gpl.html


*


* If you wish to use the DaoGen generator to produce code for closed
-
source


* commercial applications, you must pay the

lisence fee. The price is


* 5 USD or 5 Eur for each database table, you are generating code for.


* (That includes unlimited amount of iterations with all supported languages


* for each database table you are paying for.) Send mail to


* "Tuomo.Lukk
a@iki.fi" for more information. Thank you!


*/




public class NotFoundException extends Exception {



/**



*



*/


private static final long serialVersionUID = 1L;



/**


* Constructor for NotFoundException. The input message is


* returned in
toString() message.


*/


public NotFoundException(String msg) {


super(msg);


}


}


6.

Creación del Servidor de Objetos



En el directorio montado
BancoServer
_IDL


creemos un paquete de nombre
view
.



En este paquete creemos una clase de nombre

Object
Server

y reemplacemos el
código generado por el siguiente.


package view;



import org.omg.CORBA.ORB;

import org.omg.CosNaming.NameComponent;

import org.omg.CosNaming.NamingContextExt;

import org.omg.CosNaming.NamingContextExtHelper;

import org.omg.
PortableServer.POA;

import org.omg.PortableServer.POAHelper;


import interfaces.IUser;

import interfaces.IUserHelper;

import logic.Impl_User;



Universidad del Cauca


FIET


Depart
amento de Telemática.

Sistemas Distribuidos.



public class ObjectServer {



public static void main(String args[]) {


try{


// create and initialize
the ORB


ORB orb = ORB.init(args, null);



// get reference to rootpoa & activate the POAManager


POA rootpoa =
POAHelper.narrow(orb.resolve_initial_references("RootPOA"));


rootpoa.the_POAManager().activate();



// create servant
and register it with the ORB


Impl_User impl = new Impl_User();


impl.setORB(orb);



// get object reference from the servant


org.omg.CORBA.Object ref = rootpoa.servant_to_reference(impl);


IUser href = IUserHelper.narrow(ref);





// get the root naming context


org.omg.CORBA.Object objRef =


orb.resolve_initial_references("NameService");


// Use NamingContextExt which is part of the Interoperable


// Naming Service (INS) specification.


NamingC
ontextExt ncRef = NamingContextExtHelper.narrow(objRef);



// bind the Object Reference in Naming


String name = "Interfaz";


NameComponent path[] = ncRef.to_name( name );


ncRef.rebind(path, href);



System.out.println("Servidor e
sperando peticiones ...");



// espera por invocaciones de los clientes


orb.run();


}




catch (Exception e) {


System.err.println("ERROR: " + e);


e.printStackTrace(System.out);


}





System.out.println("servi
dor terminando ...");



}

}



7.

Creación del cliente que utilizará los métodos remotos.



Creemos el proyecto
BancoCliente
_IDL
.



Creemos en este proyecto el paquete
view

con las clases
Client

y
MessageBean

Nota:
La clase
client

es una GUI creada con plugin de
eclipse llamado Visual
Editor.


Código de MessageBean (MessageBean.java)

Universidad del Cauca


FIET


Depart
amento de Telemática.

Sistemas Distribuidos.






/**


* Title: BeanMensajes


* Description: Bean para manejar los diferentes Mensajes


* Copyright: Copyright (c) 2002


* Company: UNICAUCA


* @author Oscar Ca
icedo, realizado a partir de una versión hecha por
Diego Andrés Acosta


* @version 1.0


*/

package view;


import java.awt.Container;

import javax.swing.JOptionPane;


public class MessageBean implements java.io.Serializable{



/**



*



*/


private stat
ic final long serialVersionUID = 1L;



/**


* Contenedor en el que se desplegará el mensaje


*/


private Container cPadre;



/**


* Representa el diálogo de error


*/


private String titError ="Error";



/**


* Representa el

diálogo de advertencia


*/


private String titAdvertencia ="Cuidado";



/**


* Representa el diálogo de información con icono


*/


private String titInformacion ="Información";






/**


* Representa el diálogo de texto plan
o sin icono


*/


private String titTextoPlano ="Información";



/**


* Representa el diálogo de elección Si, No, Cancelar


*/


private String titSiNoCancelar="Seleccione una opción";



/**


* Representa el diálogo de elección Si
, No


*/


private String titSiNo="Escoja una opción";



/**


* Representa el diálogo OK, Cancel


*/


private String titOKCancel="Atención";



/** Creates new BeanMensajes */

Universidad del Cauca


FIET


Depart
amento de Telemática.

Sistemas Distribuidos.




public MessageBean() {


}



/** Creates new Bean
Mensajes */


public void setCFather(Container C) {


cPadre=C;


}



/**


* Método para desplegar un mensaje, sin ícono


* @param mensaje, el mensaje a desplegar


*/


public void message(String mensaje){


mensaje="<html><f
ont color=blue><b>"+mensaje+"</b></font></html>";


JOptionPane.showMessageDialog(cPadre,mensaje);


return;


}



/**


* Método para desplegar un mensaje de error, con icono


* @param mensaje, el mensaje a desplegar


*/


public

void error(String mensaje){


mensaje="<html><font color=red><b>"+mensaje+"</b></font></html>";


JOptionPane.showMessageDialog(cPadre,mensaje,titError,JOptionPane.ERROR_MESSAG
E);


return;


}



/**


* Metodo para desplegar un mensaj
e de avertencia, con ìcono


* @param mensaje, el mensaje a desplegar.


*/


public void warning(String mensaje){


mensaje="<html><font color=red><b>"+mensaje+"</b></font></html>";


JOptionPane.showMessageDialog(cPadre,mensaje,titAdverte
ncia,JOptionPane.WARNIN
G_MESSAGE);


return;


}



/**


* Método para desplegar un mensaje de información


* @param mensaje, el mensaje a desplegar


*/


public void information(String mensaje){


mensaje="<html><font color=blue>
<b>"+mensaje+"</b></font></html>";


JOptionPane.showMessageDialog(cPadre,mensaje,titInformacion,JOptionPane.INFORM
ATION_MESSAGE);


return;


}



/**


* Mètod para desplegar un mensaje plano


* @param mensaje, el mensaje a desplegar



*/


public void text(String mensaje){


mensaje="<html><font color=blue><b>"+mensaje+"</b></font></html>";


JOptionPane.showMessageDialog(cPadre,mensaje,titTextoPlano,JOptionPane.PLAIN_M
ESSAGE);


return;


}



/**


* Método pa
ra desplegar un mensaje con las opciones Si,No,Cancelar

Universidad del Cauca


FIET


Depart
amento de Telemática.

Sistemas Distribuidos.




* @param mensaje, el mensaje a desplegar


* @return la opción escogida Si=0, No=1, Cancelar=2


*/


public int IfNoCancel(String mensaje){


Object[] options = {"Si","No","Cancelar"
};


mensaje="<html><font color=green><b>"+mensaje+"</b></font></html>";


int n =
JOptionPane.showOptionDialog(cPadre,mensaje,titSiNoCancelar,JOptionPane.YES_NO
_CANCEL_OPTION,JOptionPane.QUESTION_MESSAGE,null,options,options[2]);


return n;



}



/**


* Método para desplegar un mensaje con las opciones Si, No


* @param mensaje, el mensaje a desplegar


* @return n, la opción escogida. Si=0, No=1


*/


public int IfNo(String mensaje){


Object[] options = {"Si","No"};


mensaje="<html><font color=green><b>"+mensaje+"</b></font></html>";


int n =
JOptionPane.showOptionDialog(cPadre,mensaje,titSiNo,JOptionPane.YES_NO_OPTION,
JOptionPane.WARNING_MESSAGE,null,options,options[1]);


return n;


}



/**


* Método para desplegar un mensaje con opciones Aceptar, Cancelar


* @param mensaje, el mensaje a desplegar


* @return la opción escogida Aceptar=0, Cancelar=1;


*/


public int AceptCancel(String mensaje){


Object[] options = {"Aceptar"
,"Cancelar"};


mensaje="<html><font color=green><b>"+mensaje+"</b></font></html>";


int n =
JOptionPane.showOptionDialog(cPadre,mensaje,titOKCancel,JOptionPane.OK_CANCEL_
OPTION,JOptionPane.WARNING_MESSAGE,null,options,options[1]);


return n;


}

}



Código de
Client

(
Client
.java)


package view;


import java.awt.GraphicsConfiguration;

import java.awt.HeadlessException;


import javax.swing.JButton;

import javax.swing.JFrame;

import javax.swing.JLabel;

import javax.swing.JPanel;

import javax.s
wing.JTextField;


import interfaces.User;

import control.BankControl;

import javax.swing.JScrollPane;

import javax.swing.JTextArea;


public class Client extends JFrame {


private BankControl bc;


private MessageBean bm;



Universidad del Cauca


FIET


Depart
amento de Telemática.

Sistemas Distribuidos.




/**



*



*/


private static fin
al long serialVersionUID = 1L;


private JPanel jContentPane = null;


private JTextField cedula = null;


private JTextField login = null;


private JTextField nombre = null;


private JLabel jLabel = null;


private JLabel jLabel1 = null;


private JLabel jLabe
l2 = null;


private JButton add = null;


private JButton find = null;


private JButton update = null;


private JButton delete = null;


private JButton lister = null;


private JTextArea listUsers = null;


public Client() throws HeadlessException {



super()
;



// TODO Auto
-
generated constructor stub



initialize();


}



public Client(GraphicsConfiguration arg0) {



super(arg0);



// TODO Auto
-
generated constructor stub



initialize();


}



public Client(String arg0) throws HeadlessException {



super(arg0);



// TODO Auto
-
generated constructor stub



initialize();


}



public Client(String arg0, GraphicsConfiguration arg1) {



super(arg0, arg1);



// TODO Auto
-
generated constructor stub



initialize();


}



/**



* This method initializes cedula




*




* @r
eturn javax.swing.JTextField




*/


private JTextField getCedula() {



if (cedula == null) {




cedula = new JTextField();




cedula.setBounds(new
java.awt.Rectangle(62,15,81,20));



}



return cedula;


}



/**



* This method initializes login




*




*
@return javax.swing.JTextField




*/


private JTextField getLogin() {

Universidad del Cauca


FIET


Depart
amento de Telemática.

Sistemas Distribuidos.





if (login == null) {




login = new JTextField();




login.setBounds(new java.awt.Rectangle(63,73,80,20));



}



return login;


}



/**



* This method initializes nombre




*




* @r
eturn javax.swing.JTextField




*/


private JTextField getNombre() {



if (nombre == null) {




nombre = new JTextField();




nombre.setBounds(new
java.awt.Rectangle(62,41,80,20));



}



return nombre;


}



/**



* This method initializes Add




*




* @r
eturn javax.swing.JButton




*/


private JButton getAdd() {



if (add == null) {




add = new JButton();




add.setBounds(new java.awt.Rectangle(158,8,89,27));




add.setText("Add");




add.addActionListener(new
java.awt.event.ActionListener() {





public

void
actionPerformed(java.awt.event.ActionEvent e) {






System.out.println("Add"); // TODO Auto
-
generated Event stub actionPerformed()






//agregar un usuario






if(bc.addUser(Integer.parseInt(cedula.getText()),nombre.getText(
),login.getText()))







clean();






else







bm.error("Inserción fallida");











}




});



}



return add;


}



/**



* This method initializes find




*




* @return javax.swing.JButton




*/


private JButton getFind() {



if (find == null) {




find = new JButton(
);




find.setBounds(new java.awt.Rectangle(159,43,89,28));




find.setText("Find");

Universidad del Cauca


FIET


Depart
amento de Telemática.

Sistemas Distribuidos.






find.addActionListener(new
java.awt.event.ActionListener() {





public void
actionPerformed(java.awt.event.ActionEvent e) {






System.out.println("Find"); // TODO Au
to
-
generated Event stub actionPerformed()






//encontrar un usuario












User
u=bc.searchUser(Integer.parseInt(cedula.getText()));






cedula.setText(Integer.toString(u.getId()));






nombre.setText(u.getName());






login.setText(u.getLogin());





}




});



}



return find;


}



/**



* This method initializes update




*




* @return javax.swing.JButton




*/


private JButton getUpdate() {



if (update == null) {




update = new JButton();




update.setBounds(new
java.awt.Rectangle(159,82,90
,26));




update.setText("Update");




update.addActionListener(new
java.awt.event.ActionListener() {





public void
actionPerformed(java.awt.event.ActionEvent e) {






System.out.println("Update"); // TODO
Auto
-
generated Event stub actionPerformed()






//actualizar un usuario






if(bc.updateUser(Integer.parseInt(cedula.getText()),nombre.getTe
xt(),login.getText()))







clean();






else







bm.error("Actualización fallida");





}




});



}



return update;


}



/**



* This method initializes d
elete




*




* @return javax.swing.JButton




*/


private JButton getDelete() {



if (delete == null) {




delete = new JButton();




delete.setBounds(new
java.awt.Rectangle(160,117,88,27));




delete.setText("Delete");

Universidad del Cauca


FIET


Depart
amento de Telemática.

Sistemas Distribuidos.






delete.addActionListener(new
ja
va.awt.event.ActionListener() {





public void
actionPerformed(java.awt.event.ActionEvent e) {






System.out.println("Delete"); // TODO
Auto
-
generated Event stub actionPerformed()






//agregar un usuario






if(bc.delUser(Integer.parseInt(cedula.getT
ext())))







clean();






else







bm.error("Borrado fallido");





}




});



}



return delete;


}





/**



* This method initializes listUsers




*




* @return javax.swing.JTextArea




*/


private JTextArea getListUsers() {



if (listUsers == nu
ll) {




listUsers = new JTextArea();



}



return listUsers;


}




public void setControl(String[] args){



bc=new BankControl(args);


}



/**



* @param args



*/


public static void main(String[] args) {



// TODO Auto
-
generated method stub



Client c=n
ew Client();



c.setControl(args);



c.show();



}



/**



* This method initializes this



*



* @return void



*/


private void initialize() {



this.setSize(300, 328);



this.setContentPane(getJContentPane());



this.setTitle("Cliente");



bm=new Messa
geBean();



bm.setCFather(this);


}



/**



* This method initializes jContentPane

Universidad del Cauca


FIET


Depart
amento de Telemática.

Sistemas Distribuidos.





*



* @return javax.swing.JPanel



*/


private JPanel getJContentPane() {



if (jContentPane == null) {




jLabel2 = new JLabel();




jLabel2.setBounds(new
java.awt.Recta
ngle(10,75,45,16));




jLabel2.setText("Login");




jLabel1 = new JLabel();




jLabel1.setBounds(new
java.awt.Rectangle(9,42,45,16));




jLabel1.setText("Nombre");




jLabel = new JLabel();




jLabel.setBounds(new java.awt.Rectangle(9,17,48,16));




jLabel
.setText("Cédula");




jContentPane = new JPanel();




jContentPane.setLayout(null);




jContentPane.add(getCedula(), null);




jContentPane.add(getLogin(), null);




jContentPane.add(getNombre(), null);




jContentPane.add(jLabel, null);




jContentPane.a
dd(jLabel1, null);




jContentPane.add(jLabel2, null);




jContentPane.add(getAdd(), null);




jContentPane.add(getFind(), null);




jContentPane.add(getUpdate(), null);




jContentPane.add(getDelete(), null);



}



return jContentPane;


}




private void
clean(){



cedula.setText("");



nombre.setText("");



login.setText("");


}


} // @jve:decl
-
index=0:visual
-
constraint="10,10"





Creemos el paquete

interfaces

y copiemos

los archivos disponibles en
el
proyecto
BancoServer_IDL

(paquete interfaces)
.




Fina
lmente
, se agrega una clase control que utilice los méto
dos remotos. Crear
un paquete
control

con la clase
BankControl.java

que tenga el siguiente código:


package control;



import interfaces.IUser;

import interfaces.IUserHelper;

import interfaces.User;


import java.util.List;

Universidad del Cauca


FIET


Depart
amento de Telemática.

Sistemas Distribuidos.




import org.omg.CORBA.ORB;

import org.omg.CosNaming.NamingContextExt;

import org.omg.CosNaming.NamingContextExtHelper;



public class BankControl {


private User u=null;


private IUser ir=null;






public BankControl(String[] args){



initORB(args);



}




public void initORB(String[] args){



try {//crea e inicializa el ORB



ORB orb = ORB.init(args,null);



// get the root naming context



org.omg.CORBA.Object objRef = orb



.resolv
e_initial_references("NameService");



// Use NamingContextExt instead of NamingContext.
This is



// part of the Interoperable naming Service.



NamingContextExt ncRef =
NamingContextExtHelper.narrow(objRef);



// r
esolve the Object Reference in Naming



String name = "Interfaz";



ir = IUserHelper.narrow(ncRef.resolve_str(name));



System.out.println("Conectado con el servidor");



}catch (Exception e) {



System.out.prin
tln("ERROR : " + e);



e.printStackTrace(System.out);




}


}




public User searchUser(int id){



return ir.searchUser(id);


}




public boolean updateUser(int id,String name,String log){



boolean update=true;



if(!ir.updateUser(id,name,log))




update=false;



return update;


}




public boolean delUser(int id){



boolean del=true;



if(!ir.delUser(id))




del=false;



return del;


}


public boolean addUser(int id,String name,String log){



boolean add=true;



if(!ir.addUser(id,name,log))




a
dd=false;



return add;


}


Universidad del Cauca


FIET


Depart
amento de Telemática.

Sistemas Distribuidos.



}







8.

Ejecución de la práctica



C
orrer el ORB: Crear un archivo con extensión .bat con las siguientes lineas:

start orbd
-
ORBInitialPort 1050
-
ORBInitialHost 1
27
.1.1.1

Nota:

remplazar la dirección
IP

de la maquina

de trabajo (S
ervidor)
.



Correr el servidor, ingresando el siguiente parámetro como argumento inicial
:

-
ORBInitialPort 1050

Esto es: click derecho en la clase
ObjectServer.java

-
> run
-
>run
-
>Arguments
-
>
Program Arguments






Correr el client
e, con los siguientes argumentos iniciales:

-
ORBInitialPort 1050
-
ORBInitialHost 172.16.19.218


Nota:
cambiar la dirección IP por la de la maquina de trabajo (servidor).




Universidad del Cauca


FIET


Depart
amento de Telemática.

Sistemas Distribuidos.