WSDL reading

 

actual post in here – http://predic8.com/wsdl-reading.htm

—————————————————————————————————–

 

WSDL Reading, a Beginner’s Guide

Thomas BayerBy: Thomas Bayer
Date: 08/24/2009

This article explains how to read a WSDL document by analyzing the Web Services description of a public sample Service. During the article a tree diagram is developed from the content of the WSDL document. The tree illustrates the structure of WSDL. The reader will get an understanding of the WSDL elements and their relationships.

The root element of a WSDL document is definitions. So we start the WSDL tree with a definitionsnode as root. See figure 1:Definition and Service

Figure 1: Definition and Service

To analyse a WSDL document it is recommended to read it from the buttom upwards. At the bottom of the BLZService’s WSDL we find a child element of definitions named service.

1
2
3
4
5
6
7
8
9
10
11
<wsdl:service name="BLZService">
  <wsdl:port name="BLZServiceSOAP11port_http" binding="tns:BLZServiceSOAP11Binding">
  </wsdl:port>
  <wsdl:port name="BLZServiceSOAP12port_http" binding="tns:BLZServiceSOAP12Binding">
  </wsdl:port>
  <wsdl:port name="BLZServiceHttpport" binding="tns:BLZServiceHttpBinding">
  </wsdl:port>
</wsdl:service>
Listing 1: Service Element

The name of the service is BLZService. A service can have multiple ports marked in figure 2 with a * character. Each port describes a way to access the service. In our BLZService example there are three ports. One for SOAP 1.1, one for SOAP 1.2 and one for the HTTP binding.

Ports of a Service

Figure 2: Ports of a Service

Let’s have a look at the first port in listing 2.

1
2
3
<wsdl:port name="BLZServiceSOAP11port_http" binding="tns:BLZServiceSOAP11Binding">
</wsdl:port>
Listing 2: Port describing a SOAP 1.1 Endpoint

It’s child element address has a different XML prefix than the other elements. The prefix soap is bound to the SOAP 1.1 binding in this document. Instead of the SOAP binding other bindings for JMS or a file transport can be used. The address element has one attribute named locationpointing to an endpoint address of the service.

Endpoint Address

Figure 3: Endpoint Address

To move on, we have to look at the binding attribute of the port.
The value “tns:BLZServiceSOAP11Binding” points to a binding further up in the document. Each port is pointing to a different binding in this example. As a consequence the BLZService WSDL has three bindings.

A Port references a Binding

Figure 4: A Port references a Binding

A binding provides details about a specific transport. The binding in figure 5 has two different types of children.

SOAP Binding

Figure 5: SOAP Binding

First we have a look at the soap:binding element in listing 3. The value of the transport attribute is an URI that indicates that SOAP messages should be send over HTTP. The value “document” of the style attribute gives us a clue about the message style together with the use attribute of thesoap:body elements. In our example we have a Document/Literal message style.
A binding can specify different transport options for each method of a service.

1
2
3
4
5
6
7
8
9
10
11
12
<wsdl:binding name="BLZServiceSOAP11Binding" type="tns:BLZServicePortType">
  <soap:binding transport="http://schemas.xmlsoap.org/soap/http" style="document"/>
  <wsdl:operation name="getBank">
    <soap:operation soapAction="" style="document"/>
    <wsdl:input>
      <soap:body use="literal"/>
    </wsdl:input>
    <wsdl:output>
      <soap:body use="literal"/>
    </wsdl:output>
  </wsdl:operation>
</wsdl:binding>
Listing 3: SOAP 1.1 Binding

Let’s have a look at listing 4. There you can find transport options for the getBank operation.
Inside the wsdl:operation element there is a soap:operation element at line 2 defining details for the SOAP protocol and its transport. The soapAction is a reminiscent from the past. The Basic Profile of the Web Services Interoperability Organization stipulates that the soapAction should be used with a fixed value of an empty string.

1
2
3
4
5
6
7
8
9
<wsdl:operation name="getBank">
    <soap:operation soapAction="" style="document"/>
    <wsdl:input>
      <soap:body use="literal"/>
    </wsdl:input>
    <wsdl:output>
      <soap:body use="literal"/>
    </wsdl:output>
  </wsdl:operation>
