Menu Close

Chapter 8. The bootable JAR

You can build and package a microservices application as a bootable JAR with the JBoss EAP JAR Maven plug-in. You can then run the application on a JBoss EAP bare-metal platform or a JBoss EAP OpenShift platform.

8.1. About the bootable JAR

You can build and package a microservices application as a bootable JAR with the JBoss EAP JAR Maven plug-in.

A bootable JAR contains a server, a packaged application, and the runtime required to launch the server.

The JBoss EAP JAR Maven plug-in uses Galleon trimming capability to reduce the size and memory footprint of the server. Thus, you can configure the server according to your requirements, including only the Galleon layers that provide the capabilities that you need.

The JBoss EAP JAR Maven plug-in supports the execution of JBoss EAP CLI script files to customize your server configuration. A CLI script includes a list of CLI commands for configuring the server.

A bootable JAR is like a standard JBoss EAP server in the following ways:

  • It supports JBoss EAP common management CLI commands.
  • It can be managed using the JBoss EAP management console.

The following limitations exist when packaging a server in a bootable JAR:

  • CLI management operations that require a server restart are not supported.
  • The server cannot be restarted in admin-only mode, which is a mode that starts services related to server administration.
  • If you shut down the server, updates that you applied to the server are lost.

Additionally, you can provision a hollow bootable JAR. This JAR contains only the server, so you can reuse the server to run a different application.

Additional resources

For information about capability trimming, see Capability Trimming.

8.2. JBoss EAP Maven plug-in

You can use the JBoss EAP JAR Maven plug-in to build an application as a bootable JAR.

You can retrieve the latest Maven plug-in version from the Maven repository, which is available at Index of /ga/org/wildfly/plugins/wildfly-jar-maven-plugin.

In a Maven project, the src directory contains all the source files required to build your application. After the JBoss EAP JAR Maven plug-in builds the bootable JAR, the generated JAR is located in target/<application>-bootable.jar.

The JBoss EAP JAR Maven plug-in also provides the following functionality:

  • Applies CLI script commands to the server.
  • Uses the org.jboss.eap:wildfly-galleon-pack Galleon feature pack and some of its layers for customizing the server configuration file.
  • Supports the addition of extra files into the packaged bootable JAR, such as a keystore file.
  • Includes the capability to create a hollow bootable JAR; that is, a bootable JAR that does not contain an application.

After you use the JBoss EAP JAR Maven plug-in to create the bootable JAR, you can start the application by issuing the following command. Replace target/myapp-bootable.jar with the path to your bootable JAR. For example:

$ java -jar target/myapp-bootable.jar
Note

To get a list of supported bootable JAR startup commands, append --help to the end of the startup command. For example, java -jar target/myapp-bootable.jar --help.

Additional resources

8.3. Bootable JAR arguments

View the arguments in the following table to learn about supported arguments for use with the bootable JAR.

Table 8.1. Supported bootable JAR executable arguments

ArgumentDescription

--help

Display the help message for the specified command and exit.

--deployment=<path>

Argument specific to the hollow bootable JAR. Specifies the path to the WAR, JAR, EAR file or exploded directory that contains the application you want to deploy on a server.

--display-galleon-config

Print the content of the generated Galleon configuration file.

--install-dir=<path>

By default, the JVM settings are used to create a TEMP directory after the bootable JAR is started. You can use the --install-dir argument to specify a directory to install the server.

-secmgr

Runs the server with a security manager installed.

-b<interface>=<value>

Set system property jboss.bind.address.<interface> to the given value. For example, bmanagement=IP_ADDRESS.

-b=<value>

Set system property jboss.bind.address, which is used in configuring the bind address for the public interface. This defaults to 127.0.0.1 if no value is specified.

-D<name>[=<value>]

Specifies system properties that are set by the server at server runtime. The bootable JAR JVM does not set these system properties.

--properties=<url>

Loads system properties from a specified URL.

-S<name>[=value]

Set a security property.

-u=<value>

Set system property jboss.default.multicast.address, which is used in configuring the multicast address in the socket-binding elements in the configuration files. This defaults to 230.0.0.4 if no value is specified.

--version

Display the application server version and exit.

8.4. Specifying Galleon layers for your bootable JAR server

You can specify Galleon layers to build a custom configuration for your server. Additionally, you can specify Galleon layers that you want excluded from the server.

To reference a single feature pack, use the <feature-pack-location> element to specify its location. The following example specifies org.jboss.eap:wildfly-galleon-pack:3.0.0.GA-redhat-00001 in the <feature-pack-location> element of the Maven plug-in configuration file.

<configuration>
  <feature-pack-location>org.jboss.eap:wildfly-galleon-pack:3.0.0.GA-redhat-00001</feature-pack-location>
</configuration>

If you need to reference more than one feature pack, list them in the <feature-packs> element. The following example shows the addition of the Red Hat Single Sign-On feature pack to the <feature-packs> element:

<configuration>
    <feature-packs>
         <feature-pack>
             <location>org.jboss.eap:wildfly-galleon-pack:3.0.0.GA-redhat-00001</location>
        </feature-pack>
        <feature-pack>
            <location>org.jboss.sso:keycloak-adapter-galleon-pack:9.0.10.redhat-00001</location>
        </feature-pack>
    </feature-packs>
</configuration>

You can combine Galleon layers from multiple feature packs to configure the bootable JAR server to include only the supported Galleon layers that provide the capabilities that you need.

Note

On a bare-metal platform, if you do not specify Galleon layers in your configuration file then the provisioned server contains a configuration identical to that of a default standalone-microprofile.xml configuration.

On an OpenShift platform, after you have added the <cloud/> configuration element in the plug-in configuration and you choose not to specify Galleon layers in your configuration file, the provisioned server contains a configuration that is adjusted for the cloud environment and is similar to a default standalone-microprofile-ha.xml.

Prerequisites

  • Maven is installed.
  • You have checked the latest Maven plug-in version, such as MAVEN_PLUGIN_VERSION.X.GA.Final-redhat-00001, where MAVEN_PLUGIN_VERSION is the major version and X is the microversion. See Index of /ga/org/wildfly/plugins/wildfly-jar-maven-plugin.
  • You have checked the latest Galleon feature pack version, such as 3.0.X.GA-redhat-BUILD_NUMBER, where X is the microversion of JBoss EAP XP and BUILD_NUMBER is the build number of the Galleon feature pack. Both X and BUILD_NUMBER can evolve during the JBoss EAP XP 3.0.0 product life cycle. See Index of /ga/org/jboss/eap/wildfly-galleon-pack.
Note

The examples shown in the procedure specify the following properties:

  • ${bootable.jar.maven.plugin.version} for the Maven plug-in version.
  • ${jboss.xp.galleon.feature.pack.version} for the Galleon feature pack version.

You must set these properties in your project. For example:

<properties>
    <bootable.jar.maven.plugin.version>4.0.3.Final-redhat-00001</bootable.jar.maven.plugin.version>
    <jboss.xp.galleon.feature.pack.version>3.0.0.GA-redhat-00001</jboss.xp.galleon.feature.pack.version>
</properties>

Procedure

  1. Identify the supported JBoss EAP Galleon layers that provide the capabilities that you need to run your application.
  2. Reference a JBoss EAP feature pack location in the <plugin> element of the Maven project pom.xml file. You must specify the latest version of any Maven plug-in and the latest version of the org.jboss.eap:wildfly-galleon-pack Galleon feature pack, as demonstrated in the following example. The following example also displays the inclusion of a single feature-pack, which includes the jaxrs-server base layer and the jpa-distributed layer . The jaxrs-server base layer provides additional support for the server.

    <plugins>
          <plugin>
                <groupId>org.wildfly.plugins</groupId>
                 <artifactId>wildfly-jar-maven-plugin</artifactId>
                 <version>${bootable.jar.maven.plugin.version}</version>
                <configuration>
                     <feature-pack-location>org.jboss.eap:wildfly-galleon-pack:${jboss.xp.galleon.feature.pack.version}</feature-pack-location>
                     <layers>
                         <layer>jaxrs-server</layer>
                         <layer>jpa-distributed</layer>
                     </layers>
                     <excluded-layers>
                         <layer>jpa</layer>
                     </excluded-layers>
                     ...
    </plugins>

    This example also shows the exclusion of the jpa layer from the project.

    Note

    If you include the jpa-distributed layer in your project, you must exclude the jpa layer from the jaxrs-server layer. The jpa layer configures a local infinispan hibernate cache, while the jpa-distributed layer configures a remote infinispan hibernate cache.

