Você está na página 1de 20

Web Services

EclipseSDK/DB2| Construindo/Consumindo Servios

Mario C. Ponciano a.k.a: Razec http://razec.wordpress.com mrazec@gmail.com


28 de Novembro 2009

Sumrio
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

Objetivo
Ajudar estudantes, desenvolvedores, a desenvolver web services de maneira simples . Alm de implementar um servio 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 implementao do Web Service com Axis uma classe Java que possui mtodos pblicos.

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.

Wikipdia a enciclopdia livre define Web Service como uma soluo utilizada na integrao de sistemas e na comunicao entre aplicaes diferentes.

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 conexo ao DB2. (Quadro 01)

<- Cdigo ->


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;
//Mtodo de coneco

public static Connection getConnection() throws SQLException, ClassNotFoundException{ Properties connProperties = new Properties(); connProperties.put("user", "razec");//Definir seu usurio. connProperties.put("password", "senha");//Definir sua senha. Class.forName(driver); return DriverManager.getConnection(connectionURL,connProperties); } }

Quadro 01 Conexo com o DB2

3 Passo: Criar toda a estrutura DAO. (Figura 03).

Figura 03 Criar classe para manipular mtodos SQL.

Esta classe conter todos os mtodos SQL para manipulao dos dados. Vamos colocar o nome de: DashBoardDAOImp.java Os mtodos so: Insert, Delete, Update, Select. (Quadro 02). <- Cdigo ->
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 Mtodo insert para DB2.

Construindo Web Service


Aps todas as classes criadas e os mtodos pblicos finalizados, chegou o momento esperado a criao do web service. Atravs do Eclipse torna-se muito simples a criao.( Figura 04).

4 Passo:
Clique com o boto direito sobre a classe que implementa os mtodos citados acima. Boto Direito -> Web Services -> Create Web Service

Figura 04 Criar Web service

Em seguida abrir tela abaixo, contendo as configuraes mencionadas no inicio do tutorial. Marque a opo: [v] Publish the Web service e clique em NEXT >

Figura 05 Gerando o Web Service. Conferir as configuraes.

Na Figura 06, os mtodos criados so identificados . Estes mtodos so os que usaremos em nossa implementao. Clique NEXT >

Figura 06 Configurando o *.wsdl.

Na Figura 07, inicie o servidor. Clique Start Server Clique NEXT >

Figura 07 Iniciando o Servidor .

Na Figura 08 Com esta opo marcada permitir o registro do seu Web Service para que possamos utiliz-lo em outras aplicaes. Para Finalizar marque a opo: [v] Launch the Web Services Explorer to publish the Web service to a UDDI Registry Clique Finish

Figura 08 Registrar o Web service.

Testando o Web Service


Aps criado o seu WSDL possvel testar os seus mtodos.

5 Passo: Clique no boto 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 mtodo selectSQL(). Que neste caso implementa uma consulta, entrei com a informao 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 informao do banco de dados.

10

Criando Web Service Client


Servio criado, tudo funcionando chegou o momento de utilizar o servio, ou seja, consumi-lo. E o nosso amigo Eclipse SDK continua nos ajudando com est implementao. 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 mtodos do DashBoardDaoImp.wsdl.

Aps 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: Implementao Java/Comunicao DB2
Crie uma classe MAIN.java para consumir o servio. Neste momento estamos implementando o mtodo que est localizado em nosso web service. E o mesmo est inserindo dados dentro do DB2 utilizando uma implementao JAVA. <- Cdigo ->
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 Mtodo insert para JAVA/DB2.

7 Passo: Implementao C# /Comunicao DB2


Agora basta implementar os mtodos criados em seu Web Service em sua aplicao em C#. <- Cdigo ->
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 Mtodo insert para C#/DB2.

14

Anexos
Todos os cdigos citados esto em anexo. E esto disponveis em download.

Conexo com o DB2.

package org.db2.connector; import import import import import import java.sql.Connection; java.sql.DriverManager; java.sql.ResultSet; java.sql.SQLException; java.sql.Statement; 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 usurio. 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 import import import import import import java.sql.Array; java.sql.Connection; java.sql.PreparedStatement; java.sql.ResultSet; java.sql.SQLException; java.sql.Statement; 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); }

} catch (SQLException ex) { JOptionPane.showMessageDialog(null, ex.getMessage()); } 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(); sbDelete.append("DELETE FROM "); sbDelete.append(DASHConstants.TABLE_NAME); sbDelete.append(" WHERE ID = ?"); conn = this.conn; stmtDelete = conn.prepareStatement(sbDelete.toString()); stmtDelete.setInt(1, id); int rows = stmtDelete.executeUpdate(); if (rows != 1) {

18

throw new SQLException( "executeUpdate return value: " + rows); } } catch (SQLException ex) { JOptionPane.showMessageDialog(null, ex.getMessage()); } 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

} 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 time 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"); System.out.println("Got results:"); while (result.next()) { // process results one row at a time 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#"); } }}

Você também pode gostar