a workflow based architechture for pki

89
A Workflow Based Architecture for Public Key Infrastructure Improvements to an existing open source Certified Authority application JOHAN EKLUND Master of Science Thesis Stockholm, Sweden 2010

Upload: duongthuy

Post on 01-Jan-2017

231 views

Category:

Documents


1 download

TRANSCRIPT

Page 1: A workflow based architechture for PKI

A Workflow Based Architecture for Public Key Infrastructure

Improvements to an existing open source Certified Authority application

J O H A N E K L U N D

Master of Science Thesis Stockholm, Sweden 2010

Page 2: A workflow based architechture for PKI

A Workflow Based Architecture for Public Key Infrastructure

Improvements to an existing open source Certified Authority application

J O H A N E K L U N D

Master’s Thesis in Computer Science (30 ECTS credits) at the School of Computer Science and Engineering Royal Institute of Technology year 2010 Supervisor at CSC was Kjell Lindqvist Examiner was Karl Meinke TRITA-CSC-E 2010:047 ISRN-KTH/CSC/E--10/047--SE ISSN-1653-5715 Royal Institute of Technology School of Computer Science and Communication KTH CSC SE-100 44 Stockholm, Sweden URL: www.kth.se/csc

Page 3: A workflow based architechture for PKI

A workflow based architecture for Public Key Infrastructure

Improvements to an existing open source Certificate Authority application

Abstract

EJBCA is a Certificate Authority application currently using the Enterprise JavaBeans 2.1 framework. 

In the first part of this degree project, workflow management software was evaluated for the purpose of enrolling end users and servers for digital certificates in a Public Key Infrastructure. A workflow in this context is all the necessary high level tasks needed to complete the enrollment process. The jBPM workflow management software was found to be the best choice out of the evaluated open source applications and frameworks. A proof of concept application was implemented using the jBPM workflow execution engine. The execution engine was not working well enough to be used for certificate enrollment. A revisit to this field in the future is recommended.

In the second part of the degree project, the Java frameworks Spring 2.0 and Enterprise JavaBeans 3.0 were evaluated for the purpose of replacing Enterprise JavaBeans 2.1 as the framework used for EJBCA. In the theoretical study Enterprise JavaBeans 3.0 was selected for further evaluation. The selection was made due to its stability, potential to simplify maintenance and similarities with the currently used framework. A practical evaluation of the selected framework was performed using a selection of components of EJBCA. The results from the practical evaluation were sufficient to motivate a migration to Enterprise JavaBeans 3.0. A migration strategy was created based on the findings from both the theoretical study and the practical evaluation.

Page 4: A workflow based architechture for PKI

Arkitektur för Public Key Infrastructure baserad på arbetsflöde

Förbättringar av en existerande certifikatauktoritetsapplikation baserad på öppen källkod

Sammanfattning

EJBCA är en certifikatauktoritetapplikation som använder ramverket Enterprise JavaBeans 2.1.

I första delen av examensarbetet utvärderas mjukvara för styrning av det arbetsflöde som krävs för att registrera och ge ut digitala certifikat till användare och servrar i en Public Key Infrastructure. Ett arbetsflöde är i detta sammanhang de delmoment som krävs, ur ett högnivåperspektiv, för att genomföra registrering och utgivning. Arbets­flödemjukvaran jBPM var det bästa alternativet av de utvärderade applikationerna och ramverken. En testimplementation baserad på jBPMs motor för exekvering av arbets­flöde gjordes, men motorn fungerade inte tillräckligt bra för att kunna användas för registrering och utgivning av certifikat. En ny utvärdering av området i framtiden rekommenderas.

I andra delen av examensarbetet utvärderades Javaramverken Spring 2.0 och Enterprise JavaBeans 3.0 som ersättningskandidater för EJBCAs nuvarande ramverk Enterprise JavaBeans 2.1. I den teoretiska utvärderingen valdes Enterprise JavaBeans 3.0 på grund av dess stabilitet, potentiella möjlighet att förenkla underhåll och likheter med nu­varande ramverk. En praktiskt utvärdering av det valda ramverket gjordes med hjälp av ett urval av berörda komponenter från EJBCA. Resultaten av den praktiska utvärderingen var tillräckliga för att motivera en migrering till Enterprise JavaBeans 3.0. En migreringsstrategi skapades utifrån resultaten av både den teoretiska och praktiska utvärderingen.

Page 5: A workflow based architechture for PKI

PrefaceI would like to thank

• Tomas Gustavsson, Chief Technical Officer of PrimeKey Solutions AB for excellent support, encouragement and feedback during the entire degree project.

• Kjell Lindqvist for all the feedback and having patience with this project that ran for over two years.

• The EJBCA community and all the other developers at PrimeKey (especially for working hard to give me time to concentrate on this project).

• All of those in the other open source communities affected by this project.

Page 6: A workflow based architechture for PKI
Page 7: A workflow based architechture for PKI

Contents1 Introduction....................................................................................................................1

1.1 Background..............................................................................................................1

1.2 Problem statement....................................................................................................4

1.3 Report outline...........................................................................................................5

2 Workflow languages and page flows..............................................................................6

2.1 Workflow languages................................................................................................6

2.2 Workflow languages and standards ........................................................................7

2.3 Page flows................................................................................................................8

3 Workflow and page flow evaluation..............................................................................9

3.1 Workflow evaluation...............................................................................................9

3.2 Page flow evaluation..............................................................................................10

3.3 Test summary.........................................................................................................11

4 jBPM evaluation...........................................................................................................13

4.1 Scope of evaluation................................................................................................13

4.2 Platform requirements............................................................................................14

4.3 Tested workflows...................................................................................................14

4.4 Outline of solution.................................................................................................17

4.5 Conclusions............................................................................................................17

5 Java framework comparison.........................................................................................19

5.1 Basic concepts........................................................................................................19

5.2 Theoretical Spring framework evaluation.............................................................20

5.3 Theoretical Enterprise JavaBeans 3.0 evaluation..................................................20

5.4 Enterprise JavaBeans 3.0 is the best option...........................................................21

6 Enterprise JavaBeans 3.0 evaluation............................................................................22

6.1 Scope of evaluation and methodology...................................................................22

6.2 Java Persistence API..............................................................................................22

6.3 Stateless Session Beans..........................................................................................23

6.4 JavaServer Faces 1.2..............................................................................................23

6.5 Test application structure.......................................................................................23

6.6 Web Services.........................................................................................................23

6.7 Conclusion.............................................................................................................23

7 Final discussion............................................................................................................25

Page 8: A workflow based architechture for PKI

7.1 The lack of executable workflow solutions...........................................................25

7.2 EJBCA migration strategy.....................................................................................26

7.3 Future work............................................................................................................26

8 Abbreviations................................................................................................................27

 References......................................................................................................................29

 Appendix A: Task­list application implementation details............................................32

 Appendix B: Enterprise JavaBeans 3.0 evaluation details.............................................40

 Appendix C: Migration strategy details..........................................................................58

 Appendix D: Java frameworks.......................................................................................66

Page 9: A workflow based architechture for PKI

1 IntroductionThis chapter will give the reader a quick background and motivation for this degree project.

1.1 BackgroundEJBCA is a free open source Public Key Infrastructure Certificate Authority software. All around the world there are major installations in production, where the application is used in many different ways and in many different environments. PrimeKey Solutions AB is the maintainer of EJBCA.

Public Key Infrastructure

Public Key Infrastructure is a vital part of IT security and “consists of protocols, services, and standards supporting applications of public­key cryptography” [36]. Public Key Infrastructure is the back bone of Internet security, and is for example used as basic technology every time a secure website is visited. 

In public­key cryptography a key­pair, consisting of a private and a public key, can be used to create (digital) signatures and encrypt data. Signatures are created with the private key and can be verified using the public key. A public key certificate1 contains the public key and information about the holder of the matching private key. Given a certificate and a signature it is possible to verify that a signature has been created by the holder of the private key matching the public key in the certificate. A successful signature verification also means that the identity of the private key holder that created the signature is known, since this information is available in the certificate.

The information in the certificate has to be correct and trustworthy. A certificate is always signed by a Certificate Authority's private key to guarantee that the information about a holder of a private key is correct. The Certificate Authority has itself a certificate with a matching public key to its private key. Given this Certificate Authority certificate, and that we trust this Certificate Authority, any information in certificates issued by the authority can be trusted.

A simple use case is communication over an insecure network. Two users can verify each others identities without ever having met before if they both have valid certificates and trust the Certificate Authority that issued the other user's certificate.

The role of a Registration Authority in a Public Key Infrastructure is to correctly identify and collect information about the private key holder that should be issued a certificate.

Public Key Infrastructure is a mature and well researched area. The first design of a global infrastructure was done at MIT and standardized by the Internet Engineering 

1 The term ”certificate” is used for “public key certificate” throughout this report.

1

Page 10: A workflow based architechture for PKI

Task Force in 1993 [25]. Other types of infrastructures have been suggested in numerous papers, a proposal for a global certification infrastructure is described in [11].

For the purpose of this degree project, Public Key Infrastructure is defined as the management of public keys and certificates.

Workflow

Workflow in a general sense means how something can be done. In this report a work­flow is a description of how a set of tasks can be performed by different people and/or systems to reach a result. The description should not be too detailed and it is more important to describe who does what, than to get a detailed view of how each person or system in the workflow performs assigned tasks. Assigning tasks and keeping track of who should do what is called workflow management.

Workflows in a Public Key Infrastructure

In a Public Key Infrastructure one of the core tasks is making sure that a certificate is issued to the right private key holder. The Registration Authority is responsible for collecting correct data about the private key holder. There are many different ways of doing this depending on security requirements, history, economics and other factors. Almost every large organization have their own way of performing this task. The process of collecting the information about the holder, and issuing the certificate is called an enrollment process.

A workflow in this context is all the necessary high level tasks needed to complete the enrollment process. Typically there is a mix of both human tasks and automatic, back­ground processing.

A typical workflow of such an enrollment process for an imaginary organization could look like this:

• One of the server administrators generates a new asymmetric key­pair on a server.

• One of the server administrators generates a certificate request and sends it to the Registration Authority administrators.

• One of the Registration Authority administrators validates the request and approves or rejects the request.

• If approved, the certificate request is sent to the Certificate Authority.

• The Certificate Authority issues a certificate from the certificate request and sends it back to the server administrators.

• One of the server administrators installs the issued certificate on the server.

In the workflow above, each list item is a high level task of the workflow. Each task is assigned to a role or a system. 

2

Page 11: A workflow based architechture for PKI

The different tasks of a workflow can be represented in many different ways, including the list­form used above. A graphical representation (illustration 1) might give a better overview of the whole process and an XML representation might be interpreted and executed by the execution engine of workflow management software.

The main point of using workflow management is that there is a centralized view of the process and current progress of ongoing workflows. Changes in the workflow can be made in a single place and it is easier to get a good overview of the system compared to a decentralized system.

3

Illustration 1: A graphical representation of the example workflow

Page 12: A workflow based architechture for PKI

The Enterprise JavaBeans 2.1 framework

Java Community Process's Enterprise JavaBeans 2.1 is a standardized way of building modular server­side enterprise applications where the framework provides transactions integrity, persistence and security.

The first public release of EJBCA in 2001 was using the Enterprise JavaBeans 1.0 standard and since then the project has grown to over 200 000 lines of code. EJBCA runs on many of the major application servers and databases. 

The current version of EJBCA (3.9.2), is based on the Enterprise JavaBeans 2.1 standard. This is part of the Java 2 Enterprise Edition standard and has been superseded by the Java Enterprise Edition 5 standard. As a result of this, the XDoclet tool used for automatic code generation has not been active since 2004 [43] and the last released version cannot be used together with Java 1.5 features like generics or annotations.

In Enterprise JavaBeans 2.1, the support for different databases is very tightly coupled to the application server and a change in the database schema requires large amounts of manual work and changes to the configuration.

Furthermore, binding between different Enterprise JavaBeans 2.1 components requires application server dependent configuration due to lack of proper standardization.

1.2 Problem statementThis section describes the motivation and limitation of the degree project.

Purpose

The purpose of this project is to investigate and find answers to the following questions:

• Is there an open source workflow management framework or tool that can be used to ease the adaptation of EJBCA to different business processes?

• What is the best suited replacement for the Enterprise JavaBeans 2.1 framework for EJBCA?

Limitations

The field of workflow management frameworks is full of buzzwords and promises, and therefore the initial task was to look into how to refine selection criteria and limit the scope.

The initial approach was to find out if there were any solid standards in this field that could be used. Business Process Management Notation, Unified Modeling Language 2.0 Activity Diagrams, XML Process Definition Language, Business Process Execution Language and jBPM Process Definition Language was studied. While the last language is not a formal standard, it was included upon request by PrimeKey.

4

Page 13: A workflow based architechture for PKI

Enterprise JavaBeans 3.0 and Spring 2.0 were selected as future candidates for replacing the old framework. 

As an additional requirement, there had to be a free open source implementation of any tools, frameworks or libraries used by EJBCA. EJBCA is licensed under the GNU Lesser General Public License that grants users the right to modify, use, republish and integrate other applications with EJBCA for free as long as the same rights are passed on to derived software. If a tool or dependency of EJBCA would not live up to the same level of freedom we would not be able to:

• Expect that all users in the EJBCA community are able to use it.

• Branch it and maintain our own version if the project dies or starts evolving in the wrong direction from the EJBCA developers' point of view.

• Bundle required libraries with EJBCA.

Whenever “open source”, “free open source” or “free” is used these freedoms are implied.

1.3 Report outlineThe first half of the report is dedicated to workflow management. The next chapter will explain more in depth what the theoretical options are when it comes to workflow languages. Chapter 3 summarizes a basic evaluation of different existing open source workflow management frameworks and tools. Chapter 4 describes the findings from an evaluation of implementing Public Key Infrastructure workflows using the jBPM work­flow management framework.

The second half of the report is dedicated to finding a new Java framework for EJBCA. Chapter 5 compares the two Java frameworks Spring 2.0 and Enterprise JavaBeans 3.0 for use with EJBCA. Chapter 6 describes an evaluation of Enterprise JavaBeans 3.0 on different application servers and databases in brief.

In chapter 7, the results from both parts of the report is summarized suggested future work is presented.

Appendix A describes the details of the jBPM evaluation summarized in chapter 4.

Appendix B describes the details of the JavaBeans 3.0 evaluation summarized in chapter 6.

Appendix C describes the most important details of the EJBCA migration strategy based on the findings during this degree project.

Appendix D describes the two Java frameworks Spring 2.0 and Enterprise JavaBeans 3.0 in depth and gives a brief description of the upcoming Enterprise JavaBeans 3.1 standard.

5

Page 14: A workflow based architechture for PKI

2 Workflow languages and page flows

A centralized process of human and machine interactions can be described with a workflow language. Such a high level language can be executable and/or have a graphical representation. A page flow is a description of how and in what order to serve a set of web pages that can be used for human interaction in a workflow.

2.1 Workflow languagesA more formal definition of a workflow (also referred to as a business process) than in section 1.1  is “a series of related actions between people and a computer system” [42]. Managing workflows is called workflow management or business process management. A workflow can have a graphical representation and/or a non­graphical representation. Such a representation is called a workflow language. The system that can take a work­flow language as input and keep track of the execution is defined in [42] as a workflow management system. A workflow management system is also referred to as a workflow engine. Using such systems/engine could have several benefits:

Enterprise Application Integration

In a Service Oriented Architecture several different applications could be tied together using a workflow language describing the interactions. An example of this is Web Services Business Process Execution Language (WS­BPEL), that allows new Web Services to be created from existing Web Services. This means that old investments in legacy applications can be reused and best of breed components can be brought into the system [1].

Software that interacts with humans

In a system where several different people in different roles interact with the workflow, regular programming becomes complicated. The workflow engine keeps track of the current state of the process, a mechanism that the programmer would otherwise have to implement [42].

Maintainable and adaptable applications

A better centralized overview of the system will help optimizing and simplifying the workflow. Changing the workflow will be much simpler than trying to change an application that is hard­coded for a specific purpose. This allows an iterative development model where business analysts speaks the same language as the developers [42].

6

Page 15: A workflow based architechture for PKI

2.2 Workflow languages and standards Listed below are the major existing standards and languages for describing workflow.

Business Process Modeling Notation

Business Process Modeling Notation (BPMN) is a standard for graphically describing the workflow of business processes and is maintained by the Object Management Group [28]. The graphical representation is referred to as Business Process Diagrams. BPMN can be expressed in XML Process Definition Language [44]. 

XML Process Definition Language

XML Process Definition Language (XPDL) is a standard from the Workflow Management Coalition for exchanging business process definitions between different workflow tools [44]. XPDL is designed to keep track of both the graphical representation and process semantics. The XPDL 2.0 standard was developed to be able to represent all aspects of the BPMN Business Process Diagrams. According to [41], the XPDL specification allows vendor specific extensions through “extended attributes”. This might lead to different tools being incompatible. XPDL itself is available without licensing.

Unified Modeling Language 2.0 Activity Diagrams