Listing 4: Binding Operation

Because Web Services set the focus on messages not parameters, information about the transport of these messages can be found in the wsdl:input and wsdl:output element. A service may specify one or several faults as an alternative for the output.

Binding Operation

Figure 6: Binding Operation

The soap:body and soap:header elements can describe a message further. In the example the style is always literal.

soap:body Elements

Figure 7: soap:body Elements

It is time again to move up in the WSDL. Now we follow the value of the type attribute of the binding. It points to a portType with the same name further up in the document.

Binding referencing a PortType

Figure 8: Binding referencing a PortType

Now we have crossed the border from the concrete details about the transport and location of a service to its pure abstract description of its interface. PortType is in WSDL 1.1 similar to the interface of the Web Service. In WSDL 2.0 the term portType is substituted with the terminterface.
An interface can have several operations. An operation corresponds to a function in procedural programming.
The WSDL of the BLZService has only one portType. All of the three bindings refer to the one portType named BLZServicePortType.

Operations of a portType

Figure 9: Operations of a portType

Inside a portType we find operation elements as in the binding. But this time the input and outputdescribe the structure of the messages not transport specific options.

Input and Output of an Operation

Figure 10: Input and Output of an Operation

The message attribute of the input refers again up in the WSDL document. It refers to a message named tns:getBank. Further up in the document we find a corresponding message with this name.

1
2
3
4
5
6
<wsdl:portType name="BLZServicePortType">
  <wsdl:operation name="getBank">
    <wsdl:input message="tns:getBank"/>
    <wsdl:output message="tns:getBankResponse" wsaw:Action="http://thomas-bayer.com/blz/BLZService/getBankResponse"/>
  </wsdl:operation>
</wsdl:portType>
Listing 5: The Interface Description of the Service

Message

Figure 11: Message

The message getBank has one part element as child. A WSDL specialist will recognize the value of the attribute name, “parameters” indicates the wrapper substyle of the document/literal style.

1
2
3
<wsdl:message name="getBank">
  <wsdl:part name="parameters" element="tns:getBank"/>
</wsdl:message>
Listing 6: getBank Message

The attribute element at line 2 points again further up. It refers to an element named tns:getBank. We will find this element in a XML Schema.

A Message and its parts

Figure 12: A Message and its Parts

The next child of the definitions element is types.

The Types Section

Figure 13: The Types Section

The types element can have multiple XML schemas as children.

Schemas used in a WSDL

Figure 14: Schemas used in a WSDL

Listing 7 shows the types element and an embedded schema.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
<wsdl:types>
  <xsd:schema attributeFormDefault="unqualified" elementFormDefault="qualified" targetNamespace="http://thomas-bayer.com/blz/">
    <xsd:element name="getBank" type="tns:getBankType"/>
    <xsd:element name="getBankResponse" type="tns:getBankResponseType"/>
    <xsd:complexType name="getBankType">
      <xsd:sequence>
        <xsd:element name="blz" type="xsd:string"/>
      </xsd:sequence>
    </xsd:complexType>
    <xsd:complexType name="getBankResponseType">
      <xsd:sequence>
        <xsd:element name="details" type="tns:detailsType"/>
      </xsd:sequence>
    </xsd:complexType>
    <xsd:complexType name="detailsType">
      <xsd:sequence>
        <xsd:element minOccurs="0" name="bezeichnung" type="xsd:string"/>
        <xsd:element minOccurs="0" name="bic" type="xsd:string"/>
        <xsd:element minOccurs="0" name="ort" type="xsd:string"/>
        <xsd:element minOccurs="0" name="plz" type="xsd:string"/>
      </xsd:sequence>
    </xsd:complexType>
  </xsd:schema>
</wsdl:types>
Listing 7: Embedded XML Schema

In a schema we can find the definition of:

  • complexTypes
  • simpleTypes

and the decleration of:

  • elements

The XML Schema inside BLZService is a typical schema used for Web Services that has onlycomplexTypes and elements as toplevel schema components.
In document/literal style all the parts point to elements.A part can reference an Element

Figure 15: A Part can reference an Element

Listing 8 shows the declaration of the getBank element.