Additional resources

8.5. Using a bootable JAR on a JBoss EAP bare-metal platform

You can package an application as a bootable JAR on a JBoss EAP bare-metal platform.

A bootable JAR contains a server, a packaged application, and the runtime required to launch the server.

This procedure demonstrates packaging the MicroProfile Config microservices application as a bootable JAR with the JBoss EAP JAR Maven plug-in. See MicroProfile Config development.

You can use CLI scripts to configure the server during the packaging of the bootable JAR.

Important

On building a web application that must be packaged inside a bootable JAR, you must specify war in the <packaging> element of your pom.xml file. For example:

<packaging>war</packaging>

This value is required to package the build application as a WAR file and not as the default JAR file.

In a Maven project that is used solely to build a hollow bootable JAR, set the packaging value to pom. For example:

<packaging>pom</packaging>

You are not limited to using pom packaging when you build a hollow bootable JAR for a Maven project. You can create one by specifying true in the <hollow-jar> element for any type of packaging, such as war. See Creating a hollow bootable JAR on a JBoss EAP bare-metal platform.

Prerequisites

  • You have checked the latest Maven plug-in version, such as MAVEN_PLUGIN_VERSION.X.GA.Final-redhat-00001, where MAVEN_PLUGIN_VERSION is the major version and X is the microversion. See Index of /ga/org/wildfly/plugins/wildfly-jar-maven-plugin.
  • You have checked the latest Galleon feature pack version, such as 3.0.X.GA-redhat-BUILD_NUMBER, where X is the microversion of JBoss EAP XP and BUILD_NUMBER is the build number of the Galleon feature pack. Both X and BUILD_NUMBER can evolve during the JBoss EAP XP 3.0.0 product life cycle. See Index of /ga/org/jboss/eap/wildfly-galleon-pack.
  • You have created a Maven project, set up a parent dependency, and added dependencies for creating an MicroProfile application. See MicroProfile Config development.
Note

The examples shown in the procedure specify the following properties:

  • ${bootable.jar.maven.plugin.version} for the Maven plug-in version.
  • ${jboss.xp.galleon.feature.pack.version} for the Galleon feature pack version.

You must set these properties in your project. For example:

<properties>
    <bootable.jar.maven.plugin.version>4.0.3.Final-redhat-00001</bootable.jar.maven.plugin.version>
    <jboss.xp.galleon.feature.pack.version>3.0.0.GA-redhat-00001</jboss.xp.galleon.feature.pack.version>
</properties>

Procedure

  1. Add the following content to the <build> element of the pom.xml file. You must specify the latest version of any Maven plug-in and the latest version of the org.jboss.eap:wildfly-galleon-pack Galleon feature pack. For example:

    <plugins>
        <plugin>
            <groupId>org.wildfly.plugins</groupId>
            <artifactId>wildfly-jar-maven-plugin</artifactId>
            <version>${bootable.jar.maven.plugin.version}</version>
            <configuration>
                 <feature-pack-location>org.jboss.eap:wildfly-galleon-pack:${jboss.xp.galleon.feature.pack.version}</feature-pack-location>
                <layers>
                    <layer>jaxrs-server</layer>
                    <layer>microprofile-platform</layer>
                </layers>
             </configuration>
            <executions>
                <execution>
                    <goals>
                        <goal>package</goal>
                    </goals>
                </execution>
            </executions>
        </plugin>
    </plugins>
    Note

    If you do not specify Galleon layers in your pom.xml file then the bootable JAR server contains a configuration that is identical to a standalone-microprofile.xml configuration.

  2. Package the application as a bootable JAR:

    $ mvn package
  3. Start the application:

    $ NAME="foo" java -jar target/microprofile-config-bootable.jar
    Note

    The example uses NAME as the environment variable, but you can choose to use jim, which is the default value.

    Note

    To view a list of supported bootable JAR arguments, append --help to the end of the java -jar target/microprofile-config-bootable.jar command.

  4. Specify the following URL in your web browser to access the MicroProfile Config application:

    http://localhost:8080/config/json
  5. Verification: Test the application behaves properly by issuing the following command in your terminal:

    curl http://localhost:8080/config/json

    The following is the expected output:

    {"result":"Hello foo"}

Additional resources

8.6. Creating a hollow bootable JAR on a JBoss EAP bare-metal platform

You can package an application as a hollow bootable JAR on a JBoss EAP bare-metal platform.

A hollow bootable JAR contains only the JBoss EAP server. The hollow bootable JAR is packaged by the JBoss EAP JAR Maven plug-in. The application is provided at server runtime. The hollow bootable JAR is useful if you need to re-use the server configuration for a different application.

Prerequisites

Note

The example shown in the procedure specifies ${jboss.xp.galleon.feature.pack.version} for the Galleon feature pack version, but you must set the property in your project. For example:

<properties>
    <jboss.xp.galleon.feature.pack.version>3.0.0.GA-redhat-00001</jboss.xp.galleon.feature.pack.version>
</properties>

Procedure

  1. To build a hollow bootable JAR, you must set the <hollow-jar> plug-in configuration element to true in the project pom.xml file. For example:
<plugins>
        <plugin>
            ...
            <configuration>
                <!-- This example configuration does not show a complete plug-in configuration -->
                 ...
                <feature-pack-location>org.jboss.eap:wildfly-galleon-pack:${jboss.xp.galleon.feature.pack.version}</feature-pack-location>
                 <hollow-jar>true</hollow-jar>
            </configuration>
         </plugin>
</plugins>
Note

By specifying true in the <hollow-jar> element, the JBoss EAP JAR Maven plug-in does not include an application in the JAR.

  1. Build the hollow bootable JAR:

    $ mvn clean package
  2. Run the hollow bootable JAR:

    $ java -jar target/microprofile-config-bootable.jar --deployment=target/microprofile-config.war
    Important

    To specify the path to the WAR file that you want to deploy on the server, use the following argument, where <PATH_NAME> is the path to your deployment.

    --deployment=<PATH_NAME>
  3. Access the application:

    $ curl http://localhost:8080/microprofile-config/config/json
    Note

    To register your web application in the root directory, name the application ROOT.war.

Additional resources

8.7. CLI scripts

You can create CLI scripts to configure the server during the packaging of the bootable JAR.

A CLI script is a text file that contains a sequence of CLI commands that you can use to apply additional server configurations. For example, you can create a script to add a new logger to the logging subsystem.

You can also specify more complex operations in a CLI script. For example, you can group security management operations into a single command to enable HTTP authentication for the management HTTP endpoint.

Note

You must define CLI scripts in the <cli-session> element of the plug-in configuration before you package an application as a bootable JAR. This ensures the server configuration settings persist after packaging the bootable JAR.

Although you can combine predefined Galleon layers to configure a server that deploys your application, limitations do exist. For example, you cannot enable the HTTPS undertow listener using Galleon layers when packaging the bootable JAR. Instead, you must use a CLI script.

You must define the CLI scripts in the <cli-session> element of the pom.xml file. The following table shows types of CLI session attributes:

Table 8.2. CLI script attributes

ArgumentDescription

script-files

List of paths to script files.

properties-file

Optional attribute that specifies a path to a properties file. This file lists Java properties that scripts can reference by using the ${my.prop} syntax. The following example sets public inet-address to the value of all.addresses: /interface=public:write-attribute(name=inet-address,value=${all.addresses})

resolve-expressions

Optional attribute that contains a boolean value. Indicates if system properties or expressions are resolved before sending the operation requests to the server. Value is true by default.

Note
  • CLI scripts are started in the order that they are defined in the <cli-session> element of the pom.xml file.
  • The JBoss EAP JAR Maven plug-in starts the embedded server for each CLI session. Thus, your CLI script does not have to start or stop the embedded server.

8.8. Using a bootable JAR on a JBoss EAP OpenShift platform

After you packaged an application as a bootable JAR, you can run the application on a JBoss EAP OpenShift platform.

Important

On OpenShift, you cannot use the EAP Operator automated transaction recovery feature with your bootable JAR. A fix for this technical limitation is planned for a future JBoss EAP XP 3.0.0 patch release.

Prerequisites

Note

