Programming ANDREAS MANESSINGER ON SOFTWARE AND HOW TO MAKE IT About Contact Tutorials o Eclipse / GlassFish / Java EE 6 Tutorial An Eclipse / GlassFish / Java EE 6 Tutorial Add comments Version 1.3, last updated August 21, 2010 – 12:00 [-- hide table of contents --] 1. Applicability 2. How to use the tutorial 3. Typographical conventions 4. Tools 5. Preparing the workspace 6. Preparing the database 7. The container project (EAR project) 1. Purpose 2. Steps in Eclipse 8. The core logic (EJB project) 1. Purpose 2. Abstraction of data access (Entity Access Objects) 3. Services guard the entrance 4. Instantiation of Enterprise Java Beans i. EJB annotation ii. Lookup via JNDI iii. Calling the bean as a SOAP web service 5. Scope of EJBs 6. Accessing an EJB application from outside Search
This document is posted to help you gain knowledge. Please leave a comment to let me know what you think about it! Share it to your friends and learn new things together.
Transcript
ProgrammingANDREAS MANESSINGER ON SOFTWARE AND HOW TO MAKE IT
About Contact
Tutorialso
Eclipse / GlassFish / Java EE 6 Tutorial
An Eclipse / GlassFish / Java EE 6 TutorialAdd comments
Version 1.3, last updated August 21, 2010 – 12:00
[-- hide table of contents --]
1. Applicability
2. How to use the tutorial
3. Typographical conventions
4. Tools
5. Preparing the workspace
6. Preparing the database
7. The container project (EAR project)
1. Purpose
2. Steps in Eclipse
8. The core logic (EJB project)
1. Purpose
2. Abstraction of data access (Entity Access Objects)
3. Services guard the entrance
4. Instantiation of Enterprise Java Beans
i. EJB annotation
ii. Lookup via JNDI
iii. Calling the bean as a SOAP web service
5. Scope of EJBs
6. Accessing an EJB application from outside
9. The EJB Project
Search
1. Creating the project in Eclipse
2. Creating a service bean
3. Manual testing via GlassFish web service tester
4. Testing with soapUI
5. Prepare for persistence
6. Creating entity classes
7. Allocation sizes for sequences – a deviation
8. A simple Entity Access Object (EAO)
9. Using the EAO and looking for an error
10. Specifying the database, testing, SQL log
i. Creating connection pools and JDBC resources in the Administration Console
ii. Creating connection pools and JDBC resources using asadmin
iii. Referencing the JDBC resource from the application
11. Data Transfer Objects (DTO)
i. Where to convert?
ii. Implementation
iii. Updating definition in soapUI and testing
10. Accessing EJBs from a servlet
1. Creating a Dynamic Web Projects for servlets
2. Creating a servlet
3. Accessing the EJB
11. Unit tests
1. In-container testing
i. Project setup
ii. EJB lookup
iii. Testing and a NotSerializableException
iv. Testing internal interfaces
v. Testsuite
2. Out-of-container testing
i. Project setup
ii. Persistence unit and entity manager
iii. Simulating injection and testing
iv. Testsuite
12. Insert and Update
1. Extending the Database
2. Exceptions
3. Implementing storeZip()
4. If it does not work
i. java.sql.SQLSyntaxErrorException: Table/View ‘SEQUENCE’ does not exist
ii. Result has no id
13. Validation
1. ValidationException
2. Specifying constraints
3. Validation using interceptors
4. Testing the validator
14. Other uses of interceptors
1. A hypothetical security interceptor
2. Handling transaction rollbacks
i. The problem
ii. Towards a solution
iii. A solution using an interceptor
15. Adding extra libraries
16. Syndication Feeds
1. Realizing a feed with ROME
2. A bug in Eclipse
17. Configuration via JNDI Custom Resources
18. Access via REST
1. The REST servlet
2. The REST delegator
3. Examples of HTTP traffic
i. add()
ii. countryCount()
iii. dumpCountries()
iv. storeZip()
v. inputStream()
19. PostgreSQL as database backend
1. Installing PostgreSQL and creating a database user
2. Creating the database
3. PostgreSQL connection pool in GlassFish
4. Definition of the datasource in Eclipse
5. Entities
6. Access to PostgreSQL via SSL
20. Conclusion
In “4 – Equipment” I have committed myself to using Eclipse and the Java Enterprise Edition as my
tools, while in “5 – Patterns And Languages” I’ve declared my high-level goals for implementing a
next step of design pattern-based tools. Now, for a deeper understanding of design patterns, you
first have to use them. This post in the form of a tutorial shows some very basic project setups using
Eclipse and GlassFish.
I am no expert in this field, some important things may be missing, so just take the following
as a set of things that work for me.
As I am not immune to learning, and as I am going the use these things a lot, it is inevitable that my
understanding of certain aspects will change. I suppose that means, I will have to make changes to
this post whenever it happens. If I ever do so, I will post a short notice.
Applicability
[back to top]
This is a tutorial about using Eclipse and the GlassFish v3 Java application server to implement Java
EE 6 applications. I will show how to use different Eclipse project types for different purposes, will
show how to do manual tests and how to implement automatic unit tests. We will not create a
complete application, but more a vertical slice through an application. The idea is to just touch all
relevant areas, not to finish a project.
The tutorial assumes the existence of a relational database, and it concentrates on the Java
application used as a backend. Using JSF or another server-based GUI framework is definitely out
of scope.
How to use the tutorial
[back to top]
For your convenience and for reference I have zipped the workspace that I have used in these
examples (all but the .metadata directory) and uploaded it to my server. You can download it
fromhttp://manessinger.com/data/playground.zip. These files reflect exactly what you are going to
have, when you have completed this tutorial. No intermediate steps are contained in the archive. For
the best learning effect I suggest that you don’t use these sources, but just follow the tutorial step by
step. Eventually you will get to exactly that result.
Source listings in this tutorial can normally be taken by cut and paste. There is only one instance of
an XML file, where you can’t do it, but in that instance I explicitly say so.
If you don’t type the program texts, but instead copy them by cut and paste, it is possible to complete
the tutorial in six to eight hours. Depending upon your familiarity with the topics covered, it may be
shorter or considerably longer.
Typographical conventions
[back to top]
I’m trying to use a little bit of semantic markup here. At the moment I use the following conventions:
TERM Used for terms, normally only when they are introducedUI Element Used for user interface elements, everything that refers to GUI elementstext Used for names, texts that you type in or that you get as feedback from the GUI
Tools
[back to top]
I use the GlassFish Tools Bundle for Eclipse, and at the time of this writing, it is version 1.2, released
December 17, 2009. This package bundles the Java EE 6 reference implementation with Eclipse
3.5.1 and JDK 1.6. I have installed it on Windows 7 in the default location C:\GlassFish-Tools-Bundle-
For-Eclipse-1.2
While Eclipse 3.6 “Helios” has been released and is already supported by a new version of the
GlassFish plugin for Eclise, there is still an annoying bug, and I currently suggest that, unless you
really, really need Helios, you just use the bundle until the bug gets fixed. See “7 – Eclipse 3.6
“Helios” and GlassFish 3.01” for details.
The database is Apache Derby. This comes as part of the tools bundle. It has all the features of
“real” databases like Oracle or PostgreSQL, but it has a very small memory footprint.
For manual testing, I will use the Open Source edition of soapUI. Automatic testing will be done
using JUnit, which conveniently comes bundled with Eclipse. No further software is needed and I
have neither installed updates to GlassFish nor plugins.
I myself currently use an Eclipse workspace called playground. Every workspace will do, that’s just
what I use and what I may refer to.
Preparing the workspace
[back to top]
Eclipse has the notion of a WORKSPACE. Whenever you have an open instance of Eclipse, it
is open with a particular workspace. A workspace contains projects, where the notion
of PROJECT does not necessarily correspond to what we may regard as project in classic project
management.
Eclipse workspaces are just a collection of settings like how Eclipse itself is configured, which
servers are running, which databases you connect to, how the sub-windows (the VIEWS) and the
toolbars are arranged, which projects are part of the workspace, which files are open, etc.
A PROJECT is normally a collection of source files that compile and package to an ARTIFACT, for
instance a JAR or a WAR or an EAR file. The type of artifact depends on the type of project, for
instance a JAR is the artifact of a normal JAVA PROJECT, a WAR is the artifact of a DYNAMIC WEB
PROJECT, while an EAR is the artifact of anENTERPRISE APPLICATION PROJECT, basically a container
project that bundles collections of sub-projects into a single artifact.
Every time you open Eclipse, it asks you for the workspace to use, and when you open Eclipse for
the first time, or when you open Eclipse with a new workspace name, i.e. a workspace that does not
yet exist (for instance playground), you arrive at the welcome screen. Not much to do there, only
some documentation links, what you really want to do is go on to the workbench.
If it’s a new workspace, you’ll be in the RESOURCE PERSPECTIVE.
The PERSPECTIVE is another important concept in Eclipse. There are different perspectives for
different kinds of work. There is a JAVA EE PERSPECTIVE for working with Java in an Enterprise
Edition environment, aDATABASE DEVELOPMENT PERSPECTIVE for working with databases, and so on.
Each perspective is an arrangement of Views. A VIEW shows a particular aspect in a perspective.
You have a tree-like PROJECT EXPLORER view (normally along the left edge of the Eclipse window),
an EDITOR VIEW on an open file, a CONSOLE VIEW showing console output like in a passive terminal,
a SERVERS VIEW listing the running servers and giving access to server commands
like Start and Stop. Views can be tabbed together in groups. If something important happens in a
view, Eclipse automatically makes it the top tab in a tabbed group.
The Resource perspective is a general perspective for accessing project resources. We need two
other perspectives, Java EE and Database Development.
Use Window / Open Perspective / Java EE to change to the Java EE perspective. Now you will have
two buttons in the upper right toolbar, one labeled Java EE and the other Resource. Each of these
has a context menu (mouse right) and you can drag one button upon the other to change positions.
Try that and then choose Close from the context menu of the Resource perspective. We don’t need
it any more. In the same way you should open the Database Development perspective. Then switch
back to the Java EE perspective.
You may or may not have a server definition in the Servers view, and you may not even see
a Servers view at all. It should be in the tabbed pane at the bottom. If not, use Window / Show View /
Servers, or if it’s not directly in the menu, use Window / Show View / Other / Servers to show it.
If there is no server definition for the Bundled GlassFish v3 JEE 6 server, create a new one from the
context menu of the Servers view using New / Server. Just follow the screenshots. If you don’t use
the GlassFish Tools Bundle for Eclipse, you may have to define a new server runtime first, either
from the link on the first page of the New Server wizard, or from the menu bar via Window /
Preferences / Server / Runtime Environments / Add.
Now that we have a server, we need one more view that we’ll use frequently, and that is not visible
by default.
We use JUnit for unit tests. JUnit comes bundled with Eclipse and of course there is a JUnit view for
starting tests and viewing results. In the JEE perspective its default location is a tad awkward, thus
we will change it. If it is visible at all, it is in the bottom pane where you also find the Servers view. If
you don’t see it, open it withWindow / Show View / Other / Java / JUnit.
Now take the tab and drag it onto the tab of the Project Explorer in the left part of Eclipse. Again you
can change orders by dragging the tabs onto each other. Make sure the Project Explorer is visible,
that’s what we use most of the time.
Preparing the database
[back to top]
This is neither about object-relational mapping nor is it a meaningful sample application. I still want
at least two or three classes with foreign key relationships, thus we will use a classic master/detail
relation: a table of countries and a second table of cities, with cities being located in countries. One
more table will be added later.
The GlassFish Tools Bundle for Eclipse already comes with a pre-defined JDBC datasource for a
pre-designed Sample JavaDB Database. JavaDB is Sun’s name for Apache Derby.
We open Eclipse and first make sure that Derby is running. From the menu bar select Window /
Preferences, and in the Preferences dialog GlassFish Preferences. Make sure Start the JavaDB
database process when Starting GlassFish Server is ticked.
Next make sure that the Java EE perspective is active. In the lower part of the window there is a
tab Servers. Activate it, select Bundled GlassFish v3 Java EE 6 and start it, either with the green
arrow or from its context menu.
This will take a few seconds, maybe half a minute. In case GlassFish does not start and you get a
message box complaining about a wrong user name or password, have a look at “4 – Equipment“. You
may have run into the same problem as I did. Normally all should be well, the server running and
Derby ready for use.
Select the Database Development perspective. In the tree to the left, under Database Connections,
you will see Sample JavaDB Database. I don’t want to pollute the sample database that comes with
GlassFish. It is used in Sun’s tutorials and I recommend leaving it alone.
Let’s create a new database. From the context menu of Database Connections, we
select New and first have to select name and database type (Derby).
We click Next and now have to specify the new connection’s properties. I usecookbookdb as
database name (the name on the previous page was for display), and specify a
user cookbookuser with password cookbook. Use whatever you like. We will use this database a lot,
there won’t ever be anything of value in it, thus we can safely tick Save password. If you don’t feel
comfortable saving passwords in a development tool, you have my respect, just don’t do it, but in
any case try the Test Connection button once. You will be confirmed with a message box that Ping
succeeded. Click Finish and we’re done.
Derby is modeled after the big guys, thus we have not only databases, we have schema as
well. Looks like Oracle, huh?
Now that we have a database, we create the tables. Derby has automatically created a schema for
our user cookbookuser (though you can’t yet see it). In that schema we create two
tables, COUNTRY and CITY, the primary keys and the constraints.
In order to do this, select the new database and from its context menu choose Open SQL
Scrapbook. Make sure that our Cookbook Database is selected and connected. Now copy the
following text and paste it into the SQL window. Then right-click in the window and choose Execute
All.
---- Set up database schema--CREATE TABLE COUNTRY ( ID INTEGER GENERATED ALWAYS AS IDENTITY NOT NULL, NAME VARCHAR(50) );ALTER TABLE COUNTRY ADD CONSTRAINT COUNTRY_PRIMARY_KEY PRIMARY KEY (ID);CREATE UNIQUE INDEX COUNTRY_NAME_IDX ON COUNTRY(NAME); CREATE TABLE CITY ( ID INTEGER GENERATED ALWAYS AS IDENTITY NOT NULL, COUNTRY_ID INTEGER NOT NULL, NAME VARCHAR(50) );ALTER TABLE CITY ADD CONSTRAINT CITY_PRIMARY_KEY PRIMARY KEY (ID); ALTER TABLE CITY ADD CONSTRAINT CITY_FOREIGNKEY_COUNTRY_ID FOREIGN KEY (COUNTRY_ID) REFERENCES COUNTRY (ID);CREATE UNIQUE INDEX CITY_NAME_IDX ON CITY(NAME); ---- Initialize with some values--INSERT INTO COUNTRY (NAME) VALUES ('Austria');INSERT INTO COUNTRY (NAME) VALUES ('Italy');INSERT INTO COUNTRY (NAME) VALUES ('USA'); INSERT INTO CITY (COUNTRY_ID, NAME) VALUES ((SELECT ID FROM COUNTRY WHERE NAME = 'Austria'), 'Graz');INSERT INTO CITY (COUNTRY_ID, NAME) VALUES ((SELECT ID FROM COUNTRY WHERE NAME = 'Austria'), 'Linz');INSERT INTO CITY (COUNTRY_ID, NAME) VALUES ((SELECT ID FROM COUNTRY WHERE NAME = 'Austria'), 'Salzburg');INSERT INTO CITY (COUNTRY_ID, NAME) VALUES ((SELECT ID FROM COUNTRY WHERE NAME = 'Austria'), 'Wien'); INSERT INTO CITY (COUNTRY_ID, NAME) VALUES ((SELECT ID FROM COUNTRY WHERE NAME = 'Italy'), 'Bologna');INSERT INTO CITY (COUNTRY_ID, NAME) VALUES ((SELECT ID FROM COUNTRY WHERE NAME = 'Italy'), 'Firenze');INSERT INTO CITY (COUNTRY_ID, NAME) VALUES ((SELECT ID FROM COUNTRY WHERE NAME = 'Italy'), 'Roma');INSERT INTO CITY (COUNTRY_ID, NAME) VALUES ((SELECT ID FROM COUNTRY WHERE NAME = 'Italy'), 'Venezia'); INSERT INTO CITY (COUNTRY_ID, NAME) VALUES ((SELECT ID FROM COUNTRY WHERE NAME = 'USA'), 'Atlanta');
INSERT INTO CITY (COUNTRY_ID, NAME) VALUES ((SELECT ID FROM COUNTRY WHERE NAME = 'USA'), 'Los Angeles');INSERT INTO CITY (COUNTRY_ID, NAME) VALUES ((SELECT ID FROM COUNTRY WHERE NAME = 'USA'), 'New York');INSERT INTO CITY (COUNTRY_ID, NAME) VALUES ((SELECT ID FROM COUNTRY WHERE NAME = 'USA'), 'Washington');
This is the data we’ll work with. Now you can choose from the context menu of Database
Connections / Cookbook Database / cookbookdb / Schemas, and when you drill down, you see a
new schemaCOOKBOOKUSER with the two tables that we’ve just created.
When you look at the table definitions, you see that primary keys are declared as
ID INTEGER GENERATED ALWAYS AS IDENTITY NOT NULL;
This is Derby’s way of declaring automatically generated keys. In other databases you would use
sequences. Sequence support is already in the current version 10.6 of Derby, but the GlassFish
Tools Bundle for Eclipsestill comes with 10.5. In reality this is not important here. We are only going
to use this as a playground.
The container project (EAR project)
[back to top]
Purpose
[back to top]
There are different Eclipse project types that can be used with the JEE 6. In the most flexible setup,
you use a so-called ENTERPRISE APPLICATION PROJECT, also called an EAR PROJECT, after the
artifact it produces, anENTERPRISE ARCHIVE or EAR.
An EAR project is nothing but a container, intended to bundle the artifacts of the contained projects,
along with any libraries that they use and that are not already part of the Java Enterprise Edition. We
always begin with an EAR project, and then we create those projects, where we do the actual work,
adding each of them to the EAR. Later, for deployment, we can export the EAR project as one single
EAR file that contains all JARs from the contained projects.
Today an EAR would not be strictly needed. Today Dynamic Web Projects, the project type that
compiles to a WAR (Web Application Archive), also run under the control of an enterprise container,
thus you can use them to create Enterprise Java Beans, something that used to need an EJB
project. Still, I prefer to have my EJBs in an EJB project, and that wrapped up in an EAR. Only this
way do I get the client library that I need, when I want to access my beans via Corba/IIOP, and that’s
the protocol of choice when you want to be able to let beans participate in distributed transactions.
Steps in Eclipse
[back to top]
From now on, if not explicitly stated otherwise, we always assume that Eclipse is started, the
Database exists, GlassFish server and Derby database are started and the JEE perspective is
active.
In the JEE perspective you have the Project Explorer on the left side. If you have a fresh
workspace, then the Project Explorer will be empty. Either from the File menu or from the Project
Explorer context menu choose New / Enterprise Application Project. This opens the New EAR
Application Project dialog.
It is not so important what specific naming convention you have, but it is useful to have one. Mine is,
to have a name for the overall application, here cookbook, and then to suffix the projects with
something that tells about their type. Thus the EAR project is suffixed with EAR.
The core logic (EJB project)
[back to top]
Purpose
[back to top]
ENTERPRISE JAVA BEANS (EJB) are really just normal Java classes. Create one with new MyBean(),
and you get just a plain old Java object (POJO). It is when EJBs are instantiated under the control of
an EJB CONTAINER, that all sorts of interesting things begin to happen automatically.
For instance you can leave field variables in your beans uninitialized, and as long as they have the
right annotations, the container injects proper instances, and for performance reasons it can do that
from a pool of pre-allocated, momentarily idle instances. In a multi-threaded server this can give you
an enormous performance boost.
One of the most important aspects of EJB containers is, that they can inject datasources (for
instance JDBC datasources) and other resources, that the program only references by name, and
that are really defined in the application server.
Not only does the container manage datasources for accessing databases, it also handles
transactions, and it can do not only the simple case of handling local transactions, it also handles
and/or coordinates distributed transactions.
But again, in order for all this to work, you have to run your beans under the control of an EJB
container.
EJBs come in three flavors: STATELESS SESSION BEANS, STATEFUL SESSION BEANS and SINGLETON
BEANS. In the context of this sample application we will look at only one of them, stateless session
beans.
In the Java Enterprise Edition before version 5, entity persistence was handled by the Enterprise
Edition Container as well. This was called CONTAINER MANAGED PERSISTENCE (CMP), and although
you can still do it that way (in fact for compatibility you can still do all that tedious and verbose XML
configuration stuff), the new and much simpler way is to use the JAVA PERSISTENCE API (JPA).
When you use JPA, an Entity is again a simple Java class with getters and setters for its fields, a
POJO. You make it an entity by doing two things: annotating it with JPA annotations, and letting
an EntityManager fetch it from or persist it to the database. You get such
an EntityManager again via injection, when you get it, it is already associated with a persistence
context that manages transactions and caches entities, thus using JPA is again easy, how easy it is,
I’ll show you after some more definitions.
Abstraction of data access (Entity Access Objects)
[back to top]
Mapping relational databases to objects is a well-understood task by now, thus there are plenty of
supporting tools, and normally those tools generate code. Eclipse itself comes with a tool to create
entities from tables, so do other IDEs and of course the major UML tools can do that as well. Upon
re-generating a mapping after database changes, some of these tools can handle user-modified
entity classes, some can not. In general it is a good idea to leave generated code alone.
On the other hand, when you access the database via JPA, you either ask the EntityManager for
entities that you have an id for, or you create query objects, execute them and get lists of objects as
results. If you use queries (which you will do a lot), you express them in the JAVA PERSISTENCE
QUERY LANGUAGE. This is very much like SQL, and if you know SQL, you already know most of
what’s to learn.
Still, relational databases are not the only possible way to store data (although a good one), and
SQL is not the only way to get at data. The core logic of your application is not about getting or
storing data, it is about manipulating it. Thus it makes sense to encapsulate data access.
Traditionally Java has done a good job encapsulating data access, just think of the Data Access
Object(DAO) pattern or Java Data Objects (JDO). Here I propose a similar layer, and we will call
it ENTITY ACCESS OBJECTS (EAO). Basically I could as well have used DAO, but this name is so
burdened with reminiscences to the dark J2EE past, I don’t want to use it.
You can have one EAO per entity class, one per use case, a hierarchy of EAOs, a single one for the
whole application, it does not matter. The only thing that I recommend is, that all database access
goes through an EAO.
EAOs need database access and database access in JEE is via datasources injected by the EJB
container, thus EAOs need to be EJBs themselves. We will use Stateless Session Beans for that
purpose.
Services guard the entrance
[back to top]
J2EE, the dreaded version that gave the Java Enterprise Edition its bad reputation, required that
EJBs haveBUSINESS INTERFACES. I’ve never worked with J2EE, but I suppose that had some kind of
technical reason. As long as you stay within one Enterprise Application (EAR), this is not strictly
needed any more. EJBs that don’t implement an interface, can now be called via their so-called NO-
INTERFACE VIEW, which essentially means an implicit interface containing all public methods, and that
means you can call any of their public methods you like.
On the other hand, using interfaces for publishing the functionality that you commit to deliver, is still
considered good practice. Eclipse makes creating interfaces and keeping them in sync with their
implementation effortless, thus it won’t bog us down and instead give us a great deal more flexibility
down the road.
In other words, we design our application as a set of interfaces, and we implement these interfaces
as Stateless Session Beans. EJBs that we don’t expose, like our Entity Access Objects, neither
need nor get an interface.
Just to make sure that we know what we are talking about, we call such EJBs with public business
interfacesSERVICE BEANS.
Instantiation of Enterprise Java Beans
[back to top]
We already saw that EJBs are simple objects. They don’t do any magic, the magic is done by the
EJB container. The container holds pools of EJB instances and it controls the lifecycle of an EJB. An
EJB is an EJB only when it is instantiated by the container. Do it yourself and all you get is a POJO.
Generally there are three ways to get access to an EJB.
EJB annotation
[back to top]
The first kind is the EJB annotation. Inside of one EJB you can declare a field of the type of another
EJB class, but instead of initializing it, you annotate it.
@EJB MyBean mybean;
or
@EJB MyBusinessInterface mybean;
This is called DEPENDENCY INJECTION, because the EJB container injects a bean that we depend on.
Obviously this can only be done, when the referring object is an EJB itself, also running under the
control of the container. References can only be injected into field variables, and the injection is
done at every top-level invocation.
A top-level invocation is a call from outside of a container, into an EJB running inside of a container.
Clearly injection alone would not help us ever making top-level calls.
Although we may get a new chain of container-managed EJBs for every top-level invocation (at least
as long as we look at Stateless Session Beans), the injection mechanism is static insofar as the
container can already check for availability of all referenced types at deployment time. Thus if you try
to inject a variable of a type that is not defined at the application server (but may have been defined
in your development environment), the Enterprise Application won’t even start.
Lookup via JNDI
[back to top]
Sometimes you need more flexibility. For instance you could have different beans implementing the
same interface, and at runtime you may want to decide yourself, which type of implementation you
really want. In such a case you would decide (based on input, some calculations or an event) upon
the name of the bean type you are interested in, and then you would look it up via JNDI, the JAVA
NAMING AND DIRECTORY INTERFACE.
You do this by going through an InitialContext, just like
import javax.jws.WebService; @LocalBean@Stateless@WebServicepublic class CookbookBean implements CookbookInterface { public CookbookBean() { } @Override public long countryCount() { return 17; // FIXME call EAO method }}
If you store that change, the application running in GlassFish is automatically updated. This
automatic re-deployment works most of the time, it may fail though after major refactorings. If so, just
stop the server and start it again (did I caution you against restarting?).
GlassFish comes with a web application for administration. It’s called the ADMINISTRATION CONSOLE.
It has its own port number, and which port that is, this is our next job to find out.
There can be more than one GlassFish domain on one machine, a domain actually being an
instance of the server with its own set of port numbers. To find out what port numbers our installation
uses, we choose Openfrom the context menu of the server and come to an overview of the server
configuration. On my current instance I see 4860 as Admin Server Port Number. Thus the URL of
the console is
http://localhost:4860/
Let’s open this URL in a browser. We get to a login page. In the base development configuration the
username is admin, the password is empty.
Testing of the web service is easy now. In the tree on the left side of the browser window we
locateApplications. We click cookbookEAR and get to an Edit Application view. On the right side of
the table at the bottom, there is a link View Endpoint, and that leads to the Web Service Endpoint
Information view. Here we have three links:
Application Name takes us back to the previous page
Tester opens a Web Service Tester in a new browser window
WSDL opens a new browser window showing the WSDL
We choose Tester and get a window with a form an a button for each method of the service. If a
method has parameters, we are presented with an input box per parameter. In our case we have
only one parameter-less method, therefore we see only a single button countryCount(). We press
the button, see the SOAP XML data, and indeed, the result is 17. Just as expected.
Note: should you instead get an internal error in the tester window, and in the console log in Eclipse
a stack trace with something like the following text in the middle,
Caused by: com.sun.xml.ws.util.ServiceConfigurationError: com.sun.xml.ws.api.pipe.TransportPipeFactory: Provider com.sun.enterprise.jbi.serviceengine.bridge.transport.JBITransportPipeFactory is specified in bundle://245.0:0/META-INF/services/com.sun.xml.ws.api.pipe.TransportPipeFactory but not found
then you’ve probably updated GlassFish via the UPDATE TOOL in the administration console. Don’t do
that. It currently breaks the web service tester. There is no need to update, everything I do here
works perfectly with the original release of the GlassFish Tools Bundle for Eclipse from December
12, 2009. Uninstall the Tools Bundle, reinstall, open the workspace again and it will work.
Testing with soapUI
[back to top]
In cases where you have non-scalar parameter types, the tester application built into GlassFish does
not suffice, because it only gives you one input text field per parameter. In such cases soapUI is the
much better tool. soapUI also has a workspace metaphor and also has projects.
On the left side there is again a tree with projects, that you can open, add WSDLs to, create sample
requests for, edit requests and finally run them.
When you create a soapUI project, you are asked for a project name (I’ve used cookbookEAR and an
initial WSDL (taken from the Endpoint View in GlassFish’s administration console. In our case this is
With soapUI you can control and view all aspects of your SOAP requests and responses. You can
define additional HTTP headers, send and receive attachments and much more. For us it’s only
important, that the requests that soapUI generates, are simple XML texts that we can edit and that
way fill out complex parameter types. You send a request by clicking the small green triangle in the
upper left corner of a request window.
For now we leave it at that, but we’ll come back to soapUI later, when we treat the validation of
complex parameter types.
Prepare for persistence
[back to top]
So far we have a Stateless Session Bean that can act as a web service, but the only service method
currently returns a hardcoded dummy number 17. Now it’s time to replace that with actual results
from the database.
As regards entity classes and tables, there are two possible strategies:
generating a database schema from Java entity classes
generating Java entity classes from a database schema
Here we assume the database that we’ve already introduced. Before we actually generate entities,
we want to make some preparations.
The code generator included with Eclipse allows us to let the generated entities inherit from a class
or implement any number of interfaces. Of course it’s clear that methods declared in those interfaces
will have to be implemented. Concerning interfaces, we have the following options:
1. let the entities implement marker interfaces (without methods)
2. insert any method declared in an interface into the generated entities
3. implement the interface methods in a base class and let the entities inherit from that base class
Option #1 is perfectly possible, but only not very useful. Option #2 is ruled out, because we
absolutely want to avoid changing generated code. This leaves us with option #3, but when we
already have to extend a class that has to implement all of the interface’s methods, why do we need
an interface at all? Thus we won’t let our entities implement interfaces, but a base class might be
useful.
We use New / Project / Java EE / Utility Project to create a new JAVA EE UTILITY PROJECT. Let’s call
itjee_utilities, and whenever we happen to create a reusable class, we’ll put it there.
We add the new project to the EAR. Of course, being a standalone project, it could be added to any
other EAR, and therefore it is reusable.
Any classes in this utility project must be visible from the EJB project, thus we insert it
into cookbookEJB‘s build path by choosing Build Path / Configure Build Path / Projects / Add from
the context menu.
Now the classes are visible in Eclipse at compile time, but in order to make them accessible when
running in GlassFish, we need to put the JAR file of the utility project into the lib directory of the
EAR. We do that in theProperties dialog of the EAR project.
Then we create a package com.manessinger.util.jpa in the utility project, and there we add a
classEntity, the base class for our entities:
package com.manessinger.util.jpa; public abstract class Entity { public static boolean isId(Integer id) { return (id != null && id > 0); } public boolean hasId() { return isId(getId()); } public abstract Integer getId();}
OK, that’s how we do it, but why do we do it at all? We gain two things:
The base class bundles all entities, and whether a class is an entity or not, that can be checked
at compile and run time. So far this could have
been achieved with marker interfaces as well
We put a thin abstration layer around the fact that we will generate Integer as primary key
type, and that null is not a valid key value but instead the value of an uninitialized key variable.
We could as well have decided to generate keys of type int, taken from a sequence, and then
the value 0 would have been the value of an uninitialized key variable. Thus we basically
encapsulate the magic value nulland create an API to check if some object has a valid ID and
can possibly have been read from the database.
We’ll see the use of this base class later, for now just create it. And even if you see no value in this
exact base class, there are definitely other uses where a base class for our entities may be useful.
This is how to create it.
Creating entity classes
[back to top]
Our entities need a place to live in, thus we first create a package in the EJB project, and we call
itcom.manessinger.cookbook.entity. We won’t expose entities via business interfaces, thus the entities
clearly belong into cookbookEJB, not into the client project.
The fastest way to add a package to an existing hierarchy, is to call New / Package not from the
context menu of the project, but from the context menu of another package, because then the name
will already be initialized with the existing package. Here we just have to replace service with entity.
Now let’s generate code. In the context menu of the EJB project (and only there) you’ll find JPA
Tools / Generate Entities from Tables. That’s what we need, and it takes us to the Generate Custom
Entities-Dialog.
When the dialog opens, it can be that Eclipse has no connection to the database yet. In that case
you can connect with a click on the connection icon directly below the Connection drop-down menu.
When you are connected, you can see a list of tables in the connected schema. Check all tables that
you want to generate entities for and press Next.
In the following step you see the associations that Eclipse was able to detect. Eclipse is fairly good
at it, but of course this will only work for reasonably crafted database schemas. If you don’t use
foreign key constraints and not even name your fields in a meaningful way, then you’ll have to do the
mapping yourself. In my experience, what you need to change most often, are the property names,
i.e. the names that refer to the associations in Java. In this trivial case Eclipse has detected all there
was.
The next step is the definition of mapping defaults. Normally you will have only one strategy of
generating IDs and that will apply to all tables. In Oracle you will probably use sequences, and all the
sequences will probably be named systematically. I name mine after table and id field, and then add
a suffix _seq. For such a naming system you would enter $table_$pk_seq in the Sequence
name input field.
In our case we don’t need that. We use the value identity as Key generator, because that’s how we
have defined the keys in Derby.
In the last step we can change the defaults for tables and even down to each field. We can rename,
change datatypes, etc. Here we change the types of the generated primary keys (id)
from int to Integer. Remember to do that for both tables.
Here is the generated code, reformatted to make it more compact:
package com.manessinger.cookbook.entity; import java.io.Serializable;import javax.persistence.*;import java.util.Set; @Entitypublic class Country extends com.manessinger.util.jpa.Entity implements Serializable { private static final long serialVersionUID = 1L; @Id @GeneratedValue(strategy=GenerationType.IDENTITY) private Integer id; private String name; //bi-directional many-to-one association to City @OneToMany(mappedBy="country") private Set<City> cities; public Country() { } public Integer getId() { return this.id; } public void setId(Integer id) { this.id = id; } public String getName() { return this.name; } public void setName(String name) { this.name = name; } public Set<City> getCities() { return this.cities; } public void setCities(Set<City> cities) { this.cities = cities; } }
package com.manessinger.cookbook.entity; import java.io.Serializable;import javax.persistence.*; @Entitypublic class City extends com.manessinger.util.jpa.Entity implements Serializable { private static final long serialVersionUID = 1L; @Id @GeneratedValue(strategy=GenerationType.IDENTITY) private Integer id; private String name; //bi-directional many-to-one association to Country @ManyToOne private Country country;
public City() { } public Integer getId() { return this.id; } public void setId(Integer id) { this.id = id; } public String getName() { return this.name; } public void setName(String name) { this.name = name; } public Country getCountry() { return this.country; } public void setCountry(Country country) { this.country = country; }}}
The generated entities are normal classes, plain old Java objects or POJOs, sparingly annotated
with mapping information. During code generation you can also choose to generate the annotations
for those things that otherwise are defaulted. I wouldn’t do that though. It does not help when your
code is riddled with annotations.
Allocation sizes for sequences – a deviation
[back to top]
Let’s have a short look over the fence here. What if you use sequences for primary key generation?
You may not use Derby but Oracle, and with Oracle, sequences are the natural choice for that job.
Furthermore you may not be free to make any changes to your database, especially not to the
sequence value allocation policy. If so, you may run into a problem. Let me explain:
A sequence is a database object that you can draw numbers from. In the normal case you get
numbers beginning with 1, and each time you draw a number, the sequence increments. Two callers
never get the same value (at least not until the sequence overflows, but that is another problem) and
you never get the same value twice. The value by which the sequence is incremented after a draw
defaults to 1, but it can be set when the sequence is created using INCREMENT BY.
While it is most natural to let the sequence increment by 1, it actually makes sense to use a higher
value. Imagine a sequence incrementing by 50. Then you essentially get not one but 50 exclusive
values with one single draw. Thus the program drawing the values does not have to make 50 trips to
the database but only one. This increases performance.
GlassFish defaults to an increment fo 50, but what if your database has already been created with
an increment of 1 (or any other value but 50)? You can’t simply change the increment, because
existing database clients depend on the current value. Thus you have to tell JPA what your
increment value is.
Here is the City entity once again, but this time we use an Oracle databases with sequences:
package com.manessinger.cookbook.entity; import java.io.Serializable;import javax.persistence.*; @Entitypublic class City extends com.manessinger.util.jpa.Entity implements Serializable { private static final long serialVersionUID = 1L; @Id @SequenceGenerator(name="CITY_ID_GENERATOR", sequenceName="CITY_ID_SEQ") @GeneratedValue(strategy=GenerationType.SEQUENCE, generator="CITY_ID_GENERATOR") private Long id; private String name; //bi-directional many-to-one association to Country @ManyToOne @JoinColumn(name="COUNTRYID") private Country country; public City() { } public Long getId() { return this.id; } public void setId(Long id) { this.id = id; } public String getName() { return this.name; } public void setName(String name) { this.name = name; } public Country getCountry() { return this.country; } public void setCountry(Country country) { this.country = country; }}
We can specify the allocation size of the underlying sequence (here CITY_ID_SEQ) by specifying
the attributeallocationSize to the @SequenceGenerator annotation, for instance like this:
@Id@SequenceGenerator(name="CITY_ID_GENERATOR", sequenceName="CITY_ID_SEQ", allocationSize=1)@GeneratedValue(strategy=GenerationType.SEQUENCE, generator="CITY_ID_GENERATOR")private Long id;
The problem is, that we would have to change the generated entity, but this is something that we
don’t want to do. Ideally the code generator would have created the attribute in the first place, but
this did not happen. Fortunately there is an alternative to editing generated code.
Like everywhere in the Java Enterprise Edition, annotations are only one way to specify things. The
other way are the good old XML configuration files, and when a Java EE server sees both, the XML
configuaration wins. This is good, because you can override annotated specifications at runtime,
without having to re-compile the application. That way an administrator can make configuration
changes and does not rely on a developer.
In our case we have to create a file ejbModule/META-INF/eclipselink-orm.xml in the EJB
project. We do that by calling New / XML from the context menu of the directory META-INF in
@LocalBean@Statelesspublic class CookbookEao { @PersistenceContext EntityManager em; public CookbookEao() { } public long countCountries() { long result; Query q = em.createQuery("select count(co) from Country co"); result = (Long)q.getSingleResult(); return result; }}
We use a field variable of type ENTITYMANAGER, attributed with @PersistenceContext, and we
don’t initialize this variable. It is automatically injected by the EJB container.
The method countCountries() uses this entity manager to create a QUERY, executes the query
(that’s what happens in getSingleResult() and finally returns the result.
We could have written that much more compact as
return (Long)em.createQuery("select count(co) from Country co").getSingleResult();
but the longer variant has the advantage, that it is easier to understand, self-documenting, and you
can set a breakpoint in the debugger.
Using the EAO and looking for an error
[back to top]
Now that we have an EAO, we want to get back to our TODO item and replace the constant 17 with
public class CookbookBean implements CookbookInterface { @EJB CookbookEao eao; public CookbookBean() { } @Override public long countryCount() { return eao.countCountries(); }}
We have added a field variable eao, have attibuted it and expect an EAO instance to be injected
upon each call of the top-level method countryCount(). This actually happens, but then we get
an error.
When we call countryCount() from the GlassFish Web Service tester, instead of the expected
result 3, we get the following error:
Service invocation threw an exception with message : null; Refer to the server log for more details Exceptions details : java.lang.reflect.InvocationTargetExceptionjavax.servlet.ServletException: java.lang.reflect.InvocationTargetException at...... many lines omitted...org.apache.derby.client.am.SqlException: Table/View 'COUNTRY' does not exist. at org.apache.derby.client.am.Statement.completeSqlca(Unknown Source) at ...... many more line omitted...
This is weird. We know there is a table COUNTRY. We have created it, we have filled it, we have
used it to create an entity. We remember that we have connected to the database when we created
entities, so this just should not happen, right?
Wrong. Yes, we have connected to the database, but the connection was made in Eclipse, not in
GlassFish. Remember how we configured Eclipse to always start JavaDB when starting GlassFish?
JavaDB is a seperate process, so is GlassFish. It does not mean a thing to GlassFish, when Eclipse
is connected to a database.
And when we talk about being connected to a database: how should GlassFish know what database
to use? We have defined our schema in the Cookbook Database, but how do we communicate that?
When we created the EJB project, we have added a Java Persistence project facet, and due to that,
we were asked for a database connection. Later, when creating entities, Eclipse used that very
same connection to discover tables and their associations. Eclipse has done nothing though, to tell
GlassFish about it.
Before we come to the solution, please allow me a short digression: Let’s look at what we would
have got in Oracle.
The error message would have begun identically, only in the stack trace we would have seen a
weird series of exceptions:
The DatabaseSession has an external transaction controller defined by somethingother than the ServerPlatform. EclipseLink will permit the override of theexternal transaction controller, but we recommend you consider the alternativeof subclassing org.eclipse.persistence.platform.server.ServerPlatformBase andoverride getExternalTransactionControllerClass().
Funny, huh? Chronologically the next exception is
Unexpected exception while creating resource for pool DerbyPool.Exception : javax.resource.spi.ResourceAllocationException: Connection couldnot be allocated because:java.net.ConnectException : Error connecting to server localhost on port 1527with message Connection refused.
and then
Failed to obtain/create connection from connection pool [ DerbyPool ].Reason : com.sun.appserv.connectors.internal.api.PoolingException:Connection could not be allocated because:java.net.ConnectException : Error connecting to server localhost on port 1527with message Connection refused.
This is followed by more consecutive faults. What’s happening here? We use Oracle, but GlassFish
looks for our tables in Derby?
It turns out that GlassFish can’t know about our Oracle database, for all the reasons that we have
already explained, but Derby is GlassFish’s fallback, and the sample database that comes with
GlassFish is configured as the default database. No wonder that GlassFish couldn’t find a
table COUNTRY, even when we really used Derby. GlassFish was never told about a cookbookdb,
all it knew was the sample database.
Specifying the database, testing, SQL log
[back to top]
Whatever the database, it is clear that GlassFish has to be told about it. Let’s do that. We need to do
two things:
First we have to create a reference in GlassFish that points to the database. Second, we have to
change the application in a way that it tells GlassFish, which one of possibly several databases
defined in GlassFish we want to use. Let’s begin with creating the reference.
Such a reference consists of two parts, a JDBC connection pool and a JNDI name definition refering
to the pool. This JNDI name finally is, what we will use in the application to point to the database.
Creating connection pools and JDBC resources in the Administration Console
[back to top]
We open the administration console and go to Resources / JDBC / Connection Pools. There we see
a list of the currently defined connection pools.
Step 1 of the New JDBC Connection Pool wizard requires us to use a Resource Type. The help
page of the wizard tells us that
Available resource types are javax.sql.XADataSource (global
transactions),java.sql.ConnectionPoolDataSource (local transactions, possible performance
improvements), javax.sql.DataSource (local transactions only), and java.sql.Driver
. For the purpose of our tutorial, javax.sql.DataSource is OK, but if we create EJBs that may
eventually partake in distributed transactions, we have to choose the most general
variant javax.sql.XADataSource. They are a little more expensive, consuming more memory,
but that’s the price for the added flexibility. There will be a separate post about multi-database
scenarios shortly.
Here we enter a name for the new pool, choose Derby as database vendor and go on to the next
screen. On the top part of the page, we can leave everything as it is. The important things have to be
defined as properties. Scroll down, remove all unnecessary attributes and fill the rest with the values
that we already used when we defined the database. Before you click Finish, make sure that Ping is
enabled. This way GlassFish will test the database definition.
The next step is to define a JNDI name. Go to Resources / JDBC / JDBC Resources, add a new one
and connect it to the new pool.Creating connection pools and JDBC resources using asadmin
[back to top]
We can do that in GlassFish’s Administration Console web application as we just did, and we can
also do it using the asadmin commandline utility. Whatever you can do in the Administration Console,
you can do inasadmin as well, and then supposedly some things more. Here is a session in Windows
where I have created the same resources as in the web application.
public class CookbookBean implements CookbookInterface { @EJB CookbookEao eao; @EJB Conversion conv; public CookbookBean() { } @Override public long countryCount() { return eao.countCountries(); } @Override public List<CountryDump> dumpCountries() { List<CountryDump> result = new ArrayList<CountryDump>(); List<Country> allCountries = eao.allCountries(); for (Country c : allCountries) { CountryDump ci = conv.fromEntity(c); result.add(ci); } return result; }}
in the EAO
package com.manessinger.cookbook.eao; import java.util.List;import javax.ejb.LocalBean;import javax.ejb.Stateless;import javax.persistence.EntityManager;import javax.persistence.PersistenceContext;import javax.persistence.Query;import com.manessinger.cookbook.entity.Country; @LocalBean@Statelesspublic class CookbookEao { @PersistenceContext EntityManager em; public CookbookEao() { } public long countCountries() { long result; Query q = em.createQuery("select count(co) from Country co"); result = (Long)q.getSingleResult(); return result; } @SuppressWarnings("unchecked") public List<Country> allCountries() { List<Country> result; Query q = em.createQuery("select co from Country co");
result = (List<Country>) q.getResultList(); return result; }}
and finally in the converter
package com.manessinger.cookbook.util; import java.util.ArrayList;import java.util.List;import javax.ejb.EJB;import javax.ejb.Stateless;import com.manessinger.cookbook.dto.CountryDump;import com.manessinger.cookbook.eao.CookbookEao;import com.manessinger.cookbook.entity.City;import com.manessinger.cookbook.entity.Country; @Statelesspublic class Conversion { @EJB CookbookEao eao; public Conversion() { } public CountryDump fromEntity(Country e) { CountryDump result = new CountryDump(); result.setName(e.getName()); List<String> cities = new ArrayList<String>(); for (City city : e.getCities()) { cities.add(city.getName()); } result.setCities(cities); return result; }}
After such major changes involving new classes, you may need to restart the server. Normally
changes are automatically deployed, but if too much structure is changed, then a server restart can’t
be avoided. This is such a point. Just remember to actually stop/start the server, because restarting
has a bug right now.
Updating definition in soapUI and testing
[back to top]
We can test dumpCountries() in the GlassFish web service tester (Appplications /
projectxEAR / Modules and Components / View Endpoint / Tester), or we can do it in soapUI. In
order to do the latter, we have to make it update its definition. We do that from the context menu
of CookbookBeanPortBinding with Update Definition.
When we finally make the call, we see the expected result:
} out.println("</ul>"); } out.println("</dd>"); } out.println("</dl>"); out.println("</div>"); } out.println("</body>"); out.println("</html>"); } finally { out.close(); } } @Override public String getServletInfo() { return "Displays a list of countries and some of their cities"; }}
This is it. We get a list.
Unit tests
[back to top]
Unit tests are a means to make sure, that by adding new code or modifying existing one, you don’t
inadvertently break what already works. Unit tests are just small test programs that verify the
contracts of the units of code that they test. Programmers always have done that, it’s just
that Extreme Programming made their use mandatory, and that Kent Beck and Erich Gamma
devised a clever but simple framework called JUnit.
Unit tests can be executed from within Eclipse (or any of the other popular Java IDEs), they can be
run via Ant, and they are run by so-callen continuous integration servers like Hudson. In many
organizations and projects a successful run of the unit test suite is even precondition for a checkin
into the version control system.
In times of J2EE, unit testing EJBs was notoriously hard, mostly because the beans were not
POJOs. They completely depended on the container, and testing them independently was not
possible.
We are going to try two strategies here, in-container testing as it could have been done earlier as
well, and out-of-container testing, which has been greatly simplified with JEE 5 respectively EJB 3.
In-container testing
[back to top]
In order for in-container testing to be possible, the application must be deployed to a server. That
may have been an obstacle in the past, when servers were big, slow to start and consumed a lot of
memory, but now it’s something we hardly notice. I always run a server anyway, started from
Eclipse, and I let Eclipse automatically deploy all changes. In a time of much faster machines, plenty
of memory and lean, optimized server code (hard to tell what’s the dominant factor here ),
there’s no reason not to do so. When the server is already running, we can use it to run the
interactively started unit tests as well, and when we start the tests automatically as part of a nightly
build in an integration server or after changes in a source repository have been detected, having
them run in a server is no matter either.
Basically we have two options to call into the server from the test program. We could call via SOAP,
restricting ourselves to testing what we publish. The other option is to call “EJB style”, i.e. calling via
Corba/IIOP to a Remote Interface. This is what we do here.
The test program is a normal Java program, not a JEE application (though it would be possible to
conceive of a JUnit runner to be one), and we can only test what has exposed itself via a REMOTE
INTERFACE. If we properly set up the test project, there is no need for the remote interface to be part
of the client project, but the beans that we test must still register with the server for remote access,
and they will continue to do so in production. If that troubles you and you don’t want to expose
internal interfaces, even in the rather opaque way of not having them included in the client libraries,
in other words, if you care about making it impossible to call them, then, well, then you should
probably not use Java at all. A language that is not as easy to de-compile would suit you better. In
this context I assume that this is a non-issue.
Project setup
[back to top]
We begin setting up the test project, an ordinary Java project called cookbookJUnitInServer.
In order to have access to all beans in the server, exposed via client libraries or not, we don’t put the
client project on the build path but the EJB project cookbookEJB instead. We need to add Junit
libraries to the project, and we do this via Libraries / Add Library / JUnit / JUnit 4. Similarly we need
the client library for access to GlassFish. Note though, that you don’t get that via Libraries / Add
Library / Server Runtime / GlassFish v3 JEE 6. The library we need is called gf-client.jar and it is
located in the GlassFish modules directory. On my standard Windows 7 installation of the GlassFish
Tools Bundle For Eclipse this is located inC:\GlassFish-Tools-Bundle-For-Eclipse-1.2\glassfishv3\
glassfish\modules. You have to add the file via Libraries / Add External JARs, and when you do that,
Eclipse pulls in a host of referenced files as well. You don’t see that in the Build Path dialog, but
you’ll see it in the Project Explorer.
EJB lookup
[back to top]
The way to get access to an EJB from outside of the EJB container is via JNDI lookup, i.e. by calling
thelookup() method of an InitialContext, but in this case we have to go a little
further. InitialContextcomes with normal Java SE and it does not know about JEE or
GlassFish. We have to provide some hints when constructing the InitialContext. These hints
are given to the constructor as a set of properties. We want one place where these properties are
defined, thus we create a package in the test project calledcom.manessinger.junit. Here we create a
class Util with a static method Properties getInitProperties().
package com.manessinger.junit; import java.util.Properties; public class Util { public static Properties getInitProperties() { Properties result = new Properties(); // We need to tell the context where and how to look result.setProperty("java.naming.factory.initial", "com.sun.enterprise.naming.SerialInitContextFactory"); result.setProperty("java.naming.factory.url.pkgs", "com.sun.enterprise.naming"); result.setProperty("java.naming.factory.state", "com.sun.corba.ee.impl.presentation.rmi.JNDIStateFactoryImpl"); // Should not be necessary for local test (default values), but // currently is result.setProperty("org.omg.CORBA.ORBInitialHost", "localhost"); result.setProperty("org.omg.CORBA.ORBInitialPort", "3700"); return result; }}
The first block of three properties causes JNDI to use GlassFish-specific libraries for the lookup. The
second block
with org.omg.CORBA.ORBInitialHost and org.omg.CORBA.ORBInitialPort is interesting
though. The values specified should be default values, but fact is, that they currently are not. On the
other hand, we can use exactly these properties to access EJBs running on any host. We only have
to make sure that the calls are not blocked by a firewall. This way it is also possible to run the unit
tests on another host than the actual beans under test.
Should you ever do that, you have to make sure that GlassFish on the target machine does not only
register for localhost but for the external interface. In order to do that, you open the Administration
Console in a browser and change Configuration / ORB / IIOP Listeners / orb-listener-1 / Network
address from127.0.0.1 to either the external IP address or, better, the DNS name of the server host.
Again, you have to make sure that no firewall blocks the accesses.
Even if you don’t plan on calling to other hosts, it’s still a good idea to check Configuration / ORB /
IIOP Listeners / orb-listener-1 / Network address in the Administration Console. On Linux I have a
default of127.0.0.1 (which is OK), but on Windows I had 0.0.0.0. No idea if this is the default for
Windows (why should it be?) or if it was the result of me tinkering with the installation, but it does not
hurt to have a look.
Testing and a NotSerializableException
[back to top]
No we can write a simple test class for our EJB. Note that we always put our test classes into
packages with the same names (as packages are namespaces, essentially meaning they are in the
same package) as the classes under test. Thus we first create a
package com.manessinger.cookbook.service in the test project, and then we create the test class:
package com.manessinger.cookbook.service; import static org.junit.Assert.assertEquals;import java.util.List;import javax.naming.InitialContext;import org.junit.Before;import org.junit.Test;import com.manessinger.cookbook.dto.CountryDump;import com.manessinger.junit.Util; public class TestCookbookBean { private CookbookInterface serviceBean; @Before public void setUp() throws Exception {
serviceBean = (CookbookInterface) new InitialContext(Util.getInitProperties()) .lookup("java:global/cookbookEAR/cookbookEJB/CookbookBean" +"!com.manessinger.cookbook.service.CookbookInterface"); } @Test public void countryCountTest() { long n = serviceBean.countryCount(); assertEquals(3, n); } @Test public void dumpTest() { List<CountryDump> countries = serviceBean.dumpCountries(); assertEquals(3, countries.size()); for (CountryDump co : countries) { assertEquals(4, co.getCities().size()); } }}
We run a unit test by right-clicking in the file and calling Run As / JUnit Test from the context menu.
This pops up the JUnit view, but when you are in the Java EE perspective, it may still be down
where the Server viewand Console view are. Just take the tab and drag it onto the Project
Explorer tab on the left side or the Eclipse window. That’s where it is in the normal Java perspective,
and this is a much better place.
When you run the test like that, you will see that countryCountTest() succeeds,
and so on and so on. What’s wrong? Obviously something should be serializable and is not, but
what exactly is it. You see the solution in the server log:
WARNUNG: "IOP00100006: (BAD_PARAM) Class com.manessinger.cookbook.dto.CountryDump is not Serializable"
Is it not? Yup, GlassFish is right, it isn’t. In Java you make a class serializable by letting it implement
the marker interface java.io.Serializable. This is called a marker interface, because it does
not contain any method signatures. I think for orthogonality modern Java should provide an
annotation @Serializable, but until it does, we need to change CountryDump (in the client
project) like this:
package com.manessinger.cookbook.dto; import java.io.Serializable;import java.util.List; public class CountryDump implements Serializable { private static final long serialVersionUID = 1L; private String name; private List<String> cities; public String getName() { return name; } public void setName(String name) { this.name = name; } public List<String> getCities() { return cities; } public void setCities(List<String> cities) { this.cities = cities; }}
We didn’t get the error before, because so far we had called dumpCountries() only via SOAP,
and the SOAP serializer code obviously dose not need parameter classes to explicitly
implement Serializable.
Testing internal interfaces
[back to top]
When we look back at the test class, we see an annotation @Before on the
methodsetup(). This is a JUnit 4 annotation, and it means that the setup method is called before
each test method. There is another annotation @BeforeClass, and when we use that on a static
method, it is called before the first test method, and finally there is another pair of
annotations, @After and @AfterClass. They are obviously called after each method, respectively
after the last test method.
If we want to test the EAO (which is the only other bean at the moment anyway), we need it to
implement aREMOTE INTERFACE. We don’t want to have this interface in the client project, instead we
put it into the EJB project into the package com.manessinger.cookbook.eao, where the EAO itself is. We
do that by usingRefactor / Extract Interface from either the context menu of CookbookEao.java in
the Project Explorer or from the context menu of the class name within the file.
Extracting the interface is not enough though. We need to make it a REMOTE INTERFACE by adding
the @Remoteannotation:
package com.manessinger.cookbook.eao; import java.util.List;import javax.ejb.Remote;import com.manessinger.cookbook.entity.Country; @Remotepublic interface CookbookEaoInterface { public long countCountries(); public List<Country> allCountries();}
When we extracted the interface, the EAO has automatically been changed to implement it:
package com.manessinger.cookbook.eao; import java.util.List;import javax.ejb.LocalBean;import javax.ejb.Stateless;import javax.persistence.EntityManager;import javax.persistence.PersistenceContext;import javax.persistence.Query;import com.manessinger.cookbook.entity.Country; @LocalBean@Statelesspublic class CookbookEao implements CookbookEaoInterface { @PersistenceContext EntityManager em; public CookbookEao() { } public long countCountries() { long result; Query q = em.createQuery("select count(co) from Country co"); result = (Long)q.getSingleResult(); return result; } @SuppressWarnings("unchecked") public List<Country> allCountries() { List<Country> result; Query q = em.createQuery("select co from Country co"); result = (List<Country>) q.getResultList(); return result; }}
Now we can do just the same as for the service bean and create a test class. Of course we could as
well add the tests to our existing test class, but that scales only to a certain point. Add more beans
and it becomes quickly confusing, so why not do it right from the beginning? Again we create a
packagecom.manessinger.cookbook.eao in the test project, and here’s the test class:
package com.manessinger.cookbook.eao; import static org.junit.Assert.assertEquals;import javax.naming.InitialContext;import org.junit.Before;import org.junit.Test;import com.manessinger.junit.Util; public class TestCookbookEao { private CookbookEaoInterface eao; @Before public void setUp() throws Exception { eao = (CookbookEaoInterface) new InitialContext(Util.getInitProperties()) .lookup("java:global/cookbookEAR/cookbookEJB/CookbookEao" + "!com.manessinger.cookbook.eao.CookbookEaoInterface"); } @Test public void countryCountTest() { long n = eao.countCountries(); assertEquals(3, n); }}
Testsuite
[back to top]
Now we have one test class per class tested, both in the test project, but in the same packages as
the classes that they test. We can run each of them separately with Run As / JUnit Test, but we also
want the option to run the whole suite of tests. That’s what a JUnit test suite is for. Here is another
class that can be Run As / JUnit Test, and this class will run all the individual test classes:
package com.manessinger.cookbook; import org.junit.runner.RunWith;import org.junit.runners.Suite; @RunWith(Suite.class)@Suite.SuiteClasses({ com.manessinger.cookbook.service.TestCookbookBean.class, com.manessinger.cookbook.eao.TestCookbookEao.class,})public class AllTests { // Any global setup would go here }
Out-of-container testing
[back to top]
We already know to run unit tests on beans running in a server. In order to make this possible, the
beans must expose the methods that we test over a Remote Interface. This is not the only way of
testing though. In the next step we will look at testing without a container.
The idea is, to do in setup what the container would do normally, thus we need to simulate injection
of EJBs and entity managers.
Project setup
[back to top]
Just like with in-server testing, we create a new project, and again this project is a normal Java
project. We call it cookbookJUnitOutOfServer.
Just like with the in-server test project, we add the EJB project, the JUnit 4 libraries (Add Library /
JUnit / JUnit 4) and the GlassFish server runtime (Add Library / Server Runtime / GlassFish v3 Java
EE6). When I did the same at work with Oracle, I also needed to add the Oracle JDBC driver JAR
file, but here with Derby it is not necessary. It comes with the GlassFish runtime anyway.
Persistence unit and entity manager
[back to top]
We work with JPA for database access. JPA needs a file META-INF/persistence.xml in its class path.
We can simply copy cookbookEJB/ejbModule/META-INF and paste it to cookbookJUnitOutOfServer/src.
The name of the persistence unit was cookbookEJB, we change it to cookbookEJB_junit. This is
important, because our test project has the EJB project (and therefore the
original META-INF/persistence.xml) on the build path. We need to make sure that our name is unique,
because otherwise we would depend on which persistence.xml is found first on the path.
Apart from changing the name of the persistence unit, we have to add some properties for specifying
the database connection. In the EJB project (and also when testing in-server) the connection had
been supplied by the server in form of a JDBC data source, referenced by a JNDI name. Now we
have no server, thus we have to specify it here. This is also the way how you can use JPA without a
JEE environment.
In this sample project we use the same database for testing as we use in the EJB project. Normally
you will not do that. Interactive tests tend to change the database, but for testing you want a
database with a well-known set of records. Only then can you do such things as test for a number of
countries, etc.
Again we use a property to set the logging level to FINE, but the last property is something
new.eclipselink.target-server refers to a class that we will have to implement. When you use JPA with
the libraries supplied with GlassFish, the default for this property would refer to a GlassFish-internal
class. That’s why we normally don’t have to define this property. Here we have no GlassFish, that’s
why we need a workaround, and again we put this workaround into a
package com.manessinger.junit in the test project.
package com.manessinger.junit; import javax.transaction.TransactionManager; public class JTATransactionController extends org.eclipse.persistence.transaction.JTATransactionController {
public static final String JNDI_TRANSACTION_MANAGER_NAME = "java:comp/TransactionManager"; public JTATransactionController() { super(); } @Override protected TransactionManager acquireTransactionManager() throws Exception { return (TransactionManager) jndiLookup(JNDI_TRANSACTION_MANAGER_NAME); }}
Basically we inherit from the GlassFish-internal JTATransactionController, and we provide a way for
JPA to get a transaction manager. Finally we provide a class Util in the same package, and this
time it contains a static method that returns an EntityManager.
package com.manessinger.junit; import javax.persistence.EntityManager;import javax.persistence.Persistence; public class Util { public static EntityManager getEntityManager() { return Persistence.createEntityManagerFactory("cookbookEJB_junit") .createEntityManager(); }}
Simulating injection and testing
[back to top]
Now that we have prepared the environment, it’s easy to instrument the beans under test and to
write the test classes. Remember, we have no running container that could inject EJBs or entity
managers, thus we add constructors. Here is the changed EAO with a constructor taking
@PersistenceContext EntityManager em; public CookbookEao() { } public CookbookEao(EntityManager em) { this.em = em; } // for unit test public long countCountries() { long result; Query q = em.createQuery("select count(co) from Country co"); result = (Long)q.getSingleResult(); return result; } @SuppressWarnings("unchecked") public List<Country> allCountries() { List<Country> result; Query q = em.createQuery("select co from Country co"); result = (List<Country>) q.getResultList(); return result; }}
This version of the EAO can be used for both kinds of testing. Of course if you had no in-server
tests, you would not need CookbookEao to implement a remote interface.
In the test class (package com.manessinger.cookbook.eao in the test project) we use
the setUp()method to construct the necessary beans. Other than that, the code of the test methods
is exactly as it was in the in-server test.
package com.manessinger.cookbook.eao; import static org.junit.Assert.assertEquals;import javax.persistence.EntityManager;import org.junit.Before;import org.junit.Test;import com.manessinger.junit.Util; public class TestCookbookEao { private EntityManager _em; private CookbookEao eao; @Before public void setUp() throws Exception { _em = Util.getEntityManager(); eao = new CookbookEao(_em); } @Test public void countryCountTest() { long n = eao.countCountries(); assertEquals(3, n); }}
Again we start the test with Run As / JUnit Test.
After the same pattern we add another constructor to CookbookBean
package com.manessinger.cookbook.service; import java.util.ArrayList;import java.util.List;import javax.ejb.EJB;import javax.ejb.LocalBean;import javax.ejb.Stateless;import javax.jws.WebService;import com.manessinger.cookbook.dto.CountryDump;import com.manessinger.cookbook.eao.CookbookEao;import com.manessinger.cookbook.entity.Country;import com.manessinger.cookbook.util.Conversion; @LocalBean@Stateless@WebServicepublic class CookbookBean implements CookbookInterface { @EJB CookbookEao eao; @EJB Conversion conv; public CookbookBean() { } public CookbookBean(CookbookEao eao, Conversion conv) { // for unit test this.eao = eao; this.conv = conv; } @Override public long countryCount() { return eao.countCountries(); } @Override public List<CountryDump> dumpCountries() { List<CountryDump> result = new ArrayList<CountryDump>(); List<Country> allCountries = eao.allCountries(); for (Country c : allCountries) { CountryDump ci = conv.fromEntity(c); result.add(ci); } return result; }}
import javax.ejb.Stateless;import com.manessinger.cookbook.dto.CountryDump;import com.manessinger.cookbook.eao.CookbookEao;import com.manessinger.cookbook.entity.City;import com.manessinger.cookbook.entity.Country; @Statelesspublic class Conversion { @EJB CookbookEao eao; public Conversion() { } public Conversion(CookbookEao eao) { this.eao = eao; } // for Unit test public CountryDump fromEntity(Country e) { CountryDump result = new CountryDump(); result.setName(e.getName()); List<String> cities = new ArrayList<String>(); for (City city : e.getCities()) { cities.add(city.getName()); } result.setCities(cities); return result; }}
and finally test the service bean with a test class in package com.manessinger.cookbook.service in the
test project.
package com.manessinger.cookbook.service; import static org.junit.Assert.assertEquals;import java.util.List;import javax.persistence.EntityManager;import org.junit.Before;import org.junit.Test;import com.manessinger.cookbook.dto.CountryDump;import com.manessinger.cookbook.eao.CookbookEao;import com.manessinger.cookbook.util.Conversion;import com.manessinger.junit.Util; public class TestCookbookBean { private EntityManager _em; private CookbookEao _eao; private Conversion _conv; private CookbookBean serviceBean; @Before public void setUp() throws Exception { _em = Util.getEntityManager(); _eao = new CookbookEao(_em); _conv = new Conversion(_eao); serviceBean = new CookbookBean(_eao, _conv); }
@Test public void countryCountTest() { long n = serviceBean.countryCount(); assertEquals(3, n); } @Test public void dumpTest() { List<CountryDump> countries = serviceBean.dumpCountries(); assertEquals(3, countries.size()); for (CountryDump co : countries) { assertEquals(4, co.getCities().size()); } }}
Testsuite
[back to top]
Again we have one test class per class under test, and we want to have a suite that runs all tests:
package com.manessinger.cookbook; import org.junit.runner.RunWith;import org.junit.runners.Suite; @RunWith(Suite.class)@Suite.SuiteClasses({ com.manessinger.cookbook.service.TestCookbookBean.class, com.manessinger.cookbook.eao.TestCookbookEao.class,})public class AllTests { // Any global setup would go here }
Insert and Update
[back to top]
So far we have an extremely minimal database schema with only two tables and no insert/update
operations. This is not overly simplified, in fact it reflects the common request to construct a
reporting add-on for some existing database and application. Let’s see what we have to change,
when we need to insert/update data. What we will insert/update are ZIP codes. In the end we want
to have one more operation in the service bean:
public ZipDto storeZip(ZipDto in) throws EntityNotFoundException;
We want it to cover both inserting and updating in one single operation. When the object exists, its
attributes are updated, when not, it is created. In any case we return the object. An exception is
thrown when we get an object complete with identity (primary key set, i.e. should be in the
database), but the object is not found.
Extending the Database
[back to top]
We begin with a new table storing ZIP codes. We have ZIP codes all over the world, but there is no
common format. There could be, e.g. some twelve-digit number would certainly suffice, but it never
came to complete standardization. Instead of a common numeric format, we have country codes,
and within each country one specific system. Many countries have numbers only, for instance the
UK uses alphabetic characters as well. We will look at only Austria, Italy and the United States here.
All three have numbers only, Austria with four digits, Italy with five, and the United States use a five
digit main code, followed by a dash and a four digit sub-code. Here’s the DDL part, that can be
executed in the Database Development perspective by copying it into a SQL Scrapbook and running
it there:
---- Set up database schema--CREATE TABLE ZIP ( ID INTEGER GENERATED ALWAYS AS IDENTITY NOT NULL, COUNTRY_ID INTEGER NOT NULL, CODE VARCHAR(20), NAME VARCHAR(50) ); ALTER TABLE ZIP ADD CONSTRAINT ZIP_PRIMARY_KEY PRIMARY KEY (ID);ALTER TABLE ZIP ADD CONSTRAINT ZIP_FOREIGNKEY_COUNTRY_ID FOREIGN KEY (COUNTRY_ID) REFERENCES COUNTRY (ID);CREATE UNIQUE INDEX ZIP_CODE_IDX ON ZIP(CODE); ---- Initialize with some values--INSERT INTO ZIP (COUNTRY_ID, CODE, NAME) VALUES ((SELECT ID FROM COUNTRY WHERE NAME = 'Austria'), '8054', 'Graz-Webling');INSERT INTO ZIP (COUNTRY_ID, CODE, NAME) VALUES ((SELECT ID FROM COUNTRY WHERE NAME = 'Italy'), '30124', 'Venezia');INSERT INTO ZIP (COUNTRY_ID, CODE, NAME) VALUES ((SELECT ID FROM COUNTRY WHERE NAME = 'USA'), '20001-6000', 'Metropolitan Washington Airports Authority');
The new table has been created by executing SQL statements, thus in a way “behind the scenes”.
Eclipse’s database interface has not yet recognized it, and when we immediately try to generate the
entity for the new table, we will see, that the code generator does not know about it. One way to
refresh Eclipse’s information about database metadata, is to go to the Database
Development perspective, drill down to the tables, and to choose Refresh from the context menu
of Tables. You should see all three tables now, and so will the code generator.
Now that we have the new table in the database, we create the missing entity Zip by again
calling JPA Tools / Generate Entities from Tables from the EJB project’s context menu. We see that
the tables CITY andCOUNTRY are still selected, just as we left them the last time.
We select ZIP as well, and when we go on to the Table Associations page, we see that the foreign
key relation between Zip and Country has again been mapped automatically and correctly. The
only change from the defaults is again in the last step, where we change the primary key type
from int to Integer.
When we press Finish, we are asked if we really want to overwrite the classes already generated
before. We never change generated code, thus we can safely confirm with Yes To All.
Here is the generated code:
package com.manessinger.cookbook.entity; import java.io.Serializable;import javax.persistence.*; @Entitypublic class Zip extends com.manessinger.util.jpa.Entity implements Serializable { private static final long serialVersionUID = 1L; @Id @GeneratedValue(strategy=GenerationType.IDENTITY) private Integer id; private String code; private String name; //bi-directional many-to-one association to Country @ManyToOne private Country country; public Zip() { } public Integer getId() { return this.id; } public void setId(Integer id) { this.id = id; } public String getCode() { return this.code; } public void setCode(String code) { this.code = code; } public String getName() { return this.name; } public void setName(String name) { this.name = name; }
public Country getCountry() { return this.country; } public void setCountry(Country country) { this.country = country; } }
You may remember that Synchronize classes listed in persistence.xml was selected on the first page
of theGenerate Custom Entities wizard. Indeed Eclipse has automatically added the
class Zip topersistence.xml. What it couldn’t do though, was updating the copy that we made
inprojectxJUnitOutOfServer/src/META-INF/persistence.xml. It’s a cool idea to do that
now.
If we were using Oracle, and if we had created a file ejbModule/META-INF/eclipselink-
orm.xml in the EJB project, in order to maintain sequence allocation sizes, we would have to
update that as well.
Exceptions
[back to top]
So far we have completely ignored exceptions, but now is a good time to think about a strategy for
what exceptions to throw and when to throw them.
Our proposed method storeZip() is a method of a service bean, intended to be called by external
clients, either via the client library and Corba/IIOP, or as web service method via SOAP. As a matter
of principle we will only throw exceptions over the wire, that are meaningful in context of the interface
and explainable in all details, without needing to know the internal implementation of the service. We
will indeed hide even the fact that the service is implemented in Java, and therefore we will not throw
any Java- or GlassFish-specific exceptions. Thus, although JPA already has
an EntityNotFoundException, we won’t use it and instead define our own. We also don’t wrap
any original exceptions.
In general, exceptions are a controversial topic. Some people love them, some hate them, some use
them to the advantage of their project, some abuse them. A good strategy is, to treat exceptions as,
well, exceptional. A design shouldn’t rely on exceptions being throuwn and caught in normal
operation. It is a terrible anti-pattern to use them as kind of if statement with the else branch
realized in a catch clause. This not only hurts performance, it also makes control flow much harder
to comprehend.
A good use for exceptions is the server-side parameter checking. We need to make sure that
parameters are not only of the correct type (this is guaranteed by the protocol), but also are within
the expected value ranges. If we have a precise specification of the interface and a correct
implementation, this will always be the case. The check will always succeed, except … when it does
not. Mistakes happen, special cases don’t get anticipated, unit tests only cover what we have
thought of testing, thus even if we could be sure to always get called by a known client that we have
written ourselves (and we can’t even expect that), it would be sensible to check anyway. A server
has to protect itself from clients gone wild.
What exactly are the options that we have when we are called with invalid input data? There is no
meaningful way to go on and the whole thing won’t happen in regular use. Look at storeZip(). Its
intended semantics is to use a supplied primary key for fetching an object for update. We can fully
expect the client to only supply an id that has been read from the database. Of course this is the
classic case for an exception.
When exceptions are part of the interface, it means two things:
The server should only throw checked exceptions.
The exception classes need to be created in the client project.
Thus we create a package com.manessinger.cookbook.exception in cookbookEJBClient,
and there we create EntityNotFoundException.
package com.manessinger.cookbook.exception; public class EntityNotFoundException extends Exception { private static final long serialVersionUID = 1L; private String className; private Integer id; public EntityNotFoundException(Class< ? > clazz, Integer id) { super("Entity of class "+clazz.getSimpleName()+" with id "+id+" not found"); this.className = clazz.getSimpleName(); this.id = id; } public String getClassName() { return className; } public Integer getId() { return id; }}
We don’t give away that we use JPA for accessing the database. For a SOAP client it wouldn’t even
be obvious that the server is written in Java. We only offer a simple default message and the detail
information for clients that need to construct their own localized message.Implementing storeZip()
[back to top]
We want storeZip() to look roughly like this:
public ZipDto storeZip(ZipDto in) { Zip zip = conv.fromDto(in); eao.persist(zip); return conv.fromEntity(zip);}
We convert a DTO to an entity, store the entity, convert back and return the result. But, what exactly
is aZipDto?
Up to now we had only a single DTO, CountryDump. It was used to transfer information about a
country and all its cities. Within one object we had the name of a country and a list of strings
containing city names. We could as well have defined a CountryDto containing a list of CityDto.
Both are legitimate. The former is OK when the client does not need to know about key values of
dependent objects.
Now let’s think about typical interactions in a CRUD (Create, Retrieve, Update, Delete) client. We
would certainly have an “Add ZIP” use case. A user would have to select the ZIP’s country from a list
of already defined countries. Thus in order to define a new ZIP code, the list of countries must
already have been retrieved by the client. On the other hand, each country selectable by the user
must already exist at the server, thus it is unnecessary to send the whole country along with a new
ZIP to be inserted. We only want to insert a ZIP, not to change a country. Thus a ZipDto won’t
contain a CountryDto or even a CountryDump, but it will contain a countryId. This also means,
that we have to worry about countries that don’t exist.
When we want to stay with the proposed structure of storeZip(), the check for existence of the
country must happen in the converter within fromDto().
Here is the DTO
package com.manessinger.cookbook.dto; import java.io.Serializable; public class ZipDto implements Serializable { private static final long serialVersionUID = 1L; private Integer id; private String name; private String code; private Integer countryId;
public void setId(Integer id) { this.id = id; } public Integer getId() { return id; } public String getName() { return name; } public void setName(String name) { this.name = name; } public String getCode() { return code; } public void setCode(String code) { this.code = code; } public Integer getCountryId() { return countryId; } public void setCountryId(Integer countryId) { this.countryId = countryId; }}
and that’s the extended version of the converter:
package com.manessinger.cookbook.util; import java.util.ArrayList;import java.util.List; import javax.ejb.EJB;import javax.ejb.LocalBean;import javax.ejb.Stateless; import com.manessinger.cookbook.dto.CountryDump;import com.manessinger.cookbook.dto.ZipDto;import com.manessinger.cookbook.eao.CookbookEao;import com.manessinger.cookbook.entity.City;import com.manessinger.cookbook.entity.Country;import com.manessinger.cookbook.entity.Zip;import com.manessinger.cookbook.exception.EntityNotFoundException;import com.manessinger.util.jpa.Entity; @LocalBean@Statelesspublic class Conversion { @EJB CookbookEao eao; public Conversion() { } public Conversion(CookbookEao eao) { this.eao = eao; } public CountryDump fromEntity(Country e) { CountryDump result = new CountryDump(); result.setName(e.getName()); List<String> cities = new ArrayList<String>(); for (City city : e.getCities()) { cities.add(city.getName()); } result.setCities(cities); return result; } public ZipDto fromEntity(Zip e) { ZipDto result = new ZipDto(); result.setId(e.getId()); result.setName(e.getName());
result.setCode(e.getCode()); result.setCountryId(e.getCountry().getId()); return result; } public Zip fromDto(ZipDto d) throws EntityNotFoundException { Zip result; Integer id = d.getId(); if (Entity.isId(id)) { result = eao.findOrFail(Zip.class, id); } else { result = new Zip(); } result.setName(d.getName()); result.setCode(d.getCode()); result.setCountry(eao.findOrFail(Country.class, d.getCountryId())); return result; }}
fromEntity() is trivial, we only copy values, but fromDto() is more interesting. For the first time
we use the static method isId from the Entity base class. When the DTO comes with a key
value, we try to fetch the corresponding object from the database for update, otherwise we create a
new one. Then we fetch the referenced country from the database and finally copy values.
When accessing objects by primary key, we don’t use the JPA method find(), but instead a
wrapper with more explicit semantics: While JPA’s find() returns null in case no result is found,
we use ourfindOrFail() instead. If no object is found, it throws
our EntityNotFoundException.
This is the updated version of the EAO remote interface, that we introduced for in-server testing:
package com.manessinger.cookbook.eao; import java.util.List;import javax.ejb.Remote;import com.manessinger.cookbook.entity.Country;import com.manessinger.cookbook.exception.EntityNotFoundException;import com.manessinger.util.jpa.Entity; @Remotepublic interface CookbookEaoInterface { public long countCountries(); public List<Country> allCountries(); public <T extends Entity> T findOrFail(Class<T> clazz, Integer id) throws EntityNotFoundException; public <T extends Entity> void persist(T entity); public Country countryByName(String name);}
That’s the updated EAO:
package com.manessinger.cookbook.eao; import java.util.List;import javax.ejb.LocalBean;import javax.ejb.Stateless;import javax.persistence.EntityManager;import javax.persistence.PersistenceContext;import javax.persistence.Query; import com.manessinger.cookbook.entity.Country;import com.manessinger.cookbook.exception.EntityNotFoundException;import com.manessinger.util.jpa.Entity; @LocalBean@Statelesspublic class CookbookEao implements CookbookEaoInterface { @PersistenceContext EntityManager em; public CookbookEao() { } public CookbookEao(EntityManager em) { this.em = em; } // for unit test @Override public <T extends Entity> T findOrFail(Class<T> clazz, Integer id) throws EntityNotFoundException { T e = em.find(clazz, id); if (e == null) { throw new EntityNotFoundException(clazz.getClass(), id); } return e; } @Override public <T extends Entity> void persist(T entity) { if (entity.hasId()) { em.merge(entity); } else { em.persist(entity); if (entity.getId() == null) { em.flush(); } } } public long countCountries() { long result; Query q = em.createQuery("select count(co) from Country co"); result = (Long)q.getSingleResult(); return result; } @SuppressWarnings("unchecked") public List<Country> allCountries() { List<Country> result; Query q = em.createQuery("select co from Country co");
result = (List<Country>) q.getResultList(); return result; } @Override public Country countryByName(String name) { Country result; Query q = em.createQuery("select co from Country co where co.name = :name"); q.setParameter("name", name); result = (Country) q.getSingleResult(); return result; }}
There are two additional methods in this code. eao.persist() calls
either em.persist() or em.merge(). The former causes an INSERT statement to be issued, the
latter an UPDATE.
Note that I check if the entity has its id set after the call to em.persist(). With an underlying
Oracle database this would have been the case, with Derby we need to flush the entity manager at
this point. Obviously that’s a good reason to also offer a variant of eao.persist() that takes a
collection of entities as parameter. Flushing only once for a bunch of entities would be more efficient.
countryByName() is used nowhere so far, but it illustrates how you can set parameters in queries.
Here is the updated remote interface
package com.manessinger.cookbook.service; import java.util.List;import javax.ejb.Remote;import com.manessinger.cookbook.dto.CountryDump;import com.manessinger.cookbook.dto.ZipDto;import com.manessinger.cookbook.exception.EntityNotFoundException; @Remotepublic interface CookbookInterface { public long countryCount(); public List<CountryDump> dumpCountries(); public ZipDto storeZip(ZipDto in) throws EntityNotFoundException;}
public class ViolationDetail implements Serializable { private static final long serialVersionUID = 1L; private String attributedItem; private String invalidItemValue; private String constraintName; private List<ConstraintProperty> constraintProperties; public ViolationDetail() { } public String getAttributedItem() { return attributedItem; } public void setAttributedItem(String attributedItem) { this.attributedItem = attributedItem; } public String getInvalidItemValue() { return invalidItemValue; } public void setInvalidItemValue(String invalidItemValue) { this.invalidItemValue = invalidItemValue; } public String getConstraintName() { return constraintName; } public void setConstraintName(String constraintName) { this.constraintName = constraintName; } public void setConstraintProperties(List<ConstraintProperty> constraintProperties) { this.constraintProperties = constraintProperties; } public List<ConstraintProperty> getConstraintProperties() { return constraintProperties; }}
In case some constraint is violated, we want to return all detail that we have, and we want to do it in
a way that the client can use the information to construct a meaningful message. Simply returning a
text is not enough. Clients may want to present the details in a language different from what the
server uses. We will report the attributed item, that’s the item, attributed with a constraint, the actual
value supplied, the name of the constraint and any properties associated with that constraint.
package com.manessinger.cookbook.exception; import java.util.ArrayList;import java.util.List; public class ValidationException extends Exception { private static final long serialVersionUID = 1L; private List<ViolationDetail> details = new ArrayList<ViolationDetail>();
public ValidationException(List<ViolationDetail> details) { this.details = details; } public List<ViolationDetail> getViolationDetail() { return details; }}
The exception itself is trivial, it just takes a list of violation details. It’s a list, because in complex
parameters more than one field could be in violation of its constraints.
Specifying constraints
[back to top]
BEAN VALIDATION (JSR 303) uses annotations to specify constraints. The
packagejavax.validation.constraints (part of Java EE 6) provides a lot of useful constraints. Three of
them will be used here.
package com.manessinger.cookbook.dto; import java.io.Serializable; import javax.validation.constraints.Min;import javax.validation.constraints.Pattern;import javax.validation.constraints.Size; public class ZipDto implements Serializable { private static final long serialVersionUID = 1L; private Integer id; @Size(min=1, max=50) private String name; @Pattern(regexp="^(\\d{4,5}|\\d{5}-\\d{4})$") private String code; @Min(1) private Integer countryId; public void setId(Integer id) { this.id = id; } public Integer getId() { return id; } public String getName() { return name; } public void setName(String name) { this.name = name; } public String getCode() { return code; } public void setCode(String code) { this.code = code; } public Integer getCountryId() { return countryId; } public void setCountryId(Integer countryId) { this.countryId = countryId; }}
We have placed three constraints upon fields of ZipDto. The size restrictions of the name reflect
the limits specified in the database definition. The regular expression says that the code is either a
number with four or five digits, or it is a five-digit number followed by a dash and another four-digit
number. countryId is supposed to be the primary key of a Country record in the database, thus it
can’t possibly be zero or negative.
Note that I have placed no constraint on the value of id, because we don’t even require an id to be
present. If it is null, we insert a new ZIP. So far that’s easy, the hard part was to figure out how
exactly the validator should work, in order to give us all the details we want. Fortunately you can
simply take it as it is. We put it into the EJB project, into the same package as the converter class.
Validation using interceptors
[back to top]
Interceptors are not a new idea in the Java Enterprise Edition. An INTERCEPTOR is a class, that is
declared as such (via annotation), and that provides specific interceptor methods, that are annotated
as well. This interceptor class is, where the real work is done.
package com.manessinger.cookbook.util; import java.util.ArrayList;import java.util.List;import java.util.Map;import java.util.Set; import javax.interceptor.AroundInvoke;import javax.interceptor.Interceptor;import javax.interceptor.InvocationContext;import javax.validation.ConstraintViolation;import javax.validation.Validation;import javax.validation.Validator;import javax.validation.ValidatorFactory;import javax.validation.groups.Default; import com.manessinger.cookbook.exception.ConstraintProperty;import com.manessinger.cookbook.exception.ValidationException;import com.manessinger.cookbook.exception.ViolationDetail; @Interceptorpublic class ValidationInterceptor { // the factory is expensive but thread-safe private static ValidatorFactory factory = Validation.buildDefaultValidatorFactory(); @AroundInvoke public Object intercept(InvocationContext ctx) throws Exception { Validator v = factory.getValidator(); // for all parameters for (Object p : ctx.getParameters()) { // validate parameter
Set<ConstraintViolation<Object>> violations = v.validate(p, Default.class); if (!violations.isEmpty()) { // validation failed, gather details and throw an exception List<ViolationDetail> details = new ArrayList<ViolationDetail>(); for (ConstraintViolation<Object> violation : violations) { ViolationDetail d = new ViolationDetail(); // path to violated constraint d.setAttributedItem(violation.getPropertyPath().toString()); // what type of constraint, e.g. "Min" or "Pattern" d.setConstraintName( violation.getConstraintDescriptor() .getAnnotation().annotationType().getSimpleName() ); // construct list of constraint properties Map<String, Object> violationAttributes = violation.getConstraintDescriptor().getAttributes(); List<ConstraintProperty> properties = new ArrayList<ConstraintProperty>(); for (String propertyName : violationAttributes.keySet()) { if (propertyName.matches("^(message|payload|groups|flags)$")) { // skip unwanted property continue; } ConstraintProperty a = new ConstraintProperty(); a.setName(propertyName); a.setValue(violationAttributes.get(propertyName).toString()); properties.add(a); } d.setConstraintProperties(properties); // the value that violated the constraint Object invalidValue = violation.getInvalidValue(); d.setInvalidItemValue((invalidValue != null ? invalidValue.toString() : "null")); details.add(d); } throw new ValidationException(details); } } return ctx.proceed(); }}
OK, that’s a big one. Let me explain just two things:
The bean validator would also give us a message for each validation. In case of @Min, it would be
something like “must be greater or equal to 1″. We could get that message
with violation.getMessage(), but unfortunately, being a message, it must be in a certain
language. In my Linux installation at work I have set the locale to en_US as I hate localized
operating systems, but on my private Windows 7 computers, I use de_DE. Please don’t ask me why,
it is just that way. The problem is, that I can’t get my GlassFish on Windows 7 to produce anything
but German messages, and that although the Administration Console is in perfect English. This
seems to be a GlassFish bug, and it seems to have been fixed already, but only not in the released
version. But even if the bug were not present, what good would a message in English be for a
German or French client application? That’s the reason why I don’t transfer the message to the client
at all.
The second thing is, that I don’t report some optional constraint properties that make no sense to a
client. Take for instance groups. You can associate groups with a constraint, and when checking,
you can specify, that only constraints in certain groups should be validated. This is clearly aimed at
something like debugversus production, but in our context it does not make sense. A server has
to protect itself always, not only in debug mode.
Now that we have a validator in place, we can associate it with the service bean
method storeZip(), and we do it like this:
@Override@Interceptors(ValidationInterceptor.class)public ZipDto storeZip(ZipDto in) throws EntityNotFoundException, ValidationException { Zip zip = conv.fromDto(in); eao.persist(zip); return conv.fromEntity(zip);}
We don’t need the @Interceptors annotation at the remote interface, but we do need to add the
additional exception to it.
package com.manessinger.cookbook.service; import java.util.List;import javax.ejb.Remote;import com.manessinger.cookbook.dto.CountryDump;import com.manessinger.cookbook.dto.ZipDto;import com.manessinger.cookbook.exception.EntityNotFoundException;import com.manessinger.cookbook.exception.ValidationException; @Remotepublic interface CookbookInterface { public long countryCount(); public List<CountryDump> dumpCountries(); public ZipDto storeZip(ZipDto in) throws EntityNotFoundException, ValidationException;}
Here is the complete service bean:
package com.manessinger.cookbook.service; import java.util.ArrayList;import java.util.List;import javax.ejb.EJB;import javax.ejb.LocalBean;import javax.ejb.Stateless;import javax.interceptor.Interceptors;import javax.jws.WebService;import com.manessinger.cookbook.dto.CountryDump;import com.manessinger.cookbook.dto.ZipDto;import com.manessinger.cookbook.eao.CookbookEao;import com.manessinger.cookbook.entity.Country;import com.manessinger.cookbook.entity.Zip;import com.manessinger.cookbook.exception.EntityNotFoundException;import com.manessinger.cookbook.exception.ValidationException;import com.manessinger.cookbook.util.Conversion;import com.manessinger.cookbook.util.ValidationInterceptor; @LocalBean@Stateless@WebServicepublic class CookbookBean implements CookbookInterface { @EJB CookbookEao eao; @EJB Conversion conv; public CookbookBean() { } public CookbookBean(CookbookEao eao, Conversion conv) { // for unit test this.eao = eao; this.conv = conv; } @Override public long countryCount() { return eao.countCountries(); } @Override public List<CountryDump> dumpCountries() { List<CountryDump> result = new ArrayList<CountryDump>(); List<Country> allCountries = eao.allCountries(); for (Country c : allCountries) { CountryDump ci = conv.fromEntity(c); result.add(ci); } return result; } @Override @Interceptors(ValidationInterceptor.class) public ZipDto storeZip(ZipDto in) throws EntityNotFoundException, ValidationException { Zip zip = conv.fromDto(in); eao.persist(zip); return conv.fromEntity(zip); }}
Please note, that the ValidationInterceptor throws Exception and not only
the ValidationExceptionthat we explicitly throw. This is due to the fact that it is a wrapper
method executed around the service method. See the annotation @AroundInvoke on public
Object intercept(InvocationContext ctx)? That’s what it means. We do our validation
before the parameters are supplied to the actual method and before it is called. The call happens at
the end, in ctx.proceed(), and because the interceptor signature is generic, it can’t know about
our custom exception.
We still need to explicitly mark storeZip() as throwing ValidationException, because that’s
the way to get the class into the interface. Otherwise we would get
an UndeclaredThrowableException, and only deeply buried within its stack trace we would see
our custom exception.
Testing the validator
[back to top]
Now let’s try and call storeZip() again, but this time with deliberately wrong input. The “x” in front
of the code violates the regular expression of the pattern constraint, and the name has 51
characters, that’s more than would fit into the database field.
<soapenv:Envelope xmlns:soapenv="http://schemas.xmlsoap.org/soap/envelope/" xmlns:ser="http://service.cookbook.manessinger.com/"> <soapenv:Header/> <soapenv:Body> <ser:storeZip> <arg0> <code>x9020</code> <countryId>1</countryId> <id></id> <name>Klagenfurt, also known as "Klagenfurt am Wörthersee"</name> </arg0> </ser:storeZip> </soapenv:Body></soapenv:Envelope>
The result of the request is a SOAP fault that contains everything we want to know about what went
Well you could also get a much, much longer version of that, just like this:
<S:Envelope xmlns:S="http://schemas.xmlsoap.org/soap/envelope/"> <S:Body> <S:Fault xmlns:ns4="http://www.w3.org/2003/05/soap-envelope"> <faultcode>S:Server</faultcode> <faultstring>javax.ejb.EJBTransactionRolledbackException</faultstring> <detail> <ns2:exception class="javax.ejb.EJBTransactionRolledbackException" note="To disable this feature, set com.sun.xml.ws.fault.SOAPFaultBuilder.disableCaptureStackTrace system property to false" xmlns:ns2="http://jax-ws.dev.java.net/"> <ns2:stackTrace> <ns2:frame class="com.sun.ejb.containers.BaseContainer" file="BaseContainer.java" line="2204" method="mapLocal3xException"/> <ns2:frame class="com.sun.ejb.containers.BaseContainer" file="BaseContainer.java" line="2004" method="postInvoke"/> ... ... many, many more lines ... </ns2:exception> </detail> </S:Fault> </S:Body></S:Envelope>
If so, you need to follow the advice given in the SOAP fault, open the Administration console and set
GlassFish’s com.sun.xml.ws.fault.SOAPFaultBuilder.disableCaptureStackTrace system property to false.
You do that in the Administration Console via Enterprise Server / System Properties / Add Property.
You have to stop/start the server bevore the new property gets effective, but then you should get the
short response. This is much better, because why should we expose internal details over the
network? The same information is in the server log as well, and that is a much more appropriate
place.
OK, now that we have that out of our way, let’s look at what we’ve got:
A javax.ejb.EJBTransactionRolledbackException. Obviously the transaction was aborted,
that’s right, but what we got was just the generic exception that occurs, when an undeclared
exception has been caught by the container. Looking at the server log, we find
java.sql.SQLIntegrityConstraintViolationException: The statement was aborted because it would have caused a duplicate key value in a unique or primary key constraint or unique index identified by 'ZIP_CODE_IDX' defined on 'ZIP'.
Cool. It’s probably still not what we would want to show to the user of a client application, but it is
information that we may want to transport to the client. Btw, in Oracle we would have got
Only the message is different, but the exception is the same. It is independent of the underlying
database.
Towards a solution
[back to top]
So we want to deliver an exception that is meaningful to the client. Let’s try to catch exceptions in
the service method, analyze them, and finally throw our own TransactionRollbackException.
Just like so:
@Override@Interceptors(ValidationInterceptor.class)public ZipDto storeZip(ZipDto in) throws EntityNotFoundException, TransactionRollbackException, ValidationException { try { Zip zip = conv.fromDto(in); eao.persist(zip); return conv.fromEntity(zip); } catch (Throwable t) { throw new TransactionRollbackException(t); }}
The TransactionRollbackException could look like this:
package com.manessinger.cookbook.exception; public class TransactionRollbackException extends Exception { private static final long serialVersionUID = 1L; private String type; private String message; public TransactionRollbackException(Throwable t) { Throwable current = t; do { if (current.getCause() == null) { type = current.getClass().getSimpleName(); message = current.getMessage(); } current = current.getCause();
} while (current != null); } public String getType() { return type; } public String getMessage() { return message; }}
What it does is, it goes along the chains of causes until it reaches the ultimate cause, and in our
case that would be the SQLIntegrityConstraintViolationException. We store type and
message of the most inner exception, and due to the two getters, these will show up in the SOAP
message. The only problem is: it does not always work.
Well, actually it does work with Derby, but it does not work in Oracle. Remember how we had to
flush theEntityManager in eao.persist(), in order to immediately get ids back after
calling em.persist()? We flush early in Derby, we don’t do so in Oracle.
Let’s make another experiment: Let’s add a method eao.flush, that simply delegates
to em.flush(). Now we can write the service method as
@Override@Interceptors(ValidationInterceptor.class)public ZipDto storeZip(ZipDto in) throws EntityNotFoundException, TransactionRollbackException, ValidationException { try { Zip zip = conv.fromDto(in); eao.persist(zip); eao.flush(); return conv.fromEntity(zip); } catch (Throwable t) { throw new TransactionRollbackException(t); }}
As I said, it won’t make a difference in Derby. There you will already have seen the response
<S:Envelope xmlns:S="http://schemas.xmlsoap.org/soap/envelope/"> <S:Body> <S:Fault xmlns:ns4="http://www.w3.org/2003/05/soap-envelope"> <faultcode>S:Server</faultcode> <faultstring> The statement was aborted because it would have caused a duplicate key value in a unique or primary key constraint or unique index identified by 'ZIP_CODE_IDX' defined on 'ZIP'. </faultstring> <detail> <ns2:TransactionRollbackException xmlns:ns2="http://service.cookbook.manessinger.com/">
<message> The statement was aborted because it would have caused a duplicate key value in a unique or primary key constraint or unique index identified by 'ZIP_CODE_IDX' defined on 'ZIP'. </message> <type>SqlException</type> </ns2:TransactionRollbackException> </detail> </S:Fault> </S:Body></S:Envelope>
but now, with flusing inside of the service method, we also get a similar response in Oracle:
Please note that we only catch the exception that we actually expect, namely the default exception,
that is thrown when the container catches an exception, that has not been declared by the service
method. It would be completely wrong to catch Throwable, because then this interceptor would
interfere with the ValidationInterceptor. We actually want ValidationException to get
thrown to the client.
We’ve already seen the TransactionRollbackException, so for the sake of completeness,
here is the current EAO interface
package com.manessinger.cookbook.eao; import java.util.List;import javax.ejb.Remote;import com.manessinger.cookbook.entity.Country;import com.manessinger.cookbook.exception.EntityNotFoundException;import com.manessinger.util.jpa.Entity; @Remotepublic interface CookbookEaoInterface { public long countCountries(); public List<Country> allCountries(); public <T extends Entity> T findOrFail(Class<T> clazz, Integer id) throws EntityNotFoundException; public <T extends Entity> void persist(T entity); public Country countryByName(String name); public void flush();}
the EAO itself
package com.manessinger.cookbook.eao; import java.util.List;import javax.ejb.LocalBean;import javax.ejb.Stateless;import javax.persistence.EntityManager;import javax.persistence.PersistenceContext;import javax.persistence.Query; import com.manessinger.cookbook.entity.Country;import com.manessinger.cookbook.exception.EntityNotFoundException;import com.manessinger.util.jpa.Entity; @LocalBean@Statelesspublic class CookbookEao implements CookbookEaoInterface { @PersistenceContext EntityManager em; public CookbookEao() { } public CookbookEao(EntityManager em) { this.em = em; } // for unit test @Override public void flush() { em.flush(); } @Override public <T extends Entity> T findOrFail(Class<T> clazz, Integer id) throws EntityNotFoundException { T e = em.find(clazz, id);
if (e == null) { throw new EntityNotFoundException(clazz.getClass(), id); } return e; } @Override public <T extends Entity> void persist(T entity) { if (entity.hasId()) { em.merge(entity); } else { em.persist(entity); if (entity.getId() == null) { em.flush(); } } } public long countCountries() { long result; Query q = em.createQuery("select count(co) from Country co"); result = (Long)q.getSingleResult(); return result; } @SuppressWarnings("unchecked") public List<Country> allCountries() { List<Country> result; Query q = em.createQuery("select co from Country co"); result = (List<Country>) q.getResultList(); return result; } @Override public Country countryByName(String name) { Country result; Query q = em.createQuery("select co from Country co where co.name = :name"); q.setParameter("name", name); result = (Country) q.getSingleResult(); return result; }}
public interface CookbookInterface { public long countryCount() throws TransactionRollbackException; public List<CountryDump> dumpCountries() throws TransactionRollbackException; public ZipDto storeZip(ZipDto in) throws TransactionRollbackException, EntityNotFoundException, ValidationException;}
and finally the service bean itself.
package com.manessinger.cookbook.service; import java.util.ArrayList;import java.util.List;import javax.ejb.EJB;import javax.ejb.LocalBean;import javax.ejb.Stateless;import javax.interceptor.Interceptors;import javax.jws.WebService;import com.manessinger.cookbook.dto.CountryDump;import com.manessinger.cookbook.dto.ZipDto;import com.manessinger.cookbook.eao.CookbookEao;import com.manessinger.cookbook.entity.Country;import com.manessinger.cookbook.entity.Zip;import com.manessinger.cookbook.exception.EntityNotFoundException;import com.manessinger.cookbook.exception.TransactionRollbackException;import com.manessinger.cookbook.exception.ValidationException;import com.manessinger.cookbook.util.Conversion;import com.manessinger.cookbook.util.TransactionRollbackHandler;import com.manessinger.cookbook.util.ValidationInterceptor; @LocalBean@Stateless@WebService@Interceptors(TransactionRollbackHandler.class)public class CookbookBean implements CookbookInterface { @EJB CookbookEao eao; @EJB Conversion conv; public CookbookBean() { } public CookbookBean(CookbookEao eao, Conversion conv) { // for unit test this.eao = eao; this.conv = conv; } @Override public long countryCount() throws TransactionRollbackException { return eao.countCountries(); } @Override public List<CountryDump> dumpCountries() throws TransactionRollbackException { List<CountryDump> result = new ArrayList<CountryDump>();
List<Country> allCountries = eao.allCountries(); for (Country c : allCountries) { CountryDump ci = conv.fromEntity(c); result.add(ci); } return result; } @Override @Interceptors(ValidationInterceptor.class) public ZipDto storeZip(ZipDto in) throws TransactionRollbackException, EntityNotFoundException, ValidationException { Zip zip = conv.fromDto(in); eao.persist(zip); eao.flush(); return conv.fromEntity(zip); }}
Please note that we add the @Interceptors annotation to the class, and that means, that it will
intercept each method. Therefore we have to add a throws
TransactionRollbackException to each method. If we fail to do so, we end up with
ajava.lang.reflect.UndeclaredThrowableException.
Adding the exception to the signatures of the service methods will make the two test projects and the
Dynamic Web Project cookbookServlets go red because of the unhandled exceptions. In the test
projects you can simply throw them on, in the CountryList servlet you’d normally catch it and
return something meaningful.
In order to reach our goal of having generic exceptions replaced by our own kind of exception, that is
more specific about what really happened, we had to give a little, take a little, and although the result
is less elaborate than our naive first approach, it is still kind of a burden. There may be better
solutions, this is just what I came up with, and you or I may find something more elegant. But that’s
not the point. The point is, that this is the kind of things that you can do with interceptors, this is the
sort of tradeoffs that you have to expect.
Adding extra libraries
[back to top]
The Java Enterprise Edition is real big, but there will always be things that are not included. Basically
we can break down the choice of libraries into
1. included standardized APIs
2. included non-standardized APIs
3. non-included standardized APIs
4. non-included, non-standardized APIs
If we care about portability between application servers, we should try to stick to #1. If we need
anything else, it is not a good idea to just use #2. Those libraries may be there, but if so, it’s because
the standardized APIs happen to be implemented on top of them. Another application server may
implement its functionality on top of a set of different libraries. JPA comes to mind. In GlassFish it is
built on top of EclipseLink, code originally contributed from Oracle’s TopLink object/relational
mapping tool, while in JBoss Application Server it is of course built on top of their Hibernate family of
object relational mapping libraries. As long as we stick to JPA (i.e. libraries
in javax.persistence), we can expect our code to run in any Java EE 6 application server.
If #1 is not enough, it is usually the most portable solution, to package the non-standard and/or non-
included libraries with the application. There are two ways to do it.
1. If we need a some libraries only inside of one specific DYNAMIC WEB PROJECT, there is nothing
wrong with putting them into that project’s WebContent/WEB-INF/lib directory. It will be
packaged into the project’s WAR, the WAR will be packaged inside the EAR, and that way the
libraries are deployed and found at runtime.
2. If we need to access the libraries throughout the application, i.e. from more than one project, or
from an EJB project, it is better to package them into an auxilliary project, add that project to the
EAR, and to make sure that the libraries show up in the EAR’s lib directory at runtime.
Suppose we want to use two extra libraries, jdom.jar and rome.jar. We’ll need them for the next
chapter anyway.
With New / Project / General / Project from the context menu of the Project Explorer, we create a
plain project called cookbookExtraLibs. Neither will we be asked to add it to the EAR nor can we do
so. Basically the project will be a simple directory, and into that directory we just copy the two JARs.
When we then open the Properties for cookbookEAR dialog and go to Java EE Module
Dependencies, we can press Add JARs, select the two JARs from the new project, and they will
automatically be packaged with the EAR and deployed into the EAR’s lib directory.
Additionally, in order to make the libraries available in the development environment as well, we
have to add them to the Build Path of the projects that need them.
Syndication Feeds
[back to top]
A SYNDICATION FEED (RSS or Atom in their various incarnations) is a good method to make data
accessible on the web. So-called FEED READERS (built into all major browsers, or like Google
Reader available as web applications) make it possible to SUBSCRIBE to feeds.
A feed is just an XML document under a specific URL, the feed’s address. The contents of the
document changes. A feed is a sequence of feed entries. The number of entries is finite and
normally low. Typical are the blog posts of a month or the last 30 records in a sequence of data. A
feed reader basically polls the URLs of the subscribed feeds, and whenever a new entry turns up,
the user is notified, either visually or via a popup window. Syndication feeds are most prevalent in
the world of blogs, but they can be of use for any kind of data distribution.
Of the various XML formats used for content syndication, RSS 1.0, RSS 2.0 and Atom 1.0 are the
most important.
The Java Enterprise Edition currently does not include APIs for creating or digesting feeds. If for
instance we want to supply the list of countries as syndication feed (basically an XML variant of
what CountryListdelivers as HTML), we can of course simply copy and modify the servlet that we
have. On the other hand,ROME is a project that is dedicated specifically to creating and consuming
syndication feeds in Java, thus we will use that.
Realizing a feed with ROME
[back to top]
In order to use ROME, we have to download the two libraries jdom.jar and rome.jar and put
them into an extra libraries project as described in the last chapter. As we will need the libraries only
in the Dynamic Web Project cookbookServlets, you could as well put them
into cookbookServlets/WebContent/WEB-INF/libdirectory. If you choose to use the extra
project, don’t forget to put the two libraries onto the Build Path ofcookbookServlets.
The central data structure in ROME is the SYNDICATION FEED (SyndFeed). A feed has entries
(SyndEntry) and the entries have metadata and CONTENT (SyndContent). In the feed we deliver a
representation similar to what we produced in CountryList, here with a country per entry and the
import java.io.PrintWriter;import java.util.ArrayList;import java.util.Date;import java.util.List;import javax.ejb.EJB;import javax.servlet.ServletException;import javax.servlet.annotation.WebServlet;import javax.servlet.http.HttpServlet;import javax.servlet.http.HttpServletRequest;import javax.servlet.http.HttpServletResponse;import com.manessinger.cookbook.dto.CountryDump;import com.sun.syndication.feed.synd.SyndContent;import com.sun.syndication.feed.synd.SyndContentImpl;import com.sun.syndication.feed.synd.SyndEntry;import com.sun.syndication.feed.synd.SyndEntryImpl;import com.sun.syndication.feed.synd.SyndFeed;import com.sun.syndication.feed.synd.SyndFeedImpl;import com.sun.syndication.io.SyndFeedOutput; @WebServlet(name = "Feed", urlPatterns = { "/Feed" })public class Feed extends HttpServlet { private static final long serialVersionUID = 1L; @EJB CookbookBean cbBean; public Feed() { super(); } protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { processRequest(request, response); } protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { processRequest(request, response); } protected void processRequest(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { PrintWriter out = response.getWriter(); try { SyndFeed feed = new SyndFeedImpl(); feed.setTitle("Cookbook Sample Feed"); feed.setLink("http://localhost:8084/cookbookServlets/Feed"); feed.setDescription("This is a feed of available countries"); List<SyndEntry> entries = new ArrayList<SyndEntry>(); SyndEntry entry; SyndContent description; for (CountryDump cd : cbBean.dumpCountries()) { entry = new SyndEntryImpl(); entry.setTitle(cd.getName()); entry.setUri(String.format("http://maps.google.com/maps?q=%s", cd.getName()));
entry.setPublishedDate(new Date()); description = new SyndContentImpl(); description.setType("text/html"); StringBuilder sb = new StringBuilder(); sb.append("<ul>\n"); for (String city : cd.getCities()) { sb.append("<li>"); sb.append(city); sb.append("</li>\n"); } sb.append("</ul>\n"); description.setValue(sb.toString()); entry.setDescription(description); entries.add(entry); } feed.setEntries(entries); feed.setFeedType("rss_2.0"); response.setContentType("application/xml;charset=UTF-8"); SyndFeedOutput output = new SyndFeedOutput(); output.output(feed, response.getWriter()); } catch (Exception e) { e.printStackTrace(); String msg = "Could not generate feed of countries"; log(msg, e); response.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR, msg); } finally { out.close(); } } @Override public String getServletInfo() { return "Feed of countries"; }}
As to the feed type, ROME supports all variants of RSS and Atom, here I have simply set it to RSS
2.0. This is an ordinary servlet, thus we could either use different URLs for differnet types, or we
could use a URL parameter to select the feed type.
We would expect the feed now to be available under the URL (port number may differ)
http://localhost:8084/cookbookServlets/Feed
A bug in Eclipse
[back to top]
Surprisingly at this point neither of the two servlets may run, and in fact if we find in the server log
the following messages,
SEVERE: Class [ com/sun/syndication/feed/synd/SyndFeed ] not found. Error while loading [ class com.manessinger.cookbook.service.Feed ]WARNING: Error in annotation processing: java.lang.NoClassDefFoundError: com/sun/syndication/feed/synd/SyndFeed
somewhere in the vicinity of where we would expect a message about successful
deployment, we know that GlassFish does not know about the libraries. In fact it should, because in
the last step of setting up the extra libs directory (see last chapter), we have added them to the
EAR’s lib directory. When we check now under Properties for cookbookEAR / Java EE Module
Dependencies, we may see that the libraries are not there. When we try to export the EAR project to
an EAR file cookbookEAR.ear, rename the EAR file to cookbookEAR.zip and look inside, we
may find the two libraries in the top-level directory or the EAR, but not in the lib directory below.
Even worse, we can’t simply add the libraries again. We can try to Add JARs one more time, select
the libraries, add them, but they will still not show up, nor will the servlets be deployed.
This is obviously a bug in Eclipse. I expect it to be fixed in a future version (maybe it is already fixed
in current code), but at the moment there is a workaround:
We can open the Properties for cookbookServlets dialog, go to Java EE Module Dependencies,
press Add JARs and add the two jars. Now it should work. I’m pretty sure this is not always
necessary. Somehow I must have damaged my project setup or whatever.
If you got really bitten by this bug and if nothing works at all, you can always throw in the towel until
the bug is fixed, and simply put the libraries
into cookbookServices/WebContent/WEB-INF/lib. This smells a little bit like defeat, but at
the moment I have no better idea. Let’s check it again with the next release.
Oh, and one more thing: If you happen to have followed my advice to use an extra project for the
libraries, if you ran into the bug and if even the workaround did not work (it did for me one time,
another time it did not), and if you finally moved the libraries
tocookbookServices/WebContent/WEB-INF/lib, it could be that you suddenly can’t publish
your application any more. Sure, you will have removed the two libraries from the build path of the
servlets project. If not, do so, but it will still not publish. What’s wrong now?
Remember that we referenced the two libraries from Properties for cookbookEAR / Java EE Module
Dependencies? They are not there now, that was the bug. Unfortunately Eclipse has remembered
import javax.servlet.http.HttpServletResponse;import com.manessinger.cookbook.dto.CountryDump;import com.sun.syndication.feed.synd.SyndContent;import com.sun.syndication.feed.synd.SyndContentImpl;import com.sun.syndication.feed.synd.SyndEntry;import com.sun.syndication.feed.synd.SyndEntryImpl;import com.sun.syndication.feed.synd.SyndFeed;import com.sun.syndication.feed.synd.SyndFeedImpl;import com.sun.syndication.io.SyndFeedOutput; @WebServlet(name = "Feed", urlPatterns = { "/Feed" })public class Feed extends HttpServlet { private static final long serialVersionUID = 1L; // default if JNDI lookup fails private static final String GEO_MAP_URL_TEMPLATE = "http://maps.google.com/maps?q=%s"; @EJB CookbookBean cbBean; public Feed() { super(); } protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { processRequest(request, response); } protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { processRequest(request, response); } protected void processRequest(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { PrintWriter out = response.getWriter(); try { SyndFeed feed = new SyndFeedImpl(); feed.setTitle("Cookbook Sample Feed"); feed.setLink("http://localhost:8084/cookbookServlets/Feed"); feed.setDescription("This is a feed of available countries"); List<SyndEntry> entries = new ArrayList<SyndEntry>(); SyndEntry entry; SyndContent description; String geoMapUrlTemplate; try { // Lookup via JNDI geoMapUrlTemplate = (String) new InitialContext() .lookup("custom/url/template/geomap"); } catch (NamingException e) { // initialize with default geoMapUrlTemplate = (String) GEO_MAP_URL_TEMPLATE; }
for (CountryDump cd : cbBean.dumpCountries()) { entry = new SyndEntryImpl(); entry.setTitle(cd.getName()); entry.setUri(String.format(geoMapUrlTemplate, cd.getName())); entry.setPublishedDate(new Date()); description = new SyndContentImpl(); description.setType("text/html"); StringBuilder sb = new StringBuilder(); sb.append("<ul>\n"); for (String city : cd.getCities()) { sb.append("<li>"); sb.append(city); sb.append("</li>\n"); } sb.append("</ul>\n"); description.setValue(sb.toString()); entry.setDescription(description); entries.add(entry); } feed.setEntries(entries); feed.setFeedType("rss_2.0"); response.setContentType("application/xml;charset=UTF-8"); SyndFeedOutput output = new SyndFeedOutput(); output.output(feed, response.getWriter()); } catch (Exception e) { e.printStackTrace(); String msg = "Could not generate feed of countries"; log(msg, e); response.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR, msg); } finally { out.close(); } } @Override public String getServletInfo() { return "Feed of countries"; }}
It’s largely the same servlet as before, only the geoMapUrlTemplate is looked up in the application
server under the name custom/url/template/geomap. If nothing is found, the hardcoded
defaultGEO_MAP_URL_TEMPLATE is taken.
If no definition in the application server is present, we get a response like
<?xml version="1.0" encoding="UTF-8"?><rss xmlns:dc="http://purl.org/dc/elements/1.1/" version="2.0"> <channel> <title>Cookbook Sample Feed</title> <link>http://localhost:8084/cookbookServlets/Feed</link> <description>This is a feed of available countries</description> <item> <title>Austria</title> <description><ul><li>Linz</li>
@Statelesspublic class RESTDelegator { @EJB private CookbookBean bean; @GET @Path("add/{a}/{b}") @Consumes(MediaType.APPLICATION_XML) @Produces(MediaType.TEXT_PLAIN) public String add(@PathParam(value="a") int a, @PathParam(value="b") int b) { Integer out = a + b; return out.toString(); } @GET @Path("countryCount") @Produces(MediaType.APPLICATION_XML) public String countryCount() throws TransactionRollbackException { return "<country_count>"+bean.countryCount()+"</country_count>"; } @GET @Path("dumpCountries") @Produces(MediaType.APPLICATION_XML) public DumpResult dumpCountries() throws TransactionRollbackException { return new DumpResult(bean.dumpCountries()); } @POST @Path("storeZip") @Consumes(MediaType.APPLICATION_XML) @Produces(MediaType.APPLICATION_XML) @Interceptors(ValidationInterceptor.class) public ZipDto storeZip(ZipDto in) throws EntityNotFoundException, TransactionRollbackException, ValidationException { return bean.storeZip(in); } @POST @Path("inputStream") @Consumes(MediaType.APPLICATION_OCTET_STREAM) @Produces(MediaType.TEXT_PLAIN) public String inputStream(InputStream is) throws IOException { Long totalBytesReceived = 0L; byte[] buffer = new byte[1000]; long bytesReceived = 0; do { totalBytesReceived += bytesReceived; bytesReceived = is.read(buffer); } while (bytesReceived != -1); is.close(); return totalBytesReceived.toString(); }}
We have made the delegator a stateless session bean, in order to get access to our service bean via
injection. The class is annotated with a @Path annotation. Think of it as a resource class, a way of
grouping the resources that the methods of this class will give access to. In our context this does not
make that much sense, thus I have simply called it method. It makes, you guess it, for the next part of
the URL. We can’t omit it, because the REST servlet searches for classes with a @Path annotation.
Leave it away and the REST annotations on the methods will never be seen.
I’ve included two test methods here, that don’t delegate down to an EJB, but that show some useful
tricks. The first is add(), and it shows two things: Firstly, you can access parameters, that are given
as part of the URL, so-called PATH PARAMETERS. Here we have two parameters a and b. The
method signature declares both as integer, and if we call the REST URL with anything in one of
these positions, that can’t be converted to integer, for instance with the character “x“, we simply get
an HTTP 404, “The resource is not available”. The second thing is, that we can return only one
single scalar type, and that is java.lang.String. When we want to return an Integer, we have
to convert it to a string and return that.
countryCount() demonstrates the other way to return a scalar. It produces the MIME type
“application/xml” (in the @Produces annotations I have used the constants supplied with JAX-
RS), XML is text, thus we again return a string, this time hand-crafted XML.
In dumpCountries() and storeZip() we return DTOs. The one
in dumpCountries(), DumpResult, is a wrapper type that we need, because JAX-RS can’t
implicitly serialize lists. This wrapper type is only needed for REST, thus we create a
package com.manessinger.cookbook.dto in cookbookServlets and put it there.
Complex types like DumpResult and ZipDto are automatically serialized behind the scenes, and
again it is JAXB that does the work. Thus we can influence the serialization result by annotating the
data types and their fields. In general we don’t need anything but a
single @XmlRootElement annotation on every type that is used as a top-level parameter. Here
is DumpResult:
package com.manessinger.cookbook.dto; import java.util.List;import javax.xml.bind.annotation.XmlRootElement; @XmlRootElement(name="countries")public class DumpResult { public List<CountryDump> country; public DumpResult() { }
public DumpResult(List<CountryDump> l) { this.country = l; }}
ZipDto is also used as a parameter, thus we have to annotate it as well.
package com.manessinger.cookbook.dto; import java.io.Serializable; import javax.validation.constraints.Min;import javax.validation.constraints.Pattern;import javax.validation.constraints.Size;import javax.xml.bind.annotation.XmlRootElement; @XmlRootElement(name="zip")public class ZipDto implements Serializable { private static final long serialVersionUID = 1L; private Integer id; @Size(min=1, max=50) private String name; @Pattern(regexp="^(\\d{4,5}|\\d{5}-\\d{4})$") private String code; @Min(1) private Integer countryId; public void setId(Integer id) { this.id = id; } public Integer getId() { return id; } public String getName() { return name; } public void setName(String name) { this.name = name; } public String getCode() { return code; } public void setCode(String code) { this.code = code; } public Integer getCountryId() { return countryId; } public void setCountryId(Integer countryId) { this.countryId = countryId; }}
The default XML element name for a class is the class name. Here we have overridden it to simply
use zip.
If we ever forget to annotate a type that is used as a top-level parameter, for instance DumpResult,
then we get an error, and in the server log we’ll see, among tons of stack traces, the messages
SEVERE: A message body writer for Java type, class com.manessinger.cookbook.dto.DumpResult, and MIME media type, application/xml, was not foundSEVERE: Internal server errorjavax.ws.rs.WebApplicationException
storeZip() uses XML supplied as content of a POST request, and due to the type of the
parameter in the message signature, and due to the fact, that this type is annotated
with @XmlRootElement, deserialization is automatic. No further annotations are needed.
inputStream() is the second method, that I have added just for demonstration of a useful
feature, and that does not delegate to an EJB. Here the input is declared as
“application/octet-stream“, while the method parameter is a java.io.InputStream.
Again the mapping is automatic, and this can be used to realize a simple file upload mechanism.
In the example the stream is read and the number of bytes is returned as plain text.
Examples of HTTP traffic
[back to top]
Let me show you some HTTP traffic, that I have captured with soapUI:
add()
[back to top]
GET http://localhost:8084/cookbookServlets/REST/method/add/2/3 HTTP/1.1Accept-Encoding: gzip,deflateUser-Agent: Jakarta Commons-HttpClient/3.1Host: localhost:8084
GET http://localhost:8084/cookbookServlets/REST/method/dumpCountries HTTP/1.1Accept-Encoding: gzip,deflateUser-Agent: Jakarta Commons-HttpClient/3.1Host: localhost:8084
POST http://localhost:8084/cookbookServlets/REST/method/inputStream HTTP/1.1Accept-Encoding: gzip,deflateContent-Type: application/octet-streamUser-Agent: Jakarta Commons-HttpClient/3.1Host: localhost:8084Content-Length: 5 xxäxx
Please note that the server code simply counts bytes. On Windows 7 I get the result 5, while on
Xubuntu 10.4 at work I get 6 for the same input.
The reason is, that in Windows the default character set for soapUI (where I have created the input)
seems to be ISO-8859-1, while on Linux it is UTF-8. The third character is a german Umlaut, in UTF-
8 represented as a two-byte sequence, thus the number of bytes differs, depending on the system
where the client runs.
PostgreSQL as database backend
[back to top]
PostgreSQL is the most advanced and mature open source database on the market. To use it with
GlassFish v3, you need to download the JDBC4 driver and install it in either
GlassFish’s lib directory or the libdirectory of the GlassFish domain. On Unix a symbolic link is
sufficient. In Eclipse you have to make sure that it is in the build path of all projects, that access the
database directly, not via the application server. For us, this is only the test
project cookbookJUnitOutOfServer. You also have to add a database definition to Eclipse
(viaDatasource Explorer), in case you want to access the database from a SQL Scrapbook or simply
need to use JPA Tools / Generate Entities from Tables to generate entities.
Installing PostgreSQL and creating a database user
[back to top]
This is not even a weak attempt at providing an introduction to PostgreSQL, just some notes of what
I stumbled upon when I tried it.
When I did this at work, I simply asked our database administrators for a test database and got one
running on Linux, that I could only connect to via SSL. We run all our PostgreSQL database servers
like that. I tried to reproduce this here at home on Windows, it didn’t work initially, thus I decided to
ignore SSL, as it is not crucial to this tutorial.
When you install PostgreSQL on Windows, make sure that you run the installer as administrator. It
needs to install a service. Just accept all the defaults.
Note please, that you have to start/restart/stop the server as administrator as well. Navigate to the
menu entries in the PostgreSQL 8.4 program group, while being on the menu entry (for
exampleRestart Server), use the right mouse button and select Run as Administrator.
Immediately after the installation, without explicitly starting, the server is already running.
From Start / All Programs / PostgreSQL 8.4 / pgAdmin III you can start the PostgreSQL
administration utility. It has the familiar tree view, here called Object Browser, on the left side. At the
bottom there is something called Login Roles (for our purpose that’s users), with just one
entry postgres. From the context menu add a new login role called cookbookuser with
password cookbook. Now we’re ready to create the database.
Creating the database
[back to top]
In pgAdmin III, in the Object Browser, under Databases, you have just one database called postgres.
From the context menu of Databases choose New Database … and use the name cookbookdb. Now
you have a new, empty database. Select it, and that should make a button available in the toolbar,
the sixth from the left, a SQL editor with the tool tip Execute arbitrary SQL queries. Click it and the
editor opens.
Make sure that the title bar of the editor window says Query – cookbookdb on
postgres@localhost:5432. If not, if it reads Query – postgres on postgres@localhost:5432, you had
the wrong database selected. Close the editor, select database cookbookdb and open the editor
again.
There are two tabs in the editor, a SQL Editor and a Graphical Query Builder. We only need the SQL
editor, so make sure that’s selected, and then replace the current content with the following SQL
text:
-- Database: cookbookdb -- remove comment when re-running script-- DROP DATABASE cookbookdb; CREATE DATABASE cookbookdb WITH OWNER = cookbookuser ENCODING = 'UTF8' TABLESPACE = pg_default LC_COLLATE = 'English, United States' LC_CTYPE = 'English, United States' CONNECTION LIMIT = -1; CREATE SEQUENCE country_id_seq START WITH 1 INCREMENT BY 1 NO MAXVALUE NO MINVALUE CACHE 1;ALTER TABLE country_id_seq OWNER TO cookbookuser; CREATE TABLE country ( id integer NOT NULL, name character varying(10) NOT NULL);ALTER TABLE country OWNER TO cookbookuser;ALTER TABLE ONLY country
ADD CONSTRAINT country_name_idx UNIQUE (name);ALTER TABLE ONLY country ADD CONSTRAINT country_pk PRIMARY KEY (id); CREATE SEQUENCE city_id_seq START WITH 1 INCREMENT BY 1 NO MAXVALUE NO MINVALUE CACHE 1;ALTER TABLE city_id_seq OWNER TO cookbookuser; CREATE TABLE city ( id integer NOT NULL, country_id integer NOT NULL, name character varying(30) NOT NULL);ALTER TABLE city OWNER TO cookbookuser;ALTER TABLE ONLY city ADD CONSTRAINT city_name_idx UNIQUE (name);ALTER TABLE ONLY city ADD CONSTRAINT city_pk PRIMARY KEY (id);ALTER TABLE ONLY city ADD CONSTRAINT city_country_fk FOREIGN KEY (country_id) REFERENCES country(id) ON DELETE CASCADE; CREATE SEQUENCE zip_id_seq START WITH 1 INCREMENT BY 1 NO MAXVALUE NO MINVALUE CACHE 1;ALTER TABLE zip_id_seq OWNER TO cookbookuser; CREATE TABLE zip ( id integer NOT NULL, country_id integer NOT NULL, code character varying(20) NOT NULL, name character varying(50) NOT NULL);ALTER TABLE zip OWNER TO cookbookuser;ALTER TABLE ONLY zip ADD CONSTRAINT zip_name_idx UNIQUE (name);ALTER TABLE ONLY zip ADD CONSTRAINT zip_pk PRIMARY KEY (id);ALTER TABLE ONLY zip ADD CONSTRAINT zip_country_fk FOREIGN KEY (country_id) REFERENCES country(id) ON DELETE CASCADE; INSERT INTO country (id, name) VALUES (NEXTVAL('country_id_seq'), 'Austria');INSERT INTO country (id, name) VALUES (NEXTVAL('country_id_seq'), 'Italy');INSERT INTO country (id, name) VALUES (NEXTVAL('country_id_seq'), 'USA'); INSERT INTO city (id, country_id, name) VALUES (NEXTVAL('city_id_seq'), (SELECT id FROM country WHERE name = 'Austria'), 'Graz');INSERT INTO city (id, country_id, name)
VALUES (NEXTVAL('city_id_seq'), (SELECT id FROM country WHERE name = 'Austria'), 'Linz');INSERT INTO city (id, country_id, name) VALUES (NEXTVAL('city_id_seq'), (SELECT id FROM country WHERE name = 'Austria'), 'Salzburg');INSERT INTO city (id, country_id, name) VALUES (NEXTVAL('city_id_seq'), (SELECT id FROM country WHERE name = 'Austria'), 'Wien'); INSERT INTO city (id, country_id, name) VALUES (NEXTVAL('city_id_seq'), (SELECT id FROM country WHERE name = 'Italy'), 'Bologna');INSERT INTO city (id, country_id, name) VALUES (NEXTVAL('city_id_seq'), (SELECT id FROM country WHERE name = 'Italy'), 'Firenze');INSERT INTO city (id, country_id, name) VALUES (NEXTVAL('city_id_seq'), (SELECT id FROM country WHERE name = 'Italy'), 'Roma');INSERT INTO city (id, country_id, name) VALUES (NEXTVAL('city_id_seq'), (SELECT id FROM country WHERE name = 'Italy'), 'Venezia'); INSERT INTO city (id, country_id, name) VALUES (NEXTVAL('city_id_seq'), (SELECT id FROM country WHERE name = 'USA'), 'Atlanta');INSERT INTO city (id, country_id, name) VALUES (NEXTVAL('city_id_seq'), (SELECT id FROM country WHERE name = 'USA'), 'Los Angeles');INSERT INTO city (id, country_id, name) VALUES (NEXTVAL('city_id_seq'), (SELECT id FROM country WHERE name = 'USA'), 'New York');INSERT INTO city (id, country_id, name) VALUES (NEXTVAL('city_id_seq'), (SELECT id FROM country WHERE name = 'USA'), 'Washington'); INSERT INTO zip (id, country_id, code, name) VALUES (NEXTVAL('zip_id_seq'), (SELECT id FROM country WHERE name = 'Austria'), '8054', 'Graz-Webling'); INSERT INTO zip (id, country_id, code, name) VALUES (NEXTVAL('zip_id_seq'), (SELECT id FROM country WHERE name = 'Italy'), '30124', 'Venezia'); INSERT INTO zip (id, country_id, code, name) VALUES (NEXTVAL('zip_id_seq'), (SELECT id FROM country WHERE name = 'USA'), '20001-6000', 'Metropolitan Washington Airports Authority');
In the Object Browser you can verify that it worked by looking at the tables under Databases /
cookbookdb / Schemas / public / Tables.
PostgreSQL connection pool in GlassFish
[back to top]
In GlassFish, using the GlassFish Administration Console web application, create a new connection
pool as usual via Resource / JDBC / Connection Pools / New.
dialog page
field value
1 Name CookbookPoolPg
Resource Type javax.sql.ConnectionPoolDataSource
Database Vendor Postgresql
2 Ping Enabled
Additional Properties
DatabaseName cookbookdb
User cookbookuser
Password cookbook
ServerName localhost
PortNumber 5432
Ssl false
Instead of creating a new JDBC resource, we simply change the existing
resource jdbc/cookbookdb to point to the PostgreSQL datasource instead of the Derby datasource.
Definition of the datasource in Eclipse
[back to top]
In the Datasource Explorer we choose Database Connections / New to get to the New Connection
Profiledialog:
dialog page field value
1 Connection Profile Type
PostgreSQL
Name CookbookPg Database
2 Drivers New Driver Definition > Jar List > Add JAR/Zip > OK
Database cookbookdb
URL jdbc:postgresql:cookbookdb
User Name cookbookuser
Password cookbook
Entities
[back to top]
At this point our in-server test suite would already run, while for the out-of-server test suite we would
have to change the connection details in its copy of persistence.xml. Be aware though, that it
would only work, because we have no test case that inserts data. Inserting data requires values for
primary keys, and while Derby uses columns of type IDENTITY, in PostgreSQL we use values taken
from a sequence. Remember, in the generated entities we had
@Id@SequenceGenerator(name="CITY_ID_GENERATOR", sequenceName="CITY_ID_SEQ")@GeneratedValue(strategy=GenerationType.SEQUENCE, generator="CITY_ID_GENERATOR")private Long id;
Obviously we need different generated entities for different database types. It does not work to
generate entities into database-specific packages, because the generated entities have
an @Entity annotation without attributes, thus their internal reference name defaults to the class
name, and that’s also the default for the table name. Having different entities for e.g. table ZIP in
different packages (com.manessinger.cookbook.entity.derby and com.manessinger.cookbook.entity.pg)
does not help, because both would have the same (defaulted) entity name.
We have no way to specify entity name and table name in the code generator, but we could edit the
generated entities, changing the entity declarations from e.g.
@Entitypublic class Zip extends com.manessinger.util.jpa.Entity implements Serializable { ...}
to
@Entity(name="ZipPg")@Table(name="ZIP")public class Zip extends com.manessinger.util.jpa.Entity implements Serializable { ...}
This is all a matter of how many tables you have, how often you expect to re-generate the entities
and how likely it is to have to support differnet databases for the same data.
In practice we would most likely not care. Database switches would occur rarely if at all in the
lifetime of a project, and having to support different database systems for the same data at the same
time would be extremely rare. Thus we would keep to our principle of never changing generated
code, and simply generate to com.manessinger.cookbook.entity, accepting to have to overwrite Derby
entities if we have to change to PostgreSQL or Oracle. No big deal.
Access to PostgreSQL via SSL
[back to top]
As I said, at work our PostgreSQL database servers are configured to only accept SSL connections.
No problem, that’s what the attribute Ssl is for. Just set it to true in the datasource definition in
GlassFish. If you happen to encounter an error where the JDBC driver refuses to connect to a server
whose SSL certificate it can’t verify, you have the problem, that your PostgreSQL server uses a self-
signed certificate. You can either add your certificate to the certificate store of the Java runtime you
use, or else tell the driver with an addditional property sslfactory with
value org.postgresql.ssl.NonValidatingFactory to not validate.
In the case of the GlassFish datasource you just define the additional property. In Eclipse you need
to add the property to the URL in the style of HTTP URL parameters. It would look like this: