Download as pdf or txt
Download as pdf or txt
You are on page 1of 52

Getting Started Developing Applications Guide

1 Introduction
1.1 Downloading the quickstarts
2 Getting started with JBoss AS
2.1 Installing and starting JBoss AS on Linux, Unix or Mac OS X
2.2 Installing and starting JBoss AS on Windows
2.3 Starting JBoss AS from Eclipse with JBoss Tools
2.4 Importing the quickstarts into Eclipse
2.5 Managing JBoss Application Server
3 CDI + Servlet: Helloworld quickstart
3.1 Deploying the Helloworld example using Eclipse
3.2 The helloworld example in depth
4 CDI + JSF: Numberguess quickstart
4.1 Deploying the Numberguess example using Eclipse
4.2 The numberguess example in depth
5 CDI + JPA + EJB + JTA + JSF: Login quickstart
5.1 Deploying the Login example using Eclipse
5.2 The login example in depth
6 CDI + JSF + EJB + JTA + Bean Validation + JAX-RS + Arquillian: Kitchensink quickstart
6.1 Deploying the Kitchensink example using Eclipse
6.2 The kitchensink example in depth
6.2.1 Arquillian
7 OSGi: Helloworld OSGi quickstart
7.1 The Helloworld OSGi example in depth
7.2 Creating a new OSGi bundle using Eclipse
8 Creating your own application
9 More Resources
10 All JBoss AS 7 documentation

Introduction
This guide will walk you through installing and starting up JBoss Application Server 7. It will then introduce key features of the Java EE 6 (Web
Profile) programming model, of which JBoss AS 7 is a certified implementation.

Java EE 6
The Java EE 6 platform offers developers the ability to write distributed, transactional and portable applications quickly and
easily. We class applications that require these capabilities "enterprise applications". These applications must be fast, secure
and reliable.

Java EE has always offered strong messaging (JMS), transactional (JTA) and resource (JCA) capabilities as well as exposing
web services via SOAP (JAX-WS). Java EE 5 started a radical shift for the programming model, offering a powerful, declarative
and lightweight object-relational mapper (JPA) and annotation-driven, lightweight access to enterprise services (EJB 3). Java
EE 6 added a type-safe, loosely coupled programming model (CDI), declarative validation of constraints (Bean Validation) and
RESTful web services (JAX-RS) to produce a complete, modern development environment.

JBoss AS 7 departs from the familiar structure of previous JBoss AS versions, so we recommend all developers follow the steps in Getting started
with JBoss AS to install and start up the application server for the first time.

JBoss AS 7 comes with a series of quickstarts aimed to get you up to writing applications with minimal fuss. We recommend that you work
through the quickstarts in the order they are presented in this guide, however if you have previous experience with Java EE 6, you may wish to
skip some or all of the quickstarts:

Core

Helloworld If you have previously developed applications using technologies such as JSF or Wicket, and EJB or Spring, you may
quickstart wish to skip this quickstart.

Numberguess If you have previously developed applications using technologies such as JSF or Wicket, EJB or Spring, and JPA or
quickstart Hibernate you may wish to skip this quickstart.

Login quickstart If you are a Java EE wizard you may wish to skip this quickstart.
Kitchensink A great starting point for your project.
quickstart

Optional

Helloworld OSGi If you want to get started with OSGi in JBoss AS, check out this quickstart.
quickstart

Downloading the quickstarts


The quickstarts are distributed alongside JBoss AS (in a separate zip from the runtime) and are available for download from the JBoss AS
download page. Make sure you download the latest zip!

Getting started with JBoss AS


To run the examples with the provided build scripts, you'll need the following:

Java 1.6, to run JBoss AS and Maven


Maven 3, to build and deploy the examples
the JBoss AS 7 distribution zip
the JBoss AS 7 quickstarts zip

If you already have any of these pieces of software, there is no need to install them again!

Choose your Java runtime, and follow their installation instructions. For example, you could choose one of:

OpenJDK
Oracle Java SE
Oracle JRockit

Follow the official Maven installation guide if you don't already have Maven 3 installed. You can check which version of Maven you have installed
(if any) by running mvn --version. If you see a version newer than 3.0.0, you are ready to go.

You can also deploy the examples using your favorite IDE. We provide instructions for using Eclipse only.

Now, download JBoss AS 7 from the JBoss AS download page.

JBoss AS 7 offers the ability to manage multiple AS instances from a single control point. A collection of such servers are
referred to as members of a "domain", with a single Domain Controller process acting as the management control point.
Domains can span multiple physical (or virtual) machines, with all AS instances on a given host under the control of a Host
Controller process. The Host Controllers interact with the Domain Controller to control the lifecycle of the AS instances running
on that host and to assist the Domain Controller in managing them.

JBoss AS 7 also offers a standalone mode, which is perfect for a single server. We use this throughout the quickstart examples.

Installing and starting JBoss AS on Linux, Unix or Mac OS X


First, let's verify that verify that both Java and Maven are correctly installed. In a console, type:

You should see a version string (at least 1.6.0) printed. If not, contact your provider of Java for assistance. Next, type:

You should see a version string (at lest 3.0.0) printed. If not, contact the Maven community for assistance.

Next, we need to choose a location for JBoss AS to live. By default, JBoss AS 7 will be extracted into jboss-7.x.x.x (where 7.x.x.x matches
the version you downloaded):

Now, let's start JBoss AS in standalone mode:


If you want to stop JBoss AS, simply press Crtl-C whilst the terminal has focus.

That's it, JBoss AS is installed and running! Visit http://localhost:8080/ to check the server has started properly.

You can find the server log for standalone instances in jboss-7.x.x.x/standalone/log/server.log. The Getting
Started Guide covers more on configuring logging.

Installing and starting JBoss AS on Windows


First, let's verify that verify that both Java and Maven are correctly installed. In a Command Prompt, type:

You should see a version string (at least 1.6.0) printed. If not, contact your provider of Java for assistance. Next, type:

You should see a version string (at lest 3.0.0) printed. If not, contact the Maven community for assistance.

Next, we need to choose a location for JBoss AS to live. By default, JBoss AS 7 will be extracted into jboss-7.x.x.x (where 7.x.x.x matches
the version you downloaded). Unzip JBoss AS using your tool of choice.

Finally, let's start JBoss AS in standalone mode. Locate your JBoss AS installation and run standalone.bat located in bin.

If you want to stop JBoss AS, simply press Crtl-C whilst the terminal has focus.

That's it, JBoss AS is installed and running! Visit http://localhost:8080/ to check the server has started properly.

You can find the server log for standalone instances in jboss-7.x.x.x/standalone/log/server.log. The Getting
Started Guide covers more on configuring logging.

Starting JBoss AS from Eclipse with JBoss Tools


You may choose to use Eclipse rather than the command line to run JBoss AS, and to deploy the examples. If you don't wish to use Eclipse, you
should skip this section.

In order to use JBoss AS from Eclipse, you must first install JBoss AS for your operating system as described in Installing and
starting JBoss AS on Linux, Unix or Mac OS X or Installing and starting JBoss AS on Windows.

In order use JBoss AS from Eclipse, you'll need Eclipse Indigo (Eclipse 3.7) and JBoss Tools 3.3 M2 or newer. If you want to run the quickstarts
from Eclipse, you will also need m2eclipse. You can find instructions for installing Eclipse, m2eclipse and JBoss Tools on the JBoss Tools Site.
Make sure you install the Maven Support and Web and Java EE Development features.

Having successfully installed and started Eclipse, we need to add our JBoss AS instance to it. First, navigate to File -> New -> Other:
Now, locate the New Server Wizard:
And choose JBoss AS 7.0:
Hit Next >, and locate the JBoss AS 7 installation by clicking on Browse ...:
Now, choose the JBoss AS 7 installation directory:
Assuming you selected a valid installation, Eclipse should now allow you to hit Finish:
Now, let's start JBoss AS from Eclipse. If you previously started JBoss AS from the command line, you should stop it there first.

First, we need to make sure the Server tab is on view. Open the Window -> Show View -> Other... dialog:
And select the Server view:
You should see the Server View appear with the JBoss AS server:

Now, we can start the server. Right click on the server in the Server view, and select Start:
If you want to debug your application, you can simply select Debug rather than Start. This will start the server in debug mode,
and automatically attach the Eclipse debugger.

You'll see the server output in the Console:

That's it, we now have the server up and running in Eclipse!

Importing the quickstarts into Eclipse


In order to import the quickstarts into Eclipse, you will need m2eclipse installed. You can find instructions for installing Eclipse, m2eclipse and
JBoss Tools on the JBoss AS site.

First, choose File -> Import...:


Select Existing Maven Projects:
Click on Browse, and navigate to the quickstarts/ directory:
Finally, make sure all 4 quickstarts are found and selected, and click Finish:
Eclipse should now successfully import 4 projects:
It will take a short time to import the projects, as Maven needs to download the project's dependencies from remote repositories.

Managing JBoss Application Server


Here we will quickly outline how you can access both the command line interface and the web management interface for managing JBoss AS.
Detailed information for both can be found in the Admin Guide.

When the server is running, the web management interface can be accessed at http://localhost:9990/console. You can use the web management
interface to create datasources, manage deployments and configure the server.

JBoss AS also comes with a command line interface. To run it on Linux, Unix or Mac, execute:

Or, on Windows:

Once started, type help to discover the commands available to you.

Throughout this guide we use the jboss-as maven plugin to deploy and undeploy applications. This plugin uses the JBoss AS Native Java
Detyped Management API to communicate with the server. The Detyped API is used by management tools to control an entire domain of servers,
and exposes only a small number of types, allowing for backwards and forwards compatibility.

CDI + Servlet: Helloworld quickstart


This quickstart shows you how to deploy a simple servlet to JBoss AS. The business logic is encapsulated in a service, which is provided as a
CDI bean, and injected into the Servlet.

Contexts and Dependency Injection for Java EE


CDI is a new specification in Java EE 6, inspired by JBoss Seam and Google Guice, and also drawing on lessons learned from
frameworks such as Spring. It allows application developers to concentrate on developing their application logic by providing the
ability to wire services together, and abstract out orthogonal concerns, all in a type safe manner.

Switch to the quickstarts/helloworld directory and instruct Maven to build and deploy the application:

The quickstart uses a Maven plugin to deploy the application. The plugin requires JBoss AS to be running (you can find out how to start the server
in Installing and starting JBoss AS on Linux, Unix or Mac OS X or Installing and starting JBoss AS on Windows).

Now, check if the application has deployed properly by clicking http://localhost:8080/jboss-as-helloworld. If you see a "Hello World" message it's
all working!
Should you wish to undeploy the quickstart, or redeploy after making some changes, it's pretty easy:

mvn jboss-as:deploy - deploy any changes to the application to the application server
mvn jboss-as:undeploy - undeploy the example from JBoss AS

It's time to pull the covers back and dive into the internals of the example application.