1
<xsd:element name="getBank" type="tns:getBankType"/>
Listing 8: Declaration of the Element getBank

The type of this element is a complexType named getBankType definded somewhere else in the schema.

An Element references its Type

Figure 16: An Element references its Type

The getBankType has a sequence as modulgroup containing one element named blz of the build-in schema type string.

A ComplexType with a Sequence as Content

Figure 17: A ComplexType with a Sequence as Content

Listing 9 shows the definition of the getBankType.

1
2
3
4
5
<xsd:complexType name="getBankType">
      <xsd:sequence>
        <xsd:element name="blz" type="xsd:string"/>
      </xsd:sequence>
    </xsd:complexType>
Listing 9: The ComplexType getBankType

A sequence can consist of several elements that describe the order of elements in a SOAP message.

The entire Structure of a WSDL Document

Figure 18: The entire Structure of a WSDL Document

Finally we are through the entire WSDL description of the sample service.

All WSDL documents have the same structure as the BLZService. To understand a WSDL start reading at the bottom and work your way up by following the right attributes as shown in this article.

I hope this article was helpful to learn how to read a WSDL document.

Thomas Bayer
bayer@predic8.com

 

 

 

 

Spring JDBC

*** Actual post : http://learningviacode.blogspot.co.uk/2012/08/spring-and-jdbc.html ****

Spring and JDBC

I decided to implement the IPersonDAO interface to work with JDBC.

public class SimplePersonDAO extends SimpleJdbcDaoSupport implements IPersonDAO {
    private static final Logger logger = Logger.getLogger(PersonDAO.class);
//remaining methods
}

The class extends the DaoSupport class, thus getting direct access to the SimpleJdbcTemplate. The template has Java 5 features such as autoboxing, generics, and variable parameter lists. (As of Spring 3.1 the class has been deprecated and preference is to be given to  JdbcTemplate and NamedParameterJdbcTemplate.) I implemented the various methods available in the interface:

public List<Person> getAllPersons() {
    logger.debug("getAllPersons from system");
    final List<Person> persons = new ArrayList<Person>(0);
    //access to jdbcTemplate is available
    final List<Map<String, Object>> rows = this.getJdbcTemplate()
            .queryForList("select id, name, age from Person");
    for (final Map<String, Object> row : rows) {
        final Person lineItemToPush = new Person();
        lineItemToPush.setId((Long) (row.get("id")));
        lineItemToPush.setName((String) (row.get("name")));
        lineItemToPush.setAge((Integer) (row.get("age")));
        persons.add(lineItemToPush);
    }
    logger.debug("Total Retrieved items : " + persons.size());
    return persons;
}

The class inherits a getJdbcTemplate() that returns the SimpleJdbcTemplate. The queryForList() method returns a list of map objects. Every map object maps to a row in the database. The map holds a set of key-value pairs where the key is the column name and the value is the column value. The template also supports usage of RowMapper class. The documentation for the class says

An interface used by JdbcTemplate for mapping rows of a java.sql.ResultSet 
on a per-row basis. Implementations of this interface perform the actual 
work of mapping each row to a result object, but don't need to worry about 
exception handling. SQLExceptions will be caught and handled by the calling 
JdbcTemplate.

public Person getPersonById(final long personId) {
    logger.debug("fetching record with  id : " + personId);
    Person personRec= null;

    final Map<String, Object> params = new HashMap<String, Object>();
    params.put("id", personId);
    personRec= simpleJdbcTemplate.queryForObject(
        "select id, name, age  from Person  where id = :id",
        new RowMapper<Person>() {
            @Override
            public Person mapRow(ResultSet rs, int arg1)
                throws SQLException {
                final Person person = new Person();
                person.setId(rs.getLong(1));
                person.setName(rs.getString(2));
                person.setAge(rs.getInt(1));
                return person;
            }
        }, params);
    return lineItemToPush;
}

The template also includes method to return values.

public int findTotalPersons() {
    logger.debug("findTotalPersons: fetching record count ");
    int total = this.simpleJdbcTemplate.queryForInt("select * from PERSON");
    return total;
}

In the next post we shall see an alternative technique for executing such simpler queries.
Consider the below update and delete methods:

public void updatePerson(final Person person) {
    final String query = "update Person set name = '"
            + person.getName() + "', age = " + person.getAge()
            + " where id  = :id";
    final Map<String, Object> parameters = new HashMap<String, Object>();
    parameters.put("id", person.getId());
    this.simpleJdbcTemplate.update(query, parameters);
}

public void delete(Person person) {
    final String query = "delete from Person where id  = :id";
    final Map<String, Object> parameters = new HashMap<String, Object>();
    parameters.put("id", person.getId());
    this.simpleJdbcTemplate.update(query, parameters);        
}

The SimpleJdbcTemplate can understand named parameters in SQL. The update method includes the SQL query and the map holding the parameter to use in the query.
The template also provides support for working with prepared statements.

public void save(final Person person) {
    final String query = "insert into Person(name,age) values('"
            + person.getName() + "'," + person.getAge() + " )";
    System.out.println(query);
//    this.simpleJdbcTemplate.update(query); //did not return the id of the record        
    final KeyHolder keyHolder = new GeneratedKeyHolder();        
    jdbcTemplate.update(
        new PreparedStatementCreator() {                
            public PreparedStatement createPreparedStatement(Connection connection) throws SQLException {
                PreparedStatement ps = connection.prepareStatement(query, Statement.RETURN_GENERATED_KEYS);
                return ps;
            }
        },
        keyHolder);
//       keyHolder.getKey() now contains the generated key
    person.setId(keyHolder.getKey().longValue());        
}

The PreparedStatementCreator is used to create prepared statements. The save method will written the auto-generated identity. However the update method returns he number of affected rows and not the new Identifier. For the id, Spring provides a org.springframework.jdbc.support.KeyHolder class that holds within it the newly generated the identifier. The  Statement.RETURN_GENERATED_KEYS  value is a constant indicating that generated keys should be made available for retrieval
The spring configuration for the bean is as below:

<bean id="jdbcTemplate" class="org.springframework.jdbc.core.JdbcTemplate">
    <constructor-arg ref="c3pDataSource" />
</bean>

<bean id="simplePersonDAO" class="com.data.dao.SimplePersonDAO">
    <property name="jdbcTemplate" ref="jdbcTemplate" />
</bean>

Although PersonDAO extends SimpleJdbcDaoSupport, the class does not take simpleJdbcTemplate as a property. It takes a jdbcTemplate and creates its own internal instance of SimpleJdbcTemplate.

Maven Eclipse

Maven 3 Tutorial – Project Setup

June 11th, 2011 by David KesslerLeave a reply »

New Project

For this example I will be using Eclipse for my IDE.

  1. Download Eclipse IDE for Java EE Developers from http://www.eclipse.org/downloads/
  2. Unzip the contents in your root Eclipse folder.  In my case I unzipped it in c:/java/eclipse
  3. Run the ‘eclipse.exe’ in [eclipse root]/eclipse
  4. Select a workspace location for Eclipse to store your projects.  In my case I used the default location

m3-02

  1. Click on the ‘Workbench’ icon

m3-03[1]

  1. Select Help -> Install New Software

m3-04[1]

  1. Click the ‘Add…’ button
  2. Name: m2eclipse
  3. Location: http://m2eclipse.sonatype.org/sites/m2e
  4. Click ‘OK’

m3-05

  1. Check the ‘Maven Integration for Eclipse’ option
  2. Click ‘Next’

m3-06

  1. Click ‘Next >’

m3-07

  1. Select ‘I accept the terms of the license agreements’
  2. Click ‘Finish’

m3-08

  1. Click ‘Restart Now’

m3-09
m3-10

  1. Select Window -> Preferences

m3-11

  1. Add the Maven 3 location the you installed earlier

m3-12

  1. Create a new Maven project by selecting File -> New -> Other…

m3-13

  1. Select Maven -> Maven Project

m3-14

  1. Check ‘Create a simple project (skip archetype selection)’
  2. Click ‘Next >’