Unified Modeling Language 2.0 Activity Diagrams (UML 2.0 AD) is a graphical representation of business processes adopted by the Object Management Group and is described in [29].

Web Services Business Process Execution Language

Web Services Business Process Execution Language 2.0 (WS­BPEL) [33], also known as Business Process Execution Language (BPEL), is a standard from the Organization for the Advancement of Structured Information Standards (Oasis). WS­BPEL is an executable language designed to orchestrate Web Services by modeling high­level state transitions of a business process. The transitions are message­based, meaning that the definition specifies reactions upon incoming messages. WS­BPEL 2.0 does not support human tasks or subprocesses, which makes it unsuitable for regular Business Process Modeling. Extensions like BPEL4People tries to add support for human tasks [10] by adding concepts like users, roles and ownership of tasks.

To use the WS­BPEL specifications, a royalty­free license from the WS­BPEL stake­holders (Microsoft, IBM, BEA, SAP and Siebel) must be obtained. This license might not be compatible with LGPL for derived software [35].

jBPM Process Definition Language

jBPM Process Definition Language (JPDL) is a proprietary workflow language described in [34] for the LGPL jBPM workflow execution engine from Red Hat. JPDL can be used to manage workflows with tasks witten in Java or to organize in what order 

7

Page 16: A workflow based architechture for PKI

web pages are served to a web client user. A good description of JDPL can be found in [8].

Business Process Definition Metamodel

Business Process Definition Metamodel is a new proposed standard currently in the final phase of adoption at the Object Management Group. It tries to be more exchangeable between vendors than BPMN and includes service orchestration. Business Process Definition Metamodel is based on XML Metadata Interchange. No open source implementation exists as of spring 2008 and therefore this language will not be evaluated.

2.3 Page flowsPage flows are not suited for describing workflows, but are a way to handle conversational user interactions. By decoupling navigation from the actual web pages, changes can be made to the page flow more easily.

A stated before, the workflows for issuing certificates contain a large amount of human interaction. To achieve platform independence, these human interactions should be done through a web based user interface. My hypothesis was that page flows could simplify the human interactions with a workflow application for the developer.

Spring Web Flow

According to [21], Spring Web Flow can be used as an embedded page flow engine with JavaServer Faces or other frameworks. A copy of each step of the navigation is kept to allow the users to go back in the browsing history. The state of the conversation is kept on the client­side to reduce the web­servers memory footprint. Users can have several different conversational sessions open at the same time. Spring Web Flow uses a proprietary XML language to describe page flows.

Seam Pageflow

Seam Pageflow is built on the jBPM workflow engine and uses a simplified version of the JDPL language. The state of the conversation can be persisted in a database to reduce the web­servers memory footprint. Users can have several different conversational sessions open at the same time.

JavaServer Faces Navigation Rules

Navigation Rules are a part of the JavaServer Faces standard. These simple rules allow navigation between web pages to be conditional and specified in a separate XML­file. The outcome of a method backing an action of a command­tag is translated with help of the navigation rules to the proper page. As for the other page flow implementations, this separation of navigation and view makes changes to the navigation easier when a page is renamed or the flow changes [3]. The state of user interactions with the server can be kept for each request, for the entire session or during the application uptime [4].

8

Page 17: A workflow based architechture for PKI

3 Workflow and page flow evaluation

There are many frameworks and tools for the management of workflows and page flows. This chapter gives a quick overview of the available free tools and frameworks, and evaluates their potential for being used in EJBCA.

3.1 Workflow evaluationThis section describes potentially useful workflow frameworks and tools.

Requirements

In two articles, [12] and [22], the authors describe how well the workflow languages BPMN, UML 2.0 AD and WS­BPEL can capture different interactions in a workflow. To be able to use these results a similar study for XPDL and JPDL has to be done and a thorough description of the workflows in EJBCA is required. There are however other strongly limiting factors that affect the choice of a suitable workflow management system:

The solution must be executable

An executable solution requires the use of one of the XPDL, WS­BPEL or JPDL languages, or a tool able to translate a given workflow representation into one of these languages. Since we want to use a workflow engine for keeping track of which task is assigned to whom, WS­BPEL is not a good choice. Left to evaluate are XPDL and JPDL.

The workflow execution engine should integrate well with EJBCA

The preferred solution should not exclude the use of either Enterprise JavaBeans 3.0 or Spring 2.0, since one of them will probably be chosen as the next framework for EJBCA. If custom code for tasks that interact with EJBCA is required, the code should preferably be written in Java to be able to use one of the EJBCA client libraries.

The tools must be free as in freedom

A quick survey of the available tools showed that the number of available free open source tools for modeling and executing business processes was limited, and many of the projects were very basic or stale.

I estimate that first describing the most common Public Key Infrastructure workflows for EJBCA and then converting them from one language to another is a time consuming 

9

Page 18: A workflow based architechture for PKI

effort. If the language chosen initially is not supported by the available tools the effort would have been spent in vain. Therefore, it makes more sense to start investigating the available alternatives to see what languages that are supported in practice first.

Where nothing else is stated the tested version is the latest available during spring 2008.

XML Process Definition Language

65 different implementations of the XML Process Definition Language (XPDL) standard are listed at the Workflow Management Coalition's website [45], but only a few of them were available under a Open Source license. None of the tested frameworks or tools fulfilled the requirements.

jBPM Process Definition Language

There is only a single editor and workflow execution engine available for the jBPM Process Definition Language. Writing custom code that interact with the jBPM work­flow execution engine can be done rather easily with JBoss Seam according to [9]. The jBPM samples included with the JBoss Seam 2.1.0 package are simplified examples of such custom code and works flawlessly. Practical tests showed that it was easy to add custom Java code to the different nodes and transitions, and all the process variables can be accessed from the code.

The project is a very active one with new releases in short intervals and it has a large open source company (Red Hat, Inc.) backing it. This suggests that any problem found in this initial study would soon be corrected.

3.2 Page flow evaluationThis section describes potentially useful page flow frameworks and tools.

Spring Web Flow

Spring Web Flow applications can be developed with Spring's workflow editor that runs inside the Eclipse IDE. However, version 1.0.6 of this editor can only load existing samples and not create new ones.

Seam Pageflow