The examples shown in the procedure specify the following properties:

  • ${bootable.jar.maven.plugin.version} for the Maven plug-in version.
  • ${jboss.xp.galleon.feature.pack.version} for the Galleon feature pack version.

You must set these properties in your project. For example:

<properties>
    <bootable.jar.maven.plugin.version>4.0.3.Final-redhat-00001</bootable.jar.maven.plugin.version>
    <jboss.xp.galleon.feature.pack.version>3.0.0.GA-redhat-00001</jboss.xp.galleon.feature.pack.version>
</properties>

Procedure

  1. Add the following content to the <build> element of the pom.xml file. You must specify the latest version of any Maven plug-in and the latest version of the org.jboss.eap:wildfly-galleon-pack Galleon feature pack. For example:

    <plugins>
        <plugin>
            <groupId>org.wildfly.plugins</groupId>
            <artifactId>wildfly-jar-maven-plugin</artifactId>
            <version>${bootable.jar.maven.plugin.version}</version>
            <configuration>
                <feature-pack-location>org.jboss.eap:wildfly-galleon-pack:${jboss.xp.galleon.feature.pack.version}</feature-pack-location>
                <layers>
                    <layer>jaxrs-server</layer>
                    <layer>microprofile-platform</layer>
                </layers>
                <cloud/>
                </configuration>
                <executions>
                    <execution>
                        <goals>
                            <goal>package</goal>
                        </goals>
                    </execution>
                </executions>
        </plugin>
    </plugins>
    Note

    You must include the <cloud/> element in the <configuration> element of the plug-in configuration, so the JBoss EAP Maven JAR plug-in can identify that you choose the OpenShift platform.

  2. Package the application:

    $ mvn package
  3. Log in to your OpenShift instance using the oc login command.
  4. Create a new project in OpenShift. For example:

    $ oc new-project bootable-jar-project
  5. Enter the following oc commands to create an application image:

    $ mkdir target/openshift && cp target/microprofile-config-bootable.jar target/openshift  1
    
    $ oc import-image ubi8/openjdk-11 --from=registry.redhat.io/ubi8/openjdk-11 --confirm 2
    
    $ oc new-build --strategy source --binary --image-stream openjdk-11 --name microprofile-config-app 3
    
    $ oc start-build microprofile-config-app --from-dir target/openshift 4
    1
    Creates an openshift sub-directory in the target directory. The packaged application is copied into the created sub-directory.
    2
    Imports the latest OpenJDK 11 imagestream tag and image information into the OpenShift project.
    3
    Creates a build configuration based on the microprofile-config-app directory and the OpenJDK 11 imagestream.
    4
    Uses the target/openshift sub-directory as the binary input to build the application.
    Note

    OpenShift applies a set of CLI script commands to the bootable JAR configuration file to adjust it to the cloud environment. You can access this script by opening the bootable-jar-build-artifacts/generated-cli-script.txt file in the Maven project /target directory.

  6. Verification:

    View a list of OpenShift pods available and check the pods build statuses by issuing the following command:

    $ oc get pods

    Verify the built application image:

    $ oc get is microprofile-config-app

    The output shows the built application image details, such as name and image repository, tag, and so on. For the example in this procedure, the imagestream name and tag output displays microprofile-config-app:latest.

  7. Deploy the application:

    $ oc new-app microprofile-config-app
    
    $ oc expose svc/microprofile-config-app
    Important

    To provide system properties to the bootable JAR, you must use the JAVA_OPTS_APPEND environment variable. The following example demonstrates usage of the JAVA_OPTS_APPEND environment variable:

    $ oc new-app <_IMAGESTREAM_> -e JAVA_OPTS_APPEND="-Xlog:gc*:file=/tmp/gc.log:time -Dwildfly.statistics-enabled=true"

    A new application is created and started. The application configuration is exposed as a new service.

  8. Verification: Test the application behaves properly by issuing the following command in your terminal:

    $ curl http://$(oc get route microprofile-config-app --template='{{ .spec.host }}')/config/json

    Expected output:

    {"result":"Hello jim"}

Additional resources

8.9. Configure the bootable JAR for OpenShift

Before using your bootable JAR, you can configure JVM settings to ensure that your standalone server operates correctly on JBoss EAP for OpenShift.

Use the JAVA_OPTS_APPEND environment variable to configure JVM settings. Use the JAVA_ARGS command to provide arguments to the bootable JAR.

You can use environment variables to set values for properties. For example, you can use the JAVA_OPTS_APPEND environment variable to set the -Dwildfly.statistics-enabled property to true:

JAVA_OPTS_APPEND="-Xlog:gc*:file=/tmp/gc.log:time -Dwildfly.statistics-enabled=true"

Statistics are now enabled for your server.

Note

Use the JAVA_ARGS environment variable, if you need to provide arguments to the bootable JAR.

JBoss EAP for OpenShift provides a JDK 11 image. To run the application associated with your bootable JAR, you must first import the latest OpenJDK 11 imagestream tag and image information into your OpenShift project. You can then use environment variables to configure the JVM in the imported image.

You can apply the same configuration options for configuring the JVM used for JBoss EAP for OpenShift S2I image, but with the following differences:

  • Optional: The -Xlog capability is not available, but you can set garbage collection logging by enabling -Xlog:gc. For example: JAVA_OPTS_APPEND="-Xlog:gc*:file=/tmp/gc.log:time".
  • To increase initial metaspace size, you can set the GC_METASPACE_SIZE environment variable. For best metadata capacity performance, set the value to 96.
  • The default value for GC_MAX_METASPACE_SIZE is set as 100, but for best metadata capacity after a garbage collection, you must set it to at least 256.
  • For better random file generation, use the JAVA_OPTS_APPEND environment variable to set java.security.egd property as -Djava.security.egd=file:/dev/urandom.

These configurations improve the memory settings and garbage collection capability of JVM when running on your imported OpenJDK 11 image.

8.10. Using a ConfigMap in your application on OpenShift

For OpenShift, you can use a deployment controller (dc) to mount the configmap into the pods used to run the application.

A ConfigMap is an OpenShift resource that is used to store non-confidential data in key-value pairs.

After you specify the microprofile-platform Galleon layer to add microprofile-config-smallrye subsystem and any extensions to the server configuration file, you can use a CLI script to add a new ConfigSource to the server configuration. You can save CLI scripts in an accessible directory, such as the /scripts directory, in the root directory of your Maven project.

MicroProfile Config functionality is implemented in JBoss EAP using the SmallRye Config component and is provided by the microprofile-config-smallrye subsystem. This subsystem is included in the microprofile-platform Galleon layer.

Prerequisites

  • You have installed Maven.
  • You have configured the JBoss EAP Maven repository.
  • You have packaged an application as a bootable JAR and you can run the application on a JBoss EAP OpenShift platform. For information about building an application as a bootable JAR on an OpenShift platform, see Using a bootable JAR on a JBoss EAP OpenShift platform.

Procedure

  1. Create a directory named scripts at the root directory of your project. For example:

    $ mkdir scripts
  2. Create a cli.properties file and save the file in the /scripts directory. Define the config.path and the config.ordinal system properties in this file. For example:

    config.path=/etc/config
    config.ordinal=200
  3. Create a CLI script, such as mp-config.cli, and save it in an accessible directory in the bootable JAR, such as the /scripts directory. The following example shows the contents of the mp-config.cli script:

    # config map
    
    /subsystem=microprofile-config-smallrye/config-source=os-map:add(dir={path=${config.path}}, ordinal=${config.ordinal})

    The mp-config.cli CLI script creates a new ConfigSource, to which ordinal and path values are retrieved from a properties file.

  4. Save the script in the /scripts directory, which is located at the root directory of the project.
  5. Add the following configuration extract to the existing plug-in <configuration> element:

    <cli-sessions>
        <cli-session>
            <properties-file>
                scripts/cli.properties
            </properties-file>
            <script-files>
                <script>scripts/mp-config.cli</script>
            </script-files>
        </cli-session>
    </cli-sessions>
  6. Package the application:

    $ mvn package
  7. Log in to your OpenShift instance using the oc login command.
  8. Optional: If you have not previously created a target/openshift subdirectory, you must create the suddirectory by issuing the following command:

    $ mkdir target/openshift
  9. Copy the packaged application into the created subdirectory.

    $ cp target/microprofile-config-bootable.jar target/openshift
  10. Use the target/openshift subdirectory as the binary input to build the application:

    $ oc start-build microprofile-config-app --from-dir target/openshift
    Note

    OpenShift applies a set of CLI script commands to the bootable JAR configuration file to enable it for the cloud environment. You can access this script by opening the bootable-jar-build-artifacts/generated-cli-script.txt file in the Maven project /target directory.

  11. Create a ConfigMap. For example:

    $ oc create configmap microprofile-config-map --from-literal=name="Name comes from Openshift ConfigMap"
  12. Mount the ConfigMap into the application with the dc. For example:

    $ oc set volume deployments/microprofile-config-app --add --name=config-volume \
    --mount-path=/etc/config \
    --type=configmap \
    --configmap-name=microprofile-config-map

    After executing the oc set volume command, the application is re-deployed with the new configuration settings.

  13. Test the output:

    $ curl http://$(oc get route microprofile-config-app --template='{{ .spec.host }}')/config/json

    The following is the expected output:

    {"result":"Hello Name comes from Openshift ConfigMap"}