m3-24

  1. Enter Project Information
    1. Enter Group Id. This is the domain where the project is hosted. For example if the ‘Awesome’ project was hosted at GitHub then the Group Id would be ‘com.github.awesome’.
    2. Enter Artifact Id. This is the name of the resulting artifact. For example if Artifact Id is ‘awesome’ and the packaging is JAR the artifact will be named ‘awesome.jar’.
    3. The version can remain 0.0.1-SNAPSHOT
    4. Select the packaging that you desire
    5. Enter a Name. This name will show up in the console when you run Maven. This will also show up in the documentation that Maven generates
    6. Enter a Description. This is used in the documentation
    7. Click ‘Next >’

m3-16

  1. Add a dependency on JUnit. One of the best features of m2eclipse plugin is the ability to search for available dependencies.  (This feature does not work if you configure ‘M3_HOME’ instead of ‘M2_HOME’)

m3-17

  1. Click ‘Finish’
    • src – source and resource files
    • target – compiled files, reports and generated artifacts
    • main – application/library files
    • test – test files
    • java – java files
    • resources – non java files like XML

m3-18
Maven’s default package structure:
m3-19

  1. Open the pom.xml file.
  2. Add the compiler plugin so you can configure your JDK version. Search for the maven-compiler-plugin.

m3-20

  1. For this example set the JDK version to 1.6

m3-21

<configuration> 
	<source>1.6</source> 
	<target>1.6</target> 
</configuration>
  1. Run ‘Maven install’ to verify that the project and environment is setup correctly

m3-22

  1. The build was successful

m3-23

Link

Hibernate in 10 mins

***  For the actual post – Visit the blog  ***

http://nikojava.wordpress.com/2008/05/05/hibernate-java-10-minutes-en/

Just for the reference i copied here

———————————————————————————————————

Hibernate is a quick way to store / retrieve data to a database.

Step 1. Download all necessary files

Download MySQL from mysql.com → downloads → MySQL Community Server → Windows ZIP/Setup.EXE (x86) → Pick a mirror → No thanks, just take me to the downloads → Greece [National Technical University of Athens] HTTP → mysql-5.0.51b-win32.zip

Download JDBC driver of MySQL from mysql.com → downloads → Connectors → Connector/J → Source and Binaries (zip) → Pick a mirror → No thanks, just take me to the downloads → Greece [National Technical University of Athens] HTTP → mysql-connector-java-5.1.6.zip

Download Hibernate core from hibernate.org → Download → Hibernate Core → Download → hibernate-3.2.6.ga.zip

Download Hibernate annotations from hibernate.org → Download → Hibernate Annotations → Download → hibernate-annotations-3.3.1.GA.zip

Step 2. Make the database schema

ΜySQL is easily installed. After the installation completes, a configuration wizard opens: you should note down the root password.

In order to start MySQL go to Start → Programs → MySQL → MySQL Server 5.0 → MySQL Command Line Client → give the root password.

Write CREATE DATABASE heat;

For confirmation state show databases; and then use heat;

It would be useful to leave the command prompt window of MySQL open.

So, you have just created the database schema. What about the tables? Well, Hibernate will make them automatically!

Step 3. Concentrate all jars

Create a folder, e.g. C:/jars and copy inside:

  • hibernate-3.2.6.ga.zip/hibernate3.jar
  • everything that lies inside hibernate-3.2.6.ga.zip/lib
  • hibernate-annotations-3.3.1.GA.zip/hibernate-annotations.jar
  • hibernate-annotations-3.3.1.GA.zip/lib/hibernate-commons- annotations.jar and ejb3-persistence.jar
  • the JDBC driver mysql-connector-java-5.1.6.zip/mysql-connector- java-5.1.6-bin.jar

Step 4. Create the actual project.

Create a project with the name “Hibernate” using Eclipse or any other IDE (NetBeans, JDeveloper etc).

Add the folder with the jars into the classpath: Project → Properties → Java Build Path → Add External JARs…

Step 5. Write hibernate.cfg.xml

hibernate.cfg.xml is a special file used by Hibernate. It holds information about the database we are using.

<?xml version='1.0' encoding='utf-8'?>
<!DOCTYPE hibernate-configuration PUBLIC
 "-//Hibernate/Hibernate Configuration DTD 3.0//EN"
 "http://hibernate.sourceforge.net/hibernate-configuration-3.0.dtd">

