Archive

Posts Tagged ‘Java’

Create Java Classes from XML-Schema

December 23rd, 2011 No comments

JAXB (Java Architecture for XML Binding) is a framework to marshal Java objects to XML and vice-versa.
It is part of the JDK and comes with a command-line compiler (xjc) that creates Java classes from an existing XML-Schema.

Location
The xjc it located at the /bin folder of the JDK:
../jdk1.6.0_18/bin/xjc.exe

Usage
xjc -d [target folder] -p [package name] [xml-schema file name]

Example
The classes will be written to the folder “src” (relative to the current location) in the package “de.myproject.somepackage”.
The schema file “my-schema.xsd” will be compiled.
xjc -d src -p de.myproject.somepackage my-schema.xsd

For more information see
xjc -help

SOA Light – Usage of services in your application – Part #2

September 25th, 2011 Comments off

Welcome to Part #2 of the SOA Light  – Usage of services in your application.

In the 2nd part I want to introduce a sample project, which reflects the architecture described in part one. All the projects are prepared to be compiled with Maven 2.

The project itself consists of the following Maven modules:

  1. sampleApplication: This is the application that uses the services.
  2.  service-base: This module contains the service interface and a class which describes a DTO (Data Transfer Object).
  3. service-client: This module contains a so called façade class. This façade implements the interface from the base module. This façade also contains a property of type SampleService.So this class, the façade, is actually the bridge between the sample application and the service itself. This façade will be injected into the sampleApplication.
  4. service-server: This module offers the service itself. The service has implemented the interface from service-base. This is the place where the actual work is done. This can be communication with database or whatever comes to your mind.

A simple way to use the application and the service is to deploy them to a Jetty server. The service and the application contain a jetty plug in which can be started via
“mvn jetty:run -Djetty.port=9002.

See the attachment for the example implementations:

Service Implementation and Sample Application

 

SOA Light – Usage of services in your application – Part #1

September 8th, 2011 Comments off

Introduction

Recently I implemented for a customer a service which counts user interactions on their company website. First, I want to give you an architectural overview of this service.

 

Architectural Overview

The image above shows the architectural overview. It contains of the following parts:

  • Application: This is the application that wants to use the functionality of the service.
  • Facade: The facade contains usually an injected interface which represents an access to the functionality of the service. The facade itself usually also implements an interface to give your application an access to the facade. The facade also has the advantage that the service itself is hidden to the application. Imagine you want to replace the service. All you have to do is to change the calls, but not the application itself. Remember: Always program against interfaces!
  • Service: The service component itself. This is where the actions takes place. Usually you have here a DAO  – Layer to save data. But actually its totally up to you.
  • Communication: In the service I have worked the communication between facade / application and the service is realized by using  the Burlap Hessian protocal. The Hessian binary web service protocol makes web services usable without requiring a large framework, and without learning yet another alphabet soup of protocols. Because it is a binary protocol, it is well-suited to sending binary data without any need to extend the protocol with attachments.

The idea of the service has many advantages; namely faster development, testability, reusability.

  • Faster Development: When you develop your service you concentrate only on the development of the service itself and not be bothered in the first place how it fits into your application. Also imagine you would build your application with e.g. Maven…it can be quite time consuming to build the whole application instead of only compiling the service. Another considerable point is that you do not necessarily need to know the  application itself, all you need is to provide an interface for other programmers. You can work independently and parallel to other teams or team members. So you don’t need to wait until they are finished with their implementations.
  • Testability: Your service itself is an independent component and because of this feature the component can be test individually. Consider it like a unit test. What you also can is to test the performance of you service. Your test result won’t have the overhead of the application that uses the service.
  • Reusability: The service itself can be injected not only into one application but can be used by other applications as well. Just imagine using Dependency Injection: Add your service to other application so that they easily benefit from the service. All you have to use the service’ interface methods…thats it! The rest is already done.

In the second part I will show an sample example, explain the classes and show you how to test the service. Stay tuned!

Globale JNDI Resourcen in Tomcat

July 7th, 2011 Comments off