Deploying the Helloworld example using Eclipse


You may choose to deploy the example using Eclipse. You'll need to have JBoss AS started in Eclipse (as described in Starting JBoss AS from
Eclipse with JBoss Tools) and to have imported the quickstarts into Eclipse (as described in Importing the quickstarts into Eclipse).

With the quickstarts imported, you can deploy the example by right clicking on the jboss-as-helloworld project, and choosing Run As ->
Run On Server:

Make sure the JBoss AS server is selected, and hit Finish:


You should see JBoss AS start up (unless you already started it in Starting JBoss AS from Eclipse with JBoss Tools) and the application deploy in
the Console log:

The helloworld example in depth


The helloworld is very simple - all it does is print "Hello World" onto a web page.

The helloworld example is comprised a servlet and a CDI bean. We also include an empty beans.xml file, which tells JBoss AS to look for beans
in this application and to activate the CDI. beans.xml is located in WEB-INF, which can be found in the src/main/webapp directory of the
example. Also in this directory we include index.html which uses a simple meta refresh to send the users browser to the Servlet, which is
located at http://localhost:8080/jboss-as-helloworld/HelloWorld.

All the configuration files for this example are located in WEB-INF/, which can be found in the src/main/webapp directory of the example.

Notice that we don't even need a web.xml!

Let's start by taking a look at the servlet:

HelloWorldServlet.java

Line Note

27 If you've used Servlet before, then you'll remember having to use xml to register your servlets. Fortunately, this is a thing of the past.
Now all you need to do is add the @WebServlet annotation, and provide a mapping to a URL used to access the servlet. Much
cleaner!

30-32 Every web page needs to be correctly formed HTML. We've created static Strings to hold the minimum header and footer to write out.

34,35 We inject the HelloService (a CDI bean) which generates the actual message. This allows to alter the implementation of
HelloService at a later date without changing the view layer at all (assuming we don't alter the API of HelloService).

41 We call into the service to generate the message "Hello World", and write it out to the HTTP request.

The package declaration and imports have been excluded from these listings. The complete listing is
available in the example source code.

Now we understand how the information is sent to the browser, let's take a look at the service.

HelloService.java

The service is very simple - no registration (XML or annotation) is required!

CDI + JSF: Numberguess quickstart


This quickstart shows you how to create and deploy a simple application to JBoss AS; the application does not persist any information.
Information is displayed using a JSF view, and business logic is encapsulated in two CDI beans.

Switch to the quickstarts/numberguess directory and instruct Maven to build and deploy the application:

The quickstart uses a Maven plugin to deploy the application. The plugin requires JBoss AS to be running (you can find out how to start the server
in Installing and starting JBoss AS on Linux, Unix or Mac OS X or Installing and starting JBoss AS on Windows).

Or you can start the server using an IDE, like Eclipse.

Now, see if you can determine the most efficient approach to pinpoint the random number at the URL http://localhost:8080/jboss-as-numberguess
.

Should you wish to undeploy the quickstart, or redeploy after making some changes, it's pretty easy:

mvn jboss-as:deploy - deploy any changes to the application to the application server
mvn jboss-as:undeploy - undeploy the example from JBoss AS

It's time to pull the covers back and dive into the internals of the example application.

Deploying the Numberguess example using Eclipse


You may choose to deploy the example using Eclipse. You'll need to have JBoss AS started in Eclipse (as described in Starting JBoss AS from
Eclipse with JBoss Tools) and to have imported the quickstarts into Eclipse (as described in Importing the quickstarts into Eclipse).

With the quickstarts imported, you can deploy the example by right clicking on the jboss-as-numberguess project, and choosing Run As ->
Run On Server:
Make sure the JBoss AS server is selected, and hit Finish:
You should see JBoss AS start up (unless you already started it in Starting JBoss AS from Eclipse with JBoss Tools) and the application deploy in
the Console log:

The numberguess example in depth


In the numberguess application you get 10 attempts to guess a number between 1 and 100. After each attempt, you're told whether your guess
was too high or too low.

The numberguess example is comprised of a number of beans, configuration files and Facelets (JSF) views, packaged as a war module. Let's
start by examining the configuration files.
All the configuration files for this example are located in WEB-INF/, which can be found in the src/main/webapp directory of the example. First,
we have the JSF 2.0 version of faces-config.xml. A standardized version of Facelets is the default view handler in JSF 2.0, so there's really
nothing that we have to configure. JBoss AS goes above and beyond Java EE here, and will automatically configure JSF for you if you include
this file. Thus, the configuration consists of only the root element.

faces-config.xml

There's also an empty beans.xml file, which tells JBoss AS to look for beans in this application and to activate the CDI.

Notice that we don't even need a web.xml!

Let's take a look at the main JSF view, src/main/webapp/home.xhtml.

JSF uses the .xhtml extension for source files, but serves up the rendered views with the .jsf extension.

home.xhtml

Line Note
number

20 - 24 There are a number of messages which can be sent to the user, "Higher!" and "Lower!"

29 - 32 As the user guesses, the range of numbers they can guess gets smaller - this sentence changes to make sure they know the number
range of a valid guess.

38 - 42 This input field is bound to a bean property using a value expression.

42 A validator binding is used to make sure the user doesn't accidentally input a number outside of the range in which they can guess -
if the validator wasn't here, the user might use up a guess on an out of bounds number.

43 - 45 There must be a way for the user to send their guess to the server. Here we bind to an action method on the bean.

The example consists of 4 classes, the first two of which are qualifiers. First, there is the
@Random qualifier, used for injecting a random number:

A qualifier is used to disambiguate between two beans both of which are eligible for injection based on their type. For more, see
the Weld Reference Guide.

Random.java

There is also the @MaxNumber qualifier, used for injecting the maximum number that can be injected:

MaxNumber.java

The application-scoped Generator class is responsible for creating the random number, via a producer method. It also exposes the maximum
possible number via a producer method:

Generator.java

The Generator is application scoped, so we don't get a different random each time.

The final bean in the application is the session-scoped Game class. This is the primary entry point of the application. It's responsible for setting up
or resetting the game, capturing and validating the user's guess and providing feedback to the user with a FacesMessage. We've used the
post-construct lifecycle method to initialize the game by retrieving a random number from the @RandomInstance<Integer> bean.

You'll notice that we've also added the @Named annotation to this class. This annotation is only required when you want to make the bean
accessible to a JSF view via EL (i.e., #{game}).

Game.java

CDI + JPA + EJB + JTA + JSF: Login quickstart


This quickstart shows you how to create and deploy an application which persists information to a database to JBoss AS. Information is displayed
using JSF views, business logic is encapsulated in CDI beans, information is persisted using JPA, and transactions can be controlled manually or
using EJB.

Switch to the quickstarts/login directory and instruct Maven to build and deploy the application:

The quickstart uses a Maven plugin to deploy the application. The plugin requires JBoss AS to be running (you can find out how to start the server
in Installing and starting JBoss AS on Linux, Unix or Mac OS X or Installing and starting JBoss AS on Windows).

Or you can start the server using an IDE, like Eclipse.

Visit http://localhost:8080/jboss-as-login and try logging in with the username demo and password demo. Now, click on Logout and then on View
Users. From this screen you can add yourself as a user, and then login as this user.

Should you wish to undeploy the quickstart, or redeploy after making some changes, it's pretty easy:

mvn jboss-as:deploy - deploy any changes to the application to the application server
mvn jboss-as:undeploy - undeploy the example from JBoss AS

It's time to pull the covers back and dive into the internals of the example application.

Deploying the Login example using Eclipse


You may choose to deploy the example using Eclipse. You'll need to have JBoss AS started in Eclipse (as described in Starting JBoss AS from
Eclipse with JBoss Tools) and to have imported the quickstarts into Eclipse (as described in [Importing the quickstarts into Eclipse).

With the quickstarts imported, you can deploy the example by right clicking on the jboss-as-login project, and choosing Run As -> Run On
Server:

Make sure the JBoss AS server is selected, and hit Finish:


You should see JBoss AS start up (unless you already started it in Starting JBoss AS from Eclipse with JBoss Tools) and the application deploy in
the Console log:

The login example in depth


In the login example, all users are stored in an H2 database (an in-memory, embedded database provided out of the box in JBoss AS). Each user
is stored as an entity, and entities are mapped to the database using JPA. By default, transactions are managed manually, using the JTA API.
Optionally, you can use EJB to manage transactions (we'll look at how to enable that later). We need a transaction in progress in order to read
and write any entities.
The login example is comprised of two JSF views, an entity, and a number of CDI beans. Additionally, there are the usual configuration files in
WEB-INF/ (which can be found in the src/main/webapp directory of the example). Here we find beans.xml and face-config.xml tell
JBoss AS to enable CDI and JSF for the application. Notice that we don't need a web.xml. There are two new configuration files in
WEB-INF/classes/META-INF (which can be found in the src/main/resources directory of the example) — persistence.xml, which sets
up JPA, and import.sql which Hibernate, the JPA provider in JBoss AS, will use to load the initial users into the application when the
application starts.

persistence.xml is pretty straight forward, and links JPA to a datasource:

persistence.xml

Line Note
number

6 The persistence unit is given a name, so that the application can use multiple if needed. If only one is defined, JPA will automatically
use it.

8 The persistence unit references a data source. Here we are using the built in, sample, data source.

10 JPA allows us to configure the JPA provider specific properties. Here we tell Hibernate to automatically create any needed tables
when the application starts (and drop them when the application is stopped).

JBoss AS ships with a sample datasource java:jboss/datasources/ExampleDS. This data source is backed by H2, an
in-memory database. Whilst this datasource is great for quickstarts, you will probably want to use a different datasource in your
application. The Getting Started Guide tells you how to create a new datasource.

Let's take a look at the JSF views. First up is src/main/webapp/home.xhtml:

home.xhtml

Line Note
number

7 As we have multiple views in this application, we've created a template that defines the common elements. We'll examine this next.
Here we define the "content" section of the page, which will be inserted into the template.

9 We output any messages for the user at the top of the form, such as the welcome message when you login.

11 - 16 The login form fields are only rendered if there is no logged in user. This allows us to prevent someone from logging in twice.

17, 18 Depending on whether the user is logged in or not, we display a log out or log in button. We also display a link to the page which
shows the available users.

Now let's take a look at the template. It defines common elements for the page, and allows pages which use it to insert content in various places.

template.xhtml

Line number Note

9 The head, defined in case a page wants to add some content to the head of the page.

23 The content, defined by a page using this template, will be inserted here

Finally, let's take a look at the user management page. It uses a table to display all existing users, and provides a form to add users

users.xhtml

Line Note
number

11 The table which displays the current users in the database. The datatable references the users, and iterates over each one. Each
user is assigned to the variable u, which we can use when laying out the table structure.

13 - 15 Each column in the table is given a header, plus content.

Finally, we provide a simple form that allows you to add a new user.
The example has one entity, which is mapped via JPA to the relational database:

User.java

Line Note
number

6 The @Entity annotation used on the class tells JPA that this class should be mapped as a table in the database.

8, 9 Every entity requires an id, the @Id annotation placed on a field (or a JavaBean mutator/accessor) tells JPA that this property is the
id. You can use a synthetic id, or a natural id (as we do here).

10, 11 The entity also stores the real name of the user, and their password.

13 - 35 As this is Java, every property needs an accessor/mutator!

Next up, let's take a look at Credentials.java, a data structure used to temporarily hold the credentials the user has entered whilst logging in.

Credentials.java

Line number Note

6 The bean is request scoped, as entered data is naturally scoped to a request.

7 The bean is given a name, so we can access it from JSF.

10 - 27 The bean needs to store the username and password entered, and also make them usable via accessors and mutators.

The logic allowing a user to log in, and storing who is currently logged in, is encoded in Login.java:

Login.java

Line Note
number

12 The bean is session scoped, meaning that the currently logged user is kept until the session ends.

13 The bean is given a name, so we can access it from JSF.

18, 19 We inject the credentials filled in on the web page so we can check them in the login() method.

21, 22 We inject the user manager, which takes care of loading and adding users from the database.

26 - 32 The login method is triggered when the Login button is pressed. It asks the userManager to find a user with matching username
and password, and if a user is found, sets the currentUser and displays a message to the user.

34 - 37 The logout method is triggered when the Logout button is pressed. It clears the currentUser and displays a message to the user.

43 - 47 The current user is exposed to the application using a producer method, which means that there is no coupling between a class
wanting to know the current user, and the Login class. The LoggedIn qualifier is used to indicate that this User is special.

Now, let's look at the most interesting part of the application, how we interact with the database. As we mentioned earlier, by default the
application uses the JTA API to manually control transactions. To implement both approaches, we've defined a UserManager interface, with two
implementations, one of which (the EJB variant) is as an alternative which can be enabled via a deployment descriptor. Let's first look at the
interface, and the manual transaction control variant.

UserManager.java

The methods are fairly self explanatory, so let's move on quickly to the implementation, ManagedBeanUserManager:

ManagedBeanUserManager.java

Line Note
number

13 The bean is given a name, so we can access it from JSF.


14 The bean is request scoped, meaning that the new user object being added is the same for every invocation of userManager during
the request.

17 - 18 We inject a JDK logger so that we can log when a user is added

20 - 21 We inject the entity manager. This was set up in persistence.xml.

29 - 45 We create a named producer method that uses JPA to expose all the users currently in the database. This allows JSF to access this
list. We also make this request scoped so that the database isn't hit every time we need to display the users list.

47 - 61 addUser takes the newUser and persists it to the database.

63 - 88 The findUser() method can check whether a user with a matching username and password exists, and return it if it does.

90 - 95 The newUser is exposed to JSF by using a named producer method.

You've probably noticed two things as you've read through this. Firstly, that manually managing transactions is a real pain. Secondly, you may be
wondering how the entity manager and the logger are injected. First, let's tidy up the transaction manager, and use EJB to provide us with
declarative transaction support.

The class EJBUserManager provides this, and is defined as an alternative. Alternatives are disabled by default, and when enabled replace the
original implementation. In order to enable this variant of UserManager, edit beans.xml and uncomment the alternative. Your beans.xml
should now look like:

Now, let's look at EJBUserManager:

EJBUserManager.java

Using declarative transaction management has allowed us to remove a third of the lines of code from the class, but more importantly emphasizes
the functionality of the class. Much better!

Sharp eyed developers who are used to Java EE will have noticed that we have added this EJB to a war. This is the key
improvement offered in EJB 3.1 (which was first included in Java EE 6).

Finally, let's take a look at the Resources class, which provides resources such as the entity manager. CDI recommends using "resource
producers", as we do in this example, to alias resources to CDI beans, allowing for a consistent style throughout our application:

Resources.java

Line Note
number

13 - 16 We use the "resource producer" pattern, from CDI, to "alias" the old fashioned @PersistenceContext injection of the entity
manager to a CDI style injection. This allows us to use a consistent injection style (@Inject) throughout the application.

18 - 22 We expose a JDK logger for injection. In order to save a bit more boiler plate, we automatically set the logger category as the class
name!

That concludes our tour of the login application!

CDI + JSF + EJB + JTA + Bean Validation + JAX-RS + Arquillian:


Kitchensink quickstart
This quickstart shows off all the new features of Java EE 6, and makes a great starting point for your project.

Bean Validation
Bean Validation is a new specification in Java EE 6, inspired by Hibernate Validator. It allows application developers to specify
constraints once (often in their domain model), and have them applied in all layers of the application, protecting data and giving
useful feedback to users.
JAX-RS: The Java API for RESTful Web Services
JAX-RS is a new specification in Java EE 6. It allows application developers to easily expose Java services as RESTful web
services.

Switch to the quickstarts/kitchensink directory and instruct Maven to build and deploy the application:

The quickstart uses a Maven plugin to deploy the application. The plugin requires JBoss AS to be running (you can find out how to start the server
in Installing and starting JBoss AS on Linux, Unix or Mac OS X or Installing and starting JBoss AS on Windows).

Or you can start the server using an IDE, like Eclipse.

Now, check if the application has deployed properly by clicking http://localhost:8080/jboss-as-kitchensink. If you see a splash page it's all working!

Should you wish to undeploy the quickstart, or redeploy after making some changes, it's pretty easy:

mvn jboss-as:deploy - deploy any changes to the application to the application server
mvn jboss-as:undeploy - undeploy the example from JBoss AS

It's time to pull the covers back and dive into the internals of the example application.

Deploying the Kitchensink example using Eclipse


You may choose to deploy the example using Eclipse. You'll need to have JBoss AS started in Eclipse (as described in Starting JBoss AS from
Eclipse with JBoss Tools) and to have imported the quickstarts into Eclipse (as described in Importing the quickstarts into Eclipse).

With the quickstarts imported, you can deploy the example by right clicking on the jboss-as-kitchensink project, and choosing Run As ->
Run On Server:
Make sure the JBoss AS server is selected, and hit Finish:
You should see JBoss AS start up (unless you already started it in Starting JBoss AS from Eclipse with JBoss Tools) and the application deploy in
the Console log:

The kitchensink example in depth


The kitchensink application shows off a number of Java EE technologies such as CDI, JSF, EJB, JTA, JAX-RS and Arquillian. It does this by
providing a member registration database, available via JSF and JAX-RS.

As usual, let's start by looking at the necessary deployment descriptors. By now, we're very used to seeing beans.xml and
faces-config.xml in WEB-INF/ (which can be found in the src/main/webapp directory of the example). Notice that, once again, we don't
need a web.xml. There are two configuration files in WEB-INF/classes/META-INF (which can be found in the src/main/resources
directory of the example) — persistence.xml, which sets up JPA, and import.sql which Hibernate, the JPA provider in JBoss AS 7, will use
to load the initial users into the application when the application starts. We discussed both of these files in detail in The login example in depth,
and these are largely the same.

Next, let's take a look at the JSF view the user sees. As usual, we use a template to provide the sidebar and footer. This one lives in
WEB-INF/templates/default.xhtml:

default.xhtml

Line number Note

6 - 10 We have a common <head> element, where we define styles and more.

14 - 51, 56 - 61 This application defines a common sidebar and footer, putting them in the template means we only have to define them once/

52 - 54 The content is inserted here, and defined by views using this template.

That leaves the main page, index.xhtml, in which we place the content unique to the main page:

index.xhtml

Line Note
number

12 - 48 The JSF form allows us to register new users. There should be one already created when the application started.

22, 31, The application uses Bean Validation to validate data entry. The error messages from Bean Validation are automatically attached to
40 the relevant field by JSF, and adding a messages JSF component will display them.

53 - 77 This application exposes REST endpoints for each registered member. The application helpfully displays the URL to the REST
endpoint on this page.

Next, let's take a look at the Member entity, before we look at how the application is wired together:

Memberjava

Line Note
number

20 As usual with JPA, we define that the class is an entity by adding @Entity

21 Members are exposed as a RESTful service using JAX-RS. We can use JAXB to map the object to XML and to do this we need to
add @XmlRootElement.

22 Set the email address as a unique constraint for the table

31 - 33 Bean Validation allows constraints to be defined once (on the entity) and applied everywhere. Here we constrain the person's name
to a certain size and regular expression.

38 Hibernate Validator also offers some extra validations such as @Email.

41 - 43 @Digits, @NotNull and @Size are further examples of constraints.

Next, let's take a look at MemberListProducer, which is responsible for building the list of members, ordered by name. It uses JPA 2 criteria to
do this.

MemberListProducer.java

Line Note
number

18 This bean is request scoped, meaning that any fields (such as members) will be stored for the entire request.

26 - 30 The list of members is exposed as a producer method, it's also available via EL.
32 - 34 The observer method is notified whenever a member is created, removed, or updated. This allows us to refresh the list of members
whenever they are needed. This is a good approach as it allows us to cache the list of members, but keep it up to date at the same
time.

36 - 45 JPA 2's criteria API is used to create a list of members sorted by name. You can try out the type safe criteria API as well by
swapping the criteria statements as described.

Let's now look at MemberRegistration, the class that allows us to create new members from the JSF page

MemberRegistration.java

Line Note
number

18 This bean requires transactions as it needs to write to the database. Making this an EJB gives us access to declarative transactions -
much simpler than manual transaction control!

21 Stereotypes, such as @Model allow grouping of common functionality. Here we use the built in @Model stereotype to give us a
request scoped, named bean.

26 - 28 Seam Solder, used in this project offers an injectable logger based on JBoss Logging.

47 An event is sent every time a member is updated. This allows other pieces of code (in this example the member list is refreshed) to
react to changes in the member list without any coupling to this class.

Seam Solder is a swiss army knife for any CDI based application. It offers some basic additions to the CDI programming model
(such as an injectable, type-safe, logger) as well as utilities for developing CDI extensions. You can read more on the Solder
project page.

Now, let's take a look at the Resources class, which provides resources such as the entity manager. CDI recommends using "resource
producers", as we do in this example, to alias resources to CDI beans, allowing for a consistent style throughout our application:

Resources.java

Line Note
number

21 - 24 We use the "resource producer" pattern, from CDI, to "alias" the old fashioned @PersistenceContext injection of the entity
manager to a CDI style injection. This allows us to use.

If you want to define your own datasource, take a look at the Getting Started Guide or at the JBoss AS wiki.

Before we wrap up our tour of the kitchensink example application, let's take a look at how the JAX-RS endpoints are created. Firstly,
{JaxRSActivator}}, which extends Application and is annotated with @ApplicationPath, is the Java EE 6 "no XML" approach to activating
JAX-RS.