<hibernate-configuration>
   <session-factory>
      <!-- Database connection settings -->
      <property name="connection.driver_class">com.mysql.jdbc.Driver</property>
      <property name="connection.url">jdbc:mysql://localhost/heat</property>
      <property name="connection.username">root</property>
      <property name="connection.password">12345</property>

      <!-- SQL dialect -->
      <property name="dialect">org.hibernate.dialect.MySQLDialect</property>

      <property name="transaction.factory_class">org.hibernate.transaction.JDBCTransactionFactory</property>
      <property name="current_session_context_class">thread</property>

      <!-- Echo all executed SQL to stdout -->
      <property name="show_sql">true</property>
   </session-factory>
</hibernate-configuration>

The properties connection.* hold information that is directly used in JDBC code (Class.forName() etc.). Make sure you enter the correct password!

SQL dialect is an interesting property: We say to Hibernate that it communicates with a MySQL database.

Place hibernate.cfg.xml inside the folder of the project, e.g. inside C:/Eclipse/workspace/Hibernate, or anywhere in the classpath. This file must be in the classpath.

Step 6. Build the model

This simple application handles persons. For every person, we are interested about the name and a unique number (identifier).

class: Person

state: Long id, String name

behaviour: setId(), getId(), setName(), getName()

	public class Person {

	private Long id;
	private String name;

	public Long getId() {
		return id;
	}
	public void setId(Long id) {
		this.id = id;
	}
	public String getName() {
		return name;
	}
	public void setName(String name) {
		this.name = name;
	}

}

So, it’s a simple java bean. What we would be pottering about now is creating 1. a table “person” in the database and 2. a class with pure JDBC:insert(Person person)select(Long id)update(Person person)delete(Long id) etc. Fortunately, Hibernate takes care of both of these tasks. We just use some annotations straight from the Java Persistence API.

import javax.persistence.*;

@Entity
public class Person {

	private Long id;
	private String name;

	@Id
	@GeneratedValue
	public Long getId() {
		return id;
	}
	public void setId(Long id) {
		this.id = id;
	}
	public String getName() {
		return name;
	}
	public void setName(String name) {
		this.name = name;
	}

}

@Entity means that all the objects that derive from this class can be stored to the database.

@id declares the primary key.

@GeneratedValue means that the database will ensure the uniqueness of the primary key. (In MySQL is the AUTO_INCREMENT flag)

Step 7. Time for action

Create the table person in the database

	// usual initialization
	AnnotationConfiguration config = new AnnotationConfiguration();
	config.addAnnotatedClass(Person.class);
	config.configure();

	// create the table in the database
	new SchemaExport(config).create(true, true);

During the usual initialization the class Person is addedconfig.addAnnotatedClass(Person.class);. After that, all configuration parameters are read from hibernate.cfg.xml and all classes marked with an @Entity are configured config.configure();. These statements naturally belong to a constructor.

The statement new SchemaExport(config).create(true, true);creates the tables in the database. In case these tables are already defined, they get dropped and recreated; all their data are lost.

To confirm write show tables; at the MySQL command prompt.

Store an object in the database

	// usual initialization
	AnnotationConfiguration config = new AnnotationConfiguration();
	config.addAnnotatedClass(Person.class);
	config.configure();

	// we want to store Vincent Hanna to the database
	Person person = new Person();
	person.setName("Vincent Hanna");

	// expensive initialization
	SessionFactory factory = config.buildSessionFactory();
	// get session
	Session session = factory.getCurrentSession();
	
	// store
	session.beginTransaction();
	session.save(person);
	session.getTransaction().commit();

The statement SessionFactory factory = config.buildSessionFactory(); costs a lot. That’s why the factory object should be created once and be made available to the rest of the application (e.g. singleton pattern).

To confirm write SELECT * FROM person; at the MySQL command prompt.

You may use a class with utility static methods to tidy things up:

	// we want to store Vincent Hanna to the database
	Person person = new Person();
	person.setName("Vincent Hanna");
	DataBase.save(person);

Conclusion: We gain precious development time as it is no more necessary 1. to manually create any table in the database and 2. to write long JDBC classes with the usual operations (insert, update, select, delete).

Follow

Get every new post delivered to your Inbox.