Als Teil von Java EE kann JNDI (Java Naming and Directory Interface) heute in allen gängigen Application-Servern genutzt werden. Ein üblicher Verwendungszweck ist das Bereitstellen von DataSourcen für einzelne Webanwendung. Die Resourcen werden in diesem Szenario in der jeweiligen web.xml und context.xml definiert und sind dann im entsprechenden Application-Context verfügbar.

Unüblicher aber durchaus nützlich ist die Verwendung einer eigenen globalen Resource, die allen Applications gleichermaßen zur Verfügung steht. Im folgenden Beispiel wird eine kleine HalloWelt-Klasse als globale Resource abgelegt und genutzt.

Als erstes bearbeiten wir $CATALINA_BASE/conf/server.xml um die globale Resource anzulegen. Wir geben den Namen der Resource an, die Klasse und eine Factory zum Erstellen der Resource. Meist ist der Tag GlobalNamingResources bereits vorhanden, so dass wir unsere Resource dort lediglich hinzufügen müssen.

<GlobalNamingResources>
    <Resource auth="Container" factory="HelloWorldFactory"
        name="meine/services/HelloWorld" type="HelloWorld"/>
</GlobalNamingResources>

Als nächstes fügen wir in die globale $CATALINA_BASE/conf/context.xml einen Resource-Link ein, der auf die erstellte globale Resource verweist. Da diese context.xml von allen Applications genutzt wird, ersparen wir uns hiermit, jede einzelne webapp/WEB-INF/context.xml anpassen zu müssen.

<Context>
    <ResourceLink global="meine/services/HelloWorld"
        name="meine/services/HelloWorld" type="HelloWorld"/>
</Context>

Nun implementieren wir die globale Resource. Wir brauchen dazu lediglich drei Dateien, nämlich die HelloWorldFactory.java, das Interface HelloWorld.java und die konkrete Implementierung HelloWorldImpl.java. Alle Dateien exportieren wir als JAR-Datei und legen sie unter $CATALINA_BASE/lib/ext ab. Somit ist gewährleistet, dass alle Applications die HelloWorld Klassen durch den Common-ClassLoader im Classpath haben.

Die HelloWorldFactory erbt von ObjectFactory, welche die Standard Factory für Java Naming ist. Zurückgegeben wird die Singleton-Instanz unserer HelloWorldImpl.

1
2
3
4
5
6
public class HelloWorldFactory implements ObjectFactory {
    public Object getObjectInstance(Object obj, Name name, Context nameCtx, 
        Hashtable&lt;?, ?&gt; environment) throws Exception {
        return HelloWorldImpl.getInstance();
    }
}

Zum Interface HelloWorld muss wenig gesagt werden. Es definiert lediglich alle Methoden, die die Resource zur Verfügung stellen soll und die die konkrete Klasse implementieren muss.

1
2
3
public interface HelloWorld {
    String getHelloWorld();
}

Die Implementierung unserer Resource wird als Singleton ausgeführt, so dass die Factory immer nur eine Instanz der Resource zurückgibt.

1
2
3
4
5
6
7
8
9
10
11
public class HelloWorldImpl implements HelloWorld {
    private static instance = new HelloWorldImpl();
    public static HelloWorld getInstance() {
        return instance;
    }    
 
    @Override
    public String getHelloWorld() {
        return "Hello world!";
    }
}

Sind die Vorbereitungen abgeschlossen, können wir in einer beliebigen Application per JNDI Lookup auf die Resource zugreifen, ohne dass die Application speziell konfiguriert werden muss oder Abhängigkeiten zu unseren Klassen enthalten muss. Der JNDI Lookup nutzt den InitialContext, den uns Tomcat zur Verfügung stellt. (Im Code nicht dargestellt ist ein entsprechender Try-Catch-Block, der um das Lookup gesetzt werden muss.)

1
2
3
4
5
6
7
8
9
10
11
12
@ManagedBean
@SessionScoped
public class SampleBean {
    public String getGreetingMessage() {
        Context serverContext = (Context) new InitialContext()
            .lookup("java:/comp/env");
        HelloWorld helloWorld = (HelloWorld) serverContext
            .lookup("meine/services/HelloWorld");        
 
        return helloWorld.getHelloWorld();
    }
}

