Skip to content

GlassFish

Install and run GlassFish: secure admin, ports and paths, JVM tuning, SSL certificates, JDBC and mail resources, realms and common errors.

18 min readUpdated

GlassFish is the open-source Jakarta EE (formerly Java EE) application server maintained by the Eclipse Foundation. Payara Server is a fork of it, so most of this note also applies to Payara.

This note covers installing GlassFish on Debian, enabling remote administration, the default ports and paths, JVM and HTTP tuning, SSL certificates, JDBC and mail resources, the EJB Timer Service, file realms and fixes for errors met in practice. The commands were written for GlassFish 5.1; the asadmin subcommands are the same in later releases, but the install directory is named after the major version (glassfish7, glassfish8).

In the commands below, GLASSFISH_HOME is the unpacked directory, for example /opt/glassfish5. The domain lives in $GLASSFISH_HOME/glassfish/domains/domain1.

Install on Debian

You need Debian (or another Linux distribution) and a JDK supported by the GlassFish release you install. Download the distribution from Maven Central and unpack it into /opt:

Terminal window
wget https://repo1.maven.org/maven2/org/glassfish/main/distributions/glassfish/5.1.0/glassfish-5.1.0.zip
sudo apt install unzip
sudo unzip glassfish-5.1.0.zip -d /opt

Current releases are listed on the GlassFish download page.

Put asadmin on the PATH so the commands in this note work from any directory, and make sure the script is executable:

Terminal window
export PATH=/opt/glassfish5/bin:$PATH
chmod +x /opt/glassfish5/bin/asadmin

Enable remote access to the admin console

The admin console listens on port 4848. Opening http://your_server_IP:4848 from another machine fails with “Secure Admin must be enabled to access the DAS remotely” until secure admin is enabled:

Terminal window
asadmin --host your_server_IP --port 4848 enable-secure-admin

On a fresh domain this fails, because the default admin user has an empty password:

remote failure: At least one admin user has an empty password, which secure admin does not permit. Use the change-admin-password command or the admin console to create non-empty passwords for admin accounts.
Command enable-secure-admin failed.

Set an admin password first. The default credentials are user admin with an empty password:

Terminal window
asadmin change-admin-password

Then enable secure admin again and restart the domain, because the change only takes effect after a restart:

Terminal window
asadmin --host your_server_IP --port 4848 enable-secure-admin
asadmin restart-domain domain1

Change the HTTP port and context root

Both settings live in the domain configuration file:

Terminal window
nano /opt/glassfish5/glassfish/domains/domain1/config/domain.xml

To serve HTTP on port 80 instead of 8080, change the port attribute of http-listener-1. On Linux, binding to a port below 1024 requires root privileges.

<network-listener protocol="http-listener-1" port="8080" ...>

To serve an application at the root of the site, set its context-root to /:

<application context-root="/application" ...>

Default ports, paths and values

Ports

Default port Listener
4848 Administration console, also the admin and monitoring REST interfaces
8080 HTTP
8181 HTTPS
8686 JMX service
3700 IIOP
3820 IIOP/SSL
3920 IIOP/SSL with mutual authentication
22 SSH (used to manage remote nodes)
9009 Java debugger
7676 JMS provider
Auto-generated from the operating system’s dynamic port range Message Queue TCP port
Auto-generated from the operating system’s dynamic port range Message Queue admin port
9090 GMS TCP start port
9200 GMS TCP end port
Auto-generated between the GMS TCP start and end ports GMS listener port
Auto-generated between 2048 and 49151 GMS multicast port

Paths

The GlassFish documentation uses these placeholders for paths. The example values are for GlassFish 7 unpacked in the home directory.

Placeholder Value
as-install user's-home-directory/glassfish7/glassfish
as-install-parent user's-home-directory/glassfish7
domain-root-dir as-install/domains/
domain-dir domain-root-dir/domain-name
instance-dir domain-dir/instance-name

Administration defaults

Setting Default value or location
Domain name domain1
Master password changeit
asadmin command-line utility as-install/bin/asadmin
Configuration files domain-dir/config
Log files domain-dir/logs

Clusters

A cluster is a group of GlassFish Server instances that work together as one logical entity. It provides a runtime environment for one or more Jakarta EE applications and gives high availability through failure protection, scalability and load balancing.

The diagram below shows the parts: a load balancer (LB) spreads requests over worker nodes (WN), each running a container, while the Domain Administration Server (DAS) manages the configuration of every node.

GlassFish cluster: a load balancer in front of worker nodes, all managed by the Domain Administration Server

Manage domains and applications with asadmin

Start, stop and restart a domain

Terminal window
asadmin start-domain
asadmin stop-domain
asadmin restart-domain

Without a domain name the commands act on the only domain, usually domain1.

Deploy and undeploy an application

Terminal window
asadmin deploy /path/to/application-name.war
asadmin undeploy application-name

Add resources from a file

add-resources creates the JDBC pools, JDBC resources, mail resources and other objects defined in a glassfish-resources.xml file:

Terminal window
asadmin add-resources /path/to/glassfish-resources.xml

Avoid password prompts with a password file

Every asadmin command accepts --passwordfile, which reads the passwords from a file instead of prompting for them. The same file holds several kinds of password, each with its own prefix:

  • AS_ADMIN_PASSWORD: admin password (empty by default)
  • AS_ADMIN_MASTERPASSWORD: master password (changeit by default)
  • AS_ADMIN_USERPASSWORD: user password
  • AS_ADMIN_ALIASPASSWORD: alias password

For deploying and undeploying, the admin password is enough. Create a file named pwdfile:

pwdfile
AS_ADMIN_PASSWORD=your_admin_password

Pass it to the command, and the username and password prompts no longer appear:

Terminal window
asadmin --passwordfile pwdfile deploy /path/to/application-name.war

Keep the file readable only by its owner (chmod 600 pwdfile), since it holds the password in plain text.

Change the master password

The master password protects the keystores and defaults to changeit. Change it with:

Terminal window
asadmin change-master-password --savemasterpassword=true mydomain

--savemasterpassword=true saves the password to disk so that asadmin start-domain does not prompt for it. Omit the option if you do not want the password stored.

Reset a forgotten admin password

Admin users are stored in domain-dir/config/admin-keyfile, one line per user. To reset the password, stop the domain and replace the admin line with one of the lines below, then start the domain and set a new password with asadmin change-admin-password.

The password becomes changeit:

admin;{SSHA256}dvCEGFNHGtSyXIhJvwR5FnviH+u8fCadrUIqp6uJc1tP9Bv10CGT7A==;asadmin

The password becomes empty:

admin;{SSHA256}2GiTMM0n4ulpMfRaMPMImYvVF522XY6nW2cKSXoY1EoM2QlHrHUkDQ==;asadmin

Set JVM options

List the options passed to the Java launcher when the server starts:

Terminal window
asadmin list-jvm-options

Options can be added with asadmin create-jvm-options or by editing the <jvm-options> elements in domain.xml.

According to the GlassFish documentation on configurations, the standalone server uses server-config:

The default-config configuration is a special configuration that acts as a template for creating named configurations. Clusters and instances cannot refer to the default-config configuration. The default-config configuration can only be copied to create configurations.

So these two commands make the same change, the second naming the target explicitly:

Terminal window
asadmin create-jvm-options -Xmx4g
asadmin create-jvm-options --target server-config -- '-Xmx4096m'

The -- ends the asadmin options, so that the next argument is read as a JVM option. Run asadmin list-jvm-options afterwards; if an older -Xmx value is still listed, remove it with asadmin delete-jvm-options -Xmx512m. Restart the domain for JVM options to take effect.

Tune the JVM heap

These JDK tools help find the right heap size:

Terminal window
jps # list running JVMs and their process IDs
jmap -histo:live <pid> # histogram of live objects on the heap
jhsdb jmap --heap --pid <pid> # heap summary (JDK 9 and later)
jmap -heap <pid> # heap summary (JDK 8 only)

jmap -heap was removed in JDK 9; jhsdb jmap --heap replaces it.

The following guidelines size each space from its occupancy after a full garbage collection, which you can read from the GC logs:

Space Command-line option Size
Java heap -Xms and -Xmx 3x to 4x old generation occupancy after full GC
Permanent generation (JDK 7 and earlier) -XX:PermSize, -XX:MaxPermSize 1.2x to 1.5x permanent generation occupancy after full GC
Young generation -Xmn 1x to 1.5x old generation occupancy after full GC
Old generation Implied: total heap minus young generation 2x to 3x old generation occupancy after full GC

JDK 8 replaced the permanent generation with Metaspace. On JDK 8 and later, use -XX:MetaspaceSize and -XX:MaxMetaspaceSize instead of the PermSize options, which newer JVMs no longer accept.

Sample settings:

  • 2 GB RAM: -Xms512m -Xmx1024m -XX:CompileThreshold=8000 -XX:MetaspaceSize=256m -XX:MaxMetaspaceSize=512m
  • 8 GB RAM: -Xms2048m -Xmx4096m -XX:CompileThreshold=8000 -XX:MetaspaceSize=1024m -XX:MaxMetaspaceSize=2048m

Enable HTTP compression

Edit $GLASSFISH_HOME/glassfish/domains/domain1/config/domain.xml and add the compression attributes to the http element of http-listener-1 and http-listener-2 under the server-config configuration. The highlighted lines are the ones to change:

domain.xml
<configs>
<config name="server-config">
...
<network-config>
<protocols>
<protocol name="http-listener-1">
<http max-connections="250" default-virtual-server="server"
compression="on"
compression-min-size-bytes="128"
compressable-mime-type="text/html,text/css,text/plain,text/xml,application/javascript,application/json">
<file-cache></file-cache>
</http>
<ssl></ssl>
</protocol>
<protocol name="http-listener-2" security-enabled="true">
<http max-connections="250" default-virtual-server="server"
compression="on"
compression-min-size-bytes="128"
compressable-mime-type="text/html,text/css,text/plain,text/xml,application/javascript,application/json">
<file-cache></file-cache>
</http>
<ssl classname="com.sun.enterprise.security.ssl.GlassfishSSLImpl" cert-nickname="s1as"></ssl>
</protocol>

compression-min-size-bytes skips responses smaller than 128 bytes, where compression gains nothing. compressable-mime-type lists the content types to compress.

Install an SSL certificate

GlassFish reads its keys from domain-dir/config/keystore.jks and its trusted certificates from domain-dir/config/cacerts.jks. Both are protected by the master password (changeit unless you changed it). The steps below create a key and CSR, import the certificates your certificate authority (CA) returns, and point the HTTPS listener at the new key. Use the same keystore file name in every step, and put the finished keystore.jks in domain-dir/config.

  1. Create a working directory for the keystore and CSR:

    Terminal window
    mkdir sslcert
    cd sslcert
  2. Create the keystore and key pair:

    Terminal window
    keytool -genkey -alias youralias -keyalg RSA -keystore keystore.jks -keysize 2048

    Enter the keystore password when prompted (the master password). keytool then asks for the certificate details; they must match what you gave the CA when you bought the certificate:

    What is your first and last name? = Your domain name (e.g. www.xyz.com)
    What is the name of your organizational unit? = Your department (e.g. IT)
    What is the name of your organization? = Your organization (e.g. XYZ CA Ltd)
    What is the name of your City or Locality? = Your city (e.g. Clifton)
    What is the name of your State or Province? = Your state (e.g. New Jersey)
    What is the two-letter country code for this unit? = Your country code (e.g. US)

    Confirm the summary with y. When asked for the key password, press Enter to reuse the keystore password; GlassFish expects both to be the same.

  3. Generate the CSR, using the same alias, and send it to the CA:

    Terminal window
    keytool -certreq -alias youralias -file yourcsrname.csr -keystore keystore.jks
  4. Import the CA’s root certificate into keystore.jks (and into cacerts.jks if it is not already trusted):

    Terminal window
    keytool -import -v -trustcacerts -alias root -file addtrustexternalcaroot.crt -keystore keystore.jks
  5. Import each intermediate certificate, each under its own unique alias:

    Terminal window
    keytool -import -v -trustcacerts -alias XYZRSAAddTrustCA -file XYZRSAAddTrustCA.crt -keystore keystore.jks
    keytool -import -v -trustcacerts -alias XYZRSADomainValidationSecureServerCA -file XYZRSADomainValidationSecureServerCA.crt -keystore keystore.jks
  6. Import your domain certificate under the same alias as the key pair from step 2:

    Terminal window
    keytool -import -alias youralias -trustcacerts -file your_domain_certificate.crt -keystore keystore.jks

    On success keytool prints Certificate reply was installed in keystore. This differs from the Certificate was added to keystore message of steps 4 and 5; if you see the latter, the alias does not match the key pair.

  7. Configure http-listener-2 in the admin console under Configurations > server-config > http-listener-2:

    • On the General tab, change the port from 8181 to 443.
    • On the SSL tab, change Certificate NickName from s1as to your alias (youralias).
    • Save.
  8. In domain-dir/config/domain.xml, replace the remaining references to s1as with your alias, then restart the domain.

Configure a JDBC connection pool and data source

Make the JDBC driver available to the domain, create a connection pool, then a JDBC resource that applications look up by JNDI name. This example uses MySQL Connector/J 5.1:

Terminal window
cp ~/mysql-connector-java-5.1.5-bin.jar $GLASSFISH_HOME/glassfish/domains/domain1/lib/ext
asadmin create-jdbc-connection-pool --datasourceclassname com.mysql.jdbc.jdbc2.optional.MysqlDataSource --property user=root:password=test:DatabaseName=test:ServerName=localhost:port=3306 test-pool
asadmin create-jdbc-resource --connectionpoolid test-pool jdbc/test

Instead of copying the JAR, you can run asadmin add-library /path/to/driver.jar. Restart the domain after adding a driver.

For a pool that supports distributed transactions, use the XA data source class and set --restype javax.sql.XADataSource:

Terminal window
asadmin create-jdbc-connection-pool --restype javax.sql.XADataSource --datasourceclassname com.mysql.jdbc.jdbc2.optional.MysqlXADataSource --property user=root:password=test:DatabaseName=test:ServerName=localhost:port=3306 test-pool

Note: Connector/J 8 and later renamed these classes to com.mysql.cj.jdbc.MysqlDataSource and com.mysql.cj.jdbc.MysqlXADataSource.

Check that the pool can reach the database (the database server must be running):

Terminal window
asadmin ping-connection-pool test-pool

Configure mail resources

A mail-resource in domain.xml or glassfish-resources.xml gives applications a JavaMail session under a JNDI name. The examples below all use mail/myMailSession.

Own domain without SSL

<mail-resource jndi-name="mail/myMailSession"
host="mail.domain.com"
user="user@domain.com"
from="user@domain.com"
object-type="user"
store-protocol="imap"
store-protocol-class="com.sun.mail.imap.IMAPStore"
transport-protocol="smtp"
transport-protocol-class="com.sun.mail.smtp.SMTPTransport"
debug="true"
enabled="true">
<property name="mail.smtp.auth" value="true"/>
<property name="mail.smtp.port" value="587"/>
<property name="mail.smtp.password" value="PASSWORD"/>
<property name="mail.smtp.starttls.enable" value="false"/>
</mail-resource>

Gmail with STARTTLS and an app password