Additional resources

8.11. Creating a bootable JAR Maven project

Follow the steps in the procedure to create an example Maven project. You must create a Maven project before you can perform the following procedures:

  • Enabling JSON logging for your bootable JAR
  • Enabling web session data storage for multiple bootable JAR instances
  • Enabling HTTP authentication for bootable JAR with a CLI script
  • Securing your JBoss EAP bootable JAR application with Red Hat Single Sign-On

In the project pom.xml file, you can configure Maven to retrieve the project artifacts required to build your bootable JAR.

Procedure

  1. Set up the Maven project:

    $ mvn archetype:generate \
    -DgroupId=GROUP_ID \
    -DartifactId=ARTIFACT_ID \
    -DarchetypeGroupId=org.apache.maven.archetypes \
    -DarchetypeArtifactId=maven-archetype-webapp \
    -DinteractiveMode=false

    Where GROUP_ID is the groupId of your project and ARTIFACT_ID is the artifactId of your project.

  2. In the pom.xml file, configure Maven to retrieve the JBoss EAP BOM file from a remote repository.

    <repositories>
        <repository>
            <id>jboss</id>
            <url>https://maven.repository.redhat.com/ga</url>
            <snapshots>
                <enabled>false</enabled>
            </snapshots>
        </repository>
    </repositories>
    <pluginRepositories>
      <pluginRepository>
          <id>jboss</id>
            <url>https://maven.repository.redhat.com/ga</url>
            <snapshots>
                <enabled>false</enabled>
            </snapshots>
      </pluginRepository>
    </pluginRepositories>
  3. To configure Maven to automatically manage versions for the Jakarta EE artifacts in the jboss-eap-jakartaee8 BOM, add the BOM to the <dependencyManagement> section of the project pom.xml file. For example:

    <dependencyManagement>
      <dependencies>
        <dependency>
            <groupId>org.jboss.bom</groupId>
            <artifactId>jboss-eap-jakartaee8</artifactId>
            <version>7.3.4.GA</version>
            <type>pom</type>
            <scope>import</scope>
        </dependency>
      </dependencies>
    </dependencyManagement>
  4. Add the servlet API artifact, which is managed by the BOM, to the <dependency> section of the project pom.xml file, as shown in the following example:

    <dependency>
        <groupId>org.jboss.spec.javax.servlet</groupId>
        <artifactId>jboss-servlet-api_4.0_spec</artifactId>
        <scope>provided</scope>
    </dependency>

Additional resources

8.12. Enabling JSON logging for your bootable JAR

You can enable JSON logging for your bootable JAR by configuring the server logging configuration with a CLI script. When you enable JSON logging, you can use the JSON formatter to view log messages in JSON format.

The example in this procedure shows you how to enable JSON logging for your bootable JAR on a bare-metal platform and an OpenShift platform.

Prerequisites

  • You have checked the latest Maven plug-in version, such as MAVEN_PLUGIN_VERSION.X.GA.Final-redhat-00001, where MAVEN_PLUGIN_VERSION is the major version and X is the microversion. See Index of /ga/org/wildfly/plugins/wildfly-jar-maven-plugin.
  • You have checked the latest Galleon feature pack version, such as 3.0.X.GA-redhat-BUILD_NUMBER, where X is the minor version of JBoss EAP XP and BUILD_NUMBER is the build number of the Galleon feature pack. Both X and BUILD_NUMBER can evolve during the JBoss EAP XP 3.0.0 product life cycle. See Index of /ga/org/jboss/eap/wildfly-galleon-pack.
  • You have created a Maven project, set up a parent dependency, and added dependencies for creating an application. See Creating a bootable JAR Maven project.

    Important

    In the Maven archetype of your Maven project, you must specify the groupID and artifactID that are specific to your project. For example:

    $ mvn archetype:generate \
    -DgroupId=com.example.logging \
    -DartifactId=logging \
    -DarchetypeGroupId=org.apache.maven.archetypes \
    -DarchetypeArtifactId=maven-archetype-webapp \
    -DinteractiveMode=false
    cd logging
    Note

    The examples shown in the procedure specify the following properties:

    • ${bootable.jar.maven.plugin.version} for the Maven plug-in version.
    • ${jboss.xp.galleon.feature.pack.version} for the Galleon feature pack version.

    You must set these properties in your project. For example:

    <properties>
        <bootable.jar.maven.plugin.version>4.0.3.Final-redhat-00001</bootable.jar.maven.plugin.version>
        <jboss.xp.galleon.feature.pack.version>3.0.0.GA-redhat-00001</jboss.xp.galleon.feature.pack.version>
    </properties>

Procedure

  1. Add the JBoss Logging and Jakarta RESTful Web Services dependencies, which are managed by the BOM, to the <dependencies> section of the project pom.xml file. For example:

    <dependencies>
        <dependency>
            <groupId>org.jboss.logging</groupId>
            <artifactId>jboss-logging</artifactId>
            <scope>provided</scope>
        </dependency>
        <dependency>
            <groupId>org.jboss.spec.javax.ws.rs</groupId>
            <artifactId>jboss-jaxrs-api_2.1_spec</artifactId>
            <scope>provided</scope>
        </dependency>
    </dependencies>
  2. Add the following content to the <build> element of the pom.xml file. You must specify the latest version of any Maven plug-in and the latest version of the org.jboss.eap:wildfly-galleon-pack Galleon feature pack. For example:

    <plugins>
        <plugin>
            <groupId>org.wildfly.plugins</groupId>
            <artifactId>wildfly-jar-maven-plugin</artifactId>
            <version>${bootable.jar.maven.plugin.version}</version>
            <configuration>
                <feature-packs>
                    <feature-pack>
                        <location>org.jboss.eap:wildfly-galleon-pack:${jboss.xp.galleon.feature.pack.version}</location>
                    </feature-pack>
                </feature-packs>
                <layers>
                    <layer>jaxrs-server</layer>
                 </layers>
            </configuration>
            <executions>
                <execution>
                    <goals>
                        <goal>package</goal>
                    </goals>
                </execution>
            </executions>
        </plugin>
    </plugins>
  3. Create the directory to store Java files:

    $ mkdir -p APPLICATION_ROOT/src/main/java/com/example/logging/

    Where APPLICATION_ROOT is the directory containing the pom.xml configuration file for the application.

  4. Create a Java file RestApplication.java with the following content and save the file in the APPLICATION_ROOT/src/main/java/com/example/logging/ directory:

    package com.example.logging;
    import javax.ws.rs.ApplicationPath;
    import javax.ws.rs.core.Application;
    
    @ApplicationPath("/")
    public class RestApplication extends Application {
    }
  5. Create a Java file HelloWorldEndpoint.java with the following content and save the file in the APPLICATION_ROOT/src/main/java/com/example/logging/ directory:

    package com.example.logging;
    
    import javax.ws.rs.Path;
    import javax.ws.rs.core.Response;
    import javax.ws.rs.GET;
    import javax.ws.rs.Produces;
    
    import org.jboss.logging.Logger;
    @Path("/hello")
    public class HelloWorldEndpoint {
    
        private static Logger log = Logger.getLogger(HelloWorldEndpoint.class.getName());
        @GET
        @Produces("text/plain")
        public Response doGet() {
            log.debug("HelloWorldEndpoint.doGet called");
            return Response.ok("Hello from XP bootable jar!").build();
        }
    }
  6. Create a CLI script, such as logging.cli, and save it in an accessible directory in the bootable JAR, such as the APPLICATION_ROOT/scripts directory, where APPLICATION_ROOT is the root directory of your Maven project. The script must contain the following commands:

    /subsystem=logging/logger=com.example.logging:add(level=ALL)
    /subsystem=logging/json-formatter=json-formatter:add(exception-output-type=formatted, pretty-print=false, meta-data={version="1"}, key-overrides={timestamp="@timestamp"})
    /subsystem=logging/console-handler=CONSOLE:write-attribute(name=level,value=ALL)
    /subsystem=logging/console-handler=CONSOLE:write-attribute(name=named-formatter, value=json-formatter)
  7. Add the following configuration extract to the plug-in <configuration> element:

    <cli-sessions>
            <cli-session>
            <script-files>
                <script>scripts/logging.cli</script>
            </script-files>
        </cli-session>
    </cli-sessions>

    This example shows the logging.cli CLI script, which modifies the server logging configuration file to enable JSON logging for your application.

  8. Package the application as a bootable JAR.

    $ mvn package
  9. Optional: To run the application on a JBoss EAP bare-metal platform, follow the steps outlined in Using a bootable JAR on a JBoss EAP bare-metal platform, but with the following difference:

    1. Start the application:

      mvn wildfly-jar:run
    2. Verification: You can access the application by specifying the following URL in your browser: http://127.0.0.1:8080/hello.

      Expected output: You can view the JSON-formatted logs, including the com.example.logging.HelloWorldEndpoint debug trace, in the application console.

  10. Optional: To run the application on a JBoss EAP OpenShift platform, complete the following steps:

    1. Add the <cloud/> element to the plug-in configuration. For example:

      <plugins>
         <plugin>
             ... <!-- You must evolve the existing configuration with the <cloud/> element  -->
             <configuration >
                 ...
                 <cloud/>
              </configuration>
          </plugin>
      </plugins>
    2. Rebuild the application:

      $ mvn clean package
    3. Log in to your OpenShift instance using the oc login command.
    4. Create a new project in OpenShift. For example:

      $ oc new-project bootable-jar-project
    5. Enter the following oc commands to create an application image:

      $ mkdir target/openshift && cp target/logging-bootable.jar target/openshift 1
      
      $ oc import-image ubi8/openjdk-11 --from=registry.redhat.io/ubi8/openjdk-11 --confirm
       2
      
      $ oc new-build --strategy source --binary --image-stream openjdk-11 --name logging 3
      
      $ oc start-build logging --from-dir target/openshift 4
      1
      Creates the target/openshift subdirectory. The packaged application is copied into the openshift subdirectory.
      2
      Imports the latest OpenJDK 11 imagestream tag and image information into the OpenShift project.
      3
      Creates a build configuration based on the logging directory and the OpenJDK 11 imagestream.
      4
      Uses the target/openshift subdirectory as the binary input to build the application.
    6. Deploy the application:

      $ oc new-app logging
      
      $ oc expose svc/logging
    7. Get the URL of the route.

      $ oc get route logging --template='{{ .spec.host }}'
    8. Access the application in your web browser using the URL returned from the previous command. For example:

      http://ROUTE_NAME/hello
    9. Verification: Issue the following command to view a list of OpenShift pods available, and to check the pods build statuses:

      $ oc get pods

      Access a running pod log of your application. Where APP_POD_NAME is the name of the running pod logging application.

      $ oc logs APP_POD_NAME

      Expected outcome: The pod log is in JSON format and includes the com.example.logging.HelloWorldEndpoint debug trace.

Additional resources

8.13. Enabling web session data storage for multiple bootable JAR instances

You can build and package a web-clustering application as a bootable JAR.

Prerequisites

  • You have checked the latest Maven plug-in version, such as MAVEN_PLUGIN_VERSION.X.GA.Final-redhat-00001, where MAVEN_PLUGIN_VERSION is the major version and X is the microversion. See Index of /ga/org/wildfly/plugins/wildfly-jar-maven-plugin.
  • You have checked the latest Galleon feature pack version, such as 3.0.X.GA-redhat-BUILD_NUMBER, where X is the microversion of JBoss EAP XP and BUILD_NUMBER is the build number of the Galleon feature pack. Both X and BUILD_NUMBER can evolve during the JBoss EAP XP 3.0.0 product life cycle. See Index of /ga/org/jboss/eap/wildfly-galleon-pack.
  • You have created a Maven project, set up a parent dependency, and added dependencies for creating a web-clustering application. See Creating a bootable JAR Maven project.

    Important

    When setting up the Maven project, you must specify values in the Maven archetype configuration. For example:

    $ mvn archetype:generate \
    -DgroupId=com.example.webclustering \
    -DartifactId=web-clustering \
    -DarchetypeGroupId=org.apache.maven.archetypes \
    -DarchetypeArtifactId=maven-archetype-webapp \
    -DinteractiveMode=false
    cd web-clustering
    Note

    The examples shown in the procedure specify the following properties:

    • ${bootable.jar.maven.plugin.version} for the Maven plug-in version.
    • ${jboss.xp.galleon.feature.pack.version} for the Galleon feature pack version.

    You must set these properties in your project. For example:

    <properties>
        <bootable.jar.maven.plugin.version>4.0.3.Final-redhat-00001</bootable.jar.maven.plugin.version>
        <jboss.xp.galleon.feature.pack.version>3.0.0.GA-redhat-00001</jboss.xp.galleon.feature.pack.version>
    </properties>

