Archive for March, 2009

WebService with Java 6 (0)

March 23rd, 2009 by Frank Niedermann, under Java.

It is possible to create a WebService and a WebClient with Java 6. This is a Hello World example how to do so.

There will be the following Java Classes:

WebService:
– Hello.java: This is the Class which contains the logic that will serve as WebService
– HelloServer.java: This is the Class which will start a server and publish the WebService

WebClient:
– Hello.java: This Class will automatically be created by the wsimport tool
– HelloService.java: This Class will also automatically be created by the wsimport tool
– HelloClient.java: This is the Class which will act as WebClient connecting to the WebService

Creating the WebService

1. Declare a Java Class as WebService using Annotation @WebService:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
package webservice;
 
import javax.jws.WebService;
import javax.jws.soap.SOAPBinding;
import javax.jws.soap.SOAPBinding.Style;
 
@WebService
@SOAPBinding(style=Style.RPC)
public class Hello {
	public String returnHello(String name) {
		System.out.println("Service: generating response String");
		return "Hello " + name + "!";
	}
}

2. Create the Java Class that publishes the WebService as server:

1
2
3
4
5
6
7
8
9
10
11
package webservice;
 
import webservice.Hello;
import javax.xml.ws.Endpoint;
 
public class HelloServer {
	public static void main(String[] args) {
		Hello server = new Hello();
		Endpoint endpoint = Endpoint.publish("http://localhost:8080/hello", server);
	}
}

After starting this server it’s possible to view the WSDL: http://localhost:8080/hello?wsdl

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
<?xml version="1.0" encoding="UTF-8"?>
<!-- Published by JAX-WS RI at http://jax-ws.dev.java.net. RI's version is JAX-WS RI 2.1.1 in JDK 6. -->
<!-- Generated by JAX-WS RI at http://jax-ws.dev.java.net. RI's version is JAX-WS RI 2.1.1 in JDK 6. --><definitions xmlns:soap="http://schemas.xmlsoap.org/wsdl/soap/" xmlns:tns="http://webservice/" xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns="http://schemas.xmlsoap.org/wsdl/" targetNamespace="http://webservice/" name="HelloService">
<types></types>
<message name="returnHello">
<part name="arg0" type="xsd:string"></part>
</message>
<message name="returnHelloResponse">
<part name="return" type="xsd:string"></part>
</message>
<portType name="Hello">
<operation name="returnHello" parameterOrder="arg0">
<input message="tns:returnHello"></input>
<output message="tns:returnHelloResponse"></output>
</operation>
</portType>
<binding name="HelloPortBinding" type="tns:Hello">
<soap:binding transport="http://schemas.xmlsoap.org/soap/http" style="rpc"></soap:binding>
<operation name="returnHello">
<soap:operation soapAction=""></soap:operation>
<input>
<soap:body use="literal" namespace="http://webservice/"></soap:body>
</input>
<output>
<soap:body use="literal" namespace="http://webservice/"></soap:body>
</output>
</operation>
</binding>
<service name="HelloService">
<port name="HelloPort" binding="tns:HelloPortBinding">
<soap:address location="http://localhost:8080/hello"></soap:address>
</port>
</service>
</definitions>

That’s it – the WebService is running.

Creating a WebClient

1. Automatic generation of the necessary files for the WebClient
To tool wsimport will generate the necessary Class files for the WebClient according to a given WSDL file:

1
wsimport -keep http://localhost:8080/hello?wsdl

The -keep parameter will tell wsimport to keep the Java sourcecode files and not only the binary code.

2. Create the Java Class that will act as WebClient and connect to the WebService:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
package webclient;
 
import webclient.Hello;
import webclient.HelloService;
 
public class HelloClient {
 
	public static void main(String[] args) {
		HelloService service = new HelloService();
		Hello hello = service.getHelloPort();
		System.out.println("Response: " + hello.returnHello("Joe"));
	}
 
}

Running this Class will connect to the WebService which can be seen on the console:
WebService: Service: generating response String
WebClient: Response: Hello Joe!

Tagged with , , , , .

Of course it’s possible to use Apache Derby as database for Java apps without Eclipse:

1. Download and extract Apache Derby

http://apache.atviraskodas.com/db/derby/db-derby-10.4.2.0/db-derby-10.4.2.0-bin.zip

2. Start Apache Derby database: bin/startNetworkServer.bat

3. Create database: bin/ij.bat

1
connect 'jdbc:derby://localhost:1527/myDB;create=true;user=user1;password=user1';

4. Insert some values into database:

1
2
3
4
5
CREATE TABLE restaurants(id integer, name varchar(20), city varchar(50));
INSERT INTO restaurants VALUES (1, 'Irifunes', 'San Mateo');
INSERT INTO restaurants VALUES (2, 'Estradas', 'Daly City');
INSERT INTO restaurants VALUES (3, 'Prime Rib House', 'San Francisco');
SELECT * FROM restaurants;

5. Create new Java Class, example code:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.ResultSetMetaData;
import java.sql.Statement;
 
public class Restaurants {
  private static String url = "jdbc:derby://localhost:1527/myDB;create=true;user=user1;password=user1";
  private static String table = "restaurants";
  private static Connection con = null;
  private static Statement stmt = null;
 
