0% found this document useful (0 votes)
2 views76 pages

Getting Started With Payara Server v2

The Comprehensive Getting Started Guide for the Payara Platform provides detailed instructions on installing, starting, and deploying applications using Payara Server. It covers prerequisites such as the Java Development Kit, build tools, and Integrated Development Environments (IDEs), and offers step-by-step guidance for setting up and configuring the server. Additionally, the guide includes information on database integration, RESTful services, and advanced features for production use.

Uploaded by

balodoyxiong
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
2 views76 pages

Getting Started With Payara Server v2

The Comprehensive Getting Started Guide for the Payara Platform provides detailed instructions on installing, starting, and deploying applications using Payara Server. It covers prerequisites such as the Java Development Kit, build tools, and Integrated Development Environments (IDEs), and offers step-by-step guidance for setting up and configuring the server. Additionally, the guide includes information on database integration, RESTful services, and advanced features for production use.

Uploaded by

balodoyxiong
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 76

Comprehensive Getting

Started Guide

The Payara® Platform - Production-Ready,


Cloud Native and Aggressively Compatible. User Guide
Comprehensive Getting Started Guide

Main Chapters

Installing Starting Deploying an


Payara Payara Application in
Server Server Payara Server

Configure Do More With


And Use A Payara Server:
Database Additional
Resources

Using The
Payara
Platform In
Production
Comprehensive Getting Started Guide

Contents

Installing Payara Software 1


Choose and Download your Java Development Kit 1
Install Your Build Tool 3
Choose and Install Your IDE 5
What to Look for in an IDE? 5
Which IDEs are Available? 6
NetBeans 6
IntelliJ IDEA 6
Visual Studio Code 6
IDE Server Integration 7
NetBeans 7
Visual Studio Code 7
Install NetBeans 8
Download Payara Server 8
Starting Payara Server 9
Starting Payara Server Through the CLI 10
Starting the Payara Server Through the CLI – Modes 11
Starting Payara Server with NetBeans 11
Starting the Payara Server Through Maven – Modes 13
Deploying an Application in Payara Server 13
Deploying an Application in Payara Server Through NetBeans 14
Deploying an Application in Payara Server Through the CLI 15
Deploying an App Through the Administration Console 16
Checking Your Deployment 17
Configure And Use A Database 19
How to Store and Retrieve Data from a Database 19
Creating the Project 19
Creating the Person (@Entity) 22
Comprehensive Getting Started Guide

Creating a Repository to Manage the Entity 23


Creating a Rest Endpoint Using JAX-RS 23
Deploying the Application 25
Testing the APIs 26
Introduction to Connection Pools 28
Connection Pools in Payara Server 29
Creating the Connection Pool - Via the Admin Console 29
Creating the Connection Pool – Via The Command Line 31
Creating the Connection Pool – Per Application Resources 32
Connection Pool Sizing 32
Connection Validation 35
Via the Admin Console 35
Per Application Resources 37
Statement and Connection Leak Detection 38
Via the Admin Console 39
Via the Command Line 40
Per Application Resources 40
Choose Your Data Source Framework 42
JPA Framework 42
JDBC Framework 42
Using a Data Source with JPA 42
Using a Data Source with JDBC 46
Choose Your Database 50
Oracle DataBase 50
My SQL 50
PostgreSQL 50
Admin Console or Asadmin CLI? 51
Using Oracle Database with Payara Platform Products 51
With the Admin Console 52
With the asadmin CLI 54
Using MySQL with Payara Platform Products 56
With the Admin Console 57
Comprehensive Getting Started Guide

With the asadmin CLI command 60


Using PostgreSQL with Payara Platform Products 61
With the Admin Console 61
With the asadmin CLI command 64
Hide Passwords with Password Aliases in Payara Server 67
Do More With Payara Server: Additional Resources 70
Creating a RESTFUL Web Service with Payara Server and NetBeans 70
Security Auditing in Payara Server 70
Making Use of Payara Server’s Monitoring Service 70
Using The Payara Platform In Production 70
With Payara Enterprise Edition, you are able to: 71
Comprehensive Getting Started Guide

Using Payara Server for the first time? We’ve put together this “Getting Started Guide” to help you
with everything you need to successfully install and put Payara Server to work for you.

Installing Payara Software


You need to have a few things installed on your computer before you can install, write and deploy
an application with Payara Server. There are four main pieces of software you will need:
• Java (A Java Development Kit)
• A build tool – Maven or Gradle
• An IDE
• Payara Server

You will need to download a JDK, choose and download a build tool, choose and download an IDE,
and then you can use Payara Server.

Getting Started With Payara Server - Installing Software


If you are missing a JDK, IDE or build tool, you can follow the steps
in this ‘Get Ready’ section to prepare. We’ve also created a video
that takes you through the process of downloading and installing
the requisite software.

Choose and Download your Java Development Kit


If you don’t already have a JDK installed, you’ll need to download and install one.

You can use any supported JDK with Payara Server. Payara Platform currently runs with the JDK 8
and 11 iterations of the following:

• Azul Zulu JDK


• Oracle JDK: 8, 11
• Amazon Corretto
• Adopt Open JDK
• Adopt Open JDK with Eclipse Open J9

This extends to any JDK based on OpenJDK 8u162+ or 11.0.5+

However, in our tutorials we will be using Zulu JDK 8 version (feel free to use JDK 11 also).

Download Zulu OpenJDK from their website: https://www.azul.com/downloads/?package=jdk

We have chosen this particular OpenJDK because if you do decide to move to Payara Enterprise for
mission-critical projects, you can benefit from our partnership with Azul. With Payara Enterprise,
support for Azul Platform Core OpenJDK, the Enterprise build of Zulu, is included.

1
Comprehensive Getting Started Guide

Getting Started With Payara Server - Installing Software

Our video tutorial shows you how to install the OpenJDK. Or, if you
prefer to follow written instructions:

Steps
1. Open browser and head to the
Azul website
2. On the downloads page, select your
operating system. For this series we’ll be
using macOS
3. Download the JDK 8 installer
4. When the download is complete, run the
installer
5. You can verify everything is working as
desired by opening up the command line
and typing java –version , you should
then see something similar to the below:

2
Comprehensive Getting Started Guide

Install Your Build Tool


When creating a Java EE application it is important to deploy and test it on a server that is as close
to the target production environment as possible.

If you use Maven in your project, it is possible to do so using the Cargo plugin, which allows you to
deploy an application to an instance of Payara Server either locally or remotely:

Steps
1. Open browser and head to the Maven website
2. Head to the downloads page and download the binary distribution archive for your operating
system. This will be .zip for Windows and Mac, or tar.gz for Linux
3. Once downloaded, you need to add your Java home environment variable to point to install,
like so:

On Windows you can do this using the system settings.

4. Once done, extract the binary download to a directory of your choice

3
Comprehensive Getting Started Guide

5. Add the binary directory from this new created folder to your path environment variable
6. As with the OpenJDK, you can check this is correct by typing mvn –v in the command line,
and seeing similar to the below:

Getting Started with Jakarta EE 9: Using Gradle

You can also use Gradle as an alternative for Maven as your build
tool. It doesn't have many templates available, but you can find
out how to get started with Jakarta EE and Gradle in this video.

4
Comprehensive Getting Started Guide

Choose and Install Your IDE


If you’re looking to build a Jakarta EE (formerly Java EE) Application, whether you’re building a web
application with Java Server Faces (JSF), a web service using REST, an Enterprise Java Beans (EJB)
application, or interacting with a database using Java Persistence API (JPA) - you first need Payara
Server and an IDE (Integrated Development Environment).