Procedure

  1. Add the following content to the <build> element of the pom.xml file. You must specify the latest version of any Maven plug-in and the latest version of the org.jboss.eap:wildfly-galleon-pack Galleon feature pack. For example:

    <plugins>
        <plugin>
            <groupId>org.wildfly.plugins</groupId>
            <artifactId>wildfly-jar-maven-plugin</artifactId>
            <version>${bootable.jar.maven.plugin.version}</version>
            <configuration>
                <feature-pack-location>org.jboss.eap:wildfly-galleon-pack:${jboss.xp.galleon.feature.pack.version}</feature-pack-location>
                <layers>
                    <layer>datasources-web-server</layer>
                    <layer>web-clustering</layer>
                </layers>
            </configuration>
            <executions>
                <execution>
                    <goals>
                        <goal>package</goal>
                    </goals>
                </execution>
            </executions>
        </plugin>
    </plugins>
    Note

    This example makes use of the web-clustering Galleon layer to enable web session sharing.

  2. Update the web.xml file in the src/main/webapp/WEB-INF directory with the following configuration:

    <?xml version="1.0" encoding="UTF-8"?>
    
    <web-app version="4.0"
             xmlns="http://xmlns.jcp.org/xml/ns/javaee"
             xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
             xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee  http://xmlns.jcp.org/xml/ns/javaee/web-app_4_0.xsd">
        <distributable/>
    </web-app>

    The <distributable/> tag indicates that this servlet can be distributed across multiple servers.

  3. Create the directory to store Java files:

    $ mkdir -p APPLICATION_ROOT
    /src/main/java/com/example/webclustering/

    Where APPLICATION_ROOT is the directory containing the pom.xml configuration file for the application.

  4. Create a Java file MyServlet.java with the following content and save the file in the APPLICATION_ROOT/src/main/java/com/example/webclustering/ directory.

    package com.example.webclustering;
    
    import java.io.IOException;
    import java.io.PrintWriter;
    import javax.servlet.ServletException;
    import javax.servlet.annotation.WebServlet;
    import javax.servlet.http.HttpServlet;
    import javax.servlet.http.HttpServletRequest;
    import javax.servlet.http.HttpServletResponse;
    
    @WebServlet(urlPatterns = {"/clustering"})
    public class MyServlet extends HttpServlet {
        @Override
        protected void doGet(HttpServletRequest request, HttpServletResponse response)
                throws IOException {
            response.setContentType("text/html;charset=UTF-8");
            long t;
            User user = (User) request.getSession().getAttribute("user");
            if (user == null) {
                t = System.currentTimeMillis();
                user = new User(t);
                request.getSession().setAttribute("user", user);
            }
            try (PrintWriter out = response.getWriter()) {
                out.println("<!DOCTYPE html>");
                out.println("<html>");
                out.println("<head>");
                out.println("<title>Web clustering demo</title>");
                out.println("</head>");
                out.println("<body>");
                out.println("<h1>Session id " + request.getSession().getId() + "</h1>");
                out.println("<h1>User Created " + user.getCreated() + "</h1>");
                out.println("<h1>Host Name " + System.getenv("HOSTNAME") + "</h1>");
                out.println("</body>");
                out.println("</html>");
            }
        }
    }

    The content in MyServlet.java defines the endpoint to which a client sends an HTTP request.

  5. Create a Java file User.java with the following content and save the file in the APPLICATION_ROOT/src/main/java/com/example/webclustering/ directory.

    package com.example.webclustering;
    
    import java.io.Serializable;
    
    public class User implements Serializable {
        private final long created;
    
        User(long created) {
            this.created = created;
        }
        public long getCreated() {
            return created;
        }
    }
  6. Package the application:

    $ mvn package
  7. Optional: To run the application on a JBoss EAP bare-metal platform, follow the steps outlined in Using a bootable JAR on a JBoss EAP bare-metal platform, but with the following difference:

    1. On a JBoss EAP bare-metal platform, you can use the java -jar command to run multiple bootable JAR instances, as demonstrated in the following examples:

      $ java -jar target/web-clustering-bootable.jar -Djboss.node.name=node1
      
      $ java -jar target/web-clustering-bootable.jar -Djboss.node.name=node2 -Djboss.socket.binding.port-offset=10
    2. Verification: You can access the application on the node 1 instance: http://127.0.0.1:8080/clustering. Note the user session ID and the user-creation time.

      After you kill this instance, you can access the node 2 instance: http://127.0.0.1:8090/clustering. The user must match the session ID and the user-creation time of the node 1 instance.

  8. Optional: To run the application on a JBoss EAP OpenShift platform, follow the steps outlined in Using a bootable JAR on a JBoss EAP OpenShift platform, but complete the following steps:

    1. Add the <cloud/> element to the plug-in configuration. For example:

      <plugins>
         <plugin>
             ... <!-- You must evolve the existing configuration with the <cloud/> element  -->
             <configuration >
                 ...
                 <cloud/>
              </configuration>
          </plugin>
      </plugins>
    2. Rebuild the application:

      $ mvn clean package
    3. Log in to your OpenShift instance using the oc login command.
    4. Create a new project in OpenShift. For example:

      $ oc new-project bootable-jar-project
    5. To run a web-clustering application on a JBoss EAP OpenShift platform, authorization access must be granted for the service account that the pod is running in. The service account can then access the Kubernetes REST API. The following example shows authorization access being granted to a service account:

      $ oc policy add-role-to-user view system:serviceaccount:$(oc project -q):default
    6. Enter the following oc commands to create an application image:

      $ mkdir target/openshift && cp target/web-clustering-bootable.jar target/openshift 1
      
      $ oc import-image ubi8/openjdk-11 --from=registry.redhat.io/ubi8/openjdk-11 --confirm 2
      
      $ oc new-build --strategy source --binary --image-stream openjdk-11 --name web-clustering 3
      
      $ oc start-build web-clustering --from-dir target/openshift 4
      1
      Creates the target/openshift sub-directory. The packaged application is copied into the openshift sub-directory.
      2
      Imports the latest OpenJDK 11 imagestream tag and image information into the OpenShift project.
      3
      Creates a build configuration based on the web-clustering directory and the OpenJDK 11 imagestream.
      4
      Uses the target/openshift sub-directory as the binary input to build the application.
    7. Deploy the application:

      $ oc new-app web-clustering -e KUBERNETES_NAMESPACE=$(oc project -q)
      
      $ oc expose svc/web-clustering
      Important

      You must use the KUBERNETES_NAMESPACE environment variable to view other pods in the current OpenShift namespace; otherwise, the server attempts to retrieve the pods from the default namespace.

    8. Get the URL of the route.

      $ oc get route web-clustering --template='{{ .spec.host }}'
    9. Access the application in your web browser using the URL returned from the previous command. For example:

      http://ROUTE_NAME/clustering

      Note the user session ID and user creation time.

    10. Scale the application to two pods:

      $ oc scale --replicas=2 deployments web-clustering
    11. Issue the following command to view a list of OpenShift pods available, and to check the pods build statuses:

      $ oc get pods
    12. Kill the oldest pod using the oc delete pod web-clustering-POD_NAME command, where POD_NAME is the name of your oldest pod.
    13. Access the application again:

      http://ROUTE_NAME/clustering

      Expected outcome: The session ID and the creation time generated by the new pod match those of the of the terminated pod. This indicates that web session data storage is enabled.

Additional resources

8.14. Enabling HTTP authentication for bootable JAR with a CLI script

You can enable HTTP authentication for the bootable JAR with a CLI script. This script adds a security realm and a security domain to your server.

Prerequisites

  • You have checked the latest Maven plug-in version, such as MAVEN_PLUGIN_VERSION.X.GA.Final-redhat-00001, where MAVEN_PLUGIN_VERSION is the major version and X is the microversion. See Index of /ga/org/wildfly/plugins/wildfly-jar-maven-plugin.
  • You have checked the latest Galleon feature pack version, such as 3.0.X.GA-redhat-BUILD_NUMBER, where X is the microversion of JBoss EAP XP and BUILD_NUMBER is the build number of the Galleon feature pack. Both X and BUILD_NUMBER can evolve during the JBoss EAP XP 3.0.0 product life cycle. See Index of /ga/org/jboss/eap/wildfly-galleon-pack.
  • You have created a Maven project, set up a parent dependency, and added dependencies for creating an application that requires HTTP authentication. See Creating a bootable JAR Maven project.

    Important

    When setting up the Maven project, you must specify HTTP authentication values in the Maven archetype configuration. For example:

    $ mvn archetype:generate \
    -DgroupId=com.example.auth \
    -DartifactId=authentication \
    -DarchetypeGroupId=org.apache.maven.archetypes \
    -DarchetypeArtifactId=maven-archetype-webapp \
    -DinteractiveMode=false
    cd authentication
    Note

    The examples shown in the procedure specify the following properties:

    • ${bootable.jar.maven.plugin.version} for the Maven plug-in version.
    • ${jboss.xp.galleon.feature.pack.version} for the Galleon feature pack version.

    You must set these properties in your project. For example:

    <properties>
        <bootable.jar.maven.plugin.version>4.0.3.Final-redhat-00001</bootable.jar.maven.plugin.version>
        <jboss.xp.galleon.feature.pack.version>3.0.0.GA-redhat-00001</jboss.xp.galleon.feature.pack.version>
    </properties>