The real work goes in MemberResourceRESTService, which produces the endpoint:

MembeResourceRESTService.java

Line Note
number

20 The @Path annotation tells JAX-RS that this class provides a REST endpoint mapped to rest/members (concatenating the path
from the activator with the path for this endpoint).

23, 24 JAX-RS endpoints are CDI enabled, and can use CDI-style injection.

26 - 35 The listAllMembers() method is called when the raw endpoint is accessed and offers up a list of endpoints. Notice that the
object is automatically mapped to XML by JAXB.

37 - 42 The lookupMemberById() method is called when the endpoint is accessed with a member id parameter appended (for example
rest/members/1). Again, the object is automatically mapped to XML by JAXB.

Arquillian
If you've been following along with the Test Driven Development craze of the past few years, you're probably getting a bit nervous by now,
wondering how on earth you are going to test your application. Lucky for you, the Arquillian project is here to help!

Arquillian provides all the boiler plate for running your test inside JBoss AS, allowing you to concentrate on testing your application. In order to do
that, it utilizes Shrinkwrap, a fluent API for defining packaging, to create an archive to deploy. We'll go through the testcase, and how you
configure Arquillian in just a moment, but first let's run the test.

Before we start, we need to let Arquillian know the path to our JBoss AS install. Open up src/test/resources/arquillian.xml and set the
jbossHome property to the path to your JBoss AS install:

Now, make sure JBoss AS is not running (so that the instance started for running the test does not interfere), and then run the tests from the
command line by typing:

You should see JBoss AS start up, a test.war deployed, test executed, and then the results displayed to you on the console:

As you can see, that didn't take too long (approximately 15s), and is great for running in your QA environment, but if you running locally, you might
prefer to connect to a running JBoss AS. To do that, start up JBoss AS (as described in Getting started with JBoss AS). Now, run your test, but
use the arq-jbossas-remote profile:

Arquillian defines two modes, managed and remote. The managed mode will take care of starting and stopping the server for
you, whilst the remote mode connects to an already running server.

This time you can see the test didn't start JBoss AS (if you check the instance you started, you will see the application was deployed there), and
the test ran a lot faster (approximately 4s).

We can also run the test from Eclipse, in both managed and remote modes. First, we'll run in in managed mode. In order to set up the correct
dependencies on your classpath, right click on the project, and select Properties:
Now, locate the Maven panel:
And activate the arq-jbossas-managed profile:

Finally, hit Ok, and then confirm you want to update the project configuration:
Once the project has built, locate the MemberRegistrationTest in src/test/java, right click on the test, and choose Run As -> JUnit
Test...:

You should see JBoss AS start in the Eclipse Console, the test be deployed, and finally the JUnit View pop up with the result (a pass of course!).

