Java, java soap web service con connessione jdbc a database mySql.
-
Tabelle Country e City del database.
Capital in Country è chiave esterna in riferimento a ID di City.
CREATE TABLE IF NOT EXISTS `country` (
`Code` char(3) NOT NULL DEFAULT '',
`Name` char(52) NOT NULL DEFAULT '',
`Continent` enum('Asia','Europe','North America',
'Africa','Oceania','Antarctica',
'South America') NOT NULL DEFAULT 'Asia',
`Region` char(26) NOT NULL DEFAULT '',
`SurfaceArea` float(10,2) NOT NULL DEFAULT '0.00',
`IndepYear` smallint(6) DEFAULT NULL,
`Population` int(11) NOT NULL DEFAULT '0',
`LifeExpectancy` float(3,1) DEFAULT NULL,
`GNP` float(10,2) DEFAULT NULL,
`GNPOld` float(10,2) DEFAULT NULL,
`LocalName` char(45) NOT NULL DEFAULT '',
`GovernmentForm` char(45) NOT NULL DEFAULT '',
`HeadOfState` char(60) DEFAULT NULL,
`Capital` int(11) DEFAULT NULL,
`Code2` char(2) NOT NULL DEFAULT '',
PRIMARY KEY (`Code`)
)
CREATE TABLE IF NOT EXISTS `city` (
`ID` int(11) NOT NULL AUTO_INCREMENT,
`Name` char(35) NOT NULL DEFAULT '',
`CountryCode` char(3) NOT NULL DEFAULT '',
`District` char(20) NOT NULL DEFAULT '',
`Population` int(11) NOT NULL DEFAULT '0',
PRIMARY KEY (`ID`)
)
-
Classe Stato per la lettura di alcuni dati dalla tabella del database.
import javax.xml.bind.annotation.XmlElement;
import javax.xml.bind.annotation.XmlRootElement;
@XmlRootElement
public class Stato {
private String nome;
private String codice;
private int popolazione;
private double superficie;
private String capitol;
public Stato() {}
public Stato(String nome) {
this.nome = nome;
}
public Stato(String nome, String codice, int popolazione) {
this.nome = nome;
this.codice = codice;
this.popolazione = popolazione;
}
public Stato(String nome, String codice, int popolazione, double superficie) {
this.nome = nome;
this.codice = codice;
this.popolazione = popolazione;
this.superficie = superficie;
}
@XmlElement
public String getNome() {
return nome;
}
public void setNome(String nome) {
this.nome = nome;
}
@XmlElement
public String getCodice() {
return codice;
}
public void setCodice(String codice) {
this.codice = codice;
}
@XmlElement
public int getPopolazione() {
return popolazione;
}
public void setPopolazione(int popolazione) {
this.popolazione = popolazione;
}
@XmlElement
public double getSuperficie() {
return superficie;
}
public void setSuperficie(double superficie) {
this.superficie = superficie;
}
@XmlElement
public String getCapitol() {
return capitol;
}
public void setCapitol(String capitol) {
this.capitol = capitol;
}
}
-
Classe ListaStati per gestire un elenco di stati letti da database.
import java.util.ArrayList;
import javax.xml.bind.annotation.XmlElement;
import javax.xml.bind.annotation.XmlRootElement;
@XmlRootElement
public class ListaStati {
@XmlElement(name = "stato")
private ArrayList<Stato> lista = new ArrayList<Stato>();
public ListaStati() {}
public void add(Stato stato) {
if(stato != null) {
lista.add(stato);
}
}
public int size() {
return lista.size();
}
public Stato get(int index) {
Stato ret = null;
if (index >= 0 && index < lista.size()) {
ret = lista.get(index);
}
return ret;
}
}
-
Classe Database come utility per la gestione della connessione e delle richieste al database mySql.
Sono presenti i metodi di connessione e sconnessione oltre a metodi di interrogazione.
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
public class Database {
private String host;
private int port;
private String schema;
private String username;
private String password;
private Connection conn;
public Database(String host, int port, String schema,
String username, String password) {
this.host = host;
this.port = port;
this.schema = schema;
this.username = username;
this.password = password;
}
public int Connetti() {
int ret = -1;
try {
Class.forName("com.mysql.jdbc.Driver");
conn = DriverManager.getConnection(
"jdbc:mysql://"+host+":"+port+"/"+schema,
username, password);
ret = 0;
}
catch(Exception ex) {
ret = -1;
}
return ret;
}
public void Sconnetti() {
try {
conn.close();
}
catch(Exception ex) {
}
}
public Stato getStato(String nome) {
Stato ret = new Stato();
try {
String sql = "select * from country where name = ?";
PreparedStatement ps = conn.prepareStatement(sql);
ps.setString(1, nome);
ResultSet rs = ps.executeQuery();
if (rs != null) {
while(rs.next()) {
String n = rs.getString("Name");
String c = rs.getString("Code");
int p = rs.getInt("Population");
double s = rs.getDouble("SurfaceArea");
ret = new Stato(n, c, p, s);
}
}
}
catch(Exception ex) {
}
return ret;
}
public ListaStati getStati() {
ListaStati ret = new ListaStati();
try {
String sql = "select * from country";
PreparedStatement ps = conn.prepareStatement(sql);
ResultSet rs = ps.executeQuery();
if (rs != null) {
while(rs.next()) {
String n = rs.getString("Name");
String c = rs.getString("Code");
int p = rs.getInt("Population");
double s = rs.getDouble("SurfaceArea");
Stato stato = new Stato(n, c, p, s);
ret.add(stato);
}
}
}
catch(Exception ex) {
}
return ret;
}
public ListaStati getStatiConCapitale() {
ListaStati ret = new ListaStati();
try {
String sql = "select co.*, ci.name as capitolname "+
"from country as co, city as ci "+
"where co.capital = ci.id";
PreparedStatement ps = conn.prepareStatement(sql);
ResultSet rs = ps.executeQuery();
if (rs != null) {
while(rs.next()) {
String n = rs.getString("Name");
String c = rs.getString("Code");
int p = rs.getInt("Population");
double s = rs.getDouble("SurfaceArea");
String ca = rs.getString("capitolname");
Stato stato = new Stato(n, c, p, s);
stato.setCapitol(ca);
ret.add(stato);
}
}
}
catch(Exception ex) {
}
return ret;
}
public int AggiornaPopolazione(String name, int popolazione) {
int ret = -1;
try {
String sql = "update country "+
"set population = ? "+
"where name = ?";
PreparedStatement ps = conn.prepareStatement(sql);
ps.setString(2, name);
ps.setInt(1, popolazione);
ret = ps.executeUpdate();
}
catch(Exception ex) {
}
return ret;
}
public int setStato(Stato stato) {
int ret = -1;
String sql = "insert into country"+
"(name,code,population,surfacearea) "+
"values(?,?,?,?)";
try {
if (stato.getCodice() != null && stato.getCodice().length() > 0) {
PreparedStatement ps = conn.prepareStatement(sql);
ps.setString(1, stato.getNome());
ps.setString(2, stato.getCodice());
ps.setInt(3, stato.getPopolazione());
ps.setFloat(4, (float) stato.getSuperficie());
ret = ps.executeUpdate();
}
}
catch(Exception ex) {
ret = -1;
}
return ret;
}
public int removeStato(String codice) {
int ret = -1;
String sql = "delete from country "+
"where code = ?";
try {
if (codice != null && codice.length() > 0) {
PreparedStatement ps = conn.prepareStatement(sql);
ps.setString(1, codice);
ret = ps.executeUpdate();
}
}
catch(Exception ex) {
ret = -1;
}
return ret;
}
}
-
Classe World che implementa il web service SOAP e ne definisce i metodi.
import javax.jws.WebService;
import javax.jws.WebMethod;
import javax.jws.WebParam;
@WebService(serviceName = "World")
public class World {
Database db = new Database("localhost", 3306, "World",
"myusername", "mypassword");
/**
* This is a sample web service operation
*/
// @WebMethod(operationName = "hello")
// public String hello(@WebParam(name = "name") String txt) {
// return "Hello " + txt + " !";
// }
/**
* Web service operation
*/
@WebMethod(operationName = "getStato")
public Stato getStato(@WebParam(name = "nome") String nome) {
db.Connetti();
Stato ret = db.getStato(nome);
db.Sconnetti();
return ret;
}
/**
* Web service operation
*/
@WebMethod(operationName = "getStati")
public ListaStati getStati() {
//TODO write your implementation code here:
ListaStati stati = new ListaStati();
db.Connetti();
stati = db.getStati();
db.Sconnetti();
return stati;
}
/**
* Web service operation
*/
@WebMethod(operationName = "updPopolazione")
public int updPopolazione(@WebParam(name = "name") String name, @WebParam(name = "popolazione") int popolazione) {
db.Connetti();
int ret = db.AggiornaPopolazione(name, popolazione);
db.Sconnetti();
return ret;
}
/**
* Web service operation
*/
@WebMethod(operationName = "setStato")
public int setStato(@WebParam(name = "stato") Stato stato) {
db.Connetti();
int ret = db.setStato(stato);
db.Sconnetti();
return ret;
}
/**
* Web service operation
*/
@WebMethod(operationName = "delStato")
public int delStato(@WebParam(name = "nome") String nome) {
db.Connetti();
int ret = db.removeStato(nome);
db.Sconnetti();
return ret;
}
}
-
Esempio per la visualizzare dei dati degli stati su una JTable lato client.
if (db != null) {
ListaStati elencoStati = db.getStati();
if (((DefaultTableModel)jTable1.getModel()).getRowCount() > 1) {
((DefaultTableModel)jTable1.getModel()).setRowCount(0);
}
for(int i=0; i&<elencoStati.size(); i++) {
Object[] data = {elencoStati.get(i).getNome(),
elencoStati.get(i).getCodice(),
elencoStati.get(i).getRegione(),
elencoStati.get(i).getPopolazione()};
((DefaultTableModel)jTable1.getModel()).addRow(data);
}
}