Procedure

  1. Add the following content to the <build> element of the pom.xml file. You must specify the latest version of any Maven plug-in and the latest version of the org.jboss.eap:wildfly-galleon-pack Galleon feature pack. For example:

    <plugins>
        <plugin>
             <groupId>org.wildfly.plugins</groupId>
             <artifactId>wildfly-jar-maven-plugin</artifactId>
             <version>${bootable.jar.maven.plugin.version}</version>
             <configuration>
                 <feature-pack-location>org.jboss.eap:wildfly-galleon-pack:${jboss.xp.galleon.feature.pack.version}</feature-pack-location>
                 <layers>
                       <layer>datasources-web-server</layer>
                 </layers>
            </configuration>
            <executions>
                <execution>
                    <goals>
                        <goal>package</goal>
                     </goals>
                </execution>
            </executions>
        </plugin>
    </plugins>

    The example shows the inclusion of the datasources-web-server Galleon layer that contains the elytron subsystem.

  2. Update the web.xml file in the src/main/webapp/WEB-INF directory. For example:

    <?xml version="1.0" encoding="UTF-8"?>
    
    <web-app version="4.0"
             xmlns="http://xmlns.jcp.org/xml/ns/javaee"
             xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
             xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee  http://xmlns.jcp.org/xml/ns/javaee/web-app_4_0.xsd">
    
        <login-config>
            <auth-method>BASIC</auth-method>
            <realm-name>Example Realm</realm-name>
        </login-config>
    
    </web-app>
  3. Create the directory to store Java files:

    $ mkdir -p APPLICATION_ROOT/src/main/java/com/example/authentication/

    Where APPLICATION_ROOT is the root directory of your Maven project.

  4. Create a Java file TestServlet.java with the following content and save the file in the APPLICATION_ROOT/src/main/java/com/example/authentication/ directory.

    package com.example.authentication;
    
    import javax.servlet.annotation.HttpMethodConstraint;
    import javax.servlet.annotation.ServletSecurity;
    import javax.servlet.annotation.WebServlet;
    import javax.servlet.http.HttpServlet;
    import javax.servlet.http.HttpServletRequest;
    import javax.servlet.http.HttpServletResponse;
    
    import java.io.IOException;
    import java.io.PrintWriter;
    
    @WebServlet(urlPatterns = "/hello")
    @ServletSecurity(httpMethodConstraints = { @HttpMethodConstraint(value = "GET", rolesAllowed = { "Users" }) })
    public class TestServlet extends HttpServlet {
    
        @Override
        protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws IOException {
            PrintWriter writer = resp.getWriter();
            writer.println("Hello " + req.getUserPrincipal().getName());
            writer.close();
        }
    
    }
  5. Create a CLI script, such as authentication.cli, and save it in an accessible directory in the bootable JAR, such as the APPLICATION_ROOT/scripts directory. The script must contain the following commands:

    /subsystem=elytron/properties-realm=bootable-realm:add(users-properties={relative-to=jboss.server.config.dir, path=bootable-users.properties, plain-text=true}, groups-properties={relative-to=jboss.server.config.dir, path=bootable-groups.properties})
    /subsystem=elytron/security-domain=BootableDomain:add(default-realm=bootable-realm, permission-mapper=default-permission-mapper, realms=[{realm=bootable-realm, role-decoder=groups-to-roles}])
    
    /subsystem=undertow/application-security-domain=other:write-attribute(name=security-domain, value=BootableDomain)
  6. Add the following configuration extract to the plug-in <configuration> element:

    <cli-sessions>
        <cli-session>
            <script-files>
                <script>scripts/authentication.cli</script>
            </script-files>
        </cli-session>
    </cli-sessions>

    This example shows the authentication.cli CLI script, which configures the default undertow security domain to the security domain defined for your server.

  7. In the root directory of your Maven project create a directory to store the properties files that the JBoss EAP JAR Maven plug-in adds to the bootable JAR:

    $ mkdir -p APPLICATION_ROOT/extra-content/standalone/configuration/

    Where APPLICATION_ROOT is the directory containing the pom.xml configuration file for the application.

    This directory stores files such as bootable-users.properties and bootable-groups.properties files.

    The bootable-users.properties file contains the following content:

    testuser=bootable_password

    The bootable-groups.properties file contains the following content:

    testuser=Users
  8. Add the following extra-content-content-dirs element to the existing <configuration> element:

    <extra-server-content-dirs>
                <extra-content>extra-content</extra-content>
    </extra-server-content-dirs>

    The extra-content directory contains the properties files.

  9. Package the application as a bootable JAR.

    $ mvn package
  10. Start the application:

    mvn wildfly-jar:run
  11. Call the servlet, but do not specify credentials:

    curl -v http://localhost:8080/hello

    Expected output:

    HTTP/1.1 401 Unauthorized
    ...
    WWW-Authenticate: Basic realm="Example Realm"
  12. Call the server and specify your credentials. For example:

    $ curl -v -u testuser:bootable_password http://localhost:8080/hello

    A HTTP 200 status is returned that indicates HTTP authentication is enabled for your bootable JAR. For example:

    HTTP/1.1 200 OK
    ....
    Hello testuser

Additional resources

8.15. Securing your JBoss EAP bootable JAR application with Red Hat Single Sign-On

You can use the Galleon keycloak-client-oidc layer to install a version of a server that is provisioned with Red Hat Single Sign-On 7.4 OpenID Connect client adapters.

The keycloak-client-oidc layer provides Red Hat Single Sign-On OpenID Connect client adapters to your Maven project. This layer is included with the keycloak-adapter-galleon-pack Red Hat Single Sign-On feature pack.

You can add the keycloak-adapter-galleon-pack feature pack to your JBoss EAP Maven plug-in configuration and then add the keycloak-client-oidc. You can view Red Hat Single Sign-On client adapters that are compatible with JBoss EAP by visiting the Supported Configurations: Red Hat Single Sign-On 7.4 web page.

The example in this procedure shows you how to secure a JBoss EAP bootable JAR by using JBoss EAP features provided by the keycloak-client-oidc layer.

Prerequisites

  • You have checked the latest Maven plug-in version, such as MAVEN_PLUGIN_VERSION.X.GA.Final-redhat-00001, where MAVEN_PLUGIN_VERSION is the major version and X is the microversion. See Index of /ga/org/wildfly/plugins/wildfly-jar-maven-plugin.
  • You have checked the latest Galleon feature pack version, such as 3.0.X.GA-redhat-BUILD_NUMBER, where X is the microversion of JBoss EAP XP and BUILD_NUMBER is the build number of the Galleon feature pack. Both X and BUILD_NUMBER can evolve during the JBoss EAP XP 3.0.0 product life cycle. See Index of /ga/org/jboss/eap/wildfly-galleon-pack.
  • You have checked the latest Red Hat Single Sign-On Galleon feature pack version, such as org.jboss.sso:keycloak-adapter-galleon-pack:9.0.X:redhat-BUILD_NUMBER, where X is the microversion of Red Hat Single Sign-On that depends on the Red Hat Single Sign-On server release used to secure the application, and BUILD_NUMBER is the build number of the Red Hat Single Sign-On Galleon feature pack. Both X and BUILD_NUMBER can evolve during the JBoss EAP XP 3.0.0 product life cycle. See Index of /ga/org/jboss/sso/keycloak-adapter-galleon-pack.
  • You have created a Maven project, set up a parent dependency, and added dependencies for creating an application that you want secured with Red Hat Single Sign-On. See Creating a bootable JAR Maven project.
  • You have a Red Hat Single Sign-On server that is running on port 8090. See Starting the Red Hat Single Sign-On server.
  • You have logged in to the Red Hat Single Sign-On Admin Console and created the following metadata:

    • A realm named demo.
    • A role named Users.
    • A user and password. You must assign a Users role to the user.
    • A public-client web application with a Root URL. The example in the procedure, defines simple-webapp as the web application and http://localhost:8080/simple-webapp/secured as the Root URL.

      Important

      When setting up the Maven project, you must specify values for the application that you want to secure with Red Hat Single Sign-On in the Maven archetype. For example:

      $ mvn archetype:generate \
      -DgroupId=com.example.keycloak \
      -DartifactId=simple-webapp \
      -DarchetypeGroupId=org.apache.maven.archetypes \
      -DarchetypeArtifactId=maven-archetype-webapp \
      -DinteractiveMode=false
      cd simple-webapp
      Note

      The examples shown in the procedure specify the following properties:

      • ${bootable.jar.maven.plugin.version} for the Maven plug-in version.
      • ${jboss.xp.galleon.feature.pack.version} for the Galleon feature pack version.
      • ${keycloak.feature.pack.version} for the Red Hat Single Sign-On feature pack version.

      You must set these properties in your project. For example:

      <properties>
          <bootable.jar.maven.plugin.version>4.0.3.Final-redhat-00001</bootable.jar.maven.plugin.version>
          <jboss.xp.galleon.feature.pack.version>3.0.0.GA-redhat-00001</jboss.xp.galleon.feature.pack.version>
          <keycloak.feature.pack.version>9.0.10.redhat-00001</keycloak.feature.pack.version>
      </properties>