The tested version of Seam Pageflow was a part of the JBoss Seam 2.1.0 package. The scope of the Seam framework is much larger than page flows and only using the page flow part does not make sense. JBoss Tools (http://www.jboss.org/tools/) are used for graphical design, just as for the jBPM Process Definition Language workflows. The editor has several minor bugs, but was still usable and a couple of simple created Pageflows executed as expected.

10

Page 19: A workflow based architechture for PKI

JavaServer Faces Navigation Rules

There are several editors for creating JavaServer Faces Navigation rules, for example Eclipse Web Tools Project 1.5+, JBoss Tools and NetBeans IDE. The first two were tested and the resulting Navigation Rules executed as expected.

3.3 Test summaryNone of the tested workflow frameworks/systems are close to fulfilling all the requirements. Table 1 on page 12 lists the tested software and its properties.

The best and most promising alternative for a proof of concept is to use the jBPM execution engine with a custom front­end and the JPDL graphical editor. 

11

Page 20: A workflow based architechture for PKI

Application/project Language Type Comment

Intalio BPMN BPMN Editor and engine Not free enough.

STP BPMN Modeler BPMN Editor No working execution engine.

Enhydra JaWE XPDL Editor Not working properly. Not free enough.

JPEd  XPDL Editor Not working properly.

AgilPro 1.4.0 XPDL Editor Not working properly.

Java Workflow Toolbox 0.4

XPDL Editor Not working properly.

ProEd XPDL Editor No working execution engine.

Enhydra Shark XPDL Engine Not free enough.

AgilPro Simulator XPDL Engine Not working properly.

WfMOpen XPDL Engine Not working properly.

JawFlow XPDL Engine Dead project.

Open Business Engine XPDL Engine Not working properly. Project is not active.

OAC Business Process Management

XPDL Engine Not general enough.

Bonita XPDL Engine Not working properly.

Open For Business XPDL Engine Not general enough.

jBPM 3.1.4 JPDL Editor and engine Not working properly.

jBPM Page Flow JPDL Editor and engine Page flow framework. Minor bugs in the editor.

Spring Web Flow “XML” Editor and engine Page flow framework. Graphical editor does not work.

JavaServer Faces Navigation Rules

“XML” Page flow framework.

Table 1: Summary of tested workflow and page flow tools and frameworks

12

Page 21: A workflow based architechture for PKI

4 jBPM evaluationIn the theoretical comparison of the different workflow management systems, the jBPM workflow framework was selected for further evaluation. The workflow framework will  be used in a new small front­end application for issuing certificates with the Public Key Infrastructure software EJBCA.

4.1 Scope of evaluationIn the theoretical and practical study of the different workflow languages and engines the jBPM workflow execution engine with the jBPM Process Definition Language (JPDL) graphical editor was selected for further evaluation. Since Seam's Pageflow uses the same execution engine and graphical designer, I assumed that it would be easy to use Pageflows for workflow tasks assigned to humans.

The goal was to test using jBPM for the workflows combined with Seam's Pageflow for human tasks to fully understand the benefits and problems of this workflow technology when used within a Public Key Infrastructure.

To evaluate these components a small task­list application was created. The task­list application has the role of a Registration Authority in the Public Key Infrastructure, meaning that it is responsible for enrolling users or servers. The task­list application uses a Certificate Authority in a running EJBCA instance for issuing the certificate and is also responsible for making sure that the right user or server gets the resulting certificate.

Communication with EJBCA is done through a protocol designed for environments where only outgoing traffic is allowed from the EJBCA instance. Requests to and responses from EJBCA is stored in a database running on the same machine as the task­list application. A service running in EJBCA polls the database at regular intervals.

There are several reasons why this is a good setup for evaluation:

• Thanks to the isolation of the protocol, there are few dependencies on existing technology. This means that the environment can be chosen to best suit jBPM and avoid problems that are not related to the tested technology.

• A Registration Authority is a component where many users of EJBCA want organization specific customizations. Being able to quickly adapt the workflow here has the potential to save large amounts of development.

• Work on these tests can be done in parallel with any work on EJBCA, without having to compensate for changes in the main project as long as the used protocol is stable. This ensures that the finished software is always up to date with the latest EJBCA release.

13

Page 22: A workflow based architechture for PKI

4.2 Platform requirementsNor the Seam Framework or jBPM have any formal requirement on Enterprise JavaBeans or the use of an application server. Both jBPM and the EJBCA database protocol client libraries depend on Hibernate for persistence. This means that the evaluation project can be deployed as a simple Web Application. This lightweight approach would allow the use of a simple Servlet container like Tomcat instead of an application server.

4.3 Tested workflowsThe selected workflows are similar to requests by customers of PrimeKey Solution AB or requests on EJBCA's public forum and mailing list on SourceForge.

There are several roles defined in the workflows below:

• An administrator is authorized to approve or reject requests.

• A registrator is authorized to enroll (or request to enroll) for a certificate on behalf of a user or server.

• A user is authorized to enroll (or request to enroll) himself/herself

All administators are part of the group “administrators” and all registrators are part of the group “registrators”. Group and role is used interchangeably in this chapter.

In all the workflows below, every new task for the administrators or registrators generates an email to the group. Another email is sent to the same group when someone from the group has reserved or started working on the task.

A keystore is a bundle of a certificate and an asymmetric key­pair generated by the Certificate Authority.

Workflow­1: Public registration for server generated keystore

A screenshot of the graphical representation of this workflow from the JBPM workflow editor is shown in illustration 2 on page 16.

• A user registers data that should go into the certificate, an email address and additional contact info.

• An administrator approves or rejects the request.

• If approved, a notification email is sent to the user's email address with a URL to the new keystore. Otherwise a rejection email is sent and the workflow ends.

• If approved, the user can fetch the resulting keystore.

• If approved, the administrator calls the person referenced in the “contact info” to tell him/her the password for the keystore. The keystore is removed from the system when the task is complete.

14

Page 23: A workflow based architechture for PKI

Workflow­2: Registrator requested server generated keystore

A screenshot of the graphical representation of this workflow from the JBPM workflow editor is shown in illustration 3 on page 16.

• A registrator starts a new process and enters the data that should go into the certificate.

• The administrator approves, rejects or sends the request for correction.

• If the request is sent for correction, a registrator corrects the request and sends it back for approval.

• If the request is rejected, the registrators are notified with an email and the work­flow ends.

• If approved, the registrators get a new task to fetch the resulting keystore.

• When the fetch­task is completed the keystore is removed from the database.

Workflow­3: Self registration with client generated keys

A screenshot of the graphical representation of this workflow from the JBPM workflow editor is shown in illustration 5 on page 16.

• A user browses to a page and enters a semi­secret password.

• The user registers the user's data and a private key is generated in the browser with its corresponding certificate signing request. The certificate signing request is added to the user's data.

• The administrator approves or rejects the request with a comment.

• If rejected, the user is informed by email that the request has been rejected and the workflow ends.

• If approved, the user is informed by email where the finished certificate can be found. One of several passwords used to fetch the certificate is sent in the email.

• The administrators get a new task to call, SMS or send the additional passwords by other means to the user.

• The user logs on using all the passwords and fetches the certificate.

Workflow­4: Servlet­started certificate request flow

A screenshot of the graphical representation of this workflow from the JBPM workflow editor is shown in illustration 4 on page 16.

• A certificate signing request, notification­email and contact info is sent to a Servlet that starts a new business process.

• An administrator approves or rejects the request.

15

Page 24: A workflow based architechture for PKI

• An email is sent to the requester with either a link to the certificate or a rejection message.

16

Illustration 2:  Workflow­1 Illustration 3:  Workflow­2

Illustration 5:  Workflow­3 Illustration 4:  Workflow­4

Page 25: A workflow based architechture for PKI

4.4 Outline of solutionSince the workflows described earlier in this chapter require human interaction a web based task­list application was created. The jBPM execution engine is used by the task­list application to keep track of which task of the different running workflows that are assigned to which group or user (in this context a user is a client to the task­list application and can have any role from the workflow perspective). 

A typical use­case would be:

• The user is notified that a new task is waiting for someone with the user's role

• The user logs in with a certificate or username/password depending on the security level required for the user's role.

• The user is presented with a list of tasks assigned to the user's role and another list with personally assigned tasks.

• The user can, if authorized, start, resume, cancel, change priority of, reserve or yield tasks.

• The user can, if authorized, start a new workflow.

When a task is started or resumed from the web based user interface, the user is sent to a Seam Pageflow and when the flow ends the user is sent back to the list of tasks.

Workflows can also be started by users filling out and submitting a form or by submitting a certificate request to a Servlet.

Illustration 6 on page 18 shows a screenshot of the finished task­list application's web interface.

Implementation details of the task­list application are described in appendix A.

4.5 ConclusionsThe implementation of the task­list application using jBPM for workflow management and Seam Pageflow for human tasks has shown the complexity in the framework. The finished task­list application also revealed signs of concurrency issues in the underlying framework. The Pageflow implementation of the simple human tasks in the tested workflows were not worth the added complexity compared to using regular JavaServer Faces.

17

Page 26: A workflow based architechture for PKI

18

Illustration 6: Screenshot of the task­list application using full debug­info

Page 27: A workflow based architechture for PKI

5 Java framework comparisonThis chapter will give a theoretical comparison of the two Java frameworks Spring 2.0 and Enterprise JavaBeans 3.0. The two Java frameworks are described in detail in appendix D. The comparison will focus on how the frameworks can be used for EJBCA.

5.1 Basic conceptsIn the following chapters terms like POJO and JavaBean will be used. This is a quick definition and/or overview of what they mean in this context.

Plain Old Java Object

Plain Old Java Object (POJO) has no formal definition, but is usually used to describe a Java object that has no restrictions except for those enforced by the Java language. The term POJO is used here to point out that a Java object has no dependencies on the framework in the way that it is implemented.

JavaBeans

A JavaBean is a specific way to implement a Java object. The most important requirements on a JavaBean object is that it has to:

• Have a public no­argument constructor (or no constructor).

• Use getters and setters to access private variables.

• Implement java.io.Serializable.

Using this object design a framework can easily instantiate, persist and manipulate the object. Details are available in the JavaBeans concept [39].

JavaServer Faces Managed Beans

JavaServer Faces Managed Beans are Java objects used with the JavaServer Faces web framework. These objects have to implement:

• A public no­argument constructor (or no constructor).

• Getters and setters to access private variables.

Details are available in the JavaServer Faces reference [4].

Enterprise JavaBeans

There are several different types of Enterprise JavaBeans. Entity Beans and Stateless Session Beans are used in EJBCA. The different types of Enterprise JavaBeans are described in Enterprise JavaBeans standard overview in appendix D.

19

Page 28: A workflow based architechture for PKI

5.2 Theoretical Spring framework evaluationSpring can be used in many different ways. For EJBCA there are two relevant use­cases.

If Spring is used as an add­on library inside the application server or if all Enterprise JavaBeans are converted to simple JavaBeans and Spring is used as the container for transactions:

• XDoclet can be removed.

• Database abstraction would be simplified.

• One kind of XML configuration would be replaced with another of similar extent.

Spring's auto­wiring does not seem suitable for a project of EJBCA's magnitude and would make debugging much more difficult, since Spring only injects “null” instead of a value if a bean was misspelled or had it is name changed.

The loose coupling is a very nice feature where resources and beans are injected into other beans. Even though the authors of Spring in Action [6] claim that this makes Spring applications more flexible since there is no dependencies on the framework, I know of no other solution that would handle the exact same JavaBeans exactly the same way. That way there still is a dependency on the framework. Also, most of the useful features like abstracting away all SQL exceptions introduce dependencies on the framework.

XDoclet comments for transactions will be replaced with XML configuration. This will make it more difficult to get a good overview of the transactions and the code at the same time.

5.3 Theoretical Enterprise JavaBeans 3.0 evaluation

Moving from XDoclet to Enterprise JavaBeans 3.0 looks very straightforward. All the XDoclet comments for Session Beans have Enterprise JavaBeans 3.0 annotation counterparts. The Local and Remote interfaces generated by XDoclet should be kept and converted to regular Java interfaces.

Java Persistence API will allow the creation of write database agnostic persistence code.

Due to the configuration by exception policy, minimal or no XML configuration will be needed.

EJB 3.0 has similar features to Spring for injection of resources and beans into other beans.

20

Page 29: A workflow based architechture for PKI

5.4 Enterprise JavaBeans 3.0 is the best optionBoth frameworks bring several important features to the table, but Enterprise JavaBeans 3.0 does it better and is the only real candidate for further testing.

A stable standard

An EJBCA installation can live for 10 years or more, so to make sure it is maintainable EJBCA needs stability and standards more than the latest and greatest features. My impression of Spring is that it is a useful integration framework, compared with Enterprise JavaBeans 2.1, for building small loosely coupled applications from scratch. Good new ideas are quickly incorporated in the project, but this might be done at the price of backward compatibility.

Enterprise JavaBeans 3.0 on the other hand is a proper Java Community Process standard [27] where the best ideas from Spring and similar frameworks are incorporated in a stable format.

Configuration by exception

Large amounts of XML configuration is difficult to overview and maintain. Spring would not be easy to maintain for such a big project as EJBCA.

With Enterprise JavaBeans 3.0 minimal XML configuration is required and the same application could be used with many different application servers and databases without having to change the configuration to any great extent.

Easy migration path

Replacing XDoclet with Spring would require a large amount of code changes as where Enterprise JavaBeans 3.0 would require changes from comments to annotations with similar names. This similarity between XDoclet and Enterprise JavaBeans 3.0 will make the migration easier.

21

Page 30: A workflow based architechture for PKI

6 Enterprise JavaBeans 3.0 evaluation

This chapter describes the evaluation of the Enterprise JavaBeans 3.0 framework on several different application servers and databases in brief. Details of this evaluation is  available in appendix B. A reader that is not familiar with Java Enterprise Edition 5 should read appendix D or other literature on the subject to gain a full understanding of the evaluation.

6.1 Scope of evaluation and methodologyFrom the theoretical study of Spring 2.0 and Enterprise JavaBeans (EJB) 3.0, the EJB 3.0 standard looks like a superior candidate for the next generation of EJBCA. To evaluate this technology a small Enterprise application was created. The goal further down the road was to give recommendations for the migration of EJBCA, so the components in the evaluation EAR should represent components in EJBCA while still being simple enough for easy construction and testing.

The test application contains isolated and converted versions of some of EJBCA's Stateless Session Beans and an Entity Bean. The Entity Bean is used from Stateless Session Beans and the Stateless Session Beans are used from other Stateless Session Beans and Servlets and JavaServer Faces Managed Beans.

6.2 Java Persistence APIEJBCA uses the large character object database type to store Java objects. All the currently supported databases are able to store objects with a character representation of up to 1 GiB. Automatic mapping of these objects using annotation metadata was only working with the Java Persistence API provider Hibernate. If this provider was not used, explicit mapping of large character objects has to be specified for each database type and Entity Bean. The automatic mapping is not a fully specified feature of Java Persistence API so this will lock in the solution to Hibernate.

Simple Java types like integers were easy to convert to their Java Persistence API counterpart. Java Database Connectivity queries were also easily converted to helper methods with type safety.

22

Page 31: A workflow based architechture for PKI

6.3 Stateless Session BeansEach Stateless Session Bean has a common, a local and a remote interface. Some of the existing remote interfaces in EJBCA currently have nonserilizable method parameter objects. These methods can never have been used and was removed from the test application.

Transaction metadata was applied to the implementing Stateless Session Bean.The remote interface of an Stateless Session Bean is accessed through Java Naming and Directory Interface (JNDI). Different application servers uses different naming schemes to use the Stateless Session Bean remotely. Additional metadata has to be used in the @Stateless­annotation to be able to use the same look up pattern on different application servers.

6.4 JavaServer Faces 1.2Injection of a Stateless Session Bean's local interface with the @EJB­annotation in a JavaServer Faces Managed Bean was tested. The necessary libraries were available on all the application servers where the injection with JavaServer Faces 1.2 was working.

6.5 Test application structureThe project layout of the deployed test application is very similar to how a deployed Enterprise Application is packaged. This will hopefully make it simpler for anyone who have not worked on this specific project before, but are familiar with Java Enterprise Edition packaging to navigate the project.

6.6 Web ServicesThe preferred way to integrate with EJBCA is through the Web Service interface. In EJB 3.0, the server side Web Services can be backed by a Stateless Session Bean instead of Servlets. The Web Services Description Language (WSDL) file is generated automatically at runtime and will not change even though the implementation changes.

The implementing Stateless Session Bean has to use the @WebService­annotation with all the necessary metadata used for the WSDL generation.

6.7 ConclusionA summary of the EJB 3.0 support is shown in table 2 on page 24. Of the tested application servers, EJBCA can be expected to work in full with Geronimo 2.1.3, Glassfish v2 and JBoss 5.0.0.GA.

23

Page 32: A workflow based architechture for PKI

Application Server Enterprise JavaBeans 3.0 and JavaServer Faces 1.2 support

Geronimo 2.1.3 full with proprietary configuration

Glassfish v2 full

JBoss 4.2.3.GA not supported

JBoss 5.0.0.GA full

JOnAS 5.1­M2 work in progress

OC4J 10.1.3.4.0 not supported

WebLogic 10.3 Express works with proprietary configuration except remote EJB invocation

WebSphere 7.0 Express certified, but not working

Table 2: Summary of EJB 3.0 and JSF 1.2 support on different application servers

24

Page 33: A workflow based architechture for PKI

7 Final discussionIn this chapter the tested workflow management systems are dismissed as insufficient for use with EJBCA. A Java framework migration strategy for EJBCA is presented together with some suggestions for future work.

7.1 The lack of executable workflow solutionsThe first half of this report has shown that there is no good open source workflow management system that can be used for implementing Public Key Infrastructure work­flows with EJBCA at the time of evaluation.

jBPM under Seam in a Web ApplicationThe problems observed during testing could depend on two things as I see it:

• Technical issues due to the combination of Seam Pageflows and jBPM workflow in a Web Application. This might not have been properly tested before since I have not been able to find any explicit examples or documentation of this combination.

• Lack of proper documentation, causing me to misinterpret or miss important usage or configuration.

The resulting web application revealed signs of concurrency issues in the underlying framework and would therefore be useless in production.

Since jBPM workflow execution engine is complex to use, it would take another Java developer quite some time before he or she becomes productive. This is hardly acceptable in an open source community where many different developers improve the code according to their requirements. Having a simplified graphical representation that gives an overview of a workflow was much easier to interpret than trying to read a textual description. However, this impression was a bit inaccurate, since the complexity of the underlying implementation took far more time than regular code to get a grip of. Since the resulting web application does not work, there is not much need for deeper analysis or speculation on how much one would gain from using jBPM and Seam.

PageflowsAll of the Pageflows could easily have been modeled easier using JavaServer Faces. It is difficult to justify the extra requirements in the form of dependencies on jBPM, Seam and the JBoss Tools package for editing Pageflows in the Eclipse IDE for the Pageflows used in the proof of concept application.

25

Page 34: A workflow based architechture for PKI

ConclusionI would definitely recommend looking closer into this field in a couple of years and hope for improvements in the frameworks, documentation or both. If such a survey is undertaken, I would also recommend looking into the possibility of implementing a highly customizable pure Java­based solutions that can handle different workflows as plug­ins.

7.2 EJBCA migration strategyThis report has shown that Enterprise JavaBeans 3.0 is a good choice as the new Java framework for EJBCA, if the application server support is acceptable. EJBCA can, after a migration to Enterprise JavaBeans 3.0, be expected to work fully on Geronimo 2.1.3, Glassfish v2 and JBoss 5.0.0.GA.

I believe that Glassfish v2 would be the most suitable application server to use during the migration since it is not as forgiving as JBoss and comes with an EAR verification tool that can detect standard violations.

Since Sun's support for Java Standard Edition 5 ends 2009­10­30 [38], the new version of EJBCA only has to support Java Standard Edition 6 and later.There are no design decisions that are affected by the upcoming Java Enterprise Edition 6 standard (described in appendix D) as far as I can see. It only confirms that there will be an upgrade path from Enterprise JavaBeans 3.0 to Enterprise JavaBeans 3.1 and that the standard is getting more portable between application servers and makes life easier for developers.

A strategy to migrate EJBCA from Enterprise JavaBeans 2.0 to 3.0 was developed. Details of the migration strategy are described in appendix C.

7.3 Future workThere are some issues that have come to my attention during this work and in discussions with others.

Java Contexts and Dependency Injection

It is probably a good idea to avoid introducing any new web frameworks until Java Contexts and Dependency Injection described in Java Specification Request 299 is investigated further. A study of this standard should be initiated as soon as the migration is finished.

Future workflow management system evaluation

Workflow management systems have some potential benefits and should be reevaluated in the future.

26

Page 35: A workflow based architechture for PKI

8 AbbreviationsAPI Application programming interface 

BPEL Business Process Execution Language 

BPMN Business Process Management Notation 

CLOB Character Large Object 

EJB Enterprise JavaBeans 

EJBCA Enterprise JavaBeans Certificate Authority 

GNU GNU is Not Unix 

GPL GNU Public License 

HTML Hypertext Markup Language 

HTTP Hypertext Transfer Protocol 

IDE Integrated Development Environment 

J2EE Java 2 Platform Enterprise Edition 

JAR Java Archive 

JAX­RPC Java API for XML­based Remote Procedure Call 

JAX­WS Java API for XML­based Web Service 

jBPM A product/project name. Java/JBoss (?) Business Process Modeling

JDBC Java Database Connectivity 

JNDI Java Naming and Directory Interface 

JPDL jBPM Process Definition Language 

JTA Java Transaction API 

LDAP Lightweight Directory Access Protocol 

LGPL Lesser GNU Public License 

POJO Plain Old Java Object 

SOAP Simple Object Access Protocol 

SQL Structured Query Language 

UML 2.0 AD Unified Modeling Language 2.0 Activity Diagrams 

URL Uniform Resource Locator 

UTF Unicode Transformation Format 

WAR Web Application Archive 

27

Page 36: A workflow based architechture for PKI

WS­BPEL Web Service Business Process Execution Language 

WSDL Web Services Description Language 

XDPL XML Process Definition Language 

XML Extensible Markup Language 

28

Page 37: A workflow based architechture for PKI

References

[1] A.F. Vojdani, Tools for RealTime Business Integration and Collaboration, IEEE Transactions on power systems, vol. 18, no. 2, May 2003

[2] Bill Burke & Richard Monson­Haefel, Enterprise JavaBeans 3.0, 2006, O'Reilly, ISBN 9780596009786

[3] Budi Kurniawan, JavaServer Faces Programming, 2004, Tata Mcgraw Hill, ISBN 9780070586871

[4] Chris Schalk, Ed Burns, James Holmes, JavaServer Faces: The Complete Reference, 2007, McGraw­Hill, ISBN 9780072262407

[5] Christian Bauer and Gavin King, Java Persistence with Hibernate, 2007, Manning, ISBN 1932394885

[6] Craig Walls and Ryan Breidenbach, Spring in Action 2nd ed, 2007, Manning, ISBN 1933988134

[7] Debu Panda, Reza Rahman, Derek Lane, EJB 3 in Action, 2007, Manning, ISBN 1933988347

[8] Jim Farley, Practical JBoss Seam Projects, 2007, Apress, ISBN 9781590598634

[9] Joseph Faisal Nusairat, Beginning JBoss Seam, 2007, Dreamtech Press, ISBN 9788181286451

[10] IBM and SAP. WS­BPEL Extension for People – BPEL4People, http://download.boulder.ibm.com/ibmdl/pub/software/dw/specs/ws­bpel4people/BPEL4People_white_paper.pdf, Visited 2009­10­30

[11] Nada Kapidzic Cicovic, Extended Certificate Management System: Design and Protocols, Stockholm Univerity/Royal Institute of Technology, Department of Computer and System Sciences, 1997, http://daisy.dsv.su.se/fil/visa?id=26012, Visited 2010­01­29, ISBN 91­7153­617­5

[12] Workflow Patterns Initiative. On the Suitability of BPMN for Business Process Modelling, http://www.workflowpatterns.com/documentation/documents/BPMN­eval­BPM06.pdf, Visited 2009­10­30

[13] The Server Side. Java EE 6 Overview, http://www.theserverside.com/tt/articles/content/JavaEE6Overview/article.html, Visited 2009­02­25

[14] The Server Side. New Features In EJB 3.1 part 1, http://www.theserverside.com/tt/articles/content/NewFeaturesinEJB3­1/article.html, Visited 2009­01­16

29

Page 38: A workflow based architechture for PKI

[15] The Server Side. New Features In EJB 3.1 part 2, http://www.theserverside.com/tt/articles/content/NewFeaturesEJB31/article.html, Visited 2009­01­16

[16] The Server Side. New Features In EJB 3.1 part 3, http://www.theserverside.com/tt/articles/content/NewFeaturesEJB31­3/article.html, Visited 2009­01­16

[17] The Server Side. New Features In EJB 3.1 part 4, http://www.theserverside.com/tt/articles/content/NewFeaturesinEJB3­Part4/article.html, Visited 2009­01­16

[18] The Server Side. New Features In EJB 3.1 part 5, http://www.theserverside.com/tt/articles/content/NewFeaturesinEJB31­Part5/article.html, Visited 2009­01­16

[19] Sun Microsystems. Using Generics with Java Persistence, https://blueprints.dev.java.net/bpcatalog/ee5/persistence/generics.html, Visited 2009­07­01

[20] Sun Microsystems. Naming Conventions for Java Persistence, https://blueprints.dev.java.net/bpcatalog/ee5/persistence/namingconventions.html, Visited 2009­07­01

[21] Seth Ladd, Darren Davison, Steven Devijver, Colin Yates, Expert Spring MVC and Web Flow, 2006, Apress, ISBN 9781590595848

[22] Object Management Group. Process Modeling Notations and Workflow Patterns, http://www.bpmn.org/Documents/Notations_and_Workflow_Patterns.pdf, Visited 2010­01­29

[23] Internet Engineering Task Force. Internet X.509 Public Key Infrastructure Certificate and Certificate Revocation List (CRL) Profile, http://www.ietf.org/rfc/rfc3280.txt, Visited 2010­01­14

[24] Internet Engineering Task Force. Internet X.509 Public Key Infrastructure Certificate and Certificate Revocation List (CRL) Profile, http://www.ietf.org/rfc/rfc3280.txt, Visited 2010­01­14

[25] Internet Engineering Task Force. Privacy Enhancement for Internet Electronic  Mail Part I: Message Encryption and Authentication Procedures, http://www.ietf.org/rfc/rfc1421.txt, Visited 2010­01­29

[26] Internet Engineering Task Force. X.509 Internet Public Key Infrastructure Online Certificate Status Protocol, http://www.ietf.org/rfc/rfc2560.txt, Visited 2009­08­17

[27] Java Community Process. JSR­000220 Enterprise JavaBeans 3.0 (Final Release), http://jcp.org/aboutJava/communityprocess/final/jsr220/index.html, Visited 2009­08­17

[28] Object Management Group. Business Process Modeling Notation V1.1, http://www.omg.org/spec/BPMN/1.1/PDF, Visited 2010­01­14

[29] Object Mangement Group. Unified Modeling Language 2.0: Superstructure specification, http://www.omg.org/spec/UML/2.0/Superstructure/PDF/, Visited 2010­01­29

30

Page 39: A workflow based architechture for PKI

[30] Oracle. Getting started after installing Oracle Application Server, http://download.oracle.com/docs/cd/B25221_04/core.1013/b25209/getting.htm#i1025213, Visited 2009­06­25

[31] Oracle. OTN Forum: OC4J 11g tp replaced by 10.1.3.4, http://forums.oracle.com/forums/thread.jspa?messageID=2839467, Visited 2009­06­25

[32] Oracle. OTN Forum: Toplink and MySQL problem with BLOB, http://forums.oracle.com/forums/thread.jspa?messageID=2453919, Visited 2009­06­25

[33] Organization for the Advancement of Structured Information Standards. Web Services Business Process Execution Language Version 2.0, http://docs.oasis­open.org/wsbpel/2.0/OS/wsbpel­v2.0­OS.pdf, Visited 2010­01­29

[34] Red Hat Middleware. jBPM jPDL 3.2 User Guide, http://docs.jboss.com/jbpm/v3.2/userguide/pdf/jbpm­jpdl.pdf, Visited 2010­01­29

[35] Red Hat Middleware. JBPMBPELLicense, http://www.jboss.org/community/wiki/JBPMBPELLicense, Visited 2010­01­29

[36] RSA Security Inc. RSA Laboratories' Frequently Asked Questions About Today's  Cryptography, Version 4.1, http://www.rsasecurity.com/rsalabs/faq/files/rsalabs_faq41.pdf, Visited 2010­01­29

[37] Sun Microsystems. Core J2EE Patterns ­ Data Access Object, http://java.sun.com/blueprints/corej2eepatterns/Patterns/DataAccessObject.html, Visited 2010­01­14

[38] Sun Microsystems. Java SE & Java SE for Business Support Road Map, http://java.sun.com/products/archive/eol.policy.html, Visited 2009­07­01

[39] Sun Microsystems. JavaBeans concept, http://java.sun.com/docs/books/tutorial/javabeans/whatis/index.html, Visited 2009­10­25

[40] Sun Microsystems. Project Conventions for Enterprise Applications Early Access 1, http://java.sun.com/blueprints/code/projectconventions.html, Visited 2009­07­01

[41] The Server Side. Bonita v2 Series: Part One, http://www.theserverside.com/tt/articles/content/BonitaPart1/article.html, Visited 2009­06­25

[42] The Server Side. The State Of Workflow, http://www.theserverside.com/tt/articles/content/Workflow/article.html, Visited 2009­07­01

[43] XDoclet. XDoclet News, http://xdoclet.sourceforge.net/xdoclet/status.html, Visited 2009­06­15

[44] Workflow Management Coalition. XPDL, http://www.wfmc.org/xpdl.html, Visited 2010­01­14

[45] Workflow Management Coalition. XPDL Implementations, http://www.wfmc.org/xpdl­implementations.html, Visited 2009­06­12

31

Page 40: A workflow based architechture for PKI

Appendix A: Task­list application implementation details

This section will describe some of the implementation details of the task­list application for one of the implemented Public Key Infrastructure workflows to elaborate on problems with using jBPM and Seam's Pageflow for workflow management. This will  also show some of the complexity with using the framework. Later in this section the different approaches to modeling human tasks with Pageflow is exemplified and compared with regular JavaServer Faces.

Dependencies and RequirementsThis section describes dependencies to build and use the task­list application.

Server side componentsJBoss JPDL 3.3.0.GA: for workflow and Pageflow execution.

EJBCA External Registration Authority client library 3.8.0 (with custom mod): For communication with the Certificate Authority. This is a modified version to support certificate requests in the Certificate Request Message Format.

JBoss Seam 2.1.0.SP1: Framework used for injection, web and Pageflow and jBPM integration.

Hibernate 3.0: Used for persistence.

Apache Commons Configuration 1.5: For reading configuration files.

Apache Log4J 1.2.7: For logging from static methods.

BouncyCastle Security Provider 1.41b04: Crypto library.

EJBCA Utils 3.8.0: Used by  External Registration Authority Client Library

EJBCA Online Certificate Status Protocol Client library 3.8.0: For checking validity of administrators certificates.

A properly configured EJBCA installation with a running External Registration Authority Service.

An additional JBoss application server running the web application in it is embedded Tomcat server. The build uses libraries from the JBoss installation but is portable to a simple Servlet container.

32

Page 41: A workflow based architechture for PKI

Client side componentsA browser with JavaScript enabled. Mozilla Firefox 3.x is required to be able to use Workflow­3 (described on page 15), since client generation of asymmetric keys in browsers are vendor specific. It is not important for this evaluation how the certificate signing request is generated, since we only want to know how client­side generated keys affects the workflow compared with server­side generated keys. Support for additional browsers or a custom client could easily be added later.

Structure and special filesThe task­list application is packaged as web archive (WAR) web application called “extragui.war”. The used framework requires the following special files to exist:

• extragui.war/WEB­INF/pages.xml: Used for login and security declarations.

• extragui.war/WEB­INF/components.xml: Declaration of Java objects used in Expression Language tags and Pageflows.

• extragui.war/WEB­INF/pages.xml: Configuration of coupling between URLs and a Pageflows.

Basic functionalityThe goal for the first version of the task­list application was to create a simple task­list and an implementation of Workflow­2 (described on page 15). The task­list is accessed by an administrator with a valid X509 certificate [24]. Mappings of roles to certificates are stored in a configuration file.

By declaring a page as login­page, Seam will run an Authenticator each time this page is accessed. Any page declared to require login will redirect the user to this page. Using

<page view-id="/secure/*" login-required="true"/>

<page view-id="/login.jsp" action="#{identity.login}">

<navigation>

<rule if="#{!s:hasRole('public')}">

<redirect view-id="/secure/taskList.jsp"/>

</rule>

</navigation>

</page>

in extragui.war/WEB­INF/pages.xml and

<security:identity authenticate-method="#{authenticator.authenticate}"/>

in extragui.war/WEB­INF/components.xml will make sure that anyone accessing any page under /secure/ will be redirected to the login. At the login, a custom authenticator will validate the user's X509 certificate with the Online Certificate Status Protocol [26] and login the user with the correct roles. The user is then redirected to the tasklist if not 

33

Page 42: A workflow based architechture for PKI

given the role 'public'.  The user experiences that accessing the web­application will instantly display the task list in the user's browser.

Creation of new processes is done programmatically by manipulating an injected org.jboss.seam.bpm.BusinessProcess object, since the Seam annotation for this does not work for unknown reasons. Tasks are started or resumed by using the Seam org.jboss.seam.annotations.bpm.StartTask and BeginTask annotations. To enable a user to abort a business process in a single request (one click in the task­list web user interface), annotations and code have to be combined:

@StartTask @EndTask

public void removeProcess() {

ProcessInstance.instance().end();

}

or

@BeginTask @EndTask

public void removeProcessWithStartedTask() {

ProcessInstance.instance().end();

}

Without using the annotations, the BusinessProcessContext will not be available and the ProcessInstance will be unaccessible.

Reserving or yielding a task is done using the built in Seam methods assignToCurrentActor() and unassign(), from  org.jboss.seam.bpm.PooledTask.

Priority of tasks can be changed by directly manipulating the priority­fields of the tasks, that are exposed to the user as shown in illustration 6 on page 18.

To simplify the implementation, the name of any human task is restricted to be the same as the name of the corresponding Pageflow. The first task of Workflow­2  (described on page 15) would look like this in JDPL:

<task-node name="registerEntity">

<task name="registerEntity"

...

</task>

...

</task-node>

This task definition will, when executed, initialize the Pageflow registerEntity.jdpl.xml:

<pageflow-definition ... name="registerEntity">

<start-page view-id="/secure/registerEntity.jsp"

...

</start-page>

...

</pageflow-definition>

34

Page 43: A workflow based architechture for PKI

Seam is made aware of the Pageflow by defining it in the Seam configuration file extragui.war/WEB­INF/components.xml:

<bpm:jbpm>

<bpm:process-definitions>

<value>process-definitions/enrollEntity/enrollEntity.jpdl.xml</value>

...

</bpm:process-definitions>

<bpm:pageflow-definitions>

<value>pageflows/registerEntity.jpdl.xml</value>

...

</bpm:pageflow-definitions>

</bpm:jbpm>

The Pageflow is coupled to a web page in the Seam configuration file extragui.war/WEB­INF/pages.xml: <page view-id="/secure/registerEntity.jsp">

<begin-conversation join="true" pageflow="registerEntity" nested="false"/>

</page>

When a user clicks on a task in the task­list the name of the task is used to resolve which page to send the user to. Since the name of the initial page of each Pageflow is set to “/secure/name­of­the­task.jsp” Seam will be able to find the correct Pageflow to use from the extragui.war/WEB­INF/pages.xml configuration file.

Combining Seam Pageflow and jBPMThere exists several different contexts that can store references to objects in the Seam framework such as the BusinessProcessContext, ApplicationContext, EventContext and ExecutionContext.

There are three ways of accessing a process or task in the current Seam context.

• Injection using the In annotation which requires the variable to be present in the current context of the Seam component:

@org.jboss.seam.annotations.In

private org.jbpm.taskmgmt.exe.TaskInstance taskInstance;

This requires that org.jboss.seam.bpm.TaskInstance object is available for all uses of the Seam component where this injection is declared. This might be a problem if a component is used from different Seam contexts.

• Using the Seam jBPM wrapper classes that return the org.jbpm.taskmgmt.exe.TaskInstance object in this org.jboss.seam.contexts.EventContext's org.jbpm.JbpmContext with the id of the task found in the current org.jboss.seam.contexts.ConversationContext:

35

Page 44: A workflow based architechture for PKI

org.jbpm.taskmgmt.exe.TaskInstance taskInstance = org.jboss.seam.bpm.TaskInstance.instance();

This requires that the wrapper classes in org.jboss.seam.bpm has been properly initialized, which is not always possible.

• Programmatically using the org.jbpm.graph.exe.ProcessInstance from the ApplicationContext. All existing org.jbpm.taskmgmt.exe.TaskInstances can be accessed through processInstance.getTaskMgmtInstance().getTaskInstances(). Since this returns the list of all tasks, iteration over this list is required to find the task of interest.

Direct usage of the jBPM context like JbpmConfiguration.getInstance().getCurrentJbpmContext() does not work, not even through the Seam wrapper component org.jboss.seam.bpm.ManagedJbpmContext. 

Non­String Business Process Variables requires special attention. To increase compatibility between different databases each non­String Business Process Variable is broken down to a number of blocks of bytes called a org.jbpm.bytes.ByteArray that is easier to store. Unfortunately the reverse conversion is not done when a task is fetched back from persistence, so a workaround is needed to restore Business Process Variables before they are used in a task. This is especially problematic for human tasks using a Pageflow or mail tasks, where the first interaction with a variable is a getter expression. Instead of using Expression Language access of the form #{processVariableName} we have to resort to reinitializing the variables each time the task is started programmatically or using a helper method like #{helperComponent.processVariables['processVariableName'].value}. The helper method public Map<String, Object> getProcessVariables() would loop through all Business Process Variables, restore the original value for any non­String Business Process Variables and return a Map with references to the corrected Business Process Variables.

Accessing the Business Process Variables can be just as complicated as accessing tasks or processes. There are several ways of accessing the same variables. As an example, an ActionHandler can be invoked during a transition between two states. Setting a value of a Business Process Variable in an ActionHandler can be done in the following ways: //Usable later in the process definition, from other tasks and actions:

Contexts.getBusinessProcessContext().set(BPV_MESSAGEID, messageId);

//Usable later from other actions (executionContext is Action-specific):

executionContext.setVariable(BPV_MESSAGEID, messageId);

//Usable later from other tasks:

org.jbpm.taskmgmt.exe.TaskInstance taskInstance = TaskInstance.instance();

taskInstance.setVariable(BPV_MESSAGEID, messageId);

//Usable later in the process definition and from other tasks:

org.jbpm.graph.exe.ProcessInstance processInstance = ProcessInstance.instance();

processInstance.getContextInstance().setVariable(BPV_MESSAGEID, messageId);

Only the first way, by using the BusinessProcessContext directly, works in the ActionHandler for accessing the variable later from all possible scenarios like 

36

Page 45: A workflow based architechture for PKI

MailTasks, other ActionHandlers or Pageflow tasks. However, the other methods work in their limited context. As mentioned in the beginning of this section, a reference to a Process and Task can also be injected instead of using the instance()­pattern.

The scheduler service does not work properly when mixing Pageflow with regular jBPM workflow. An easy way to recreate this problem is to create a reminder for a task and then end the task from the Pageflow with  <page name="showIncompleteTasks" view-id="/secure/taskList.jsp">

<end-task/>

<redirect/>

</page>

This will prevent the scheduler's timer in the jBPM execution engine from being canceled properly. My theory is that the Pageflow hides the original JbpmContext (according to the source code, it looks like the creation of a new context pushes the old context on a stack), which makes the original scheduler service unavailable, but I have not been able to confirm this. It might be possible to work around this by ending the task in some other way.

A similar problem occurs when a task is used with the property async="true". Without asynchronous operations the user ending the task has to wait for any automated node or decision between the current task and the next task. A typical use of this property is shown in illustration 7 on page 38. The task waitForResultDecision executes a loop that regularly polls the incoming message queue for a response from the Certificate Authority and uses the property async="true". Without asynchronous execution the user approving the action (ending approveEntity­task) would have to wait for the Certificate Authority to reply and the workflow to reach the next task (fetchResult) before the web­browser returned to the tasklist. 

Unfortunately, the use of the property async="true" to end a task from a Pageflow causes an error about jBPM not to be able to locate the 'message' service used for asynchronous operations. 

By replacing the waitForResultDecision Decision with the waitForTimerEvent Task assigned to a new “system” actor, the problem with asynchronicity can be avoided. A special timer Servlet that runs in a Seam context was created and the Servlet executes all pending tasks assigned to the “system” actor at regular intervals. Illustration 8 on page 38 shows what the modified process looks like.

The described workaround for asynchronous tasks revealed another problem. Simultaneous operations on a business process cause a wide range of different problems. For example, tasks might disappear or the entire process definition might disappear from Seam's contexts so no new workflow processes can be started.

37

Page 46: A workflow based architechture for PKI

The revealed problem was not related to the timer Servlet implementation, since manually starting two processes within a small time­interval often leads to the exact same problems. Due to the spontaneous nature of these errors and since they have only been observed during concurrent operations, this leads me to believe that they are related to lack of synchronization in either Seam or jBPM, but the exact cause has not been proven.

PageFlowsPageflows are used for human tasks in the workflow. The same functionality can some­times be modeled in several different ways.

The human task used to exemplify this is the “registerEntity” task. A Registration Authority registrator enters information about an entity (end user or server) in a web page. The administrator can switch between several templates that can be used for different type of entities. The entered information is later used in the workflow to create a certificate request.

The Pageflow for registration of an entity can for example be modeled with Pageflow as shown in both illustration 10 and 9 on page 39 or implemented using standard JavaServer Faces.

38

Illustration 8: Screenshot of a workflow with the asynchronous operation workaround

Illustration 7: Screenshot of a  workflow with an asynchronous waitdecision

Page 47: A workflow based architechture for PKI

In the version shown in illustration 9, the registrator is first presented with a web page to select template and then a second web page where the entity fields are filled in. Changing template sends the registrator back to the first page and a reset reloads the web page to fill out. Validation of the submit is not shown to the user unless it fails.

In the version shown in illustration 10, the registrator is presented with a single web page where the required values for the default entity template can be entered or the template changed. A change of template reloads the web page with a different set of fields to fill out. A reset is the same as changing template to the default. Validation of the submission is not shown to the registrator unless it fails.

Using JavaServer Faces, a “h:form” tag and “h:selectOneMenu” tag (drop down box) could be used to select the template. A second “h:form” and “h:dataTable” could be used to render the available fields to fill out. Custom validators could be used for input validation and displaying error­messages if the submit failed.

I am not convinced that using Pageflow is motivated for such simple human tasks as the ones that are used in the different implemented workflows. I find regular JavaServer Faces less complex and it requires no extra tools than the Java Enterprise Edition development version of the Eclipse IDE and no extra libraries to deploy for any of the working application servers listed in section 7.2.

39

Illustration 9: Screenshot of the Pageflow registerEntity

Illustration 10: Screenshot of the Pageflow registerEntityAlternative

Page 48: A workflow based architechture for PKI

Appendix B: Enterprise JavaBeans 3.0 evaluation details

This chapter describes the details of the Enterprise JavaBeans 3.0 framework evaluation. A reader that is not familiar with Java Enterprise Edition 5 should read appendix D or other literature on the subject to gain a full understanding of the evaluation.

Scope of evaluation and methodologyFrom the theoretical study of Spring 2.0 and Enterprise JavaBeans (EJB) 3.0, the EJB 3.0 standard looks like a superior candidate for the next generation of EJBCA. To evaluate this technology a small Enterprise Application (referred to as EAR or ejb3probe from now) was created. The goal further down the road was to give recommendations for the migration of EJBCA, so the components in the evaluation EAR should represent components in EJBCA while still being simple enough for easy construction and testing.

Specification of the test applicationSuitable components to include in the first round of tests are:

• An Entity Bean that should:

• use Java Persistence API instead of EJB 2.1 Container­Managed Persistence.

• store a large object for portability testing of different databases.

• A Stateless Session Bean for accessing the Entity Bean.

• Another Stateless Session Bean providing a service.

• A bundled Web Applications (referred to as WAR from now), containing:

• a Servlet that can access a Stateless Session Bean locally in the Servlet initialization.

• a Servlet that can access a Stateless Session Bean locally from a Servlet request.

• a Servlet that can access a Stateless Session Bean remotely from a Servlet request.

40

Page 49: A workflow based architechture for PKI

• a simple web page for invoking the Servlets.

One of the main points of testing this is also to see how Java Persistence API Entity Beans can be used as POJOs and how this will affect the existing code.

Every Stateless Session Bean in EJBCA has more than one dependency on other Stateless Session Beans or Entity Beans, but one Stateless Session Bean stands out as an easy point of attack:

LocalAuthenticationSessionBean

The LocalAuthenticationSessionBean is a Stateless Session Bean with a local interface. This Stateless Session Bean references LogSessionBean, LocalUserAdminSessionBean and the Entity Bean UserDataBean. The Stateless Session Bean is very small with a total of only 267 lines of code including comments and imports. 

It is easy to create a simplified LogSessionBean implementation using a simple console logger. The 3 methods that are used in LocalUserAdminSessionBean can also be implemented in a simplified way by ignoring any authorization checks. 

The UserDataBean contains persistence mappings of ints, longs, searchable strings and a non­searchable string. 

Outline of solutionThe test application will be built against a compiled version of EJBCA, so all non­Java Enterprise Edition classes that the application might depend on are present. These classes are also included as a library in the test application.

Currently all Stateless Session Beans extend BaseSessionBean for marginally simpler logging and reference to a EJB 2.x ServiceLocator­pattern helper. It also stores the current session context. None of these services are required any longer so the BaseSessionBean will not be used. EJBCA does not use any Stateful Session Beans or Message Driven Beans.

By minimizing the number of changes, it is easier to distinguish between required and optional migration work and avoid introducing new bugs.

Piece­by­piece conversion of Stateless Session BeansThe LocalAuthenticationSessionBean is only named so for historic reasons and exposes both remote and local methods. It will be renamed AuthenticationSessionBean.

Since it has both remotely and locally exposed methods, the following interfaces will be used: 

• AuthenticationSession is the interface for common methods.

• AuthenticationSessionLocal extends AuthenticationSession and contains methods that are only exposed locally. The interface is annotated with @Local.

41

Page 50: A workflow based architechture for PKI

• AuthenticationSessionRemote extends AuthenticationSession and contains methods that are only exposed remotely. The interface is annotated with @Remote.

The AuthenticationSessionBean is annotated with @TransactionAttribute(TransactionAttributeType. ...) on both the class and method level if required.

For the other Stateless Session Beans we only need to expose a local interface since these beans are invoked locally from the AuthenticationSessionBean. To save effort, the interfaces are copied from the XDoclet generated EJB 2.1 interfaces in an EJBCA build and then modified.

The Stateless Session Beans that AuthenticationSessionBean depends on must also be converted. To avoid conversion of every single Stateless Session Bean in EJBCA, simplified implementations are created for these dependencies.

Entity Bean conversionUserDataVO is a value object used to represent the old UserDataBean in for example the graphical user interface. It would be nice to be able to replace this value object with the Entity Bean UserData that could be used for both persistence and as a value object. But since the UserDataVO object is used from many of the EJBCA classes referenced by the test application, a simple converter will be used instead so the referenced classes do not have to be changed for this simple test. UserData will however still be used in converted Stateless Session Beans.

NamedQueries vs. Helper methods vs. Data Access Object

Entity Beans can have something called Named Queries, which are predefined database queries. For our UserData Entity Bean they would look like this:

@NamedQueries({

@NamedQuery(name="findBySubjectDNAndCAId", query="from UserData a WHERE a.subjectDN=:subjectDN AND a.caId=:caId"),

@NamedQuery(name=...

...

})

And used in the following way:

Query query = entityManager.createNamedQuery("findBySubjectDNAndCAId");

query.setParameter("subjectDN", subjectDN);

query.setParameter("caId", caId);

UserData userData = (UserData) query.getSingleResult();

No parameter type validation is performed and it requires about 4 lines of code for a simple search. Another thing to take into consideration is that you have to know how the query is defined in order to be able to set the right parameters. Therefore it makes more sense to implement a helper method:

42

Page 51: A workflow based architechture for PKI

public static UserData findBySubjectDNAndCAId(EntityManager entityManager, String subjectDN, int caId) {

Query query = entityManager.createQuery("from UserData a WHERE a.subjectDN=:subjectDN AND a.caId=:caId");

query.setParameter("subjectDN", subjectDN);

query.setParameter("caId", caId);

return (UserData) query.getSingleResult();

}

The query is right next to the parameter names and it is obvious of what type the arguments should be (String and int) and proper JavaDoc can be added. The method could be used both from a Stateless Session Bean or a standalone application: UserData.findBySubjectDNAndCAId(entityManager, subjectDn, caId);

The simplicity is striking and the query is still confined to the UserData class so all object­relational mapping only exists in one place.The book EJB 3 in Action [7] suggests the use of an Entity Access Object pattern that is an updated version of the Data Access Object pattern [37] for the Java Persistence API. The goal of using Entity Access Object is to remove all dependencies from the business logic layer of an application on the persistence implementation. This is accomplished by adding a new persistence implementation object that is accessed through a new interface, where the interface has no dependency on the persistence framework. In my opinion, the added complexity of adding an additional object and interface for each Entity Bean to maybe be able to change persistence technology easier in the future does not motivate the use of this pattern right now.

Storing large amounts of data in a single column

All databases work a bit differently. Basic mapping of integers and other simple Java­types to the databases native column types works well on all databases. However, for large binary objects and character columns the mappings differ more. EJBCA stores any large object or binary data as a string. This can be an XML­serialized object or base­64 encoded binary data. In table 3 on page 44 the currently supported databases and their limits for large text­columns are shown.

43

Page 52: A workflow based architechture for PKI

Database Data type name Size limit

DB2 CLOB 2 GiB

Derby CLOB 2 GiB – 1 byte

Hypersonic VARCHAR N/A, has a 2 GiB table limit.

Informix TEXT 2 GiB

Mysql LONGTEXT 4 GiB

MS SQL 2k TEXT 2 GiB – 1 byte

Oracle 8i & 9i CLOB 4 GiB

PostgreSQL TEXT 1 GiB

SapDB LONG  2 GiB

Sybase CLOB 4 GiB

Table 3: Properties of large text­columns on different databases

According to the JavaDoc of @javax.persistence.Column, the length­property can be specified on string valued columns. The idea here would be to try to specify a common length (1 GiB) that would work for all the databases above except the non­production database Hypersonic and let the Java Persistence API do the required mapping instead of specifying it manually. Knowing this limit is useful even without using the automated mapping, since no object should be allowed to grow larger than this. For EJBCA, 1 GiB of space can really be considered unlimited, since the largest objects stored in the database are Certificate Revocation Lists [23] with a size of about 30 MiB for 500 000 revoked certificates.

Practical evaluation using JBoss Application Server 4.2.3.GA and 5.0.0.GA shows that the Hibernate Java Persistence API provider handles mapping when @Lob and @Column are combined without any problems. However, using Glassfish v2 and the TopLink Java Persistence API provider this fails. On the Derby database a @Lob annotated string maps to the column type “CLOB(64000)” that can hold 64 KB, which is much less than the required 30 MiB. According to a forum post [32] using the length­parameter for large datatypes is not supported in TopLink as the practical tests has shown. This means we have to either use separate XML mapping corresponding to the annotation @Column(columnDefinition=”...”) or bundle Hibernate with the application. 

The drawback of bundling Hibernate is that we might not follow the correct interpretation of the standard and have a dependency on a specific provider. Mapping 

44

Page 53: A workflow based architechture for PKI

each Entity Bean however requires a large amount of XML and we lose some of the simplicity of coding entity beans. A typical mapping file for Derby would look like this:

<?xml version="1.0" encoding="UTF-8"?>

<entity-mappings version="1.0" xmlns="http://java.sun.com/xml/ns/persistence/orm"

xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"

xsi:schemaLocation="http://java.sun.com/xml/ns/persistence/orm

http://java.sun.com/xml/ns/persistence/orm_1_0.xsd">

<entity class="org.ejbca.development.TestData" access="PROPERTY">

<table name="TestData"/>

<attributes>

<id name="id">

<column name="id" nullable="false"/>

</id>

<basic name="extendedInformationData">

<column name="extendedInformationData" column-definition="CLOB(1073741823)"/>

<lob/>

</basic>

</attributes>

</entity>

</entity-mappings>

The <entity>­tag is repeated for every new class and column­definitions have to be specified for each database type. Since most of the metadata is defined in the actual Entity Bean, it is only necessary to override the large types. A typical mapping file template would then look like this:<?xml version="1.0" encoding="UTF-8"?>

<entity-mappings ...>

...

<column name="extendedInformationData" column-definition="@database.lobcoldef@"/>

...

</entity-mappings>

The column­definition can be injected during the build, based on the configured data­base in a property file in the test application. So the database­type has to be configured and we have to keep a mapping­file for all supported databases.

Bundling Hibernate is as simple as adding 11 libraries to the EAR's “lib”­directory and explicitly specifying the provider in the Java Persistence API configuration file:<?xml version="1.0" encoding="UTF-8"?>

<persistence version="1.0"

xmlns="http://java.sun.com/xml/ns/persistence"

xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"

xsi:schemaLocation="http://java.sun.com/xml/ns/persistence http://java.sun.com/xml/ns/persistence/persistence_1_0.xsd"

>

45

Page 54: A workflow based architechture for PKI

<persistence-unit name="ejbca" transaction-type="JTA">

<provider>org.hibernate.ejb.HibernatePersistence</provider>

        ...

</persistence-unit>

</persistence>

With Hibernate the extendedInformationData column is created as a “CLOB(1073741823)” (that can hold 1 GiB – 1 byte) for Derby, without the application being explicitly configured for Derby and any need for explicit object relational mapping.

Conclusion: The trade­off is between configuring manual support for every supported database or using a not fully specified feature of Java Persistence API locking in the solution to the Hibernate framework.

Deploying the test applicationIn the first test iteration the goal was to deploy the Enterprise JavaBeans, try out EJB­injection and see how Java Persistence API was handled by the different providers bundled with different application servers.

Initial tests showed that the location of the Java Persistence API configuration file persistence.xml mattered. In the deployed test application persistence.xml was kept in ejb3probe.ear/lib/ejbprobe­entity.jar/META­INF/persistence.xml. No SQL dialect was specified whenever Hibernate was used as the persistence provider.

No Class­Path was specified in the EAR's META­INF configuration file.

Glassfish v2 with Derby

GlassFish v2 uses TopLink as Java Persistence API provider. This combination works flawlessly with both the bundled Hibernate provider or with the default TopLink provider together with explicit object­relation mapping for large columns.

JBoss Application Server 4.2.3.GA with MySQL

EJB injection in Servlets does not work with JBoss Application Server 4.2.3.GA. JBoss Application Server 4.2.3.GA with MySQL seems to be unable to handle Java Persistence API properly. Since this application server is not Java Enterprise Edition 5 certified, no more effort was spent on trying to get this working.

JBoss Application Server 5.0.0.GA with MySQL

EJB injection in Servlets works for JBoss Application Server 5.0.0.GA and persistence with MySQL works flawlessly with the native Hibernate Java Persistence API provider and without using explicit object­relational mapping.

46

Page 55: A workflow based architechture for PKI

JOnAS 5.1.0­M2 with MySQL

The final release of JOnAS 5.1.0 will be Java Enterprise Edition 5 certified. The tested version has a bit random and unpredictable behavior.

EJB injection in Servlets works. The default Java Persistence API provider is Hibernate, so nothing special has to be done to deploy the test­application and create the tables when it was tested with MySQL.

The JOnAS application server is currently not officially supported by EJBCA.

Oracle WebLogic Server 10.3 with Oracle 10

Oracle WebLogic Server 10.3 deploys the ejb3probe application, and complains about non­serializable method parameters on remote interfaces. This is a valid error and should be corrected in EJBCA.

Weblogic 10.3 uses Oracle Kodo (based on the OpenJPA project) as Java Persistence API provider. Trying to use the persistence as for the previously tested application servers does not work very well, even with Kodo specific Java Persistence API configuration, manual pre­creation of the database table and explicit object­relational mapping.

Bundling the Hibernate Java Persistence API provider works, as long as

<property name="hibernate.transaction.manager_lookup_class" value="org.hibernate.transaction.WeblogicTransactionManagerLookup" />

is specified in the Java Persistence API configuration.

Oracle OC4J 10.1.3.4.0 with Oracle 10

Even though OC4J 10.1.3.4.0 includes the necessary libraries to build an EJB 3.0 application, the test application could not locate the annotated Stateless Session Beans for EJB injection. According to the getting started guide [30] “Oracle Containers for J2EE (OC4J) is a complete Java 2 Enterprise Edition environment.” which means that it cannot be expected to work with EJB 3.0. According to Steve Button at Oracle the OC4J 11g release that would support Java Enterprise Edition 5 has been discontinued, since Oracle has acquired Weblogic from BEA [31].

WebSphere 7.0 Express with DB2

EJB injection does not work for WebSphere 7.0. The default Java Persistence API provider OpenJPA is not able to handle container managed transactions and requires explicit object relational mapping configuration for the proper creation of large columns.

Bundling Hibernate gets rid of the transaction­related errors, but does not create large object columns of the specified size as with other databases and application servers without explicit object relational mapping configuration. By successfully running the 

47

Page 56: A workflow based architechture for PKI

test application on JBoss 5.0.0.GA with DB2 it is clear that the @Column annotation's attribute “length” is somehow filtered by WebSphere.

After spending a long time reading documentation and searching for a solution to the problems mentioned above, I conclude that the Java Enterprise Edition 5 support in WebSphere 7.0 is incomplete, difficult to configure right or poorly documented. Websphere 7.0 will therefore be excluded from further testing. 

Apache Geronimo 2.1.3 with PostgreSQL

Apache Geronimo 2.1.3 is Java Enterprise Edition 5 certified.

Geronimo requires application server specific configuration in ejb3probe.ear/META­INF/geronimo­application.xml to make the configured DataSource available to the test application:

<?xml version="1.0" encoding="UTF-8"?>

<app:application

xmlns:dep="http://geronimo.apache.org/xml/ns/deployment-1.2"

xmlns:app="http://geronimo.apache.org/xml/ns/j2ee/application-2.0">

<dep:environment>

<dep:dependencies>

<dep:dependency>

<dep:groupId>console.dbpool</dep:groupId>

<dep:artifactId>EjbcaDS</dep:artifactId>

<dep:version>1.0</dep:version>

<dep:type>rar</dep:type>

</dep:dependency>

</dep:dependencies>

</dep:environment>

</app:application>

EJB injection in Servlets works, but the default Java Persistece API provider OpenJPA is unable to create the required database tables in PostgreSQL.

Bundling Hibernate as Java Persistence API provider currently requires a custom implementation for looking up the Geronimo Java Transaction API Transaction Manager. With the custom lookup, persistence works flawlessly and large objects were correctly mapped to “text”­column type in the database.

Test summary

Table 4 lists the Java Persistence API support on the tested application servers. Bundling or using the native Hibernate implementation will allow the creation of complete database schemes using only annotation metadata without specifying the data­base type in the application. All the server administrator would have to know is the name of the DataSource and where the application server resides on the file system.

48

Page 57: A workflow based architechture for PKI

Application server Native Java Persistence API

Comment

Geronimo 2.1.3 OpenJPA Works with bundled Hibernate and some extra configuration.

Glassfish v2 TopLink Works with explicit object­relational mapping or Hibernate.

JBoss 4.2.3.GA Hibernate Works.

JBoss 5.0.0.GA Hibernate Works.

JOnAS 5.1­M2 Hibernate Works.

OC4J 10.1.3.4.0 TopLink To unstable to test. Discontinued application.

WebLogic 10.3 Exp Kodo Works with bundled Hibernate. Call by value.

WebSphere 7.0 Exp OpenJPA Works with bundled Hibernate and explicit object relational mapping.

Table 4: Java Persistence API support on different application servers

The platforms that work with the current layout are the following: JBoss 5.0.0.GA, JOnAS 5.1­M2, Geronimo 2.1.3, Glassfish v2 and Weblogic 10.3. The only application specific configuration (except to bundle or use native Hibernate) is the declaration of the DataSource on Geronimo. Weblogic's proprietary call­by­value configuration was ignored and Weblogic users can expect slightly worse performance than with the other application servers.

Using JavaServer Faces 1.2The goals for the tests described in this section are to add a JavaServer Faces presentation layer and:

• Display a text and a value from JavaServer Faces Managed Bean through an injected EJB that performs a database fetch.

• Invoke an action method on the JavaServer Faces Managed Bean through the Expression Language.

• Verify if there is a need to bundle JavaServer Faces libraries.

The JavaServer Faces Managed Bean must be declared in ejb3probe.ear/ejb3probe.war/WEB­INF/faces­config.xml:

49

Page 58: A workflow based architechture for PKI

<managed-bean>

<managed-bean-name>testManagedBean</managed-bean-name>

<managed-bean-class>org.ejbca.development.TestManagedBean</managed-bean-class>

<managed-bean-scope>request</managed-bean-scope>

</managed-bean>

Working application servers

JavaServer Faces Managed Bean invocation works flawlessly for Geronimo 2.1.3 with PostgreSQL, Glassfish v2 with Derby and JBoss 5.0.0.GA with MySQL for both lookup and EJB injection. There is no need to bundle JavaServer Faces­libraries.

JOnAS 5.1.0­M2 with MySQL

The JOnAS 5.1.0­M2 application server tries to access a local home interface during EJB injection. Since there are no such home interfaces in EJB 3.0 this fails. The conclusion is that it is noticeable that JOnAS is not yet Java Enterprise Edition 5 certified and no further effort was spent on this application server.

WebLogic 10.3 with Oracle

JavaServer Faces is not deployed by default on WebLogic, but the library to deploy it is bundled with the application server and can be deployed using the application server's web based user interface.

To use this library from the test application, Weblogic­specific configuration is needed in ejb3probe.ear/ejb3probe.war/WEB­INF/weblogic.xml:

<?xml version="1.0" encoding="UTF-8"?>

<weblogic-web-app>

<library-ref>

<library-name>jsf</library-name>

<specification-version>1.2</specification-version>

<implementation-version>1.2</implementation-version>

<exact-match>false</exact-match>

</library-ref>

</weblogic-web-app>

When this is added the application EJB injection works flawlessly.

Test summary

Table 5 shows the JavaServer Faces support on the tested application servers.

50

Page 59: A workflow based architechture for PKI

Application server JavaServer Faces support

Geronimo 2.1.3 No need to bundle libraries. Can use EJB injection.

Glassfish v2 No need to bundle libraries. Can use EJB injection.

JBoss 4.2.3.GA Not tested.

JBoss 5.0.0.GA No need to bundle libraries. Can use EJB injection.

JOnAS 5.1­M2 Incomplete support and/or documentation.

OC4J 10.1.3.4.0 Not tested.

WebLogic 10.3 Exp No need to bundle libraries. Can use EJB injection. Requires proprietary configuration.

WebSphere 7.0 Exp Not tested.

Table 5: JavaServer Faces support on different application servers

Deployed test application structureThe project layout of the deployed test application is very simple where the files for each module are clearly separated. This will hopefully make it simpler for anyone who have not worked on this specific project before, but are familiar with Java Enterprise Edition packaging. I have not been able to find any recommendations for Java Enterprise Edition 5 projects, like there are for Java 2 Platform Enterprise Edition projects [40].

It would also be really easy to extend the current project with additional build­script targets that would build a sub­set of the modules or a tool that depended on some of the modules.

The project structure is shown in illustration 11 and the packaging of the ejb3probe application is shown in illustration 12 on page 52.

51

Page 60: A workflow based architechture for PKI

52

Illustration 11: ejb3probe project structure

Illustration 12: ejb3probe EAR structure

Page 61: A workflow based architechture for PKI

Adding Web ServicesSo far we have only looked at the inner workings of the test application, but interfaces to the outside world is just as important for those that integrate with EJBCA. The preferred way to integrate with EJBCA is through the Web Service interface.

Creating Web Services with standard Java annotations has been possible since Java Standard Edition 5.0 using the Java API for XML Web Services and the current EJBCA implementation relies on this feature backed by Servlets. In EJB 3.0, the server side Web Services can be backed by a Stateless Session Bean instead. The main benefit is that all the necessary XML files like the Web Services Description Language (WSDL) file is generated automatically at runtime. This makes configuring and making changes to the Web Services much easier. The code generation on the client side can be kept intact for those that rely on the current EJBCA Web Services client library.

The tool com.sun.tools.ws.ant.WsGen that ships with the Java Development Kit and can be used for generation of the WSDL file from the @WebService­annotated Stateless Session Bean. This generated WSDL file can then be used to generate client classes without requiring the Web Services to be deployed.

The ejb3probe application was modified to use a mock implementation of the methods from the EJBCA Web Service interface. The interface was annotated with @WebService.@WebService

public interface Ejb3ProbeWs {

...

public abstract boolean isAuthorized(String resource) throws EjbcaException;

...

}

The implementing Stateless Session Bean is also annotated with Web Services properties:@Stateless

@WebService(name="EjbcaWS", serviceName="EjbcaWSService", targetNamespace="http://ws.protocol.core.ejbca.org/", portName="EjbcaWSService")

public class Ejb3ProbeWsSessionBean implements Ejb3ProbeWs {

...

public abstract boolean isAuthorized(String resource) throws EjbcaException {

...

}

}

If seamless migration is possible the old EJBCA Web Service client that is bundled with EJBCA should be able to access the new Web Services backed by a Stateless Session Bean. A small client application using generated classes based on the annotated Stateless Session Bean was created to make sure that generation was successful.

53

Page 62: A workflow based architechture for PKI

The Glassfish v2 EJB 3.0 validation tool found a potential issue where several of the Web Service methods throws java.rmi.RemoteException. This is not required and illegal in EJB 3.0 since the implementing Stateless Session Bean will use locally injected Stateless Session Beans. The changes in the Web Service interface by removing java.rmi.RemoteException has no effect on old clients. 

On Weblogic 10.3 the Stateless Session Bean name is ignored when the WSDL was created. 

The resulting default WSDL URLs for the tested application servers are shown in table 6.

Application server WSDL URL

JBoss 5.0.0.GA http://localhost:8080/ejb3probe­ejb3probe­ejb/Ejb3ProbeWsSessionBean?wsdl 

Glassfish v2 http://localhost:8080/EjbcaWSService/EjbcaWS?wsdl

Geronimo 2.1.3 http://localhost:8080/EjbcaWSService/EjbcaWS?wsdl

WebLogic 10.3 Exp http://localhost:7001/Ejb3ProbeWsSessionBean/EjbcaWSService?WSDL

Table 6: Test application's WSDL URL on different application servers

Remote Enterprise JavaBean invocationAn Enterprise JavaBeans can have a remote interface. Invocations of methods defined in the remote interface are invoked on a reference (a “stub”) that is looked up and downloaded from the application server. Method parameters are serialized and the invocation is sent over the Remote Method Invocation Internet Inter­Orb Protocol or another protocol supported by the application server. On the server the parameters are deserialized and the method of the implementing Stateless Session Bean is invoked.

Looking up remote references

Both the EJBCA command line interface and system tests use a EJB 2.1 ServiceLocator pattern to lookup references to remote objects. The lookup is performed using Java Naming and Directory Interface (JNDI). Access to the JNDI is application server specific and specified in a jndi.properties­file somewhere in the client's classpath.

The JNDI names will be standardized in EJB 3.1, but in EJB 3.0 the names are still application server specific. LogMockSessionBean was chosen at random as a test subject for remote EJB invocation.

54

Page 63: A workflow based architechture for PKI

To see if there was an informal consensus or if explicit naming is required the default naming was investigated. JBoss, Glassfish and Geronimo generated proper objects in the JNDI when the test application was deployed. The JNDI names are shown in table 7. Weblogic crashes with a stack overflow exception when trying to view the JNDI content from the server's web based user interface. After implementing a custom JNDI content reader I was able to see that there was a stub­binding for the remote interface. This stub did however not implement the remote interface when it was used by the remote client.

Application server Java Naming and Directory Interface name

JBoss 5.0.0.GA ejb3probe/LogSessionMockBean/remote

Geronimo 2.1.3 LogSessionMockBeanRemote

Glassfish v2 org.ejbca.core.ejb.log.LogSessionRemote

Table 7: Default Remote EJB JNDI name on different application servers

As described in appendix D, EJB 3.1 will use the following JNDI naming convention:   java:global[/<application­name>]/<module­name>/<bean­name>#<interface­name>

It might be a good idea to introduce this naming convention right away. In this case the annotation @Stateless(mappedName=”ejb3probe/ejb3probe­ejb/LogSessionMockBean#org.ejbca.core.ejb.log.LogSessionRemote”) would be a suitable choice for the LogMockSessionBean.

When the test application was deployed, JBoss and Glassfish responded directly by changing their remote mappings, but Weblogic responded with several errors during deployment. Geronimo requires proprietary configuration in the file ejb3probe.ear/ejb3probe­ejb/META­INF/openejb­jar.xml:<openejb-jar>

<properties>

openejb.jndiname.format = ejb3probe/ejb3probe-ejb/{ejbClass.simpleName}#{interfaceClass}

</properties>

</openejb-jar>

Using these mapping we can accomplish the EJB 3.1 style JNDI naming shown in table 8 on page 56.

55

Page 64: A workflow based architechture for PKI

Application server Java Naming and Directory Interface name

JBoss 5.0.0.GA ejb3probe/ejb3probe­ejb/LogSessionMockBean#org.ejbca.core.ejb.log.LogSessionRemote

Geronimo 2.1.3 ejb3probe/ejb3probe­ejb/LogSessionMockBean#org.ejbca.core.ejb.log.LogSessionRemote

Glassfish v2 ejb3probe/ejb3probe­ejb/LogSessionMockBean#org.ejbca.core.ejb.log.LogSessionRemote

Table 8: Custom Remote EJB JNDI name on different application servers

Even though this might seem unnecessarily complicated, the EJB 3.1 syntax is for a good reason. An application server should be able to deploy (different versions of) the same EJB in different EARs. In this case we know that there will only exist one deployment of each bean inside the EAR and it will either be the remote or local interface that is invoked through JNDI lookup. We even know that the Stateless Session Bean interface will only have one implementing Stateless Session Bean inside the application and the naming schema will guarantee that the interface's short classname is unique. Therefore a name like “ejb3probe/LogSessionRemote” would be sufficient to distinguish between different EJB stubs and still guarantee uniqueness on the server level. The client code for this JNDI lookup would be:LogSessionRemote logSession = (LogSessionRemote) context.lookup("ejb3probe/" + LogSessionRemote.class.getSimpleName());

The Stateless Session Bean annotation would be:@Stateless(mappedName="ejb3probe/LogSessionRemote")

It would be even better if the prefix is taken from a common source for all Stateless Session Beans, if the application is ever renamed in the future:@Stateless(mappedName=(GlobalConstants.APP_JNDI_PREFIX + "LogSessionRemote"))

Geronimo's proprietary configuration would change to:<openejb-jar>

<properties>

openejb.jndiname.format = ejb3probe/{interfaceClass.simpleName}

</properties>

</openejb-jar>

With this approach we could use a general lookup pattern for all remote references: public static <T> T getRemoteSession(Class<T> remoteInterface) {

String jndiName = GlobalConstants.APP_JNDI_PREFIX + remoteInterface.getSimpleName();

try {

return (T) getContext().lookup(jndiName);

} catch (ClassCastException e) {

56

Page 65: A workflow based architechture for PKI

log.error("JNDI object " + jndiName + " is not if type " + remoteInterface.getName());

} catch (NamingException e) {

log.error("", e);

}

return null;

}

Serialization of Stateless Session Bean method parameters

The most common nonserializable method parameter in EJBCA is probably java.util.Collection. It might be the case that these methods are never used in practice over the remote interfaces or it could be that some application servers are able to serialize a Collection if the objects contained in the Collection are serializable.

A simple test that invokes a remote method with a Collection as parameter would show if this is handled automatically. A second test where a remote method with a regular nonserializable object as parameter would serve as a reference that such invocation will fail.

Application server Serialization test result

JBoss 5.0.0.GA Using Collections of serializable objects work. Simple nonserializeable object fails.

Glassfish v2 Using Collections of serializable objects work. Simple nonserializeable object fails.

Geronimo 2.1.3 Using Collections of serializable objects work. Simple nonserializeable object fails.

Table 9: Serialization behavior on different application servers

Implementing serialization of a Collection is not difficult, so it seems reasonable that this is supported in general. The results and reasoning implies that exposed methods that uses other nonserializable objects in one form or another is never used remotely and should be removed from the remote Stateless Session Bean interfaces of EJBCA.

57

Page 66: A workflow based architechture for PKI

Appendix C: Migration strategy details

This chapter will outline a possible way to migrate EJBCA from Enterprise JavaBeans 2.0 to 3.0. The most important tasks based on the findings in this report will  be described in more detail. Illustration 13 on page 59 shows a possible workflow for  the migration. Darker boxes in the illustration require more work and the large area with darker background shows the tasks that have to be done during a feature freeze.

Remove XDoclet

XDoclet is the framework for automatic generation of Enterprise JavaBeans 2.1 interfaces and XML configuration files. These files should be generated one last time and then added to version control. 

Creating a new project layout

As with the ejb3probe­project, new directories for Enterprise JavaBeans 3.0 interfaces, Entity Beans and Stateless Session Beans should be created. Each Web Application should also get its own directory. New Apache Ant build scripts will be created for building each module.

Setting up automated tests

The existing JUnit tests should be divided into two parts. One for testing helper objects and one for system tests that invoke remote Enterprise JavaBeans interfaces or other protocols. The helper object tests should run right away and the system tests should be modified as soon as the new remote interfaces are in place. The system tests will of course fail until the tested implementation is in place, but since we should not change the behavior of the application all the test should eventually succeed.

Entity Beans

Move each Entity Bean to its new folder and rename it to XxData, where “Xx” is taken from its current name. The Naming Conventions for Java Persistence [20] suggest using just Xx, but for historic reasons this would lead to naming collisions. Since Enterprise JavaBeans 3.0 entity beans can also be used as detached value objects, XxDataBean would not really make sense for all use­cases.

58

Page 67: A workflow based architechture for PKI

59

Illustration 13: Migration overview

Page 68: A workflow based architechture for PKI

Annotate the former Entity Bean class, make sure it implements Serializable and Clonable and that it has a basic constructor:@Entity

@Table(name="XxData")

public class XxData implements Serializable, Cloneable {

private static final long serialVersionUID = 1L;

public XxData() {}

Change abstract getters and setters public abstract String getXx();

public abstract void setXx(String xx);

to normal getters and setters private String xx;

public String getXx() { return xx; }

public void setXx(String xx) { this.xx = xx; }

for all values in values in the file. Also change XDoclet comments * @ejb.pk-field

* @ejb.persistence column-name="xx"

to annotations @Id

@Column(name="xx")

Getters that are not commented with * @ejb.interface-method

should be annotated @Transient. The Enterprise JavaBeans 2.1 mandatory methods public PkClass ejbCreate(Xx xx, ...) throws CreateException { ...

public void ejbPostCreate(Xx xx ...) { ...

are replaced by a regular constructor public XxData(Xx xx) { ...

For large objects commented with * @ejb.persistence jdbc-type="LONGVARCHAR"

we need to use the Hibernate proprietary Java Persistence API implementation feature where we define the length of the column as @Column(name="yy", length=1024*1024*1024-1)

@Lob

where length should never be more than 1 GiB – 1 byte since this is the largest common value for the most common databases. Using this max is probably not desirable if the actual storage requirement is less than 1 GiB, so it would be better to set this on a case by case basis. Looking in the old mapping files under ejbca/src/deploy/ejb/merge/ in the EJBCA 3.9 branch source code repository will give a hint of the currently used sizes.

Queries defined as comments should also be converted from

60

Page 69: A workflow based architechture for PKI

* @ejb.finder

* description="findByXx"

* signature="org.ejbca.xx.XxDataLocal findByXx(Xx xx)"

* query="SELECT OBJECT(a) from XxDataBean a WHERE a.xx=?1"

to public static XxData findByXx(EntityManager entityManager, Xx xx) {

return (XxData) entityManager.createQuery("SELECT a from XxData a WHERE a.xx=:xx")

.setParameter("xx", xx).getSingleResult();

}

The “SELECT a” is mandatory in the Java Persistence API Query Language [5], but not in the Hibernate Query Language. It will still work without the “SELECT a” since we only rely on Hibernate as Java Persistence API provider, but it seems like a really bad practice to add additional dependencies on the framework.

Queries that return more than one object should be converted from XDoclet comments like * @ejb.finder

* description="findByYy"

* signature="java.util.Collection findByYy(Yy yy)"

* query="SELECT OBJECT(a) from YyDataBean a WHERE a.yy=?1"

to public static List<YyData> findByYy(EntityManager entityManager, Yy yy) {

return entityManager.createQuery("SELECT a from YyData a WHERE a.yy=:yy")

.setParameter("yy", yy).getResultList();

 } 

where the generics gives extra type safety [19].

One­to­many

AdminGroupDataBean has a one­to­many relationship with both AccessRulesDataBean and AdminEntityDataBean that requires special attention. Java Persistence API requires one­to­many relationships that uses a foreign key (like AdminGroupDataBean does) to be bidirectional [7].

So AdminGroupData would have @OneToMany(mappedBy="AdminGroupData_adminEntities")

public Collection<AdminEntityData> getAdminEntities() { return adminEntityDatas; }

public void setAdminEntities(Collection<AdminEntityData> adminEntityDatas) { this.adminEntityDatas = adminEntityDatas; }

@OneToMany(mappedBy="AdminGroupData_accessRules")

public Collection<AccessRulesData> getAccessRules() { return accessRulesDatas; }

public void setAccessRules(Collection<AccessRulesData> accessRulesDatas) { this.accessRulesDatas = accessRulesDatas; }

61

Page 70: A workflow based architechture for PKI

and both AccessRulesData and AdminEntityData would also have the required reference @ManyToOne(fetch=FetchType.LAZY)

private AdminGroupData adminGroup;

To avoid loading all access rules until they are used, lazy loading is used by default using the @OneToMany annotation. If AdminGroupData were ever to be used in a detached state we will not be able to use lazy loading this way.

Removing a single AccessRuleData from an AdminGroupData using the one­to­many association will (lazily) load the entire collection of access rules. It would be better to implement a custom Java Persistence API Query Language query to take care of this and to handle the borderline case where no access rules are left.

Stateless Session Bean interfaces

The old Stateless Session Bean source code should be used for creating the new local, remote and common interfaces. All the XDoclet comment tags in XxSessionBean should be converted to their Enterprise JavaBeans 3.0 counterpart. The XDoclet comments look like this: * @ejb.bean view-typ="both"

* @ejb.interface-method view-type="both"

The common interface is extended by both the remote and local interface. Methods with view­type “both” should reside in the common interface, “remote” in the remote interface and “local” in the local interface. 

If the Stateless Session Bean name is for example XxSessionBean, the interfaces should be named XxSession, XxSessionLocal and XxSessionRemote. The local interface should be annotated with @Local and the remote interface with @Remote.

All Collection, List and Set parameters should use Java generics. 

Methods that have object parameters that do not extend Serializable should not be a part of the remote interface even if they are declared that way today.

Stateless Session Beans

XDoclet comments on Stateless Session Beans should be transformed from * @ejb.bean type="Stateless"

into the @Stateless class annotation. XDoclet comments like * @ejb.transaction type="Required"

should be transformed into the @TransactionAttribute(TransactionAttributeType.REQUIRED) class annotation or simply nothing since REQUIRED is the default transaction attribute. Other transaction attributes have to be converted to their Enterprise JavaBean 3.0 counterpart.

The Java Naming and Directory Interface name comment

62

Page 71: A workflow based architechture for PKI

* @ejb.bean ...

* jndi-name="YySession"

translates into

@Stateless(mappedName=(GlobalConstants.APP_JNDI_PREFIX + "YySessionRemote"))

where GlobalConstants.APP_JNDI_PREFIX is “ejbca/” and declared in the interface JAR file.

Any other bean that is used from within the bean should be injected using @EJB private YySessionLocal yySession;

instead of using any form of manual lookup.

XDoclet method level comments like * @ejb.transaction type="Supports"

also have to be transformed. This means that the same method in XxSessionBean should be annotated with @TransactionAttribute(TransactionAttributeType.SUPPORTS).

If the Session Bean contains references to Entity Beans, additional development is required. Instead of working on the Enterprise JavaBeans 2.1 Entity Bean interface, Enterprise JavaBeans 3.0 uses the EntityManager, so Stateless Session Beans that use persistence have to inject this object: @PersistenceContext(unitName="ejbca") EntityManager entityManager;

where “ejbca” is defined in ejbca.ear/ejbca­entity.jar/META­INF/persistence.xml.

Since the fetched object stays managed as long as the transaction is running, it might sometimes be useful to covert it to a value object that is detached from the EntityManager. There is no way of detaching a single object, so cloning or using converters to existing value objects is recommended. Existing value objects should not be replaced with their Java Persistence API equivalents during the migration process, since it would require a large amounts of extra work and changes to the Stateless Session Bean interfaces.

The EntityManager is also used to persist (create new) objects in the database and merge (replace) existing object with a detached one. Merge can always be used even if the entity does not already exist, but the developer has to be aware that it is only the returned object that is part of the persistence context.

Remote Enterprise JavaBeans command line interface

The EJBCA command line interface should be updated to use remote Enterprise JavaBeans 3.0 interfaces and lookup. The lookup pattern from the ejb3probe application can be reused here.

63

Page 72: A workflow based architechture for PKI

Web Services

The EJBCA Web Services should be moved from it is current Servlet based implementation to a Stateless Session Bean based implementation. This process is described in depth in the ejb3probe Web Services iteration.

Scheduling

ServiceTimerSessionBean can still implement javax.ejb.TimedObject and use an ejbTimeout­method just as it currently does. It would however be more appropriate to use the Enterprise JavaBeans 3.0 standard for all parts of EJBCA. Instead of using the TimedObject interface, the ejbTimeout­method should be annotated with @Timeout.

Java Database Connectivity replacement

The Java Persistence API Query Language in Enterprise JavaBeans 3.0 can handle paging, JOINs, DISTINCT, LIKE, ORDER BY, GROUP BY, HAVING, sub­queries, bulk UPDATEs and bulk DELETEs. This should be enough to replace most of the Java Database Connectivity code in EJBCA. For example the getLastExport method (21 rows) in ProtectedLogSessionBean: public ProtectedLogExportRow getLastExport() {

...

con = JDBCUtil.getDBConnection(JNDINames.DATASOURCE);

String sql="SELECT * FROM ProtectedLogExportData ORDER BY exportEndTime DESC";

ps = con.prepareStatement(sql);

ps.setFetchSize(1);

ps.setMaxRows(1);

rs = ps.executeQuery();

if (rs.next()) {

protectedLogExportRow = new ProtectedLogExportRow(rs);

}

...

}

could be replaced by something like this (only 1 row): public ProtectedLogExportRowData getLastExport() {

return ProtectedLogExportRowData.getLastExport(entityManager);

}

The getLastExport method in ProtectedLogExportRowData would then look like this (only 5 rows):

public static ProtectedLogExportRowData getLastExport(EntityManager entityManager) {

return (ProtectedLogExportRowData) entityManager.createQuery(

"SELECT a FROM ProtectedLogExportData a ORDER BY a.exportEndTime DESC")

.setMaxResult(1).getSingleResult();

64

Page 73: A workflow based architechture for PKI

}

I think it is best to decide the most suitable Java Database Connectivity transformation on a case­by­case basis instead of giving general advice on this issue since Java Database Connectivity is used for custom database access and most use cases are different. However, it would still be good to use the pattern above with a static helper method on the Java Persistence API entity to keep all custom SQL in one place and make re­use easier.

Graphical user interface

There is a large amount of legacy JavaServer Pages code in EJBCA. Any Enterprise JavaBean references should be pushed to a JavaBean and converted to use Enterprise JavaBeans 3.0 injection. It might also make sense to convert the affected web­pages to JavaServer Faces if major restructuring is required.

Standalone Online Certificate Status Protocol responder build

EJBCA can be built as a standalone Online Certificate Status Protocol responder with a Servlet entry point. This code should be updated to use Enterprise JavaBeans 3.0 injection.

Java Persistence API in the External Registration Authority library

The EJBCA sub­project “External Registration Authority” currently uses pure Hibernate. Since the Java Persistence API class used for the database access is already available, switching to Java Persistence API should be simple. The benefit would be that we use a single database access technology for the entire EJBCA project.

65

Page 74: A workflow based architechture for PKI

Appendix D: Java frameworks

This chapter describes the two evaluated frameworks Spring 2.0 and Enterprise JavaBeans 3.0 in detail. The main features of the upcoming Enterprise JavaBeans 3.1 standard are described in brief.

Spring 2.0Spring (short for Spring Framework) is an open source Java framework backed by VMware Inc. designed to ease development of enterprise applications. Spring 1.0 was released in 2004 and version 2.0 was released in 2006. This section is based on [6]. 

ArchitectureSpring was designed to simplify the development of enterprise applications that requires services like distributed computing, transactions and security. These services are already available with Enterprise JavaBeans 2.1, but are complicated to use and test. Spring uses a loose definition of conventional JavaBeans simply referred to as Beans.

The entire framework is built on well­defined modules, on top of the core container module. Modules can be replaced by external modules from other frameworks or libraries if needed.

Spring's lightweight core container module takes care of configuring, creating and managing Bean instances.

The application context module makes Spring a framework by supplying services like Java Naming and Directory Interface access, Enterprise JavaBeans integration, remoting, scheduling and internationalization.

Some available modules are the Aspect­Oriented Programming module, Data Access Objects module, Object­relational mapping integration module, Java Management Extension  module, Java Enterprise Edition Connector API module, Spring Model­View­Controller framework, Spring Portlet Model­View­Controller, Spring Web module, Remoting module and Java Message Service module.

The Spring distribution does not contain an executable like application servers do and is more like a library.

Features

This section describes the main features of Spring 2.0.

66

Page 75: A workflow based architechture for PKI

Dependency InjectionDependency Injection (also known as Inversion of Control) means that Beans are given their dependencies instead of having to look them up. Since the Bean only accesses an interface of the injected resource the actual implementation can be a local, remote or a dummy object. This loosely coupled architecture simplifies testing since each Bean can be tested in a fully controlled environment and typically has no Spring­dependent code. A dependency can be a Bean, a primitive value or a collection of the first two.

Aspect­Oriented ProgrammingAspect­Oriented Programming allows application objects to concentrate on business logic. Services like transactions and logging can be applied as an aspect without the object being aware of it. 

The Aspect can be split into Advice (what to do and when to do it) and Pointcut (where to apply the Advice). All potential Pointcuts are called Joinpoints.

Spring's proxy­based built­in Aspect­Oriented Programming module can be applied before, after and around methods. The Aspect is a plain POJO and the Pointcut methods are defined with regular expressions in Spring's XML­based configuration.

Bean Wiring and CreationA Spring application is created by configuring in XML how the container should inject dependencies into other Beans at run­time. This runtime linking is known as Bean Wiring and is performed at creation by the container's BeanFactory instance.

Auto­wiring can be used to keep the configuration smaller and is especially useful when there are few object of the same type. The container then tries to match the different setters of an object with available Beans. Normally when multiple Beans are found an exception is thrown, but if no match is found “null” will be injected instead. Auto­wiring might also make it more difficult to study and debug the coupling between Beans for both developers and tools.

Scripts from Ruby, Groovy and BeanShell can be incorporated as any other Bean and the underlying script can be hot­swapped or changed almost instantly.

PersistenceSpring encourages a model with a Data Access Object hidden behind an interface and accessed through a Service Object.

By using templates for the desired persistence provider that is injected into the Data Access Object, only “execute in transaction” and “return data” callbacks have to be implemented. This mean that most of the underlying persistence layer is hidden and that a hierarchy of unchecked database exceptions can be used for better handling of data­base errors.

The DataSource for the persistence layer is either injected from a Java Naming and Directory Interface lookup when running inside an application server or configured 

67

Page 76: A workflow based architechture for PKI

separately. To have a pooled DataSource in a non­application server environment, Jakarta Commons Database Connection Pools can be used.

Java Database ConnectivityUsing Java Database Connectivity is greatly simplified by hiding all the code for managing connections, cleaning up resources and handling exceptions in parent classes.

HibernateBoth version 2 and 3 of Hibernate are supported. Hibernate's mapping files or annotations can be used. The Hibernate specific code is minimized to using template specific methods for saving, loading or finding objects. An alternative is to use an injected Hibernate session. This removes dependence on Spring, but requires Hibernate specific error­handling.

Java Persistence APIJava Persistence API is a POJO­based persistence mechanism using annotations, based on ideas from both Hibernate and Java Data Objects.

Spring templates takes care of managing the Java Persistence API EntityManager, transactions and exceptions. The EntityManager can be managed by the application or by the container in a Java Enterprise Edition environment. The actual choice is abstracted away by the template, but the choices are configured differently.

iBATISiBATIS is a object­query mapping solution that allows more fine grained control than Hibernate and Java Persistence API. Object­relation mapping and queries are specified with XML­formatted configuration and iBATIS can then be used through a template­class.

TransactionsTransactions should be atomic (all or nothing), consistent (defined state after the transaction), isolated (the data involved is not affected by other processes during the transaction) and durable (all changes must be persisted before the transaction is complete). 

Spring's transaction manager delegates all transaction handling to the underlying persistence mechanism or to the used Java Transaction API implementation. When using Java Transaction API, mixing Java Database Connectivity and Java Persistence API might not always work.

Both programmatic and declarative transactions can be used. A declarative transaction is a form of Aspect Oriented Programming that can handle propagation behavior (scope of transaction), isolation level (locking behavior), read­only hints (to optimize database access), timeout, and rollback rules (which exceptions triggers a rollback).

68

Page 77: A workflow based architechture for PKI

CacheData Access Objects can be intercepted by a caching proxy. No such proxy is supplied with Spring, but several third party caching solutions are supported. Caching can be applied with annotations.

Other Java Enterprise Edition features

Java Naming and Directory Interface WiringAny object in the Java Naming and Directory Interface can easily be wired into Beans. If the sought­after object is not found, a default object can be wired instead.

Mail serviceBy configuring a MailSender with wiring or Java Naming and Directory Interface lookup, Beans can send email. The MailSender is based on the JavaMail API.

Timer ServiceThere are two kinds of timer services available. One is only able to run at intervals and another based on the Quartz project can be configured to run at specific times using the same kind of configuration as the cron­utility.

SecuritySpring Security is based on Aspect Oriented Programming proxies and injected Servlet filters. It can handle authentication and authorization for both web requests and Bean methods.

When an invocation is intercepted by the Security Interceptor all or some of the Authentication Manager, Access Decision Manager, Run­As Manager and After­Invocation Manager are invoked.

The Authentication Manager verifies principals and credentials and can use several different authentication providers, including database/LDAP verification, Java Authentication and Authorization Service, web container verification, X509AuthenticationProvider and many more.

The Access Decision Manager checks authorization to a resource by polling one or more objects for votes. The result depends on if the voting is Affirmative, ConsensusBased or UnanimousBased and if the allowIfAllAbstain property is set. An interface for implementing voters is available.

The Run­As Manager applies a new role and After­Invocation Manager checks authorization on returned data.

Access control for Bean methods can be controlled by using wildcards in the Spring configuration or by using special metadata tags. For example all methods with a name starting with “get” can have different access control requirements than methods with a name starting with “set”.

69

Page 78: A workflow based architechture for PKI

Requesting secure web content requires several steps. First a session filter tries to identify the request to an existing session, then authentication filters processes the request, security related exceptions (if any) are translated by another set of filters. Finally the security interceptor filter processes the request by invoking the Authentication Manger and Access Decision Manager.

A special taglib allows dynamic generation of page content depending on the security­role of the requester.

RemotingFive remote protocols are supported in Spring: Remote Method Invocation, Hessian, Burlap, Spring's HTTP Invoker and Java API for XML­based Remote Procedure Call. A remote service is injected into other Beans as any local Bean and the remote service throws unchecked exceptions for problems related to the connection.

Writing a Remote Method Invocation service is simplified to writing a simple interface and a POJO that are configured dynamically to be exposed.

Hessian or Burlap are two lightweight HTTP­based protocols. These services are exposed with the help of regular Servlet mappings.

Spring's HTTP Invoker works similar to Hessian or Burlap, but only between two Spring applications.

Spring does not include a default implementation for contract­last Web Services, but can use the XFire package. This allows a Bean to be exposed as Web Services through a Servlet with some minor configuration (for each Bean to expose). The Java API for XML Web Services annotations can also be used with an additional XFire package and some more configuration. Consuming a contract­last Web Service is best done with the XFire client package that requires minimal configuration.

Setting up contract­first Web Services requires more configuration. First a contract is defined by typically converting a sample message into a Simple Object Access Protocol schema that is manually modified. When using HTTP­based Web Services a special Servlet can be configured to dispatch incoming Simple Object Access Protocol requests to a Web Service endpoint. The Web Services Description Language contract for the service can be automatically generated and supplied through the same Servlet as the service. On the client­side a template­pattern is used together with a marshaller to simplify the Web Service invocation as much as possible.

Enterprise JavaBeans IntegrationBoth Enterprise JavaBeans 2.x and Enterprise JavaBeans 3.0 Stateless Session Beans can be wired and injected into Spring Beans by using a special proxy object that looks up the correct reference from Java Naming and Directory Interface. This works just like remoting.

Enterprise JavaBeans 2.x Beans can be Spring­enabled by extending a specific class. This allows lookup of Spring Beans through the Java Naming and Directory Interface.

70

Page 79: A workflow based architechture for PKI

Support for some of the Enterprise JavaBeans 3.0 annotations for injecting resources (from both Java Naming and Directory Interface and the Spring container) and using interceptors are available by using the Springfork add­on project.

Servlet filtersServlet filters are applied by using a proxy that chains the selected filters for each desired URL­pattern. Besides filters for secure requests, there are filters that handles sessions.

Model­View­ControlIn Spring's Model­View­Control (MVC) module each request is handled by a DispatcherServlet. The DispatcherServlet asks a HandlerMapping what controllers the request should use. The request is sent to each controller and a Model­and­View object is returned. When all controllers have handled the request the DispatcherServlet asks a ViewResolver for a suitable View for the result and forwards the Model­and­View object. The View generates the resulting data that is sent back to the client (for example using HTML).

Requests can be mapped to Controllers in several different ways, including finding a controller with a name corresponding to the requested URL. There are several different types of base­controllers to allow minimal parameter validation and binding in the business logic: View, Simple, Throwaway, MultiAction, Command, Form and Wizard. Declarative validation of requests can be performed using Commons Validator from Apache.

The View that is used to render the response can either be an internal resource (JavaServer Pages or similar) or a Bean for more complex content. It also possible to render different responses based on the configuration for the user's locale.

Spring has a JavaServer Pages taglib that allows incorrect forms to be repopulated with the entered data so the user does not have to start over from scratch. Both messages and error­messages can be externalized and internationalized.

Spring supports a combination of JavaServer Pages and Tiles from the Apache Struts Framework, Apache Velocity and FreeMarker. Velocity, a less powerful and complex language than JavaServer Pages, can be extended by Spring to support internationalized messages. FreeMarker is more powerful then Velocity, but there is no real difference when they are both used together with Spring.

Spring MVC can produce output in different formats. Excel content is produced with Apache Poor Obfuscation Implementation, Portable Document Format content with the iText library and Really Simple Syndication­flows with the Rome utility.

Spring Web FlowSpring has a special type of controller to allow web applications to keep a conversational state and follow a defined page flow. Six different states exist: Action, Decision, End, Start, SubFlow and View. The page flow is defined in XML and can 

71

Page 80: A workflow based architechture for PKI

invoke any Bean method as an Action and use any kind of Model­View­Control View to display information or receive submitted information in the View­state.

Both Apache Struts and JavaServer Faces can be customized to use Spring Web Flow.

Integration with other Web frameworksIntegration with Struts 1.x is accomplished by delegating all requests to Struts­Actions declared inside Spring application context as any other Bean.

Struts 2.x is prepared for integration with Spring and only minimal configuration is required to declare Struts actions inside the Spring application context.

Spring Beans can be injected and used by Tapesty 4 by using an integration module from the Diaphragma­project.

Integration of Spring with JavaServer Faces is accomplished by adding a Resolver that lets the JavaServer Faces pages resolve variables from the Spring application context.

By using the Asynchronous JavaScript and XML library Direct Web Remoting, any Bean or Bean­method can be exposed to be used from JavaScript in web­clients. This allows highly dynamic content to be created.

Java Management ExtensionJava Management Extension can be used to notify Java Management Extension­enabled listeners of events or changing properties at runtime by invoking exposed methods. The basic component in Java Management Extension is a special type of JavaBean called Managed Bean. Springs makes interactions with the Managed Bean easier by proxying them. 

TestingSpring can simplify testing in several ways:

• Database tests can run inside a transaction that is rolled back after the test is done.

• Values of returned Model­And­View objects can be validated.

• Special application contexts for integration testing exists.

EasyMock works well with Spring for creating mock­objects that can be injected during testing instead of the objects injected in the full application.

ConfigurationDue to the immense amount of configuration required for an application, the author of [6] recommends splitting the XML­configuration into one file for each layer: Security, Web, Services and Persistence.

72

Page 81: A workflow based architechture for PKI

Enterprise JavaBeans 3.0Enterprise JavaBeans is a standardized Java framework from the Java Community Process. Enterprise JavaBeans allows the creation of reusable components in a distributed environment where transactional integrity is ensured. Version 1.0 of the standard was announced in 1998, version 2.1 was released in 2003 and version 3.0 was released in 2006.

This section is mainly based on [2].

ArchitectureEach Enterprise JavaBeans (EJB) class must have one or more of the following interfaces:

● A local interface: allows access from other EJBs in the same EJB Container.

● A remote interface: allows access from components outside the EJB Container.

● An endpoint interface: allows access to the EJB by the Java API for XML­based Remote Procedure Call protocol.

● A Web Service interface: allows access to Stateless Session Beans by the Java API for XML­based Web Services protocol.

Interfaces can be generated at runtime by using annotations. This allows simpler code in scenarios with a single implementation.

Methods that are invoked through a local interface use call­by­reference (where a reference to the object is used as parameter) and methods using the other interfaces use call­by­value (where a copy of the object is used as parameter).

Enterprise JavaBeans ContainerThe EJB Container provides services such as transaction, security, concurrency and run­time naming for different EJBs. An EJB interacts with the container by registering methods it wants to have invoked during runtime. The registered method(s) will be invoked when a relevant event occurs.

By using the model where all clients access interfaces, the real invocations can use container generated stubs. This enables transparent remote invocation and allows the container to apply security and transaction functionality to the invocation.

EJBContextAll Session Beans implement a subclass of the EJBContext interface. The methods of this interface provide some security functionality, transactional functionality and a Java Naming and Directory Interface wrapper for fetching resources.

73

Page 82: A workflow based architechture for PKI

Getting references to resourcesJava Naming and Directory Interface is the service used by EJBs to locate distributed objects or resources. 

Each Session Bean has it is own registry called Enterprise Naming Context. Enterprise Naming Context is implemented on top of Java Naming and Directory Interface with the URI “java:comp/env” and is populated from either annotations, XML­configuration or both. Examples of resources that can populate the Enterprise Naming Context are EJB interfaces, DataSources, EntityManagers, Timer Service and primitive values. These resources can be injected into a Session Bean by using annotations.

Persistence

Java Persistence APIEJB 3.0 uses Entity Beans, representing data, that are POJOs. These Entity Beans do not require an application server and can be sent over a network. To make the Entity Beans interact with a database an EntityManager is used. The EntityManager can create, update, find, query and remove Entity Beans from the database.

The object­relational mapping is extensive and makes persistence more portable between different vendors. Every table and column can be defined by annotating the corresponding class, setter­method or variable.

Java Persistence API supports all different relationship types between Entity Beans. Three types of Entity Inheritance are supported: single table per class, one table per concrete class and one table per subclass. A single table per class has the best performance and is easiest to implement.

The Enterprise JavaBeans Query Language (also known as Java Persistence API Query Language) is used to do more advanced database queries than finding an Entity by its primary key. This query language is a limited and portable version of regular SQL, adapted to suit Java. Native SQL code can be used for non­portable tasks like running stored procedures.

Entity Beans can have callback listeners to get notifications of object specific events, which can be used for logging database access.

Persistence ContextThe persistence context is a set of Entity Beans managed by an EntityManager. As long as an Entity Bean is a part of a persistence context all changes are tracked and flushed to the database according to the current configuration.

A transaction­scoped persistence context lasts during a transaction and can only be used when the EntityManager is injected.

Using an extended persistence context, the Entity Beans are managed even after a transaction has finished.

74

Page 83: A workflow based architechture for PKI

TransactionsTransactions involving EJBs should be atomic (all or nothing), consistent (defined state after the transaction), isolated (the data involved is not affected by other processes during the transaction) and durable (all changes must be persisted before the transaction is complete).

It is not recommended to use explicit transaction management, instead Declarative Transactions can be added with annotations or XML­configuration.

All the EJBs involved in a transaction are together known as the Transaction Scope. Support for transactions can be modified for each bean­method and is one of:

• NotSupported: An active transaction will not be propagated.

• Supports: An active transaction will be propagated.

• Required: An active transaction will be propagated. A new transaction will be started if no transaction is available.

• RequiresNew: A new transaction will always be started.

• Mandatory: An active transaction will be propagated. If no transaction is active the method invocation will fail.

• Never: If an transaction is active the method invocation will fail.

The isolation level of transactions depends on configuration and the database implementation and is controlled in a vendor specific way.

Transactions are rolled back by system exceptions and application exceptions where rollback behavior is specified. Other application exceptions allows the invoking business method to try to recover.

Session BeansSession Beans contain business logic and are usually used for accessing data through Entity Beans.

Stateful Session BeansStateful Session Beans can be viewed as an extension of the client, performing tasks on behalf of the client and maintaining a conversational state. This also means that a Stateful Session Bean is dedicated to a specific client until the client times out or explicitly terminates the session. This type of bean is suitable for scenarios where each task depend on the result from previous invocations.

To avoid clogging up to much resources during it is lifetime, a Stateful Session Bean can be passivated when the connection is idle. This means that the client keeps its connection, but the bean is temporarily evicted from memory. When another request arrives the bean is activated. Passivation and activation requires special care from the developer to avoid problems with special data types.

75

Page 84: A workflow based architechture for PKI

Stateless Session BeansStateless Session Beans do not maintain a state and can for that reason be reassigned to different clients for every request or task. This also means that they are very efficient and do not require any activation or passivation. A drawback is that all input to methods must come from the method parameters or the environment.

A Stateless Session Bean can never assume that a client will ever use the same Bean from the EJB server's pool during the following invocations. For that reason, it can only cache generic variables.

Other Java Enterprise Edition features

Timer ServiceThe EJB Container provides a Timer Service API that allows a Stateless Session Bean to set a timer that results in a callback to a bean method when the time expires. Specific dates, intervals or a combination of these can be used.

InterceptorsInterceptors are objects that can be attached to life­cycle events of EJBs. This is usually common code that should not be mixed with the business logic. Examples of interceptors are time profiling code, debug code or security. Interceptors can be applied with both annotations or XML­configuration.

SecurityThe available security functions are authentication and authorization for Session Beans. How authentication is performed is however not a part of the standard. Some vendors use a system based on passing credentials through Java Naming and Directory Interface, others use Java Authentication and Authorization Service. Securing connections using cryptography is vendor specific.

Authorization is role­based and can be applied with both annotations and XML­configuration. By using the RunAs annotation the invokers role can be overridden. There are also some limited functionality for programmatic security. The mapping between users and roles are set during deployment.

Web ServicesWeb Services in EJB 3.0 are based on a combination of XML, Simple Object Access Protocol (SOAP) 1.1 and Web Services Description Language (WSDL) 1.1, called Basic Profile 1.1 from Web Service Integration Organization.

SOAP is a network agnostic, distributed object protocol defined by an XML Schema. EJB 3.0 supports SOAP over HTTP 1.1.

WSDL is a programming language, platform and protocol agnostic XML­document that describes Web Services. EJB 3.0 uses WSDL for SOAP 1.1 and 1.2.

76

Page 85: A workflow based architechture for PKI

The Web Service implementation used in EJB 3.0 is Java API for XML­based Web Services (JAX­WS) 2.0. JAX­WS is designed for simplicity and a Stateless Session Bean can be exposed as a Web Service and fully configured using annotations. It is also possible to expose a special Web Service interface that is implemented by a Stateless Session Bean.

ServletsServlets are server­side components used for generating responses to web requests. A Servlet is similar to a Stateless Session Bean in the way that resources can be accessed including injection, but it cannot contain business methods or use container managed transactions.

JavaServer PagesJavaServer Pages is a language for dynamically generating web pages, by allowing embedded server parsed Java code in HTML­pages. JavaServer Pages pages are compiled at runtime and run as Servlets [4].

JavaServer FacesJavaServer Faces is a Java framework built on top of JavaServer Pages and Servlets [4]. A Model­View­Control model enforces use of framework components, so no business code is embedded in pure JavaServer Faces pages. JavaServer Faces comes with many standard user interface components, such as input fields, that can easily be added using tag­libraries. These user interface components can interact with Managed Beans using the Expression Language. Validators can be added to user interface components for validating input. Using JavaServer Faces' output components makes it easier to avoid cross­site­scripting attacks than with pure JavaServer Pages since script tags are escaped by default and will not be processed by the client's web browser.

There is also a plethora of third­party plug­in tag libraries with support for Asynchronous JavaScript And XML, output encoding and additional user interface components.

PackagingThe Java ARchive (JAR) file format is used to package Java classes and associated metadata.

Web components are packaged with a deployment descriptor and libraries as a Web application ARchive (WAR or .war) file. WARs can be packaged together with EJB JARs and an optional deployment descriptor into a Enterprise ARchive (EAR or .ear) file called a Java Enterprise Edition Application. Special attention has to be paid to the directory structure of the included components.

Both WAR­ and EAR­files are themselves in the JAR file format.

77

Page 86: A workflow based architechture for PKI

ConfigurationEJB 3.0 supports the concept of “configuration by exception” and the default values are chosen to minimize the need for any configuration. To minimize the need for XML­configuration files, most configuration can be applied as annotations directly on the class, method or variable. The annotations can be used as the default configuration and still be overridden by XML­configuration files in specific deployment scenarios.

Enterprise JavaBeans 3.1 and Java Enterprise Edition 6This summary is based on the ongoing standardization work for Java Enterprise Edition 6 and Enterprise JavaBeans 3.1 presented in 6 articles ([14], [15], [16], [17], [18], [13]) by Reza Rahman on theserverside.com. Rahman is a member of the Java Community Process Java Specification Requests 318 expert group.

Optional interfaces for Enterprise JavaBeans

Session Beans no longer need interfaces. This is accomplished by directly annotation the Session Bean with @Stateless or @Stateful.

Singleton BeansThe Singleton Bean is a middleware version of the Singleton pattern. Its primary use is to store application­wide shared data, like for instance a database cache. Annotating a Plain Old Java Object with @Singleton makes it a Singleton Bean. By using @ConcurrencyAttribute(READ_LOCK) on methods we can allow concurrent reads. The specification will not include clustered Singleton Beans.

Time Service with schedulingUsing the @Schedule(second=.., minute=.., hour=.., day­of­month=.., month=..., year=...) annotation on a method, we can determine when to execute the method. There might also be support for a more compact expression like @Schedule(expression=”0 0 0 1 * * *”). New methods will also be added to the TimerService interface to allow programmatic setting of timers and when in the future the first execution should occur.

Asynchronous invocation of Session BeansInstead of using Message Driven Beans, a simple @Asynchronous annotation on a method will make the invocation asynchronous. The return type java.util.concurrent.Future<V> (and javax.ejb.AsyncResult<V>) will be supported, so it is possible to check for completion, exceptions and return values.

Enterprise JavaBeans LiteOne of the Java Enterprise Edition 6 profiles is Enterprise JavaBeans Lite. This profile will support synchronous Stateless, Stateful and Singleton Session Beans using local or 

78

Page 87: A workflow based architechture for PKI

no interface. It will also support interceptors, declarative security and both declarative and programmatic transactions. Enterprise JavaBeans classes could be added directly to the WEB­INF/classes directory of a WAR file. It is expected that Servlet containers like Tomcat and Jetty will implement the EJB Lite profile.

Java Contexts and Dependency InjectionThe Java Specification Requests 299 for Java Contexts and Dependency Injection was inspired by JBoss Seam and Google Guice frameworks. By annotation a Plain Old Java Object with @Component it is registered with the container as a bean. @Named(“beanName”) assigns a name to the component that the container can reference this bean by. The bean can then be referenced from JavaServer Pages or JavaServer Faces using Expression Language expressions.

The @In annotation can be used for injecting other components in the current context. A Entity Bean can for example be annotated as a component and injected to the Session Bean so it can be persisted. This type of injection can also be used for any other Plain Old Java Object, allowing even looser coupling between objects.

Standardized global Java Naming and Directory Interface namesThe name under which Enterprise JavaBeans are registered in Java Naming and Directory Interface will be standardized. The standardization will benefit components that cannot use dependency injection. The format is

    java:global[/<application­name>]/<module­name>/<bean­name>#<interface­name>

where the application­name is not used if the Enterprise JavaBean is deployed in a simple web application. The interface­name can be omitted if there only exists a single interface or no interface.

Enterprise JavaBeans Embeddable ContainerAn embeddable container will allow unit­testing, batch processing and similar tasks utilizing Enterprise JavaBeans Lite services in a Java Standard Edition environment.

Removal of dead meatJava API for XML­based Remote Procedure Call, Enterprise JavaBeans 2.x Entity Beans, Java API for XML Registries, Java Service Request 88 for Java Enterprise Edition Application Deployment and the Java Service Request 77 for Java Enterprise Edition Management features will all be dropped in Java Enterprise Edition 6.

Java Persistence API 2.0The ability to model Collections, Lists and Maps as well as Unidirectional one­to­many relationships are introduced in Java Persistence API 2.0. Queries can be used to fetch the first or a limited number of results. More advanced dynamic queries can be used. Pessimistic locking, standardizing Java Database Connectivity properties and configurable time outs are other new features.

79

Page 88: A workflow based architechture for PKI

Servlet 3.0In the Servlet 3.0 specification, annotations like @WebServlet, @ServletFilter and @WebServletContextListener are introduced to reduce configuration in the web.xml file. Fragments of web.xml can be included in libraries to perform for example boot­strapping. In the previous Servlet versions, frameworks such as JavaServer Faces required manual configuration in the web.xml file.

Java API for RESTful Web Services 1.1Java API for RESTful Web Services 1.1 aims at reducing Representational State Transfer (REST) programming to the annotation of Plain Old Java Objects. The library includes integration with Servlets, Weld and Enterprise JavaBeans.

80

Page 89: A workflow based architechture for PKI

TRITA-CSC-E 2010:047 ISRN-KTH/CSC/E--10/047--SE

ISSN-1653-5715

www.kth.se