An IDE is where you’ll write your code, debug and even deploy or run your application. An IDE typ-
ically has a code editor with syntax highlighting.

They also usually have tips and autocomplete. A great feature is that it can highlight errors in real time,
so you don’t have to compile before finding out you left off a semicolon (nor spend ages searching
for it)! Most can compile your code for you without having to use javac or mvn from the command
line. It also handily comes with a debugger too.

What to Look for in an IDE?


As Payara Server is designed to run EE (Enterprise Edition) applications, you’re probably interested
in IDEs which work well with Java EE, or Jakarta EE, as it’s now known.

Look for an IDE with the following:

• Syntax highlighting
• Debugger
• Error Highlighting
• Content assist, also known as autocomplete
• Ability to see Javadoc when hovering over a method or class
• EE support (so the above still work when you're working with a Servlet, JSP or Facelet)
• Server connectors so you can deploy your code to the server from the click of a button in
your IDE
• Active IDE project (in software development, new versions, frameworks, and APIs are often
released and you need your IDE to be able to support these)

5
Comprehensive Getting Started Guide

Which IDEs are Available?


Payara Server works well with most IDEs, including four of the most commonly used IDEs for Jakarta
EE developers:
• NetBeans
• Eclipse IDE (Note: Pick the EE specific distribution! )
• IntelliJ IDEA ( this requires the ‘Ultimate’ paid-for edition to work with EE projects)
• Visual Studio Code (VS Code)

NetBeans Eclipse IDE IntelliJ IDEA Visual Studio Code

The Apache Software The Eclipse IntelliJ is Jetbrains’ Made by Microsoft,


Foundation main- Foundation, the same IDE. It’s important you’d be forgiven for
tains NetBeans. organization that has to note here that the thinking this works
It was donated to taken over Java EE free version doesn’t only with Windows.
them by Oracle (as Jakarta EE), also support EE, just Java It works on Linux
when they bought provides the Eclipse SE (Standard Edition). and a Mac too. Out
Sun Microsystems. IDE. Using Eclipse The paid version, of the box it’s just
NetBeans is what ensures it’ll work with called ‘Ultimate’ a code editor with
most of the engi- future EE releases. works with EE. syntax highlighting.
neering team use Note: There’s more Ultimate works out of Everything you want
at Payara. We find than 1 distribution the box with Payara to use will need to be
it works well for our of Eclipse IDE, you’ll Server. If you've used added as an exten-
needs. need to get the one IntelliJ Idea Ultimate sion. Java Support
that’s specifically for with GlassFish you’ll is one extension. It
EE. Don’t get the Java find the set up for works well with Git
SE distribution. Payara Server is the (a content versioning
same as for Glassfish. system). It’s also a
very active project,
which means you
get frequent new
features.

6
Comprehensive Getting Started Guide

IDE Server Integration


Payara has plugins for the following IDE servers, which allow you to deploy and debug to Payara
Server within each of these IDEs.

NetBeans IntelliJ IDEA Ultimate


NetBeans has a project wizard that allows you IntelliJ IDEA Ultimate comes with the
to create a Java EE 8 application. Using that GlassFish plugin installed and enabled which
same wizard, you can select Payara Server as can be used to start, stop and debug Payara
the runtime for your application and download Server along with other server functionality.
and install a Payara Server installation directly IntelliJ IDEA also includes the Payara
from this wizard. Platform Tools plugin, which provides all the
features available in the GlassFish plugin, plus
Eclipse IDE additional tooling features available in Payara -
like the Hot Deploy functionality.
Eclipse IDE relies on the Maven Archetype you
need to choose Maven as your build tool (more IntelliJ IDEA Ultimate has many advanced
on this later) and create a Maven project that features that makes development much easier
is immediately imported into the IDE itself. for a Jakarta EE developer and many tools
However, once the project is created, you can built-in so you don’t need to leave your IDE.
run it on Payara Server using the plugin.

Once the project is created, you can run it on Visual Studio Code
Payara Server using the plugin. The plugin
We have created a specific plugin for Payara
allows you to start and stop the application,
products that can be used with the IDE.
and also lets you look at the logging and the
Once the plugin is added to the IDE, you can
domain configuration file.
configure the Payara Server from the plugin so
you can run the application directly from within
the IDE.

Once you have chosen your IDE, you will need to create your project in your IDE of choice. We
have specific guides and videos for set up with each of the four IDEs above, linked here.

If you are looking to follow our Getting Started with Payara Server video tutorials, we would
recommend using NetBeans. We will be using it as the integration between NetBeans, Maven and
Payara Server will make creating an application very straightforward. NetBeans comes with a set
of built-in integration tools for Payara Platform which makes starting the server, and managing our
deployments through it, really easy.

7
Comprehensive Getting Started Guide

Install NetBeans

Steps
1. Open browser and head to NetBeans
website
2. Click through downloads buttons to get to
the final downloads page:
https://netbeans.apache.org/download/
3. Pick the installer for your operating
system
4. Once downloaded, open the installer and
go through the steps that it provides you
with – and that’s NetBeans installed!

Download Payara Server


Now that you’ve got all the necessary preparations out of the way – here’s how to download and
install Payara Server:

Steps
1. Head to the payara.fish website
and download the Payara Platform
Community Edition, which is the open
source, freely available edition of
Payara Server designed for develop-
ment projects:
2. Click download on the latest version of
Payara Server
3. Once the downloaded file is complete,
extract the ZIP file to a location of choice

8
Comprehensive Getting Started Guide

Starting Payara Server


Now all the software is downloaded, you can start an instance of Payara Server. There are two meth-
ods for starting Payara Server: through the IDE tool, which we’ve chosen to be NetBeans, or through
the Command Line Interface (CLI).

Getting Started with Payara Server - Starting Payara Server

Below, and in this accompanying video, we show you how to


achieve success with both methods.

9
Comprehensive Getting Started Guide

Starting Payara Server Through the CLI

Steps 5. You can then create a custom domain,


by typing in the create -domain com-
1. With your bash terminal open, the first mand followed by the name you want to
step is to cd into the directory where give it
you installed Payara Platform 6. Once you press enter, you’ll be
2. You can then cd into the bin directory, prompted to enter a username and
where you get access to the asadmin. password. Note: if you don’t want to use
Asadmin is the shortened name for one for your own admin systems, just
‘Application Server Administration’. press enter and it will use a default
This is the main way of interfacing
commands between the Payara Server
and the CLI. All Payara Server admin-
istration commands are sub-com-
mands of this utility, and as such,
each command must be prepared
with this function (e.g. ./asadmin
do-a-little-dance)
3. To start the domain, therefore, after
./asadmin you simply have to type
start- domain and then press enter.
A domain is essentially a server at 7. To start this new domain, type ./
runtime. asadmin start-domain followed by
the name of the domain – and after a
couple of seconds, the domain will
be started!

4. The domain will start in the background,


which may take a couple of minutes
depending on your machine – and then
the server is started!

10
Comprehensive Getting Started Guide

Starting the Payara Server Through the CLI – Modes


You can start the domain at this point using -- debug – to start the server in debug mode. You
can also use the –d flag to do this.

You can also use -- verbose to start the server in verbose mode, printing the logs out into the
terminal. You can also use the –v flag to do this.

For both these functionalities, type the desired command after ./asadmin start-domain

Starting Payara Server with NetBeans


Alternatively, you can start the server with your IDE.

As mentioned previously, we will be using NetBeans, as this has default integration tools with Payara
Platform which make starting very easy. This allows you to add Payara Server as a recognized server
in NetBeans and then deploy and manage applications from the NetBeans interface. Adding the
Payara NetBeans plugins can be done with the following steps:

Steps 3. You can then choose Payara Server which


is there by default
1. Open up NetBeans (which you should
have installed previously – see page 6
for instructions)
2. Head to services tab, right click on server
and then click ‘add server’

11
Comprehensive Getting Started Guide

4. Pick the directory where you extracted


Payara 5 last time
5. Press next, and you need to pick which
domain you want to use. It will give you
the option of all available domains
6. Type in the username to be admin, and
if you are using a custom domain, use
whichever username you had before
7. You’ll now see a new Payara Server entry
under the servers. You can start this by
right-clicking and pressing start.
9. After this is completed, you can see that
the server starts, and you should get
some code printing out in the log below,
like so:

8. When prompted with the Java SE


Platform screen, you can choose JDK 8 or
11, but please note that Payara does not
run on any JDKs above those versions
yet. If you don’t get prompted with JDK
1.8 as an option, simply press the
‘Manage Platforms’ button to add it

To stop the instance of Payara Server, simply go back to the Payara Server entry under the servers,
right click and press ‘stop’. Once the loading icon has disappeared, you will know the server has
stopped. You can also restart the domain by right-clicking and pressing ‘start’.

12
Comprehensive Getting Started Guide

Starting the Payara Server Through Maven – Modes


By right clicking on ‘Payara Server’ under ‘Servers’ in Maven, you will have the option to start in Debug
mode, start in Profile mode and various other options. This makes managing the server really easy.

Deploying an Application in Payara Server


We will show you three different ways you can deploy an app in Payara Server – through NetBeans,
through the CLI and through the Admin Console.

Getting Started with Payara Server - Deploying An Application

You can watch us demonstrate in this video, or follow the steps


below. We won’t be showing you how to create an app, but instead
focus on deploying an application in Payara Server.

13
Comprehensive Getting Started Guide

Deploying an Application in Payara Server Through NetBeans

Steps The console will start building our project for


the first time. This will ensure we have all the
1. Go to the project window, right click and dependencies for the project downloaded and
select “new project” the project is created and ready for deployment.
It will look like something similar to the below:

Now that we have the project built, we can right


click on ‘Payara Server’ under ‘Servers’ again, and
simply click the “run” button. This will automat-
ically start up an instance of Payara Server. We
will be able to go and access the application at
its URL.

You can stop the domain by navigating to it under


2. Select Java with Maven and Web
the ‘Servers’ tab – this will not undo the deploy of
Application
your file, rather it will be waiting for you the next
3. Name your project on the ‘Name and
time you wish to start it up.
Location’ Window
4. On the next window, ‘Settings’ set your The Maven and Payara Platform integration tools
server to be the Payara Server instance allows us to automatically update our server on
you created previously with the Java ver- Payara whenever we make any changes. We sim-
sion of Java EE 8 Web – and press finish ply have to right-click on the server, click ‘Clean
and Build’ and re-run the application to deploy it.

14
Comprehensive Getting Started Guide

Deploying an Application in Payara Server Through the CLI


The first step is making sure you are in the correct directory – where you previously set up your
Payara install, and in the bin directory, so you have access to the asadmin tool.

Steps
1. Start the domain
2. Once your instance of Payara Server is started, to deploy, type ./asadmin and use the
deploy command: ./asadmin deploy
3. Follow this with the directory we have the application we want to deploy at. In the case
of the Hello World app used for this demonstration, this will be under the name of the
project we created, followed by /target/ the name of the application I.e. Projects/
payara-server-hello-world/target/payara-server-hellow-world-1.0-

When the deployment has executed successfully, it will show this in the log:

15
Comprehensive Getting Started Guide

Deploying an App Through the Administration Console


The Admin Console is an easy-to-navigate graphical interface to configure Payara Server and your
applications that includes help documentation.

When deploying using the Admin Console:

Steps 4. This will give you an option to choose


which file to deploy to the server. If you
1. Start your Payara Server instance using click this, you can then navigate through
the CLI or your IDE, as outlined on pages the file system to find the application you
7 – 11 wish to deploy
2. Once this is done, navigate to localhost:
4848. This will automatically reload the
page and take you to the Admin Console
3. To deploy an application, head to the
applications tab on the left hand side of
the screen and click the deploy button

5. Click Open
6. You can leave location information as
default, and it will automatically recog-
nize the type of application you want
to deploy. You can then click ok – and
it’s as simple as that, the application is
deployed on Payara Server

16
Comprehensive Getting Started Guide

Checking Your Deployment


You can now head into the browser and navigate to localhost, the version and the name of your
application, with the version, to check that you have the access page you were expecting. So in the
case of this demonstration, the URL is localhost:8080/payara-server-hello-world - local host, the
code for OpenJDK 8 and the name of our application.

17
Comprehensive Getting Started Guide

The resulting screen shows that the application has been deployed and we have access to the web
page that we expect to be there.

If using the Admin Console method, there is no need to manually enter the URL – you can access
the application by clicking ‘launch’ on the Applications section of the interface, and selecting one of
the URLs given.

18
Comprehensive Getting Started Guide

Configure And Use A Database


You’ll need to start with storing and retrieving data from the database.

How to Store and Retrieve Data from a Database

Creating the Project


As a first step, we will create a simple Maven web application in the Apache NetBeans IDE :

Steps 2. In the New Project wizard, expand


the Maven category and select Web
1. In the IDE, choose File → New Project Application as shown in the figure below,
(Ctrl-Shift-N) from the main menu, as then click Next :
shown in the figure below :

19
Comprehensive Getting Started Guide

3. Enter "simple-jpa-example" in the Project 5. Apache NetBeans IDE will create the
name text box and specify the Project maven web project with the follow-
Location to any directory on your system ing structure:
and click Next (as shown in the figure
below) :

6. Now right click on project → Properties →


4. Select the Payara Server to which you Run → set the Context Path to root ‘/’ :
want to deploy the application:

20
Comprehensive Getting Started Guide

Creating persistence.xml
Then, create the persistence.XML.

Steps 2. Enter POSTGRESQL_PU the in the


Persistence Unit name text box and select
1. To create persistence.xml, go to the File already configured data-source in the
menu → New File → Persistence cate- Payara Server and click Next:
gory, select Persistence Unit and click
Next :

Note: If the data-source is not defined in persistence.xml then a default data source
with JNDI name java:comp/DefaultDataSource will be wired to the default JDBC
resource provided by the container.

21
Comprehensive Getting Started Guide

Creating the Person (@Entity)


The next thing we’re going to do is create a Person entity with a primary key.

// the package and imports omitted for brevity

@Entity
public class Person {

@Id
@GeneratedValue
private Long id;

private String name;

private String address;

// the typical getters and setters omitted for brevity


}

Note: If you’re missing the imports, press Alt+Shift+I, NetBeans will add the imports
and for the getter/setter methods, press Alt+Insert → select Getter and Setter to
generate. Other IDEs offer a similar shortcut.

Here you have a Person class with three attributes: id, name, and the address. The Person class
is annotated with @Entity, indicating that it is a JPA entity. As @Table annotation is not defined at
class-level, Persistence provider assumes that this entity will be mapped to a table named Person.
@Table annotation is required if database table name is different from the class name.

The id attribute is annotated with @Id so that persistence provider will recognise it as primary
key column. The id attribute is also annotated with @GeneratedValue to indicate that it should
be automatically generated by the database. The other two attributes, name and address are left
unannotated with @Column. So the persistence provider assumes that attributes will be mapped
to columns that share the same name as the attributes themselves.

22
Comprehensive Getting Started Guide

Creating a Repository to Manage the Entity


We’ll now create a repository class that talks to the database and accesses the Person’s data.

@ApplicationScoped
public class PersonRepository {

@PersistenceContext(unitName = "POSTGRESQL_PU")
private EntityManager em;

@Transactional(REQUIRED)
public void create(Person person) {
em.persist(person);
}

public List<Person> findAll() {


return em.createQuery("SELECT p FROM Person p", Person.class)
.getResultList();
}

public Person find(Long id) {


return em.find(Person.class, id);
}

Creating a Rest Endpoint Using JAX-RS


The next step is creating a Rest Endpoint Using JAX-RS.

To create a rest endpoint, we first need to configure the application using the default implementa-
tions of javax.ws.rs.core.Application subclass.

@ApplicationPath("")
public class ApplicationConfig extends Application {

23
Comprehensive Getting Started Guide

Let’s define the REST APIs and expose the endpoints. We'll begin by creating a new class named
PersonController :

@Path("/api/person")
@ApplicationScoped
public class PersonController {

@Inject
private PersonRepository personRepository;

@POST
public Response createPerson(Person person) {
personRepository.create(person);
return Response.ok(person).build();
}

@GET
public List<Person> getAllPeople() {
List<Person> people = personRepository.findAll();
return people;
}

@GET
@Path("/{id}")
public Response getPerson(@PathParam("id") Long id) {
LOG.log(Level.FINE, "REST request to get Person : {0}", id);
Person person = personRepository.find(id);
if (person == null) {
return Response.status(Response.Status.NOT_FOUND).build();
} else {
return Response.ok(person).build();
}
}

The @Path annotation defines that this class will handle calls made to the URL ‘/api/person’.

24
Comprehensive Getting Started Guide

Deploying the Application


We’ve successfully created all of the APIs. Let’s now deploy the application and test the APIs. Just
right click on the project and select deploy option:

The application will start at Payara’s default port 8080.

25
Comprehensive Getting Started Guide

Testing the APIs


Now, it’s time to test our APIs and REST endpoints using curl commands or postman.

Steps
1. Execute the following curl command to create the Person :

curl -X POST http://localhost:8080/api/person --header "Content-Type:


application/json" -d "{\"name\":\"Gaurav Gupta\", \"address\":\"Lucknow,
India\"}"

2. Retrieving all the People using the following curl command :

curl -X GET http://localhost:8080/api/person

26
Comprehensive Getting Started Guide

3. Retrieving a single Person using the following curl command :

curl -X GET http://localhost:8080/api/person/2

The application that we created in this guide had only one domain model. Of course, you may extend
it by adding more domain models and defining the relationship using JPA annotations.

You can find the source code of the example used in this guide on the GitHub repository. Feel free
to clone the repository and build upon it.

Next, before you connect Payara Server to a database and use the data source from an application,
you will need to set up a connection pool. Then, you will be ready to choose and configure your
database and data source framework.

27
Comprehensive Getting Started Guide

Introduction to Connection Pools


A connection pool is a store of database connections that can be used and (most importantly) re-used
to connect to a database.

Database connections are expensive to create and also to maintain.

The reasons for this are many, including:


• Establishing a network connection to the database server
• Parsing the connection string information
• Performing user authentication
• Initializing the database connection in the database
• Establishing transactional contexts
Now, if you have a web application with a single user you can simply create a database connection at
the start of the user session and then close it at the end. However, this is a highly unlikely scenario!

Now, imagine a more realistic scenario where your web application will be accessed by hundreds
or thousands of users. If each user’s session creates a database connection, firstly your users will
experience a delay whilst that connection is set up and secondly the overall performance of your
system will deteriorate.

Therefore, connection pools both improve the performance and scalability of your system.

Rather than creating a new connection each time one is needed a pool of connections is created
when your application server is started. These connections can then be used and re-used. When a
new connection is required, the pool is searched for an available connection. If one is available it is
returned to the requester. If one is not available then the request is either queued or a new connec-
tion is established depending on how many connections are already in the pool and how the pool is
configured. Once the connection is finished with, rather than closing it the connection is returned
to the connection pool for use by the next requester.

28
Comprehensive Getting Started Guide

Connection Pools in Payara Server


For this practical demonstration we will use the following:
• Operating System - Ubuntu 18.04
• Java Version - 1.8.0_172
• App Server – Payara Server 5.181
• Database - H2
If you are using different versions of any of the above then the results may differ.

Creating the Connection Pool - Via the Admin Console


Firstly, start up Payara Server. This can be done from a terminal window with the following Asadmin
CLI command:

(we'll assume the current directory is /<payara-home>/bin)

./asadmin start-domain

Once the server has started you can access the Admin Console at http://localhost:4848

In the left hand panel go to Resources → JDBC → JDBC Connection Pools

Click New and enter the following values:


• Pool Name - test-pool
• Resource Type - javax.sql.XADataSource
• Driver Vendor – H2
Click Next.

29
Comprehensive Getting Started Guide

For this example, we’ll use an in-memory database using H2 called "test". This is done by scrolling
all the way down in the next shown screen and adding the following property:

url => jdbc:h2:mem:test

30
Comprehensive Getting Started Guide

The other properties can be left at their defaults: Testing the Connection
• Click on the connection pool name
(test-pool).
• Click the Ping button at the top of
the screen.
You should see a message stating
Ping Succeeded.

(Note that the properties shown here are dynam-


ically scanned from the DataSource implemen-
tation that's being used, which in case of H2 is
org.h2.jdbcx.JdbcDataSource)

Now click Finish, accepting all other


default values.

You will then want to test the connection.

Creating the Connection Pool – Via The Command Line


You can also create a connection pool using the Asadmin CLI Tool with the following:

./asadmin create-jdbc-connection-pool \
--datasourceclassname org.h2.jdbcx.JdbcDataSource \
--restype javax.sql.XADataSource \
--property url="jdbc\:h2\:mem\:test" test-pool2

Note how the colons have to be escaped here. This is needed since the unescaped ones are used to
delimit multiple properties and their values. For instance -

-property user=root:password=test:port=3306.

Also note that we’ll use "test-pool2" for the pool created via the command line.

To test the connection from the command line run the following Asadmin CLI command:

./asadmin ping-connection-pool test-pool2

31
Comprehensive Getting Started Guide

Creating the Connection Pool – Per Application Resources


The connection pools created above are server managed, global pools. This means they are applica-
ble for all applications deployed to Payara Server. Via Jakarta EE annotations as well as deployment
descriptors, we can create those per application as well. There's a difference though, and that's
that via the Jakarta EE alternative a "data source" ("jdbc-resource"), is created together with the
connection pool.

Using an annotation:

@DataSourceDefinition(
name = "java:app/MyApp/MyDS",
className = "org.h2.jdbcx.JdbcDataSource",
url = "jdbc:h2:mem:test"
)

Using an entry in web.xml, ejb-jar.xml or application.xml.

<data-source>
<name>java:app/MyApp/MyDS</name>
<class-name>org.h2.jdbcx.JdbcDataSource</class-name>
<url>jdbc:h2:mem:test</url>
</data-source>

Connection Pool Sizing


Connection pools should be sized to cater for the maximum number of concurrent connections.

The maximum size should be set in accordance with the maximum number of client requests your
system can process. If your application receives 100 requests and each of those requires a database
connection then if your connection pool is anything less than 100 some of those requests will have
to wait for a connection to either be created or become available.

The minimum size of the connection pool ensures that a number of connections to the database are
always established - this means that if you have a pool with a minimum size of 10 and you receive
10 requests then all can retrieve a database connection without waiting for the pool to create a
new connection.

32
Comprehensive Getting Started Guide

There is always a trade off with setting these values as the minimum value requires that those con-
nections are maintained regardless of system load and the maximum value could potentially require
a large number of concurrent database connections.

These values will be different for everyone. There are no magic numbers so it's a case of under-
standing your application, what your expected load (both steady and worst case) will be, monitoring
to see if this changes and setting values accordingly. As a general rule of thumb though, if you find
yourself having to constantly increase the maximum value, say from 200 to 300, from 300 to 500
etc, then you may have to look at your software architecture. For instance, in a transaction process-
ing system, saving each transaction independently to a database could perhaps be replaced with a
system where multiple transactions are queued first, and then saved to a database in one go using
a JDBC or JPA batch.

You can set Min/Max Sizes via the Admin Console.

Click on the connection pool name and under Pool Settings you will find Initial and Minimum Pool
Size and Maximum Pool Size. Set these to your required sizes.

You can also set min/max sizes via the command line.

33
Comprehensive Getting Started Guide

To set the initial & minimum pool size:

./asadmin set resources.jdbc-connection-pool.test-pool2.steady-pool-size=10

To set the maximum pool size:

./asadmin set resources.jdbc-connection-pool.test-pool2.max-pool-size=200

You can also create Min/Max Sizes per Application Resources.

Using an annotation:

@DataSourceDefinition(
name = "java:app/MyApp/MyDS",
className = "org.h2.jdbcx.JdbcDataSource",
initialPoolSize = 10,
minPoolSize = 10,
maxPoolSize = 200,
url = "jdbc:h2:mem:test"

Using an entry in web.xml, ejb-jar.xml or application.xml:

<data-source>
<name>java:app/MyApp/MyDS</name>
<class-name>org.h2.jdbcx.JdbcDataSource</class-name>
<initial-pool-size>10</initial-pool-size>
<max-pool-size>200</max-pool-size>
<min-pool-size>10</min-pool-size>
<url>jdbc:h2:mem:test</url>
</data-source>

Note that Payara Server's steady-pool-size property translates to two standard properties here, while
coincidentally max-pool-size has the exact same name in the standard descriptors.

34
Comprehensive Getting Started Guide

Connection Validation
Connection validation ensures that connections aren't assigned to your application after the con-
nection has already gone stale.

Connection validation is always a trade-off between how sure you want to be that a connection is
valid and the performance impact from validation. There will be a negative performance impact by
having to return an invalid connection by your application and borrow a new one, so finding the right
balance is key.

Before using a connection from the pool, a simple query is sent to test the connection. If there is an
issue with the connection it is removed from the pool and another one used. The issue here is that
if you have an issue such as the database being down and you have a large number of connections
then each of those connections will be tested and removed.

In order to avoid this, you can set connection validation so that if a connection fails all connections
are closed.

Via the Admin Console


• Click on the name of the pool
• Select the advanced tab
• Scroll down to Connection Validation and select the following settings:
• Connection Validation - required
• Validation method - custom-validation
• Validation class name – org.glassfish.api.jdbc.validation.H2ConnectionValidation
From the same screen you can also set whether to close all connections on failure.

35
Comprehensive Getting Started Guide

Via the Command Line


To turn on connection validation:

./asadmin set resources.jdbc-connection-pool.test-pool2.is-connection-


validation-required=true
./asadmin set resources.jdbc-connection-pool.test-pool2.connection-validation-
method=custom-validation
./asadmin set resources.jdbc-connection-pool.test-pool2.validation-
classname=org.glassfish.api.jdbc.validation.H2ConnectionValidation

36
Comprehensive Getting Started Guide

You can also set whether to close all connections on failure with the following command:

./asadmin set resources.jdbc-connection-pool.test-pool2.fail-all-


connections=true

Per Application Resources


Using an annotation:

@DataSourceDefinition(
name = "java:app/MyApp/MyDS",
className = "org.h2.jdbcx.JdbcDataSource",
initialPoolSize = 10,
minPoolSize = 10,
maxPoolSize = 200,
url = "jdbc:h2:mem:test",
properties = {
"fish.payara.is-connection-validation-required=true",
"fish.payara.connection-validation-method=custom-validation",
"fish.payara.validation-classname=org.glassfish.api.jdbc.validation.
H2ConnectionValidation"
})
)

37
Comprehensive Getting Started Guide

Using an entry in web.xml, ejb-jar.xml or application.xml:

<data-source>
<name>java:app/MyApp/MyDS</name>
<class-name>org.h2.jdbcx.JdbcDataSource</class-name>
<url>jdbc:h2:mem:test</url>
<property>
<name>fish.payara.is-connection-validation-required</name>
<value>true</value>
</property>
<property>
<name>fish.payara.connection-validation-method</name>
<value>custom-validation</value>
</property>
<property>
<name>fish.payara.validation-classname</name>
<value>org.glassfish.api.jdbc.validation.H2ConnectionValidation</value>
</property>
<initial-pool-size>10</initial-pool-size>
<max-pool-size>200</max-pool-size>
<min-pool-size>10</min-pool-size>
</data-source>

Note that there are no standard properties corresponding to connection validation. Payara Server
supports setting these as vendor specific properties. These properties are normally mainly intended
as data source properties. The Jakarta EE / common annotations spec makes no clear distinction
between properties intended for the data source and those intended for the connection pool. Payara
Server makes this distinction by prefixing properties intended for the pool with "fish.payara.".

Statement and Connection Leak Detection


Statement and Connection Leak Detection allows you to set time-outs so that if Statements or
Connections haven't been closed by an application they can be logged and/or closed.

In testing it’s recommended that you set it so leaks are simply logged but not closed. However, in
production we would recommend that leaks are closed. If you have tested thoroughly enough then
there shouldn't be any, but if there are you don't want to leave them open.

Monitoring software should be configured to alert on detected leaks and then further investigation
can take place and fixes can be put in place.

By default, these values are set to 0 meaning detection is turned off.

38
Comprehensive Getting Started Guide

Via the Admin Console


• Click on the name of the pool
• Select the advanced tab
• Scroll down to Connection Settings
• Set the Connection Leak Timeout and Statement Leak Timeout value

39
Comprehensive Getting Started Guide

Via the Command Line

./asadmin set resources.jdbc-connection-pool.test-pool2.statement-leak-timeout-


in-seconds=5
./asadmin set resources.jdbc-connection-pool.test-pool2.connection-leak-
timeout-in-seconds=5

Per Application Resources


Using an annotation:

@DataSourceDefinition(
name = "java:app/MyApp/MyDS",
className = "org.h2.jdbcx.JdbcDataSource",
initialPoolSize = 10,
minPoolSize = 10,
maxPoolSize = 200,
url = "jdbc:h2:mem:test",
properties = {
"fish.payara.is-connection-validation-required=true",
"fish.payara.connection-validation-method=custom-validation",
"fish.payara.validation-classname=org.glassfish.api.jdbc.validation.
H2ConnectionValidation",
"fish.payara.connection-leak-timeout-in-seconds=5",
"fish.payara.statement-leak-timeout-in-seconds=5"
})
)

40
Comprehensive Getting Started Guide

Using an entry in web.xml, ejb-jar.xml or application.xml:

<data-source>
<name>java:app/MyApp/MyDS</name>
<class-name>org.h2.jdbcx.JdbcDataSource</class-name>
<url>jdbc:h2:mem:test</url>
<property>
<name>fish.payara.is-connection-validation-required</name>
<value>true</value>
</property>
<property>
<name>fish.payara.connection-validation-method</name>
<value>custom-validation</value>
</property>
<property>
<name>fish.payara.validation-classname</name>
<value>org.glassfish.api.jdbc.validation.H2ConnectionValidation</value>
</property>
<property>
<name>fish.payara.connection-leak-timeout-in-seconds</name>
<value>5</value>
</property>
<property>
<name>fish.payara.statement-leak-timeout-in-seconds</name>
<value>5</value>
</property>
<initial-pool-size>10</initial-pool-size>
<max-pool-size>200</max-pool-size>
<min-pool-size>10</min
-pool-size>
</data-source>

Once these values are set if connection or statement leaks are detected you will see messages
similar to the ones below in the application log.

WARNING: A potential connection leak detected for connection pool test-pool. The
stack trace of the thread is provided below:

At this point you can go back to your development team and get them to investigate the root cause.

41
Comprehensive Getting Started Guide

As with all server configuration settings you should always take a close look at your application's
needs before making changes. You should always performance test and load test your application
to ascertain the best settings, particularly before making changes in production. One size does not
fit all! Once you have decided upon the optimal settings you should then monitor and re-evaluate
regularly to ensure you are always running with the best settings.

Choose Your Data Source Framework


You can use JDBC or JPA as your data source framework, to connect to your database of choice
(which you will be choosing later on). But which data source framework will you choose?

JPA Framework
JPA is an object relational mapping framework. You can use any data source with the JPA frame-
work. You'll need to define the mapping between your database table and its associated Java entity
object. One of the advantages of the JPA framework is that you can remove a lot of boilerplate code
and errors which are common in the JDBC framework.

JDBC Framework
JDBC is part of the Java SE specification. JDBC is considered low-level as you need to retrieve and
manage connections, statements, and results-sets yourself. If you fail to close or properly manage
them, you'll have errors and exceptions. JDBC requires a lot of boilerplate code but the advantage
of JDBC is the control you have over your database queries.

Whichever you decide on, we show you how to use it with Payara Server and there is an accompa-
nying video.

Using a Data Source with JPA

Using a Data Source with JPA

We’ve created a video taking you through using a data source with
the JPA framework, summarized below. This uses an example
program with a single dependency, the Jakarta EE 8 dependency,
which also uses the JPA framework.

42
Comprehensive Getting Started Guide

The main configuration of the JPA framework is done in the persistence.xml file (which we’ve showed
you how to create earlier in the guide).

Within this file, you will need to define the JNDI name for the data source that holds the connection
to the database. In the ‘Choose Your Database’ section, we will how you how to find the specific
JNDI name dependent on your database of choice – see below using the default for the Jakarta EE
compliant server.

Besides the data source, you can also define properties for the configuration of the framework. In the
below example, we’ve defined that tables need to be created at start up (as it is a demonstration),
and there is also the EclipseLink specific configuration, as Payara uses the EclipseLink configuration
for JPA. Logging level is set to FINEST, so we have a lot of information about what is happening
within the JPA framework.

43
Comprehensive Getting Started Guide

#Using JPA, you can also define your EJB classes, so there is mapping between the JAR and the
database. Below, we have defined the class Company which will be mapped to the table company
in the database.

The id column is the primary key, and the name column can be used to store the names.

Retrieving data from the database is then achieved using an entity manager, which you can inject as
below into this EJB, which automatically defines the transactions. In the below example, we launch
a query for a company that has matching id as the primary key.

To complement this, create a JAX-RS endpoint to set a boundary to retrieve a certain value from the
database and return it as a JSON value.

44
Comprehensive Getting Started Guide

As in this example, if the application is created with Maven, you can create the WAR artifact that
needs to be deployed with the command mvn clean package.

It will then build the application, compile data sources and all the required files, in a single WAR file.
It is ready now to be deployed on the server. It will verify the configuration you have done for JPA
and check the database connection is valid.

If everything is ok, you can then call the endpoint which returns the result of the database.

45
Comprehensive Getting Started Guide

Using a Data Source with JDBC

Using a Data Source with JDBC

As for the JPA framework, we have created a video with a simple


demo application, showing you through how to refer to the data
source – also explained below.

You can define a single dependency for the Jakarta API, although the JDBC is not part of the Jakarta
EE Enterprise specification but of Java SE. However, if the rest of the application is using Jakarta
EE (as a Payara Server application will be), including the REST endpoints, you will need the Jakarta
EE dependency.

When you retrieve the connection, you refer to the JNDI name where the connection is available in
the server. In the ‘Choose Your Database’ section, we will how you how to find the specific JNDI
name dependent on your database of choice – see below using the default for any Jakarta EE com-
pliant server.

46
Comprehensive Getting Started Guide

This framework is low-level, as mentioned above, so you will need to maintain all the parts
yourself

Steps
1. First, retrieve a connection.
2. Then prepare a statement which is sent to the database.

3. You can then execute a query and look over the results.

47
Comprehensive Getting Started Guide

Here, we are executing a query to the company table, where we specify a certain parameter as id.
Note: Don’t forget to use placeholders here, otherwise your application could be vulnerable – you
could be vulnerable to an SQL attack where they change or delete your database. Also make sure
all artifacts are properly closed – here using the try with resources statements.

The company will have no specific annotations like the JPA equivalent because this is using Java
SE, with the constructor to populate the values.

You can then create a REST endpoint where you can query the database for a certain record and the
result will be returned as JSON.

48
Comprehensive Getting Started Guide

As in this example, the application is created with Maven, you can create the WAR artifact that needs
to be deployed with the command mvn clean package. This will compile the Java coder and
assemble everything into a WAR file that can then be deployed on the server. The application is now
ready to be used.

In the case of JDBC, there is not much verification that is done up front. This is in contrast with JPA
framework. In JDBC, everything is done at runtime to check the connection is valid and the database
is active, for example.

If you then call the endpoint with the correct .id from the table, you receive the result as JSON
through the REST endpoint – and you can see that the datasource of the JDBC framework is used.

49
Comprehensive Getting Started Guide

Choose Your Database


You can choose the database you want to use with the Payara Server. We have created videos and
accompanying guides to help you configure the PostGreSQL, MySQL and PostgreSQL database.

Oracle DataBase My SQL PostgreSQL


Oracle XE is the version that is MySQL is an open-source rela- PostgreSQL is a fully SQL-
most suitable for developers tional database you may wish Compliant relational database
for small or personal projects, to use with Payara Server, that you can use with Payara Server
and should also be compatible excels at fast reads and is com- and with no commercial licens-
with the full version of Oracle monly used as storage for a ing requirements it is well suited
database. CMS. for production environments.

When you have chosen the database you wish to use, navigate to our relevant resources to set it up
below.

50
Comprehensive Getting Started Guide

Admin Console or Asadmin CLI?


For all three databases, we show you how to set them up both with the Admin Console and the
asadmin CLI tool. Using the Admin Console is useful if you are a first time Payara Server user as
you can see in the graphical interface what is required and it makes the process easy. However, the
downside is that you can make errors easily in typos, perhaps in the name of the server or the name
of the user. Using a script with the asadmin CLI is useful for noticing and correcting errors.

Using Oracle Database with Payara Platform Products


Configuration of the Oracle Database with Payara Server is best done with the Asadmin CLI tool but
you can also use the Admin Console or configure the Oracle Database using the DataSource defini-
tion, part of Jakarta EE framework. This option is best suited for Payara Micro, but both options can
be done with either Payara Server or Payara Micro.

Using Oracle DB with Payara Platform Products

In this video demonstration, learn how to configure the connection


to the Oracle Database and how to use it with JPA or JDBC frame-
work, and various options for using it with the Payara Platform.

51
Comprehensive Getting Started Guide

We also summarize here:

With the Admin Console

Steps
1. Add the JDBC driver for the Oracle Database to the environment. Use the add-library
command where you specify the current location of the JAR file.

2. Go to the Admin Console to define the configuration, using the specific menu item, under
JDBC – JDBC Connection Pool.
3. Create a Connection Pool to the Oracle Database.

4. Specify a name, resource type and vendor. Specifying the vendor will automatically fill many
properties.

Note: You do not need all the properties auto filled. You can delete them all and specify the ones
needed. The properties needed as a minimum are: URL, pointing to the database, for Oracle, oracle
jdbc;oracle;thin ; username and the password that needs to be connected with that user. You
can make use of the password alias property in Payara to ensure maximum security at this point,
we show you how to do this on page 58 of this guide.
Comprehensive Getting Started Guide

5. Next, create a JNDI name for the connection through the JDBC resources

6. Link to the correct pool – in this demonstration, the pool we have just created

53
Comprehensive Getting Started Guide

Now this JNDI name is ready for use in your application and you can specify it within the JPA or JDBC
configuration.

With the asadmin CLI


You can create a connection pool and JNDI name with the asadmin command line tool, with a script
similar to this:

54
Comprehensive Getting Started Guide

You can always use the enable Asadmin Recorder tool here to help automate the process - and
then whenever you perform the action on the UI a script will be generated. You can then use it in
your environment.

Steps
1. The creation of the connection pool is specified by the create-jdbc-connection-pool
where we specify that the oracle-pool needs to be created (see image above.)
2. We also need to specify the data source name, and as in the UI, the three properties – URL,
username and password
3. You then need to execute the statements

4. The last thing you need to do is define the JNDI name, which can be done using the cre-
ate-jdbc-resource command, where you assign the oracle-pool you have created in the
previous statement a certain JNDI name, in this case JDCB/local oracle

55
Comprehensive Getting Started Guide

5. This JNDI name needs to be made available to a single instance

6. Execute these two additional asadmin commands. If they execute successfully, this JNDI
name can be used within the application, within the JPA or JDBC

Using MySQL with Payara Platform Products

Using MySQL with Payara Platform Products

In this video demonstration, learn how to configure the connection


to the MySQL and how to use it with JPA or JDBC framework, and
various options for using it with the Payara Platform.

We also summarize here:

Configuration of the MySQL with Payara Server is best done with the Asadmin CLI tool, because
it is scripted and repeatable. You can also use the Admin Console for your first time, to make the
process easier.

56
Comprehensive Getting Started Guide

With the Admin Console

Steps
1. Add the JDBC driver for the MySQL Database to the environment. Use the add-library
command where you specify the current location of the JAR file

2. Next, go to the Admin Console so you can configure the MySQL connection with the server
3. Go to the Admin Console to define the configuration, using the specific menu item, under
JDBC – JDBC Connection Pool
4. Create a Connection Pool for the MySQL database
5. Specify a name, resource type and vendor. Specifying the vendor will automatically fill
many properties

57
Comprehensive Getting Started Guide

Note: You do not need all the properties auto filled. You can delete them all and
specify the ones needed. The properties needed as a minimum are:

• server name, the DNS name for the IP address where the MySQL database is running.
• Port number for the instance of the database (default 3306)
• Specific database name
• Username
• Password

You can make use of the password alias property in Payara to ensure maximum
security at this point, we show you how to do this on page 67 of this guide.

6. Next, create a JNDI name for the connection through the JDBC resources

58
Comprehensive Getting Started Guide

7. Link to the correct pool – in this demonstration, the pool we have just created

Now this JNDI name is ready for use in your application and you can specify it within the JPA or JDBC
configuration.

59
Comprehensive Getting Started Guide

With the asadmin CLI command


You can create a connection pool and JNDI name with the asadmin command line tool, with a script
similar to this:

You can always use the enable Asadmin Recorder tool here, and then whenever you perform the
action on the UI a script will be generated. You can then use it in your environment.

1. The creation of the connection pool is specified by the create-jdbc-connection-pool


where we specify that the MySQL data source which is located within the jdbc driver of
MySQL which is added to the server
2. We also need to specify the type and give the connection pool a name
3. We then define each of the 5 properties of the pool as in the Admin Console
4. You then need to execute the statements

60
Comprehensive Getting Started Guide

5. The next last thing you need to do is define the JNDI name, which can be done using the
create-jdbc-resource command, where you assign the name you have created
6. The JNDI name needs to be made available to the correct instance, whether that is deploy-
ment group, a standalone instance or as in this case, the server
7. Execute these two additional asadmin commands. If they execute successfully, this JNDI
name can be used within the application, within the JPA or JDBC

Using PostgreSQL with Payara Platform Products

Using PostgreSQL with Payara Platform Products

In this video demonstration, learn how to configure the connection


to the PostgreSQL and how to use it with JPA or JDBC framework

We also summarize here:

Configuration of the PostgreSQL with Payara Server is best done with the Asadmin CLI tool, because
it is scripted and repeatable. You can also use the Admin Console for your first time, to make the
process easier.

With the Admin Console

Steps
1. Add the JDBC driver for the PostgreSQL Database to the environment. Use the add-li-
brary command where you specify the current location of the JAR file

61
Comprehensive Getting Started Guide

2. Next, go to the Admin Console so you can configure the PostgreSQL connection with the
server
3. Go to the Admin Console to define the configuration, using the specific menu item, under
JDBC – JDBC Connection Pool
4. Create a Connection Pool for the PostgreSQL database
5. Specify a name, resource type and vendor. Specifying the vendor will automatically fill
many properties

Note: You do not need all the properties auto filled. You can delete them all and
specify the ones needed. The properties needed as a minimum are:

• server name – where the database is located, in this case local host
• Port number for the instance of the database, for PostgreSQL this is 5432
• Specific database name
• Username
• Password

62
Comprehensive Getting Started Guide

You can make use of the password alias property in Payara to ensure maximum
security at this point, we show you how to do this on page 67 of this guide.

6. Next, create a JNDI name for the connection through the JDBC resources

7. Link to the correct pool – in this demonstration, the pool we have just created

63
Comprehensive Getting Started Guide

Now this JNDI name is ready for use in your application and you can specify it within the JPA or JDBC
configuration.

With the asadmin CLI command


You can create a connection pool and JNDI name with the asadmin command line tool, with a script
similar to this:

You can always use the enable Asadmin Recorder tool here, and then whenever you perform the
action on the UI a script will be generated. You can then use it in your environment.

64
Comprehensive Getting Started Guide

Steps
1. The creation of the connection pool is specified by the create-jdbc-connection-pool
where we specify that the PostgreSQL data source which is located within the jdbc driver of
PostGreSQL which is added to the server
2. We also need to specify the type and give the connection pool a name; in this case
postgres-pool
3. We then define each of the 5 properties of the pool as in the Admin Console
4. You then need to execute the statements

5. The next last thing you need to do is define the JNDI name, which can be done using the
create-jdbc-resource command, where you assign the pool name you have created

65
Comprehensive Getting Started Guide

6. The JNDI name needs to be made available to the correct instance, whether that is deploy-
ment group, a standalone instance or as in this case, the server. This done through the last
command, create-resource-ref
7. Execute these two additional asadmin commands. If they execute successfully, this JNDI
name can be used within the application, within the JPA or JDBC

66
Comprehensive Getting Started Guide

Hide Passwords with Password Aliases in Payara Server


As promised, we will now show you how to hide passwords in Payara Server, to ensure maximum
security for your application, using the Password Alias feature.

As you have seen above in the database section, when performing the configuration of the Payara
Server for your application, you often need to supply a password. The password to connect to the
database is a classic example, but there are many situations where you need to enter this kind of
sensitive data.

With Payara Server, you have the option to hide this kind of sensitive data from the user, so that this
information is much better secured. Those sensitive values are no longer used in commands and
on the pages of the Admin Console. They are encrypted and stored in the domain configuration and
only the values are referenced by a name. Those references do not expose the value and thus the
sensitive data are stored safely.

As an example, here's the procedure for hiding the actual password for a database connection. But
the feature can be used in a much broader context. It is not limited to only the password field of the
database connection where it is supported but it is part of the variable substitution feature of the
Payara Platform.

But first, the below describes how you can create a password alias.

There is an asadmin command to create such value. The command is as follows:

./asadmin create-password-alias dbpass


Enter the alias password>
Enter the alias password again>

You explicitly need to type the password in (and retype it) and you cannot specify it on the command
line. This to prevent the password from being stored in your command line history.

You can list all the aliases that are known by the system with the following command:

./asadmin list-password-aliases

But you cannot list the actual value of the password.

67
Comprehensive Getting Started Guide

The same functionality is also available within the Admin Console:

It lists all available Password Aliases in the domain, you can create and delete them and change the
value of it. Make sure that the Secure Admin option is enabled by Payara Server so that the contents
of the password Alias are sent encrypted (through SSL) to the server.

Once you have the Password Alias in place, you can use it to define the value for the password in the
database connection field. With the field, you can place the following info:

${ALIAS=dbpass}

When the Payara Platform resolves the values, it looks up the Password Alias and decrypts the value.
This value is only present in memory and never stored.

This way, you can define sensitive values but they never show up in the output of an asadmin
command or on the Admin Console screens.

As already mentioned, the support is not limited to the password field but the Password Alias
can be used at all locations where variable substitution is supported. This includes XML descrip-
tor files, annotations, properties files, and more. For a comprehensive list, you can have a look at
our documentation.

But the values can also be retrieved at runtime so that your code can also make use of the sensi-
tive data. An example is the private key that is used to sign the JWT message that you send to a
remote service. An example is the private key that is used to sign the JWT message that you send
to a remote service.

68
Comprehensive Getting Started Guide

The following code snippet injects the value into a property using the MicroProfile Config functionality:

@Inject
@ConfigProperty(name = "dbpass")
private String password;

Our MicroProfile Config implementation includes a Config Source that looks up the key as Password
Alias. If found, it decrypts it and returns the value.

The encryption of the value makes use of the KeyStore functionality of the JVM itself. It uses the
master password and a random value to generate a symmetric key (Password-Based Encryption).
This key is used to encrypt the value of the Password Alias. The key used to encrypt the value itself is
never stored in the configuration directory, only the random value, and the resulting encrypted value.

Based on the stored random value, the symmetric key can be reconstructed using the master pass-
word and the encrypted value can be decrypted to its original value.

It is safe to change the Master Password in the situation you have some Password Aliases stored.
Actions are performed to make sure the value can still be used with the new master password.

69
Comprehensive Getting Started Guide

Do More With Payara Server:


Additional Resources
Congratulations – if you made it this far, you are up and running with Payara Server! Now you are ready
to add more functionality. We have a wealth of free articles, cheat sheets, guides, and videos availa-
ble, and you can search through them on our resources page by topic or using our handy search bar.

In the meantime, here are a few to get you started:

Creating a RESTFUL Web Service with Payara Server and NetBeans


• Learn How to Create a RESTful Web Service with Payara Server & NetBeans
• Consuming a RESTful Web Service
• Creating a User Interface with JSF
• Securing a REST Service
• How to Test Applications with Payara Server Using Arquillian

Security Auditing in Payara Server


• Security Auditing in Payara Server Part 1
• Security Auditing in Payara Server Part 2
• Create a Custom Audit Module
• Debugging: Diagnose and Detect the Cause of Errors in Application

Making Use of Payara Server’s Monitoring Service


• Setting Up JMX Monitoring Service
• Integrating with Logstash and Elasticsearch
• Using Kibana to Visualise the Data

Using The Payara Platform In Production


This guide has assumed use of Payara Platform Community Edition – our open source server runtime
for development projects.

However, if you are looking to run your deployment in production, we offer Payara Platform Enterprise
Edition as stable, supported software for mission critical systems in production.

70
Comprehensive Getting Started Guide

With Payara Enterprise Edition, you are able to:

Get support directly from engineers Security alerts and fixes

There is no need to count the number of Payara You will automatically receive notifications of
Server units being used - Migration & Project security issues and fixes in all current and previ-
Support subscription covers an unlimited num- ous versions of Payara Platform.
ber of units in development environments. There
is no limit on the number of tickets that you can
raise during your support contract. Stability

You will again exclusive access to monthly


Enjoy a 10-year software lifecycle releases of Payara Server Enterprise Edition,
including crucial fixes and patches. New features
Major versions of Payara Server and Payara Micro are added only once they are stable and ready for
come with 10 years of support and a well-defined production use.
lifecycle model maintaining stability of your pro-
duction environment: Payara Server and Payara
Micro 4.x support until 2024, Payara Server and OpenJDK support
Payara Micro 5.x support until 2028. So, unlike
with Payara Platform Community Edition, you You will benefit from Payara’s partnership
won’t have to worry about upgrading a year or with Azul, providing you with access to use
two after you implement a Payara solution. Zulu Platform Core - Fully-Supported Builds of
OpenJDK - with Payara Server.

Monthly releases, bug fixes and You will receive all these benefits and more with a
patches Payara Enterprise subscription – find full list here.
With Payara Enterprise, you will join the list of
Our community involvement and public open global companies who trust our solution to deliver
source development ensures that bugs, feature their mission critical environments, including
suggestions and feedback are rolled into Payara some from the Fortune 500 list. For example,
Platform Enterprise products making Payara Rakuten Card moved to an 100% cloud-native
Server the best option for production Jakarta EE architecture using Payara Enterprise, and BMW
(Java EE) applications. successfully migrated from GlassFish to Payara
Server in 2016 – and never looked back!

  
[email protected] +44 207 754 0481 www.payara.fish

Payara Services Ltd 2021 All Rights Reserved. Registered in England and Wales; Registration Number 09998946
Registered Office: Malvern Hills Science Park, Geraldine Road, Malvern, United Kingdom, WR14 3SZ

71

You might also like