Gmail requires an app password for SMTP authentication:

  1. Turn on 2-Step Verification under Google Account > Security.
  2. Create an app password under Google Account > Security > 2-Step Verification > App passwords.
  3. The app password looks like abcd efgh ijkl mnop. Remove the spaces when you use it.
<mail-resource
jndi-name="mail/myMailSession"
host="smtp-relay.gmail.com"
user="user@gmail.com"
from="user@gmail.com"
enabled="true">
<property name="mail.smtp.auth" value="true"/>
<property name="mail.smtp.starttls.enable" value="true"/>
<property name="mail.smtp.port" value="587"/>
<property name="mail.smtp.password" value="abcdefghijklmnop"/>
</mail-resource>

smtp-relay.gmail.com is the SMTP relay service of Google Workspace and must be enabled in the Workspace admin console. For a personal Gmail account, use smtp.gmail.com as the host.

Gmail with SSL

<mail-resource jndi-name="mail/myMailSession"
host="smtp.gmail.com"
user="user@gmail.com"
from="user@gmail.com"
object-type="user"
store-protocol="imaps"
store-protocol-class="com.sun.mail.imap.IMAPSSLStore"
transport-protocol="smtps"
transport-protocol-class="com.sun.mail.smtp.SMTPSSLTransport"
debug="true"
enabled="true">
<property name="mail.smtps.auth" value="true"/>
<property name="mail.smtps.password" value="PASSWORD"/>
</mail-resource>

Yandex with SSL

<mail-resource jndi-name="mail/myMailSession"
host="smtp.yandex.com"
user="user@domain.com"
from="user@domain.com"
object-type="user"
store-protocol="imaps"
store-protocol-class="com.sun.mail.imap.IMAPSSLStore"
transport-protocol="smtp"
transport-protocol-class="com.sun.mail.smtp.SMTPTransport"
debug="true"
enabled="true">
<property name="mail.smtp.auth" value="true"/>
<property name="mail.smtp.starttls.enable" value="true"/>
<property name="mail.smtp.port" value="587"/>
<property name="mail.smtp.password" value="PASSWORD"/>
<!-- Trust this host for the SSL connection: a host name, or * for all -->
<property name="mail.smtp.ssl.trust" value="smtp.yandex.com"/>
<property name="mail.imaps.auth" value="true"/>
<property name="mail.imaps.starttls.enable" value="false"/>
<property name="mail.imaps.host" value="imap.yandex.com"/>
<property name="mail.imaps.port" value="993"/>
<property name="mail.imaps.password" value="PASSWORD"/>
<!-- Trust this host for the SSL connection: a host name, or * for all -->
<property name="mail.imaps.ssl.trust" value="*"/>
</mail-resource>

debug="true" logs the SMTP and IMAP conversation to the server log, which helps while setting up; turn it off in production.

Serve files from outside the application (alternatedocroot)

An alternate document root serves files, such as uploaded images, from a directory outside the WAR. Add the property to glassfish-web.xml:

glassfish-web.xml
<property description="Uploaded images" name="alternatedocroot_1" value="from=/images/* dir=/var/app/uploads"/>

Reference the files by their URL path in a page, for example with PrimeFaces:

<p:graphicImage value="/images/logo.png"/>
  • The from path is appended to dir, so the files must be in /var/app/uploads/images.
  • Use the value attribute of p:graphicImage, not name.

Store EJB timers in your own database

By default the EJB Timer Service uses the jdbc/__TimerPool resource. To keep timers in your application database, create the timer table there and point the service at your JDBC resource. See also Set/configure the EJB Timer Service’s DataSource on Stack Overflow.

Create the timer table

GlassFish ships the DDL for each database in $GLASSFISH_HOME/glassfish/lib/install/databases/ejbtimer_[DB_ENGINE].sql, where DB_ENGINE is, for example, mysql. Run it against your database. The MySQL version:

ejbtimer_mysql.sql
CREATE TABLE EJB__TIMER__TBL (
`CREATIONTIMERAW` BIGINT NOT NULL,
`BLOB` BLOB,
`TIMERID` VARCHAR(255) NOT NULL,
`CONTAINERID` BIGINT NOT NULL,
`OWNERID` VARCHAR(255) NULL,
`STATE` INTEGER NOT NULL,
`PKHASHCODE` INTEGER NOT NULL,
`INTERVALDURATION` BIGINT NOT NULL,
`INITIALEXPIRATIONRAW` BIGINT NOT NULL,
`LASTEXPIRATIONRAW` BIGINT NOT NULL,
`SCHEDULE` VARCHAR(255) NULL,
`APPLICATIONID` BIGINT NOT NULL,
CONSTRAINT `PK_EJB__TIMER__TBL` PRIMARY KEY (`TIMERID`)
);

Point the timer service at the data source

  1. Open the admin console, usually at http://localhost:4848.
  2. Go to Configurations > server-config > EJB Container.
  3. Open the EJB Timer Service tab.
  4. Set Timer Datasource to your JDBC resource, for example mysql-pu. The default is jdbc/__TimerPool.
  5. Restart the server.

The server log then shows the timer service starting on your data source:

INFO: [TimerBeanContainer] Created TimerBeanContainer: TimerBean
INFO: EJB5181:Portable JNDI names for EJB TimerBean: [java:global/ejb-timer-service-app/TimerBean, java:global/ejb-timer-service-app/TimerBean!com.sun.ejb.containers.TimerLocal]
INFO: WEB0671: Loading application [ejb-timer-service-app] at [/ejb-timer-service-app]
INFO: EJB5109:EJB Timer Service started successfully for data source [mysql-pu]
INFO: Setting DBReadBeforeTimeout to false
INFO: ==> Restoring Timers ...
INFO: There are no EJB Timers owned by this server
INFO: <== ... Timers Restored.

For clusters, see To Deploy an EJB Timer to a Cluster in the Oracle GlassFish documentation.

Timer service stops working after many redeployments

After many deploy-on-save cycles from an IDE, the timer service can become unavailable with these errors:

Severe: Exception while loading the app
Severe: Undeployment failed for context /ejb-timer-service-app
Warning: Cannot deploy or load EJBTimerService: org.glassfish.deployment.common.DeploymentException: Error in linking security policy for ejb-timer-service-app -- Inconsistent Module State

To recover:

  1. Stop GlassFish.
  2. Delete the contents of $GLASSFISH_HOME/glassfish/domains/yourdomainname/generated.
  3. Start GlassFish.

This fixes the state until it breaks again, so you may have to repeat it after further redeployments.

Protect an application with the file realm

A realm is the user store GlassFish authenticates against. The reference pages for create-auth-realm and create-file-user list all options.

Create a realm

Terminal window
asadmin create-auth-realm --classname realm_class [--help] [--property(name=value)[:name=value]*] [--target target_name] auth_realm_name

If realm creation fails with remote failure: Creation of Authrealm jdbcbid failed., the cause can be the JVM locale. Set it to English and restart the server:

Terminal window
asadmin create-jvm-options -Duser.language=en
asadmin create-jvm-options -Duser.region=US

Set up BASIC authentication

  1. Log in to the admin console at http://localhost:4848.
  2. Go to Security > Realms > file.
  3. Enter the group names Administrators:Members in the Assign Groups field.
  4. Click Manage Users at the top of the page.
  5. Click New, add a user (for example testuser) and give it a password.
  6. Enter Administrators:Members in the Group List. Separate multiple groups with a colon.
  7. Map the groups to roles in glassfish-web.xml and protect the URLs in web.xml, as below.

glassfish-web.xml maps each GlassFish group to an application role:

glassfish-web.xml
<glassfish-web-app>
<security-role-mapping>
<role-name>Administrator</role-name>
<group-name>Administrators</group-name>
</security-role-mapping>
<security-role-mapping>
<role-name>Member</role-name>
<group-name>Members</group-name>
</security-role-mapping>
</glassfish-web-app>

