Java EE 7 with GlassFish 4 Application Server

4 (1 reviews total)
  • Instant online access to over 7,500+ books and videos
  • Constantly updated with 100+ new titles each month
  • Breadth and depth in over 1,000+ technologies
  1. Getting Started with GlassFish

About this book

GlassFish is a free, open source application server which supports all the major Java features such as Enterprise JavaBeans, JPA, JavaServer Faces, JMS, RMI, JavaServer Pages, and servlets. It is the first Java EE 7 compliant application server. All major Java EE technologies and API's are covered in this version of Java. GlassFish server allows the user to work with the extensile, adaptable, and lightweight Java EE 7 platform.

This book explores the installation and configuration of GlassFish, and then moves on to Java EE 7 application development, covering all major Java EE 7 APIs. It focuses on going beyond the basics to develop Java applications deployed to the GlassFish 4 application server. The book covers all major Java EE 7 APIs including JSF 2.2, EJB 3.2, CDI 1.1, the Java API for WebSocket, JAX-WS, JAX-RS and more.

The book also introduces JSON-P, the Java API for JSON (Javascript Object Notation) Processing. This advanced topic deals with how the two APIs are used to process JSON function, namely the Model API and the Streaming API. Apart from revisiting Java Server Faces (JSF), it explains why Facelets, the new features introduced in modern versions of JSF, are the preferred view technology over Java Server Pages (JSP)

The later chapters explore competing implementations of the WebSocket standard in Java, describing the updates in JMS; which aims to provide a simpler API and reduction in boilerplate code among a host of other features. Readers will also learn how to secure Java EE applications by taking advantage of GlassFish's built-in security features. Finally, we learn more about the RESTful web service development using the JAX-RS specification.

Publication date:
March 2014
Publisher
Packt
Pages
348
ISBN
9781782176886

 

Chapter 1. Getting Started with GlassFish

In this chapter, we will discuss how to get started with GlassFish. The following are some of the topics discussed in this chapter:

  • An overview of Java EE and GlassFish

  • Obtaining GlassFish

  • Installing and starting GlassFish

  • Explaining the concept of GlassFish domains

  • Deploying Java EE applications

  • Setting up Database Connectivity

 

An Overview of Java EE and GlassFish


Java Enterprise Edition (Java EE, formerly called J2EE or Java 2 Enterprise Edition) is a standard set of technologies for server-side Java development. Java EE technologies include JavaServer Faces (JSF), Enterprise JavaBeans (EJBs), the Java Messaging Service (JMS), the Java Persistence API (JPA), the Java API for WebSocket, Contexts and Dependency Injection (CDI), the Java API for XML Web Services (JAX-WS), the Java API for RESTful Web Services (JAX-RS), and the Java API for JSON Processing (JSON-P), among others.

Several commercial and open source application servers exist. Java EE application servers allow developers to develop and deploy Java EE-compliant applications, GlassFish being one of them. Other open source Java EE application servers include Red Hat's WildFly (formerly JBoss), the Apache Software Foundation's Geronimo, and ObjectWeb's JOnAS. Commercial application servers include Oracle's WebLogic, IBM's WebSphere, and the Oracle Application Server.

GlassFish is the Java EE 7 reference implementation; as such, it implements the latest Java EE APIs before any other application server in the market. GlassFish is open source and freely available, and is licensed under the Common Development and Distribution License (CDDL).

Note

You can find out more about the CDDL license at http://opensource.org/licenses/CDDL-1.0.

Like all Java EE-compliant application servers, GlassFish provides the necessary libraries to allow us to develop and deploy Java applications compliant with Java EE specifications.

What's new in Java EE 7?

Java EE 7, the latest version of the Java EE specification, includes several improvements and additions to the specification. The following sections list the major improvements to the specifications that are of interest to enterprise application developers:

JavaServer Faces (JSF) 2.2

Java EE 7 includes a new version of the JavaServer Faces (JSF) specification. JSF 2.2 includes the following notable new features:

  • JSF 2.2 features the HTML5 friendly markup, that is, web pages can be written using the standard HTML 5 markup and using JSF-specific attributes on the HTML tags.

  • JSF 2.2 also includes Faces Flows, which provides a way to encapsulate related pages with defined entry and exit points.

  • Resource library contracts are the third major JSF feature introduced in JSF 2.2. Resource library contracts allow us to easily develop web applications that can have a different look and feel for different users using JSF.

Java Persistence API (JPA) 2.1

JPA was introduced as a standard part of Java EE in version 5 of the specification. JPA replaced entity beans as the standard object relational mapping framework for Java EE. JPA adopted ideas from third-party object relational frameworks such as Hibernate and JDO, and made them a part of the standard.

JPA 2.1 introduces the following new features:

  • JPA 2.1 introduces the concept of Converters, which allows custom code conversions between values stored in the database and values stored in Java objects. For instance, a common problem when working with database data is that the desired value in Java code differs from the value stored in the database. For example, the values 1 and 0 are commonly stored in the database to denote true and false respectively. Java has a perfectly good boolean type, so true and false can be used directly.

  • The JPA Criteria API can now perform bulk updates and deletes.

  • JPA 2.1 now supports stored procedures.

  • JPA 2.1 introduces the @ConstructorResult annotation, which allows returning standard Java classes (but not the JPA entities) from native SQL queries.

Java API for RESTful Web Services (JAX-RS) 2.0

JAX-RS is a Java API for developing RESTful web services. RESTful web services use the Representational State Transfer (REST) architecture. Java EE 6 adopted JAX-RS as an official part of the Java EE specification.

JAX-RS 2.0 includes the following new features:

  • JAX-RS 2.0 introduces a new client-side API. While previous versions of JAX-RS made it easy to develop RESTful web services, each implementation defined its own proprietary client-side API.

  • Extension points, method filters, and entity interceptors are also introduced in JAX-RS 2.0. These features allow Aspect Oriented Programming (AOP) when developing RESTful web services.

  • JAX-RS 2.0 also introduces asynchronous processing both on the server side and as part of the client API.

Java Message Service (JMS) 2.0

The Java Message Service (JMS) API has been completely revamped in Java EE 7. Previous versions of JMS required lots of boilerplate code; with the new revamped JMS 2.0 API, this is no longer the case.

Java API for JSON Processing (JSON-P) 1.0

JSON-P is a brand new API introduced in Java EE 7. JSON-P allows us to parse and generate JSON (JavaScript Object Notation) strings.

Java API for WebSocket 1.0

Traditional web applications use a request-response model, that is, a client (typically a web browser) requests resources and the server provides a response. In this model, communication is always initiated by the client.

WebSockets were introduced as part of the HTML5 specification; they provide full-duplex communication between the client and the server.

GlassFish advantages

With so many options in Java EE application servers, why choose GlassFish? Besides the obvious advantage of GlassFish being available free of charge, it offers the following benefits:

  • Java EE reference implementation: GlassFish is the Java EE reference implementation. What this means is that other application servers may use GlassFish to make sure their product complies with the specification. GlassFish could theoretically be used to debug other application servers. If an application deployed under another application server is not behaving properly, but it does behave properly when deployed under GlassFish, then more than likely the improper behavior is due to a bug in the other application server.

  • Supports the latest versions of the Java EE specification: Since GlassFish is the reference Java EE specification, it tends to implement the latest specifications before any other application server in the market. As a matter of fact, at the time of writing, GlassFish is the only Java EE application server in the market that supports the complete Java EE 7 specification.

 

Obtaining GlassFish


GlassFish can be downloaded at https://glassfish.java.net.

Note

GlassFish 4.0 is also bundled with the NetBeans IDE version 7.4 or newer.

Once there, you will see a window as shown in the following screenshot:

Clicking on the Download link takes us to a wizard page that provides several options to download GlassFish as shown in the following screenshot:

The download page has several options; we can get the full Java EE platform or the web profile. We can also download GlassFish as a compressed ZIP file or as a native installer for the operating system of our choice.

To be able to follow all of the examples in this book, we need to download the full Java EE platform version of GlassFish. We will download the compressed ZIP file version since the instructions to install it are very similar across any operating system; feel free to download a platform-specific installer if you prefer.

 

Installing GlassFish


We will use the ZIP installer to illustrate the installation process. This installation process works under all major operating systems.

Installing GlassFish is an easy process; however, GlassFish assumes that some dependencies are present in your system.

GlassFish dependencies

In order to install GlassFish 4, a recent version of the Java Development Kit (JDK) must be installed on your workstation (JDK 1.7 or newer required), and the Java executable file must be in your system PATH. The latest JDK can be downloaded at http://www.oracle.com/technetwork/java/javase/downloads/index.html. Please refer to the JDK installation instructions for your particular platform at http://docs.oracle.com/javase/7/docs/webnotes/install/index.html.

Performing the installation

Once JDK has been installed, the GlassFish installation can begin by simply extracting the download compressed file as shown in the following screenshot:

Note

All modern operating systems including Linux, Windows, and Mac OS X include out-of-the-box support to extract compressed ZIP files; consult your operating system documentation for details.

After extracting the ZIP file, a new directory named glassfish4 will be created. This new directory contains our GlassFish installation.

 

Starting GlassFish


To start GlassFish from the command line, change your directory to [glassfish installation directory]/glassfish4/bin and execute the following command:

./asadmin start-domain domain1

Note

The preceding command, and most commands shown in this chapter, assume a Unix or Unix-like operating system such as Linux or Mac OS. For Windows systems, the initial ./ is not necessary.

A few short seconds after executing the preceding command, we should see a message similar to the following at the bottom of the terminal:

$ ~/GlassFish/glassfish4/bin $ ./asadmin start-domain
Waiting for domain1 to start ........
Successfully started the domain : domain1
domain  Location: /home/heffel/GlassFish/glassfish4/glassfish/domains/domain1
Log File: /home/heffel/GlassFish/glassfish4/glassfish/domains/domain1/logs/server.log
Admin Port: 4848
Command start-domain executed successfully.

Tip

Downloading the example code

You can download the sample code files for all the Packt books that you have purchased from your account at http://www.packtpub.com. If you purchased this book elsewhere, you can visit http://www.packtpub.com/support and register to have the files e-mailed directly to you.

We can then open a browser window and type the following URL in the browser's location text field:

http://localhost:8080

If everything goes well, we should see a page indicating that your GlassFish server is now running as shown in the following screenshot:

Tip

Getting Help

If any of the preceding steps fail or for help with GlassFish in general, a great resource is the GlassFish forum at https://www.java.net/forums/glassfish/glassfish.

Deploying our first Java EE application

To further confirm that our GlassFish installation is running properly, we will deploy a WAR (Web ARchive) file and make sure the file deploys and executes properly. Before moving on, please download the file simpleapp.war from this book's web site at www.packtpub.com.

Deploying an application through the Web Console

To deploy simpleapp.war, open a browser and navigate to http://localhost:4848. You should be greeted with the default GlassFish server administration page as shown in the following screenshot:

By default, GlassFish is installed in development mode. In this mode, it is not necessary to enter a username and password to access the GlassFish web console. In production environments, it is highly advisable to configure the web console so that it is password protected.

At this point, we should click on the Deploy an Application item under the Deployment section on the main screen.

To deploy our application, we should select the Local Packaged File or Directory That is Accessible from GlassFish Server radio button and either type the path to our WAR file or select it by clicking on the Browse Files... button. Once this is done, you will see a window as shown in the following screenshot:

After we have selected our WAR file, a number of input fields that allow us to specify several options are shown. For our purposes, all defaults are fine. We can simply click on the OK button at the top right of the page as shown in the following screenshot:

Once we deploy our application, the GlassFish web console displays the Applications window, with our application listed as one of the deployed applications as shown in the following screenshot:

To execute the simpleapp application, type the following URL in the browser's location text field:

http://localhost:8080/simpleapp/simpleservlet

The resulting page should look like the following screenshot:

That's it! We have successfully deployed our first Java EE application.

Undeploying an application through the GlassFish Admin Console

To undeploy the application we just deployed, log in to the GlassFish Admin Console by typing the following URL in the browser:

http://localhost:4848

Then, either click on the Applications menu item in the navigation pane on the left, or click on the List Deployed Applications item on the administration console's home page.

Either way should take us to the application management page as shown in the following screenshot:

The application can be undeployed simply by selecting the checkbox next to the simpleapp name from the list of deployed applications and clicking on the Undeploy button above the list of deployed applications.

Once our application has been undeployed, it is no longer shown on the application management page as shown in the following screenshot:

Deploying an application through the command line

There are two ways in which an application can be deployed through the command line—it can be done either by copying the artifact we want to deploy to an autodeploy directory, or by using GlassFish's asadmin command-line utility.

The autodeploy directory

Now that we have undeployed the simpleapp WAR file, we are ready to deploy it using the command line. To deploy the application in this manner, simply copy simpleapp.war to [glassfish installation directory]/glassfish4/glassfish/domains/domain1/autodeploy. The application will automatically be deployed just by copying it to this directory.

We can verify that the application has successfully been deployed by looking at the server log. The server log can be found by typing [glassfish installation directory]/glassfish4/glassfish/domains/domain1/logs/server.log. The last few lines on this file should look something like the following:

[2013-08-02T10:57:45.387-0400] [glassfish 4.0] [INFO] [NCLS-DEPLOYMENT-00027] [javax.enterprise.system.tools.deployment.autodeploy] [tid: _ThreadID=91 _ThreadName=AutoDeployer] [timeMillis: 1375455465387] [levelValue: 800] [[

  Selecting file /home/heffel/GlassFish/glassfish4/glassfish/domains/domain1/autodeploy/simpleapp.war for autodeployment]]

[2013-08-02T10:57:45.490-0400] [glassfish 4.0] [INFO] [] [javax.enterprise.system.tools.deployment.common] [tid: _ThreadID=91 _ThreadName=AutoDeployer] [timeMillis: 1375455465490] [levelValue: 800] [[

  visiting unvisited references]]

[2013-08-02T10:57:45.628-0400] [glassfish 4.0] [INFO] [AS-WEB-GLUE-00172] [javax.enterprise.web] [tid: _ThreadID=91 _ThreadName=AutoDeployer] [timeMillis: 1375455465628] [levelValue: 800] [[

  Loading application [simpleapp] at [/simpleapp]]]

[2013-08-02T10:57:45.714-0400] [glassfish 4.0] [INFO] [] [javax.enterprise.system.core] [tid: _ThreadID=91 _ThreadName=AutoDeployer] [timeMillis: 1375455465714] [levelValue: 800] [[

  simpleapp was successfully deployed in 302 milliseconds.]]

[2013-08-02T10:57:45.723-0400] [glassfish 4.0] [INFO] [NCLS-DEPLOYMENT-00035] [javax.enterprise.system.tools.deployment.autodeploy] [tid: _ThreadID=91 _ThreadName=AutoDeployer] [timeMillis: 1375455465723] [levelValue: 800] [[


  [AutoDeploy] Successfully autodeployed : /home/heffel/GlassFish/glassfish4/glassfish/domains/domain1/autodeploy/simpleapp.war.]]

We can, of course, also verify the deployment by navigating to the same URL for the application, which we used when deploying through the web console: http://localhost:8080/simpleapp/simpleservlet.

Once here, the application should execute properly.

An application deployed this way can be undeployed by simply deleting the artifact (WAR file, in our case) from the autodeploy directory. After deleting the file, we should see a message similar to the following in the server log:

[2013-08-02T11:01:57.410-0400] [glassfish 4.0] [INFO] [NCLS-DEPLOYMENT-00026] [javax.enterprise.system.tools.deployment.autodeploy] [tid: _ThreadID=91 _ThreadName=AutoDeployer] [timeMillis: 1375455717410] [levelValue: 800] [[

  Autoundeploying application:  simpleapp]]


[2013-08-02T11:01:57.475-0400] [glassfish 4.0] [INFO] [NCLS-DEPLOYMENT-00035] [javax.enterprise.system.tools.deployment.autodeploy] [tid: _ThreadID=91 _ThreadName=AutoDeployer] [timeMillis: 1375455717475] [levelValue: 800] [[

  [AutoDeploy] Successfully autoundeployed : /home/heffel/GlassFish/glassfish4/glassfish/domains/domain1/autodeploy/simpleapp.war.]]
The asadmin command-line utility

An alternate way of deploying an application through the command line is to use the following command:

asadmin deploy [path to file]/simpleapp.war

Note

The preceding command must be executed from the [glassfish installation directory]/glassfish4/bin path.

We should see the following confirmation on the command line terminal letting us know that the file was deployed successfully:

Application deployed with name simpleapp.

Command deploy executed successfully.

The server logfile should show a message similar to the following:

[2013-08-02T11:05:34.583-0400] [glassfish 4.0] [INFO] [AS-WEB-GLUE-00172] [javax.enterprise.web] [tid: _ThreadID=37 _ThreadName=admin-listener(5)] [timeMillis: 1375455934583] [levelValue: 800] [[

  Loading application [simpleapp] at [/simpleapp]]]

[2013-08-02T11:05:34.608-0400] [glassfish 4.0] [INFO] [] [javax.enterprise.system.core] [tid: _ThreadID=37 _ThreadName=admin-listener(5)] [timeMillis: 1375455934608] [levelValue: 800] [[

  simpleapp was successfully deployed in 202 milliseconds.]]

The asadmin executable can be used to undeploy an application as well by issuing a command like the following:

asadmin undeploy simpleapp

The following message should be shown at the bottom of the terminal window:

Command undeploy executed successfully.

Please note that the file extension is not used to undeploy the application, the argument to asadmin undeploy should be the application name, which is, by default, the WAR file name (minus the extension).

 

GlassFish domains


Alert readers might have noticed that the autodeploy directory is under a domains/domain1 subdirectory. GlassFish has a concept of domains. Domains allow a collection of related applications to be deployed together. Several domains can be started concurrently. GlassFish domains behave like individual GlassFish instances; a default domain called domain1 is created when installing GlassFish.

Creating Domains

Additional domains can be created from the command line by issuing the following command:

asadmin create-domain domainname

The preceding command takes several parameters to specify ports where the domain will listen to for several services (HTTP, Admin, JMS, IIOP, Secure HTTP, and so on). Type the following command in the command line to see these parameters:

asadmin create-domain --help

If we want several domains to execute concurrently on the same server, these ports must be chosen carefully since specifying the same ports for different services (or even the same service across domains) will prevent one of the domains from working properly.

The default ports for the default domain1 domain are listed in the following table:

Service

Port

Admin

4848

HTTP

8080

Java Messaging System (JMS)

7676

Internet Inter-ORB Protocol (IIOP)

3700

Secure HTTP (HTTPS)

8181

Secure IIOP

3820

Mutual Authorization IIOP

3920

Java Management Extensions (JMX) administration

8686

Please note that when creating a domain, the only port that needs to be specified is the admin port. If the other ports are not specified, the default ports listed in the preceding table will be used. Care must be taken when creating a domain, since, as explained above, two domains cannot run concurrently in the same server if any of their services listen for connections on the same port.

An alternate method of creating a domain, without having to specify ports for every service, is to issue the following command:

asadmin create-domain --portbase [port number] domainname

The value of the --portbase parameter dictates the base port for the domain; ports for the different services will be offsets of the given port number. The following table lists the ports assigned to all the different services:

Service

Port

Admin

portbase + 48

HTTP

portbase + 80

Java Messaging System (JMS)

portbase + 76

Internet Inter-ORB Protocol (IIOP)

portbase + 37

Secure HTTP (HTTPS)

portbase + 81

Secure IIOP

portbase + 38

Mutual Authorization IIOP

portbase + 39

Java Management Extensions (JMX) administration

portbase + 86

Of course, care must be taken when choosing the value for --portbase, making sure that none of the assigned ports collide with any other domain.

Tip

As a rule of thumb, creating domains using a portbase number greater than 8000 and divisible by 1000 should create domains that don't conflict with each other. For example, it should be safe to create a domain using a portbase of 9000, another one using a portbase of 10000, so on and so forth.

Deleting domains

Deleting a domain is very simple. It can be accomplished by issuing the following command in the command line:

asadmin delete-domain domainname

We should see the following message on the terminal window:

Command delete-domain executed successfully.