Procedure

  1. Add the following content to the <build> element of the pom.xml file. You must specify the latest version of any Maven plug-in and the latest version of the org.jboss.eap:wildfly-galleon-pack Galleon feature pack. For example:

    <plugins>
        <plugin>
            <groupId>org.wildfly.plugins</groupId>
            <artifactId>wildfly-jar-maven-plugin</artifactId>
            <version>${bootable.jar.maven.plugin.version}</version>
            <configuration>
                <feature-packs>
                    <feature-pack>
                        <location>org.jboss.eap:wildfly-galleon-pack:${jboss.xp.galleon.feature.pack.version}</location>
                    </feature-pack>
                    <feature-pack>
                        <location>org.jboss.sso:keycloak-adapter-galleon-pack:${keycloak.feature.pack.version}</location>
                    </feature-pack>
                </feature-packs>
                <layers>
                    <layer>datasources-web-server</layer>
                    <layer>keycloak-client-oidc</layer>
                </layers>
            </configuration>
            <executions>
                <execution>
                    <goals>
                        <goal>package</goal>
                    </goals>
                </execution>
            </executions>
        </plugin>
    </plugins>

    The Maven plug-in provisions subsystems and modules that are required for deploying the web application.

    The keycloak-client-oidc layer provides Red Hat Single Sign-On OpenID Connect client adapters to your project by using the keycloak subsystem and its dependencies to activate support for Red Hat Single Sign-On authentication. Red Hat Single Sign-On client adapters are libraries that secure applications and services with Red Hat Single Sign-On.

  2. In the project pom.xml file, set the <context-root> to false in your plug-in configuration. This registers the application in the simple-webapp resource path. By default, the WAR file is registered under the root-context path.

    <configuration>
        ...
         <context-root>false</context-root>
         ...
    </configuration>
  3. Create a CLI script, such as configure-oidc.cli and save it in an accessible directory in the bootable JAR, such as the APPLICATION_ROOT/scripts directory, where APPLICATION_ROOT is the root directory of your Maven project. The script must contain commands similar to the following example:

    /subsystem=keycloak/secure-deployment=simple-webapp.war:add( \
        realm=demo, \
        resource=simple-webapp, \
        public-client=true, \
        auth-server-url=http://localhost:8090/auth/, \
        ssl-required=EXTERNAL)

    This script example defines the secure-deployment=simple-webapp.war resource in the keycloak subsystem. The simple-webapp.war resource is the name of the WAR file that is deployed in the bootable JAR.

  4. In the project pom.xml file, add the following configuration extract to the existing plug-in <configuration> element:

    <cli-sessions>
        <cli-session>
            <script-files>
                <script>scripts/configure-oidc.cli</script>
            </script-files>
        </cli-session>
    </cli-sessions>
  5. Update the web.xml file in the src/main/webapp/WEB-INF directory. For example:

    <?xml version="1.0" encoding="UTF-8"?>
    
    <web-app version="2.5" xmlns="http://java.sun.com/xml/ns/javaee"
       xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
       xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd"
       metadata-complete="false">
    
        <login-config>
            <auth-method>BASIC</auth-method>
            <realm-name>Simple Realm</realm-name>
        </login-config>
    
    </web-app>
  6. Optional: Alternatively to steps 7 through 9, you can embed the server configuration in the web application by adding the keycloak.json descriptor to the WEB-INF directory of the web application. For example:

    {
        "realm" : "demo",
        "resource" : "simple-webapp",
        "public-client" : "true",
        "auth-server-url" : "http://localhost:8090/auth/",
        "ssl-required" : "EXTERNAL"
    }

    You must then set the <auth-method> of the web application to KEYCLOAK. The following example code illustrates how to set the <auth-method>:

        <login-config>
            <auth-method>KEYCLOAK</auth-method>
            <realm-name>Simple Realm</realm-name>
        </login-config>
  7. Create a Java file named SecuredServlet.java with the following content and save the file in the APPLICATION_ROOT/src/main/java/com/example/securedservlet/ directory.

    package com.example.securedservlet;
    
    import java.io.IOException;
    import java.io.PrintWriter;
    import java.security.Principal;
    
    import javax.servlet.ServletException;
    import javax.servlet.annotation.HttpMethodConstraint;
    import javax.servlet.annotation.ServletSecurity;
    import javax.servlet.annotation.WebServlet;
    import javax.servlet.http.HttpServlet;
    import javax.servlet.http.HttpServletRequest;
    import javax.servlet.http.HttpServletResponse;
    
    @WebServlet("/secured")
    @ServletSecurity(httpMethodConstraints = { @HttpMethodConstraint(value = "GET",
        rolesAllowed = { "Users" }) })
    public class SecuredServlet extends HttpServlet {
    
        @Override
        protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
            try (PrintWriter writer = resp.getWriter()) {
                writer.println("<html>");
                writer.println("<head><title>Secured Servlet</title></head>");
                writer.println("<body>");
                writer.println("<h1>Secured Servlet</h1>");
                writer.println("<p>");
                writer.print(" Current Principal '");
                Principal user = req.getUserPrincipal();
                writer.print(user != null ? user.getName() : "NO AUTHENTICATED USER");
                writer.print("'");
                writer.println("    </p>");
                writer.println("  </body>");
                writer.println("</html>");
            }
        }
    }
  8. Package the application as a bootable JAR.

    $ mvn package
  9. Start the application. The following example starts the simple-webapp web application from its specified bootable JAR path:

    $ java -jar target/simple-webapp-bootable.jar
  10. Specify the following URL in your web browser to access the webpage secured with Red Hat Single Sign-On. The following example shows the URL for the secured simple-webapp web application:

    http://localhost:8080/simple-webapp/secured
  11. Log in as a user from your Red Hat Single Sign-On realm.
  12. Verification: Check that the webpage displays the following output:

    Current Principal '<principal id>'

Additional resources

8.16. Packaging a bootable JAR in dev mode

The JBoss EAP JAR Maven plug-in dev goal provides dev mode, Development Mode, which you can use to enhance your application development process.

In dev mode, you do not need to rebuild the bootable JAR after you make changes to your application.

The workflow in this procedure demonstrates using dev mode to configure a bootable JAR.

Prerequisites

Procedure

  1. Build and start the bootable JAR in Development Mode:

    $ mvn wildfly-jar:dev

    In dev mode, the server deployment scanner is configured to monitor the target/deployments directory.

  2. Prompt the JBoss EAP Maven Plug-in to build and copy your application to the target/deployments directory with the following command:

    $ mvn package -Ddev

    The server packaged inside the bootable JAR deploys the application stored in the target/deployments directory.

  3. Modify the code in your application code.
  4. Use the mvn package -Ddev to prompt the JBoss EAP Maven Plug-in to re-build your application and re-deploy it.
  5. Stop the server. For example:

    $ mvn wildfly-jar:shutdown
  6. After you complete your application changes, package your application as a bootable JAR:

    $ mvn package

8.17. Applying the JBoss EAP patch to your bootable JAR

On a JBoss EAP bare-metal platform, you can install the patch to your bootable JAR by using a CLI script.

The CLI script issues the patch apply command to apply the patch during the bootable JAR build.

Important

After you apply a patch to your bootable JAR, you cannot roll back from the applied patch. You must rebuild a bootable JAR without the patch.

Additionally, you can apply a legacy patch to your bootable JAR with the JBoss EAP JAR Maven plug-in. This plug-in provides a <legacy-patch-cli-script> configuration option to reference the CLI script that is used to patch the server.

Note

The prefix legacy-* in <legacy-patch-cli-script> is related to applying archive patches to a bootable JAR. This method is similar to applying patches to regular JBoss EAP distributions.

You can use the legacy-patch-cleanup option in the JBoss EAP JAR Maven plug-in configuration to reduce the memory footprint of the bootable JAR by removing unused patch content. The option removes unused module dependencies. This option is set as false by default in the patch configuration file.

The legacy-patch-cleanup option removes the following patch content:

  • The <JBOSS_HOME>/.installation/patches directory.
  • Original locations of patch modules in the base layer.
  • Unused modules that were added by the patch and are not referenced in the that existing module graph or patched modules graph.
  • Overlays directories that are not listed in the .overlays file.
Important

The legacy-patch-clean-up option variable is provided as a Technology Preview. Technology Preview features are not supported with Red Hat production service level agreements (SLAs), might not be functionally complete, and Red Hat does not recommend to use them for production. These features provide early access to upcoming product features, enabling customers to test functionality and provide feedback during the development process.

Note

The information outlined in this procedure also pertains to the hollow bootable JAR.

Prerequisites

  • You have set up an account on the Red Hat Customer Portal.
  • You have downloaded the following files from the Product Downloads page:

    • The JBoss EAP JBoss EAP 7.4.4 GA patch
    • The JBoss EAP XP 3.0.0 patch

Procedure

  1. Create a CLI script that defines the legacy patches you want to apply to your bootable JAR. The script must contain one or more patch apply commands. The --override-all command is required when patching a server that was trimmed with Galleon layers, for example:

    patch apply patch-oneoff1.zip --override-all
    
    patch apply patch-oneoff2.zip --override-all
    
    patch info --json-output
  2. Reference your CLI script in the <legacy-patch-cli-script> element of your pom.xml file.
  3. Rebuild the bootable JAR.

Additional resources