  public static void main(String[] args) {
    try {
      Class.forName("org.apache.derby.jdbc.ClientDriver").newInstance();
      con = DriverManager.getConnection(url);
      stmt = con.createStatement();
      ResultSet rs = stmt.executeQuery("select * from " + table);
      ResultSetMetaData rsmd = rs.getMetaData();
      int cols = rsmd.getColumnCount();
      for (int i=1; i<=cols; i++) {
      System.out.print(rsmd.getColumnLabel(i) + "\t\t");
    }
    System.out.println("\n----------------------------------------");
    while (rs.next()) {
      System.out.println(rs.getInt("ID") + "\t\t" +  rs.getString("NAME") + "\t\t" + rs.getString("CITY"));
    }
    rs.close();
    stmt.close();
    con.close();
    } catch (Exception e) {
      System.err.println("Error: " + e.getMessage());
    }
  }
}

6. Compile Java Class:
javac.exe -classpath .;derby.jar;derbyclient.jar;derbynet.jar;derbytools.jar Restaurants.java

7. Run Java Class:
java.exe -classpath .;derby.jar;derbyclient.jar;derbynet.jar;derbytools.jar Restaurants
ID NAME CITY
—————————————-
1 Irifunes San Mateo
2 Estradas Daly City
3 Prime Rib House San Francisco

That’s it.

It’s also possible with Derby to share a database. After creation and inserting data just copy the file bin/myDB (myDB is the name of the database) to another Derby bin directory – done.

Tagged with , , , .

This is how to use Apache Derby as database in Eclipse. Partly based on the Derby documentation from http://db.apache.org/derby/

1. Download Apache Derby Eclipse plugin:

http://ftp.uni-erlangen.de/pub/mirrors/apache/db/derby/db-derby-10.4.2.0/derby_core_plugin_10.4.2.zip

http://ftp.uni-erlangen.de/pub/mirrors/apache/db/derby/db-derby-10.4.2.0/derby_ui_plugin_1.1.2.zip

2. Unzip the two plugins into Eclipse’s plugin directory

3. (Re-)Start Eclipse

4. Create new Java project in Eclipse

5. Integrate Derby libs in Java project: Right-click on Project, select Apache Derby / Add Apache Derby nature

6. Start Derby server: Right-click on Project, select Apache Derby / Start Derby Network Server
The green symbol on the Java Project will indicate a running Derby server for this project.

7. Create database: Right-clickon Project, select Apache Derby / ij (interactive SQL) and enter:

1
connect 'jdbc:derby://localhost:1527/myDB;create=true;user=user1;password=user1';

8. Insert some values into database:

1
2
3
4
5
create table restaurants(id integer, name varchar(20), city varchar(50));
insert into restaurants values (1, 'Irifunes', 'San Mateo');
insert into restaurants values (2, 'Estradas', 'Daly City');
insert into restaurants values (3, 'Prime Rib House', 'San Francisco');
select * from restaurants;

9. Create new Java Class in Java project, example code:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.ResultSetMetaData;
import java.sql.SQLException;
import java.sql.Statement;
 
 
public class Restaurants {
	private static String url = "jdbc:derby://localhost:1527/myDB;create=true;user=user1;password=user1";
	private static String table = "restaurants";
	private static Connection con = null;
	private static Statement stmt = null;
 
	public static void main(String[] args) {
		createConnection();
		insertRestaurants(4, "LaVals", "Berkeley");
		selectRestaurants();
		closeConnection();
	}
 
	private static void createConnection() {
		try {
			Class.forName("org.apache.derby.jdbc.ClientDriver").newInstance();
			con = DriverManager.getConnection(url);
		} catch (Exception e) {
			System.err.println("Unable to connect to database: " + e.getMessage());
		}
	}
 
	private static void insertRestaurants(int id, String name, String city) {
		try {
			stmt = con.createStatement();
			stmt.execute("insert into " + table + " values (" + id + ",'" + name + "','" + city + "')");
			stmt.close();
		} catch (SQLException e) {
			System.err.println("Error with SQL insert: " + e.getMessage());
		}
	}
 
	private static void selectRestaurants() {
		try {
			stmt = con.createStatement();
			ResultSet rs = stmt.executeQuery("select * from " + table);
			ResultSetMetaData rsmd = rs.getMetaData();
			int cols = rsmd.getColumnCount();
			for (int i=1; i<=cols; i++) {
				System.out.print(rsmd.getColumnLabel(i) + "\t\t");
			}
			System.out.println("----------------------------------------");
			while (rs.next()) {
				System.out.println(rs.getInt("ID") + "\t\t" +  rs.getString("NAME") + "\t\t" + rs.getString("CITY"));
			}
			rs.close();
			stmt.close();
		} catch (SQLException e) {
			System.err.println("SQL error: " + e.getMessage());
		}
	} 
 
	private static void closeConnection() {
		try {
			if (stmt != null) {
				stmt.close();
			}
			if (con != null) {
				con.close();
			}
		} catch (SQLException e) {
			System.err.println("Error while closing connection: " + e.getMessage());
		}
	}
}

That’s it :)

Tagged with , , , , , .