Starten wir nun unseren Tomcat, wird durch den globalen Kontext gleich zu Begin die ObjectFactory aufgerufen und die Singleton-Instanz unserer Resource erstellt. Beim Zugriff auf die Resource durch die Applications, steht die Resource somit schon fertig initialisiert zur Verfügung. Dies kann besonders dann von Vorteil sein, wenn die Resource eine gewisse Zeit braucht um zur Verfügung zu stehen.

Preventing the db2jcc driver to commit running connections

September 2nd, 2010 Comments off

When using the DB2 JDBC Driver db2jcc on z/OS with type 2 connectivity, running connections to the database will commit its transactions, while the JVM is terminating. This may or may not be the wanted behavior, but this is the default. However, you are able to change this behavior.

To do so you either have to place a file named DB2JccConfiguration.properties in your classpath or you specify a different filename by adding the following VM argument to your java call:

-Ddb2.jcc.propertiesFile=C:/db2jcc.properties

In this file you have to add the following properties:

db2.jcc.promoteAbortToAbend=yes
db2.jcc.rollbackOnShutdown=true

Without the first property a canceled java process will still commit its remaining transactions, because its termination is considered normal. If set to yes or true, the cancel will be promoted to the abend state, which will lead to the action specifed by the second property.
With this property, the db2jcc driver registers a shutdown hook on JVM termination which disables all running connections. After this, no further statements will be accepted by any connection. Right after this the shutdown hook starts to rollback all transactions one by one.

Categories: Database, Development, Java Tags: ,

Spring Jdbc Abstraction Layer

December 13th, 2009 Comments off

The Spring-JDBC component is a part of the Spring framework and is an abstraction on top of the standard Java JDBC API. It takes care of all the low-level API-calls and provides some base classes to implement the DAO-pattern.

The only work left to the developer is:

  • Creation of the statement
  • Extraction of the result
  • Execution of the statement

Additionally all tasks are simplified to the minimum.


Configuration of Spring-JDBC

The configuration can be done by just defining two more beans in your spring context configuration. The first one is the datasource, providing the JDBC connections. The other one simplifies the configuration for your own DAO implementations.


<bean id=“dataSource” class=“org.apache.commons.dbcp.BasicDataSource”

destroy-method=“close”>

<property name=“driverClassName” value=“yourJdbcDriverClass”/>

<property name=“url” value=“yourUrlToTheDatabase”/>

<property name=“username” value=“user”/>

<property name=“password” value=“password”/>

</bean>


<bean id=“abstractBaseDAO” abstract=“true”

class=“org.springframework.jdbc.core.simple.SimpleJdbcDaoSupport”>

<property name=“dataSource” ref=“dataSource”/>

</bean>


<bean id=“userDAO” parent=“abstractBaseDAO” class=“org.xyz.dao.UserDAO”/>


Now every bean, declaring the abstractBaseDAO as its parent, gets the dataSource injected. (i.e. the userDAO bean – remember the UserDAO has to extend the SimpleJdbcDaoSupport)

There are three DaoSupport classes, which serve one of three JdbcTemplates to their subclasses.

  • JdbcTemplate the central class of the JDBC abstraction
  • NamedParameterJdbcTemplate allows the use of named parameters
  • SimpleJdbcTemplate allows the use of Java 5 features like generics and varargs

The SimpleJdbcTemplate builds on top of the NamedParameterJdbcTemplate and the NamedParameterJdbcTemplate build on top of the JdbcTemplate.


Creation of the statement

By using the SimpleJdbcTemplate you are able to use named parameters for your statement.


String sql = “SELECT * FROM USERS WHERE ID = :id”;


The value for the named parameters can be defined in different ways, like a Map:


Map<String, Object> params = new HashMap<String, Object>();

params.put(“id”, Integer.valueOf(1));


or a SqlParameterSource:


SqlParameterSource params = new MapSqlParameterSource(“id”,

Integer.valueOf(1));

SqlParameterSource params = new BeanPropertySqlParameterSource(user);


The SqlParameterSource is an interface for defining named parameters. One implementation is the MapSqlParameterSource which simply holds a map of defined parameters.