We can also run the test in an already running instance of Eclipse. Simply change the active profile to arq-jbossas-remote:
Now, make sure JBoss AS is running, right click on the test case and choose Run As -> JUnit Test:
Again, you'll see the test run in the server, and the JUnit View pop up, with the test passing.

So far so good, the test is running in both Eclipse and from the command line. But what does the test look like?

MemberRegistrationTest.java

Line Note
number

23 @RunWith(Arquillian.class) tells JUnit to hand control over to Arquillian when executing tests

25 The @Deployment annotation identifies the createTestArchive static method to Arquillian as the one to use to determine
which resources and classes to deploy

28 We add just the classes needed for the test, no more

29 We also add persistence.xml as our test is going to use the database

30 Of course, we must add beans.xml to enable CDI

24 - 28 Arquillian allows us to inject beans into the test case

41 - 49 The test method works as you would expect - creates a new member, registers them, and then verifies that the member was
created

As you can see, Arquillian has lived up to the promise - the test case is focused on what to test (the @Deployment method) and how to test (the
@Test method). It's also worth noting that this isn't a simplistic unit test - this is a fully fledged integration test that uses the database.

Now, let's look at how we configure Arquillian. First of all, let's take a look at arquillian.xml in src/test/resources.

arquillian.xml
Line Note
number

9 Arquillian deploys the test war to JBoss AS, and doesn't write it to disk. For debugging, it can be very useful to see exactly what is in
your war, so Arquillian allows you to export the war when the tests runs

13 - 17 Arquillian currently needs configuring to use JMX to connect to JBoss AS

Now, we need to look at how we select between containers in the pom.xml:

pom.xml

Line number Note

204 The profile needs an id so we can activate from Eclipse or the command line

206 - 211 Arquillian decides which container to use depending on your classpath. Here we define the managed JBoss AS container.

222 - 217 Arquillian decides which container to use depending on your classpath. Here we define the remote JBoss AS container.

And that's it! As you can see Arquillian delivers simple and true testing. You can concentrate on writing your test functionality, and run your tests
in the same environment in which you will run your application.

Arquillian also offers other containers, allowing you to run your tests against Weld Embedded (super fast, but your enterprise
services are mocked), GlassFish, and more

That concludes our tour of the kitchensink quickstart. If you would like to use this project as a basis for your own application on JBoss AS, you can
of course copy this application sources and modify it.

OSGi: Helloworld OSGi quickstart


This quickstart shows you how to create and deploy a simple OSGi Bundle.

What is OSGi?
OSGi is a new feature in JBoss AS 7. It provides standards-based modularity and micro-services as defined in the OSGi 4.2
Core Specifications. You can deploy OSGi bundles directly into JBoss AS.

For more information on OSGi and on how to develop OSGi bundles, see the OSGi 4.2 Core Specification and the OSGi 4.2
Core Javadoc.

More information on the OSGi component in JBoss AS can be found on the JBoss OSGi project pages.