web.xml restricts each URL pattern to a role and selects BASIC authentication against the file realm:

web.xml
<web-app>
<security-constraint>
<web-resource-collection>
<web-resource-name>Administrator Area</web-resource-name>
<url-pattern>/administrator/*</url-pattern>
</web-resource-collection>
<auth-constraint>
<role-name>Administrator</role-name>
</auth-constraint>
</security-constraint>
<security-constraint>
<web-resource-collection>
<web-resource-name>Member Area</web-resource-name>
<url-pattern>/member/*</url-pattern>
</web-resource-collection>
<auth-constraint>
<role-name>Member</role-name>
</auth-constraint>
</security-constraint>
<login-config>
<auth-method>BASIC</auth-method>
<realm-name>file</realm-name>
</login-config>
<security-role>
<role-name>Administrator</role-name>
</security-role>
<security-role>
<role-name>Member</role-name>
</security-role>
</web-app>

Troubleshooting

OutOfMemoryError

Raise the maximum heap in $GLASSFISH_HOME/glassfish/domains/domain1/config/domain.xml. The default is <jvm-options>-Xmx512m</jvm-options>; set a higher value such as <jvm-options>-Xmx1024m</jvm-options>.

If that does not help, capture a heap dump when the error occurs by adding this option to domain.xml:

<jvm-options>-XX:+HeapDumpOnOutOfMemoryError</jvm-options>

The JVM then writes a .hprof file when it runs out of memory. Open it in the Eclipse Memory Analyzer (MAT) to find which objects fill the heap.

PKIX path building failed

The full message, here from the AWS SDK, is:

software.amazon.awssdk.core.exception.SdkClientException: Unable to execute HTTP request: sun.security.validator.ValidatorException: PKIX path building failed: sun.security.provider.certpath.SunCertPathBuilderException: unable to find valid certification path to requested target

The JVM does not trust the certificate chain of the server it connects to. The fix is to import the missing root or intermediate certificate into the trust store that GlassFish uses.

Save the server’s certificates to a file. This command prints the chain:

Terminal window
openssl s_client -showcerts -connect sns.eu-west-1.amazonaws.com:443

This one writes the first certificate straight to yourcert.pem:

Terminal window
echo | openssl s_client -connect yourserver:port 2>&1 | sed -ne '/-BEGIN CERTIFICATE-/,/-END CERTIFICATE-/p' > yourcert.pem

When you need a root or intermediate certificate rather than the server’s own, copy that block from the -showcerts output into the file.

Import it into the JDK trust store:

Terminal window
sudo keytool -import -alias <server_name> -keystore $JAVA_HOME/lib/security/cacerts -file yourcert.pem -storepass changeit

On JDK 8 the file is $JAVA_HOME/jre/lib/security/cacerts. GlassFish uses its own trust store, so import the certificate there as well, then restart GlassFish:

Terminal window
keytool -import -alias <server_name> -keystore $GLASSFISH_HOME/glassfish/domains/domain1/config/cacerts.jks -file yourcert.pem -storepass changeit

-storepass is the master password; changeit is the default.

Other useful keytool commands:

Terminal window
# Delete a certificate
sudo keytool -delete -noprompt -alias aws -keystore $JAVA_HOME/lib/security/cacerts -storepass changeit
# List the certificates in a trust store or keystore
keytool -list -keystore $JAVA_HOME/lib/security/cacerts -storepass changeit > list.txt
keytool -v -list -keystore $GLASSFISH_HOME/glassfish/domains/domain1/config/keystore.jks > list.txt

For JavaMail connections only, you can instead tell the client to trust specific hosts. This skips certificate verification for those hosts, so prefer importing the certificate:

MailSSLSocketFactory sf = new MailSSLSocketFactory();
sf.setTrustAllHosts(true);
properties.put("mail.imap.ssl.trust", "imap.yandex.com"); // or "*" for all hosts
properties.put("mail.imap.ssl.socketFactory", sf);
properties.put("mail.smtp.ssl.trust", "smtp.yandex.com"); // or "*" for all hosts
properties.put("mail.smtp.ssl.socketFactory", sf);

Further reading:

NoSuchMethodError: Handshaker.setApplicationProtocols

java.lang.NoSuchMethodError: sun.security.ssl.Handshaker.setApplicationProtocols([Ljava/lang/String;)V

Older GlassFish versions ship an old copy of the JDK’s internal sun.security.ssl classes in grizzly-npn-bootstrap.jar, which clashes with the JDK’s own. Remove the sun directory from the JAR:

Terminal window
cd $GLASSFISH_HOME/glassfish/modules/endorsed
# List the contents of the JAR
jar -tf grizzly-npn-bootstrap.jar
# Remove the sun directory and everything under it
zip -d grizzly-npn-bootstrap.jar sun\*

The same zip -d works for any file or directory in a JAR:

Terminal window
zip -d file.jar unwanted_file.txt
zip -d file.jar unwanted_folder/

Error generating artifacts for the WSDL

Error generating artifacts for the following WSDL []. Possible causes can be invoking https when the application is not configured for security.

On a local server both the ?WSDL and ?Tester links of a JAX-WS service work; on a remote server ?WSDL works but ?Tester fails with this error.

The cause is the default restriction on access to external schemas. In the IDE or the Maven build this is usually lifted with the -Djavax.xml.accessExternalSchema=all JVM argument. On GlassFish, add the same option to domain.xml so the server can parse the WSDL and generate the test client, then restart the server:

<java-config>
...
<jvm-options>-Djavax.xml.accessExternalSchema=all</jvm-options>
</java-config>

See Getting Started with JAX-WS Web Services (section “Enabling Access to External Schema”).

Cannot open keystore.jks when allocating a JDBC connection

Connection could not be allocated because: Cannot open file:GLASSFISH_HOME/glassfish/domains/domain1/config/keystore.jks

The MySQL driver tries to open an SSL connection with the JVM’s keystore. If the database does not need SSL, add allowPublicKeyRetrieval=true and useSSL=false under JDBC > JDBC Connection Pools > your pool > Additional Properties in the admin console, or in glassfish-resources.xml:

<jdbc-connection-pool ...>
<property name="allowPublicKeyRetrieval" value="true"/>
<property name="useSSL" value="false"/>
</jdbc-connection-pool>

Alternatively, keep SSL: import the certificate into GlassFish, change the master password, and give the JVM the keystore passwords by adding these lines to the jvm-options in domain.xml:

<jvm-options>-Djavax.net.ssl.keyStorePassword=[password]</jvm-options>
<jvm-options>-Djavax.net.ssl.trustStorePassword=[password]</jvm-options>

Master password required to start the domain

The Master Password is required to start the domain. No console, no prompting possible. You should either create the domain with --savemasterpassword=true or provide a password file with the --passwordfile option. Command start-domain failed.

This error appears when GlassFish runs in a container, for example with Docker Compose, where asadmin start-domain cannot prompt for the password. Use one of the two options the message names: save the master password with asadmin change-master-password --savemasterpassword=true (see Change the master password), or start the domain with --passwordfile pointing to a file that contains AS_ADMIN_MASTERPASSWORD (see Avoid password prompts with a password file).

References

Related notes

4 min read

Jakarta EE

Jakarta EE 10 and 11: component versions, deployment descriptor headers, Faces namespaces and a multi-module project layout.

  • Java & Jakarta EE
13 min read

Jakarta Faces (JSF)

Jakarta Faces (JSF) recipes: WebSocket push, validators with injection, resource handling, component binding, java.time and scopes.

  • Java & Jakarta EE
  • Web & Frontend
3 min read

JasperReports

JasperReports tips: localise reports with resource bundles, print page X of Y, control band splitting and page breaks, and float elements.

  • Java & Jakarta EE

Type to search the whole site.