The BeanPropertySqlParameterSource for example, obtains the parameter values from the beanproperties and maps those to the named parameters.


Handling of the the returned result

There are several ways offered by the JdbcTemplate classes to handle the result. The SimpleJdbcTemplate serves the possibility to use a ParameterizedRowMapper. This is a generic interface to map one row into a new instance of the specified target class.

A simple implementation:


new ParameterizedRowMapper<User>() {

public User mapRow(ResultSet rs, int rowNum) throws SQLException {

return new User(rs.getInt(“ID”), rs.getString(“USERNAME”));

}

};


Another already existing implementation is the ParameterizedBeanPropertyRowMapper, which maps the columns into the matching beanproperties.


Execution of the statement

The UserDAO which extends the SimpleJdbcDaoSupport inherits a method – getSimpleJdbcTemplate(). The SimpleJdbcTemplate offers a collection of methods to execute the statement.


queryForInt(…);

  • returns an integer (i.e. for “SELECT COUNT(*) …” statements)

queryForObject(…);

  • returns a single instance of the rowmappers type and throws an ‘IncorrectResultSizeDataAccessException’ if zero or more than one rows were found.

query(…);

  • returns a ‘List’ of the rowmappers type

update(…);

  • used for insert, update and delete statements

When using the ‘SimpleJdbcTemplate’ you are not tied to use only its methods. You can get an instance of one of the other JdbcTemplates too.


getNamedParameterJdbcOperations();

getJdbcOperations();


Fazit

The Spring JDBC Abstraction Layer is an easy to use framework around the standard JDBC API. You have multiple styles to choose to design your DAO – layer which affect the maintainability, but the performance too. For example the bean property reading rowmapper will never be as performant as a custom implemented rowmapper.

Categories: Java Tags: , ,

Useful little helpers making java developers live easier!

October 10th, 2009 Comments off

You may have some recurring development tasks while your daily work with java in different projects. For example you again and again write some small code that capitalizes a given String. Or you write an application with a command line interface and write code that defines and parses your command line options. Or you need some little helpers for your database handling. Or …
These are only some examples and if you don’t have already written and built your own little libraries for those tasks, you may want to have a look at Apache Commons, formerly known as Jakarta Commons. There are libraries for everyday use in different packages.
I will provide you a short overview over Apache Commons here and write some more articles about some of their libraries in the next weeks.
So, Apache Commons assign their libraries to three repositories depending on their development stage and usage (list taken from their site):

  • The Commons Proper – A repository of reusable Java components.
  • The Commons Sandbox – A workspace for Java component development.
  • The Commons Dormant – A repository of Sandbox components that are currently inactive.

I will focus on Commons Proper in this and my following articles since the contained components are ready to use and stable.

Currently, Commons Proper contains 39 components. You can categorize them into web, xml, utilities, converters and Java API extension.
The following table is taken and translated from german Wikipedia:

Category Components
Web FileUpload, Net, EL, Email, Jexl
XML Betwixt, Digester, Jelly, JXPath
Utilities BeanUtils, Pool, Validator, Daemon, Discovery, Exec, Launcher, JCI, Jelly, Modeler, SCXML, Chain
Converters Codec, Compress
Java API Extensions Lang, Collections, IO, Logging, Configuration, DBCP, DbUtils, Math, Primitives, Proxy, Validator, VFS, Attributes, CLI, Discovery, Transaction

 

Categories: Development, Java Tags: , , , ,

JEE 6 – Was ist drin?

August 5th, 2009 Comments off

Die Java EE Spezifikation in der Version 6 befindet sich noch immer im Review:
JSR 316.

Wer die neuen Features jedoch vorab schon einmal testen möchte, der kann diese mit dem Glassfish Enterprise Server Preview bereits genauer ansehen.

Es wird jedoch darauf hingewiesen, dass diese Implementierung auf dem aktuellen Entwurf der Spezifikation basieren und Änderungen daher nicht ausgeschlossen sind.

 Was genau enthalten ist, fasst SUN auf der Übersicht Java EE 6 Standards zusammen.

Categories: Java Tags: ,