Switch to the quickstarts/helloworld-osgi directory and instruct Maven to build and deploy the application:

Now, you should see the OSGi subsystem start up, and the bundle deployed and started:
If you wish to undeploy the quickstart, or redeploy after making some changes, it's pretty easy:

mvn jboss-as:deploy - deploy any changes to the application to the application server
mvn jboss-as:undeploy - undeploy the example from JBoss AS

The Helloworld OSGi example in depth


The OSGi Bundle has one Java Source file, the Bundle Activator:

Activator.java

The bundle activator is very simple, and just prints out a message when the bundle starts and stops - allowing you to verify that OSGi is working
properly.

Now, let's look at the pom.xml, where we create the bundle:

pom.xml

Line Note
numbers

10 The packaging of the maven module is set to bundle. This instructs maven and the maven-bundle-plugin to create an OSGi
bundle.

62 - 67 Since the activator uses an OSGi interface, these are provided through the OSGi interfaces artifact.

66 Use the provided scope for dependencies that are either provided by the OSGi framework (i.e. JBoss AS) itself or for
dependencies that are provided through separate bundles.

71 - 98 The maven-bundle-plugin is used to create a bundle. You can configure it create import and export statements, and to specify
the activator in use. You can read more about the OSGi Bundle Maven Plugin on the Apache Felix site.

100 - We can use the jboss-as Maven plugin to deploy the bundle to JBoss AS as usual.
108
As you can see, using OSGi with JBoss AS is pretty easy!

Creating a new OSGi bundle using Eclipse


Eclipse has built-in support for creating OSGi bundles. Eclipse is built on OSGi, therefore support for developing OSGi bundles inside Eclipse is
quite extensive.

To quickly create an OSGi Bundle using Eclipse, follow these steps. In Eclipse do File -> New -> Project -> Plug-in Project:

Select as the Target Platform a 'Standard' OSGi Framework and click Next >.

On the following page, you can specify the Bundle Symbolic Name, version, Bundle Activator and some other details. You may use the defaults,
or, for example, you could put the Activator in a different package, e.g. org.jboss.as.quickstarts.helloworld.osgi.Activator.

Click Next > again.

On the Templates page select the 'Hello OSGi Bundle' template and click Finish:
After clicking Finish, the Plug-In Development perspective will open with the Manifest Editor. The Manifest Editor facilitates editing of the OSGi
Metadata, such as the Imported Packages in the Dependencies tab and Exported Packages on the Runtime tab:
Click on the Activator link in the Manifest editor to open the Bundle Activator in the Java editor.
When finished making changes you can export your OSGi bundle so that it can be deployed directly into JBoss AS. Click on File -> Export
-> Deployable plug-ins and fragments:

You have now created an OSGi Bundle, and the JAR can be found in the plugins directory of the location specified in the screen above. You
can deploy it to JBoss AS using any of the standard deployment mechanisms described in the Getting Started Guide.

Creating your own application


What we didn't tell you about the Kitchensink quickstart is that it is generated from a Maven archetype. Using this archetype offers you the perfect
opportunity to generate your own project.

Watch and learn

To use the archetype to generate a new project, you should run:

Maven will download the archetype and it's dependencies, and ask you some questions:
Instruction

1 Enter the groupId you wish to use

2 Enter the artifactId you wish to use

3 Enter the version you wish to use, or just hit Enter if you wish to accept the default 1.0-SNAPSHOT

4 Enter the java package you wish to use, or just hit Enter if you wish to accept the default (which is copied from groupId).

5 Finally, if you are happy with your choices, hit Enter and Maven will generate the project for you.

And that's it, you now have a brand new project with the same functionality as kitchensink, but customized with your details.

Of course, you can create a project from the archetype using Eclipse, saving you the step of importing it. First, choose File -> New -> Other
:

Select the Maven Project wizard:


If you wish, customize the project creation, otherwise, just hit Next >:
Locate the jboss-javaee6-webapp archetype:
If you can't find the archetype, you probably need to add the JBoss Archetype Catalog. Hit Configure... for the Catalog:
Click on Add Remote Catalog..., and add this catalog https://repository.jboss.org/nexus/content/groups/public/archetype-catalog.xml as the
JBoss Archetype Catalog:

Now hit Ok and Ok. You should now see the jboss-javaee6-webapp archetype.
Next, fill in the groupId and artifactId, and hit Finish:

You should now have a brand new project:


Enjoy!

More Resources
Getting Started The Getting Started Guide covers topics such as server layout (what you can configure where), data source definition, and
Guide using the web management interface.

Torquebox Torque Box allows you to use all the familiar services from JBoss AS 7, but with Ruby.

JBoss AS 7 Frequently Asked Questions for JBoss AS 7


FAQ

All JBoss AS 7 documentation


There are several guides in the JBoss Application Server 7 documentation series. This list gives an overview of each of the guides:

*Getting Started Guide - Explains how to download and start JBoss Application Server 7.
*Getting Started Developing Applications Guide - Talks you through developing your first applications on JBoss Application Server 7, and
introduces you to JBoss Tools and how to deploy your applications.
*JavaEE 6 Tutorial - A Java EE 6 Tutorial.
*Admin Guide - Tells you how to configure and manage your JBoss Application Server 7 instances.
*Developer Guide - Contains concepts that you need to be aware of when developing applications for JBoss Application Server 7. Classloading is
explained in depth.
*High Availability Guide - Reference guide for how to set up clustered JBoss Application Server 7 instances.
*Extending JBoss AS 7 - A guide to adding new functionality to JBoss Application Server 7.

You might also like