Web Services EclipseSDK/DB2 Construindo/Consumindo Serviços Mario C. Ponciano a.k.a: Razec http://razec.wordpress.com mrazec@gmail.com 28 de Novembro 2009
2 Sumário Objetivo... 3 Requisitos... 3 Desenvolvimento... 3 Criando projeto no Eclipse... 3 Conectando ao DB2... 4 Construindo Web Service... 6 Testando o Web Service... 9 Criando Web Service Client... 10 Consumindo Web Service... 13
3 Objetivo Ajudar estudantes, desenvolvedores, a desenvolver web services¹ de maneira simples. Além de implementar um serviço que possui a interoperabilidade de comunicar diretamente com o DB2 Database utilizando Java e C#. Requisitos DB2 Eclipse SDK - v. +3.4 Apache Axis ou Axis2 Tomcat v.6.0 Server ou WebSphere 6.1 Desenvolvimento A implementação do Web Service com Axis é uma classe Java que possui métodos públicos. Criando projeto no Eclipse 1 Passo: Criar um projeto no Eclipse, veja Figura 01. Clique: File -> New -> Other -> Web -> Dynamic Web Project. Figura 01 Criando Dynamic Web Project. ¹ Wikipédia a enciclopédia livre define Web Service como uma solução utilizada na integração de sistemas e na comunicação entre aplicações diferentes.
4 Conectando ao DB2 2 Passo: Criar uma classe para se conectar ao DB2. O nome de nossa classe será: DB2ConnectionFactory, como demonstrado na Figura 02. Figura 02 Criar classe DB2ConnectionFactory.java Nossa classe conterá toda estrutura de conexão ao DB2. (Quadro 01) <- Código -> public class DB2ConnectionFactory static String remotedb = "localhost"; static String portdb = "50000"; static String namedb = "WSDB";//nome do seu banco. static String driver = "com.ibm.db2.jcc.db2driver"; static String connectionurl = "jdbc:db2://" + remotedb + ":" + portdb + "/" + namedb; private static Connection conn = null; //Método de conecção public static Connection getconnection() throws SQLException, ClassNotFoundException Properties connproperties = new Properties(); connproperties.put("user", "razec");//definir seu usuário. connproperties.put("password", "senha");//definir sua senha. Class.forName(driver); return DriverManager.getConnection(connectionURL,connProperties); Quadro 01 Conexão com o DB2
5 3 Passo: Criar toda a estrutura DAO. (Figura 03). Esta classe conterá todos os métodos SQL para manipulação dos dados. Vamos colocar o nome de: DashBoardDAOImp.java Os métodos são: Insert, Delete, Update, Select. (Quadro 02). <- Código -> Figura 03 Criar classe para manipular métodos SQL. public void insert(int id, int qtd, String namekey, String coordx, String coordy, String text) throws Exception // TODO Auto-generated method stub // TODO Auto-generated method stub PreparedStatement psinsert = null; Connection conn = null; if( namekey == null) throw new Exception("The value it's null"); try String SQL = "INSERT INTO DASHBOARD (ID, QTD, NAMEKEY, COORD_X, COORD_Y, TEXT)"+ "VALUES (?,?,?,?,?,?)"; conn = this.conn; psinsert = conn.preparestatement(sql); psinsert.setint(1, id); psinsert.setint(2, qtd); psinsert.setstring(3, namekey); psinsert.setstring(4, coordx); psinsert.setstring(5, coordy); psinsert.setstring(6, text); int rows = psinsert.executeupdate(); if (rows!= 1) throw new SQLException( "executeupdate return value: " + rows); catch (SQLException ex) JOptionPane.showMessageDialog(null,ex.getMessage()); finally DB2ConnectionFactory.closeStatement(psInsert); DB2ConnectionFactory.closeJDBCConnection(conn); Quadro 02 Método insert para DB2.
6 Construindo Web Service Após todas as classes criadas e os métodos públicos finalizados, chegou o momento esperado a criação do web service. Através do Eclipse torna-se muito simples a criação.( Figura 04). 4 Passo: Clique com o botão direito sobre a classe que implementa os métodos citados acima. Botão Direito -> Web Services -> Create Web Service Figura 04 Criar Web service
7 Em seguida abrirá à tela abaixo, contendo as configurações mencionadas no inicio do tutorial. Marque a opção: [v] Publish the Web service e clique em NEXT > Figura 05 Gerando o Web Service. Conferir as configurações. Na Figura 06, os métodos criados são identificados. Estes métodos são os que usaremos em nossa implementação. Clique NEXT > Figura 06 Configurando o *.wsdl.
8 Na Figura 07, inicie o servidor. Clique Start Server Clique NEXT > Figura 07 Iniciando o Servidor. Na Figura 08 Com esta opção marcada permitirá o registro do seu Web Service para que possamos utilizá-lo em outras aplicações. Para Finalizar marque a opção: [v] Launch the Web Services Explorer to publish the Web service to a UDDI Registry Clique Finish Figura 08 Registrar o Web service.
9 Testando o Web Service Após criado o seu WSDL é possível testar os seus métodos. 5 Passo: Clique no botão Figura 09 WSDL Page. Retornará a Figura 09. Figura 09 Testando o Web Service em seu web Server. Como podemos observar com à Figura 10 escolhi o método selectsql(). Que neste caso implementa uma consulta, entrei com a informação e o mesmo retornou o que está gravado dentro do banco de dados DB2. Isto significa que o teste realizado com Sucesso. Figura 10 Retornando a informação do banco de dados.
10 Criando Web Service Client Serviço criado, tudo funcionando chegou o momento de utilizar o serviço, ou seja, consumi-lo. E o nosso amigo Eclipse SDK continua nos ajudando com está implementação. Clique: File -> New -> Other -> Web Services -> Web Service Client Figura 11 Criando Web Service Client.
11 Clicando em Next -> abrirá à Figura 12 clique em: Browse... > Browse... >[-] WSDB2 [-] WebContent [-] wsdl DashBoardDAOImp.wsdl Clique [OK] Clique [OK] [OK Figura 12 Implementando os métodos do DashBoardDaoImp.wsdl. Após definir o arquivo WSDL chegou o momento de criar o cliente clique sobre: Client Project: e de o nome de [WSDB2Client ] -> [OK] e [Finish] Figura 13 Definindo nome do WS Client.
12 Se tudo ocorreu certo aparecerá a estrutura abaixo. Figura 14 Estrutura do WSDB2Client.!! IMPORTANTE: Seu Web Server assim como seu DB2 devem estar rodando para que o web service funcione corretamente.
13 Consumindo Web Service 6 Passo: Implementação Java/Comunicação DB2 Crie uma classe MAIN.java para consumir o serviço. Neste momento estamos implementando o método que está localizado em nosso web service. E o mesmo está inserindo dados dentro do DB2 utilizando uma implementação JAVA. <- Código -> public static void main(string[] args) // TODO Auto-generated method stub try DashBoardDAOImpService service = new DashBoardDAOImpServiceLocator(); DashBoardDAOImp consumingws = (DashBoardDAOImp) service.getdashboarddaoimp(); consumingws.insert(1, 2,"namekey", "123", "235", "Hello World"); catch (ServiceException e) // TODO Auto-generated catch block e.printstacktrace(); catch (RemoteException e) // TODO Auto-generated catch block e.printstacktrace(); Quadro 03 Método insert para JAVA/DB2. 7 Passo: Implementação C# /Comunicação DB2 Agora basta implementar os métodos criados em seu Web Service em sua aplicação em C#. <- Código -> using System; using WS.localhost; namespace WS.app_code public class WSDB2Csharp public WSDB2Csharp() public void test() DashBoardDAOImpService consumingdb2 = new DashBoardDAOImpService(); consumingdb2.insert(4, 5, "test", "123", "255", "C#"); Quadro 04 Método insert para C#/DB2.
14 Anexos Todos os códigos citados estão em anexo. E estão disponíveis em download. Conexão com o DB2. package org.db2.connector; import java.sql.connection; import java.sql.drivermanager; import java.sql.resultset; import java.sql.sqlexception; import java.sql.statement; import java.util.properties; public class DB2ConnectionFactory static String remotedb = "localhost"; static String portdb = "50000"; static String namedb = "WSDB";//nome do seu banco. static String driver = "com.ibm.db2.jcc.db2driver"; static String connectionurl = "jdbc:db2://" + remotedb + ":" + portdb + "/" + namedb; private static Connection conn = null; private long lasttransaction; public static Connection getconnection() throws SQLException, ClassNotFoundException Properties connproperties = new Properties(); connproperties.put("user", "razec");//definir seu usuário. connproperties.put("password", "senha");//definir sua senha. Class.forName(driver); return DriverManager.getConnection(connectionURL,connProperties); public static void closeconnection(connection conn, Statement stmt, ResultSet rs) throws Exception close(conn, stmt, rs); public static void close(connection conn, Statement stmt, ResultSet rs) throws Exception try if(rs!= null) rs.close(); if(stmt!= null) stmt.close(); if(conn!=null) conn.close(); catch(exception e) throw new Exception(e.getMessage()); public static void closejdbcconnection(final Connection conn) throws SQLException if (conn!= null) try
15 conn.close(); catch (SQLException ex) throw new SQLException(ex.getMessage()); public static void closestatement(final Statement stmt) throws SQLException if (stmt!= null) try stmt.close(); catch (SQLException ex) throw new SQLException(ex.getMessage()); public static void closeresultset(final ResultSet rs) throws SQLException if (rs!= null) try rs.close(); catch (SQLException ex) throw new SQLException(ex.getMessage());
16 DAO Classe DAO package org.dashboard.dao; public interface IDAO void insert(int id, int qtd, String namekey, String coordx, String coordy, String text) throws Exception; void delete(int id) throws Exception; void update(int id, int qtd, String namekey, String coordx, String coordy, String text) throws Exception; Classe DashBoardDAOImp package org.dashboard.dao; import java.sql.array; import java.sql.connection; import java.sql.preparedstatement; import java.sql.resultset; import java.sql.sqlexception; import java.sql.statement; import java.util.arraylist; import javax.swing.joptionpane; import org.dashboard.util.dashconstants; import org.db2.connector.db2connectionfactory; public class DashBoardDAOImp implements IDAO static Connection conn; public DashBoardDAOImp() try this.conn = DB2ConnectionFactory.getConnection(); catch (SQLException e) // TODO Auto-generated catch block e.printstacktrace(); catch (ClassNotFoundException e) // TODO Auto-generated catch block e.printstacktrace(); public void insert(int id, int qtd, String namekey, String coordx, String coordy, String text) throws Exception // TODO Auto-generated method stub // TODO Auto-generated method stub PreparedStatement psinsert = null; Connection conn = null; if( namekey == null) throw new Exception("The value it's null"); try
17 String SQL = "INSERT INTO DASHBOARD (ID, QTD, NAMEKEY, COORD_X, COORD_Y, TEXT)"+ "VALUES (?,?,?,?,?,?)"; conn = this.conn; psinsert = conn.preparestatement(sql); psinsert.setint(1, id); psinsert.setint(2, qtd); psinsert.setstring(3, namekey); psinsert.setstring(4, coordx); psinsert.setstring(5, coordy); psinsert.setstring(6, text); int rows = psinsert.executeupdate(); if (rows!= 1) throw new SQLException( "executeupdate return value: " + rows); ex.getmessage()); catch (SQLException ex) JOptionPane.showMessageDialog(null, finally DB2ConnectionFactory.closeStatement(psInsert); DB2ConnectionFactory.closeJDBCConnection(conn); public void delete(final int id) throws Exception // TODO Auto-generated method stub PreparedStatement stmtdelete = null; Connection conn = null; if (id == 0) throw new NullPointerException("id parameter"); try StringBuffer sbdelete = new StringBuffer(); conn = this.conn; stmtdelete = conn.preparestatement(sbdelete.tostring()); sbdelete.append("delete FROM "); sbdelete.append(dashconstants.table_name); sbdelete.append(" WHERE ID =?"); stmtdelete.setint(1, id); int rows = stmtdelete.executeupdate(); if (rows!= 1)
18 throw new SQLException( "executeupdate return value: " + rows); ex.getmessage()); catch (SQLException ex) JOptionPane.showMessageDialog(null, finally DB2ConnectionFactory.closeStatement(stmtDelete); DB2ConnectionFactory.closeJDBCConnection(conn); public void update(int id, int qtd, String namekey, String coordx, String coordy, String text) throws Exception PreparedStatement stmtupdate = null; Connection conn = null; // TODO Auto-generated method stub if (namekey == null) throw new NullPointerException("NameKey parameter"); try StringBuffer sbupdate = new StringBuffer(); sbupdate.append("update "); sbupdate.append(dashconstants.table_name); sbupdate.append(" SET "); sbupdate.append(" QTD =?, "); sbupdate.append(" NAMEKEY =?, "); sbupdate.append(" COORD_X =?, "); sbupdate.append(" COORD_Y =?, "); sbupdate.append(" TEXT =? "); sbupdate.append(" WHERE "); sbupdate.append(" ID =?"); conn = this.conn; stmtupdate = conn.preparestatement(sbupdate.tostring()); stmtupdate.setint(1, qtd); stmtupdate.setstring(2, namekey); stmtupdate.setstring(3, coordx); stmtupdate.setstring(4, coordy); stmtupdate.setstring(5, text); stmtupdate.setint(6, id); int rows = stmtupdate.executeupdate(); if (rows!= 1) throw new SQLException( "executeupdate return value: " + rows);
19 time catch (SQLException ex) System.out.println(ex.getMessage()); finally DB2ConnectionFactory.closeStatement(stmtUpdate); DB2ConnectionFactory.closeJDBCConnection(conn); public String[] selectsql(string fieldname) throws SQLException String[] ret = null; ArrayList arrl = new ArrayList(); Statement stmt = null; try stmt = conn.createstatement(); ResultSet result = stmt.executequery("select * FROM DASHBOARD"); System.out.println("Got results:"); while (result.next()) // process results one row at a arrl.add(result.getstring(fieldname)); ret = (String[]) arrl.toarray(new String[arrL.size()]); catch (SQLException e) // TODO Auto-generated catch block JOptionPane.showMessageDialog(null, e.getmessage()); finally DB2ConnectionFactory.closeStatement(stmt); DB2ConnectionFactory.closeJDBCConnection(conn); return ret; public int selectqtdsql(string fieldname) throws SQLException int qtd = 0; Statement stmt = null; try stmt = conn.createstatement(); ResultSet result = stmt.executequery("select * FROM DASHBOARD"); time System.out.println("Got results:"); while (result.next()) // process results one row at a qtd = result.getint(fieldname); catch (SQLException e) // TODO Auto-generated catch block JOptionPane.showMessageDialog(null, e.getmessage()); finally DB2ConnectionFactory.closeStatement(stmt); DB2ConnectionFactory.closeJDBCConnection(conn); return qtd;
20 Web Service Client / JAVA package org.wsdb2.test; import javax.xml.rpc.serviceexception; import org.dashboard.dao.dashboarddaoimp; import org.dashboard.dao.dashboarddaoimpservice; import org.dashboard.dao.dashboarddaoimpservicelocator; public class Main /** * @param args */ public static void main(string[] args) // TODO Auto-generated method stub try DashBoardDAOImpService service = new DashBoardDAOImpServiceLocator(); DashBoardDAOImp consumingws = (DashBoardDAOImp) service.getdashboarddaoimp(); consumingws.insert(1, 2,"namekey", "123", "235", "Hello World"); catch (ServiceException e) // TODO Auto-generated catch block e.printstacktrace(); catch (RemoteException e) // TODO Auto-generated catch block e.printstacktrace(); Web Service Client / C# using System; using WS.localhost; namespace WS.app_code public class WSDB2Csharp public WSDB2Csharp() public void ConsumingDB2() DashBoardDAOImpService consumingdb2 = new DashBoardDAOImpService(); consumingdb2.insert(4, 5, "test", "123", "255", "C#");