Tip

Please use the preceding command with care. Once a domain is deleted, it cannot be easily recreated (all deployed applications as well as any connection pools, data sources, and so on will be gone).

Stopping a domain

A domain that is running can be stopped by issuing the following command:

asadmin stop-domain domainname

The preceding command will stop the domain named domainname.

If only one domain is running, the domainname argument is optional, that is, we can simply stop the running domain by issuing the following command:

asadmin stop-domain

Note

This book will assume that the reader is working with the default domain called domain1 and the default ports. If this is not the case, instructions given need to be modified to match the appropriate domain and port.

 

Setting up Database Connectivity


Any nontrivial Java EE application will connect to a Relational Database Management System (RDBMS). Supported RDBMS systems include Java DB, Oracle, Derby, Sybase, DB2, PointBase, MySQL, PostgreSQL, Informix, Cloudscape, and SQL Server. In this section, we will demonstrate how to set up GlassFish to communicate with a MySQL database. The procedure is similar for other RDBMS systems.

Note

GlassFish comes bundled with an RDBMS called JavaDB. This RDBMS is based on Apache Derby. To limit the download and configuration needed to follow this book's code, all examples needing an RDBMS will use the bundled JavaDB RDBMS. The instructions in this section are to illustrate how to connect GlassFish to a third-party RDBMS.

Setting up connection pools

Opening and closing the database connections is a relatively slow operation. For performance reasons, GlassFish and other Java EE application servers keep a pool of open database connections; when a deployed application requires a database connection, one is provided from the pool; when the application no longer needs the database connection, the said connection is returned to the pool.

The first step to follow when setting up a connection pool is to copy the JAR file containing the JDBC driver for our RDBMS in the lib directory of the domain (consult your RDBMS documentation for information on where to obtain this JAR file). If the GlassFish domain where we want to add the connection pool is running when copying the JDBC driver, it must be restarted for the change to take effect. The domain can be restarted by executing the following command:

 asadmin restart-domain domainname

Once the JDBC driver has been copied to the appropriate location and the application server has been restarted, log in to the admin console by pointing the browser to http://localhost:4848.

Then, navigate to Resources | JDBC | JDBC Connection Pools. The browser should now look something like what is shown in the following screenshot:

Click on the New... button. After entering the appropriate values for our RDBMS, the main area of the page should look something like the following screenshot:

After clicking on the Next button, we should see a page similar to the one shown in the following screenshot:

Most of the default values on the top portion of the page shown in the preceding screenshot are sensible. Scroll all the way down and enter the appropriate property values for our RDBMS (at a minimum, username, password, and URL). Then, click on the Finish button at the top right of the screen.

Property names vary depending on the RDBMS we are using, but usually there is a URL property where we should enter the JDBC URL for our database, plus username and password properties where we should enter authentication credentials for our database.

Our newly created connection pool should now be visible in the list of connection pools as shown in the following screenshot:

In some cases, the GlassFish domain may need to be restarted after setting up a new connection pool.

We can verify that our connection pool was successfully set up by clicking on its pool name and then enabling the Ping button on the resulting page as shown in the following screenshot:

Our connection pool is now ready to be used by our applications.

Setting up the data sources

Java EE applications don't access connection pools directly; they access a data source instead, which points to a connection pool. To set up a new data source, click on the JDBC icon under the Resources menu item on the left-hand side of the web console, then click on the JDBC Connection Pools tab, and then click on the New... button. After filling out the appropriate information for our new data source, the main area of the web console should look something like what is shown in the following screenshot:

After clicking on the OK button, we can see our newly created data source as shown in the following screenshot:

 

Summary


In this chapter, we discussed how to download and install GlassFish. We also discussed several methods of deploying the Java EE application through the GlassFish web console, through the asadmin command, and by copying the file to the autodeploy directory. We also discussed basic GlassFish administration tasks like setting up domains and setting up Database Connectivity by adding connection pools and data sources. In the next chapter, we will cover how to develop web applications using JSF.

About the Author

Latest Reviews

(1 reviews total)
Nice book, but not so original. Information are easily found in the web
Book Title
Unlock this full book FREE 10 day trial
Start Free Trial