Sunday, October 27, 2019

Deploy Java EE7 app into Weblogic Docker domain using Maven

Weblogic 12.2.1.4

General HOWTO

 Create Weblogic Docker image

See blogpost https://danielveselka.blogspot.com/2017/10/build-weblogic-docker-image.html

Create Weblogic generic Docker domain
See sample  from Oracle
https://github.com/oracle/docker-images/tree/master/OracleWebLogic/samples/12213-domain

Weblogic installers
https://www.oracle.com/middleware/technologies/weblogic-server-installers-downloads.html
12.2.1.4 now also has SLIM image  - interesting for Kubernetes deployment

 The WebLogic slim image is supported for development and production deployment of WebLogic configurations using Docker. In order to reduce image size, it contains a subset of the binaries included in the WebLogic generic image. The WebLogic console, WebLogic examples, WebLogic clients, Maven plug-ins and Java DB have been removed - all binaries that remain included are the same as those in the WebLogic generic image. The WebLogic slim image is primarily intended for WebLogic domains managed with the WebLogic Kubernetes Operator, when WLS console-based monitoring and configuration is not required, and a smaller image size than the generic image is preferred. If there are requirements to monitor the WebLogic configuration, they should be addressed using Prometheus and Grafana or other alternatives. All servers within a domain managed with the Operator will use the same WebLogic image. Support is also provided for environments where Kubernetes and/or the WebLogic Kubernetes Operator is not being used.

Get the sample code


Clone the modified code from https://github.com/dveselka/weblogic

 https://github.com/dveselka/weblogic/tree/master/docker-domain

Install generic Weblogic - required for Oracle Maven  repo configuration
[dave@localhost Downloads]$ java -jar fmw_12.2.1.4.0_wls.jar


Configure Oracle Maven  repository


https://blogs.oracle.com/weblogicserver/docker,-java-ee-7,-and-maven-with-weblogic-1213-v2

https://docs.oracle.com/en/middleware/fusion-middleware/weblogic-server/12.2.1.4/wlprg/maven.html#GUID-C6FC7582-2D1C-4EA5-B000-71AE9A2F2B05
 cd ./oracle_common/plugins/maven/com/oracle/maven/oracle-maven-sync/12.2.1

[dave@localhost 12.2.1]$ mvn install:install-file -DpomFile=oracle-maven-sync-12.2.1.pom -Dfile=oracle-maven-sync-12.2.1.jar
[INFO] Scanning for projects...
[INFO] 
[INFO] ------------------< org.apache.maven:standalone-pom >-------------------
[INFO] Building Maven Stub Project (No POM) 1
[INFO] --------------------------------[ pom ]---------------------------------
[INFO] 
[INFO] --- maven-install-plugin:2.4:install-file (default-cli) @ standalone-pom ---
[INFO] Installing /app/weblogic/oracle_common/plugins/maven/com/oracle/maven/oracle-maven-sync/12.2.1/oracle-maven-sync-12.2.1.jar to /home/dave/.m2/repository/com/oracle/maven/oracle-maven-sync/12.2.1-4-0/oracle-maven-sync-12.2.1-4-0.jar
[INFO] Installing /app/weblogic/oracle_common/plugins/maven/com/oracle/maven/oracle-maven-sync/12.2.1/oracle-maven-sync-12.2.1.pom to /home/dave/.m2/repository/com/oracle/maven/oracle-maven-sync/12.2.1-4-0/oracle-maven-sync-12.2.1-4-0.pom

mvn com.oracle.maven:oracle-maven-sync:push -DoracleHome=/app/weblogic

[INFO] SUMMARY
[INFO] ------------------------------------------------------------------------
[INFO] PUSH SUMMARY - ARTIFACTS PROCESSED SUCCESSFULLY
[INFO] ------------------------------------------------------------------------
[INFO] Number of artifacts pushed: 1267
[INFO] 
[INFO] ------------------------------------------------------------------------
[INFO] PUSH SUMMARY - ERRORS ENCOUNTERED
[INFO] ------------------------------------------------------------------------
[INFO] No issues encountered.
[INFO] 
[INFO] IMPORTANT NOTE
[INFO] This operation may have added/updated archetypes in your repository.
[INFO] To update your archetype catalog, you should run:
[INFO] 'mvn archetype:crawl -Dcatalog=$HOME/.m2/archetype-catalog.xml'


[dave@localhost 12.2.1]$ find /home/dave/.m2/repository/com/oracle -name weblogic-maven-plugin
/home/dave/.m2/repository/com/oracle/weblogic/weblogic-maven-plugin

[dave@localhost 12.2.1]$ ls -l /home/dave/.m2/repository/com/oracle/weblogic/weblogic-maven-plugin
total 16
drwxrwxr-x. 2 dave dave 4096 Oct 27 12:40 12.2.1-0-0
drwxrwxr-x. 2 dave dave 4096 Oct 27 12:01 12.2.1-2-0
drwxrwxr-x. 2 dave dave 4096 Oct 27 12:38 12.2.1-4-0

Validate the installed Weblogic Maven plugin

mvn help:describe -DgroupId=com.oracle.weblogic -DartifactId=weblogic-maven-plugin -Dversion=12.2.1-4-0



Name: weblogic-maven-plugin
Description: The Oracle WebLogic Server 12.2.1 Maven plugin
Group Id: com.oracle.weblogic
Artifact Id: weblogic-maven-plugin
Version: 12.2.1-4-0
Goal Prefix: weblogic

This plugin has 23 goals:

weblogic:appc
  Description: This goal is a wrapper for the weblogic.appc compiler.

weblogic:create-domain
  Description: Create a domain for WebLogic Server using the default domain
    template. For more complex domain creation use the WLST goal. Note:
    Starting in WLS 12.2.1, there is a single unified version of WLST that
    automatically includes the WLST environment from all products in the
    ORACLE_HOME.

weblogic:deploy
  Description: Deploys an application to WebLogic Server (supports all
    formats WAR, JAR, RAR, EAR, etc.)

weblogic:distribute-app
  Description: Prepares deployment files for deployment by copying deployment
    files to target servers and validating them.

weblogic:install
  Description: Installs WebLogic Server

weblogic:list-apps
  Description: Lists the deployment names for applications and stand-alone
    modules deployed distributed, or installed to the domain

weblogic:purge-tasks
  Description: Flushes out retired deployment tasks

weblogic:redeploy
  Description: Redeploys a running application or part of a running
    application

weblogic:remove-domain
  Description: This class provides basic capabilities to remove a domain
    directory.

weblogic:start-app
  Description: Starts an application

weblogic:start-server
  Description: Starts WebLogic Server.

weblogic:stop-app
  Description: Stops an application

weblogic:stop-server
  Description: This goals run a stop script to stop WebLogic Server.

weblogic:undeploy
  Description: Stops the deployment unit and removes staged files from target
    servers

weblogic:uninstall
  Description: Uninstalls WebLogic Server

weblogic:update-app
  Description: Updates an application's deployment plan by redistributing the
    plan files and reconfiguring the application based on the new plan
    contents.

weblogic:wlst
  Description: This goal is a wrapper for the WLST scripting tool.
    Note: Starting in WLS 12.2.1, there is a single unified version of WLST
    that automatically includes the WLST environment from all products in the
    ORACLE_HOME.

weblogic:wlst-client
  Description: WLST wrapper for Maven that does not require a server install
    for WLST online commands.

weblogic:ws-clientgen
  Description: A Maven goal to generate client web service artifacts from a
    WSDL Note the differences between clientgen Ant task and Maven goal:
    clientgen goal only generates JAXWS web service artifacts, while Ant task
    has JAXRPC as the default. At the moment there is no way to direct
    clientgen goal to also compile and package generated artifacts.
  Deprecated. No reason given

weblogic:ws-jwsc
  Description: This goal builds a JAX-WS web service, generates source code,
    data binding artifacts, deployment descriptors, and so on into an output
    directory.
  Deprecated. No reason given

weblogic:ws-wsdlc
  Description: This goal generates, from an existing WSDL file, a set of
    artifacts that together provide a partial Java implementation of the Web
    Service described by the WSDL file.
  Deprecated. No reason given

weblogic:wsgen
  Description: Reads a JAX-WS service endpoint implementation class and
    generates all of the portable artifacts for a JAX-WS web service.

weblogic:wsimport
  Description: Parses wsdl and binding files and generates Java code needed
    to access it.

For more information, run 'mvn help:describe [...] -Ddetail'


Configure the properties for the Docker Weblogic domain


Set the weblogic Admin user/password in
./docker-domain/OracleWebLogic/samples/12214-domain-generic/properties/domain_security.properties


Create the domain using ./docker-domain/OracleWebLogic/samples/12214-domain-generic/build.sh

docker build -f Dockerfile -t 12214-weblogic-domain-generic .


This creates Docker image

[dave@localhost weblogic]$ docker images
REPOSITORY                      TAG                 IMAGE ID            CREATED             SIZE
12214-weblogic-domain-generic   latest              0c7c40704362        43 minutes ago      1.26GB


Change the domain Docker image name in run_admin_server.sh script
./docker-domain/OracleWebLogic/samples/12214-domain-generic/run_admin_server.sh

[dave@localhost weblogic]$ grep 12214-weblogic-domain-generic ./docker-domain/OracleWebLogic/samples/12214-domain-generic/run_admin_server.sh
echo "docker run -d -p 9001:7001 -p 9002:9002 --name ${adminhost} --hostname ${adminhost} -v ${scriptDir}/properties:/u01/oracle/properties -v ${domainhostvol}:/u01/oracle/user_projects/domains ${ENV_ARG} 12214-weblogic-domain-generic"
docker run -d -p 9001:7001 -p 9002:9002 --name ${adminhost} --hostname ${adminhost} -v ${scriptDir}/properties:/u01/oracle/properties -v ${domainhostvol}:/u01/oracle/user_projects/domains ${ENV_ARG} 12214-weblogic-domain-generic



List of required images
[dave@localhost 12214-domain-generic]$ docker images
REPOSITORY                      TAG                 IMAGE ID            CREATED              SIZE
12214-weblogic-domain-generic   latest              93dc22395c42        14 seconds ago       1.26GB
oracle/weblogic                 12.2.1.4-generic    b67e91a22473        46 seconds ago       1.26GB
<none>                          <none>              ba227fc7cf16        About a minute ago   2.99GB
oracle/serverjre                8                   639ea570f133        4 hours ago          356MB
oraclelinux                     7-slim              874477adb545        2 months ago         118MB


Create directory on localhost where the Docker domain volume will be mapped - in our test /app/domains/

Run the domain


[dave@localhost 12213-domain]$ ./run_admin_server.sh 
Context for docker build is /git/docker-images/OracleWebLogic/samples/12213-domain
Export environment variables from the /git/docker-images/OracleWebLogic/samples/12213-domain/properties/domain.properties properties file
 env_arg: CUSTOM_DOMAIN_NAME=daveDomain
 env_arg: CUSTOM_ADMIN_NAME=admin
 env_arg: CUSTOM_ADMIN_PORT=7001
 env_arg: CUSTOM_ADMIN_HOST=AdminContainer
 env_arg: CUSTOM_MANAGED_SERVER_PORT=8001
 env_arg: CUSTOM_MANAGED_SERVER_NAME_BASE=MS
 env_arg: CUSTOM_CONFIGURED_MANAGED_SERVER_COUNT=2
 env_arg: CUSTOM_CLUSTER_NAME=clusterdave
 env_arg: CUSTOM_CLUSTER_TYPE=DYNAMIC
 env_arg: CUSTOM_PRODUCTION_MODE_ENABLED=true
 env_arg: CUSTOM_DOMAIN_HOST_VOLUME=/app/domains/
The domain configuration will get persisted in the host volume: /app/domains/
docker run -d -p 9001:7001 -p 9002:9002 --name AdminContainer --hostname AdminContainer -v /git/docker-images/OracleWebLogic/samples/12213-domain/properties:/u01/oracle/properties -v /app/domains/:/u01/oracle/user_projects/domains  -e CUSTOM_DOMAIN_NAME=daveDomain -e CUSTOM_ADMIN_NAME=admin -e CUSTOM_ADMIN_PORT=7001 -e CUSTOM_ADMIN_HOST=AdminContainer -e CUSTOM_ADMIN_HOST=AdminContainer -e CUSTOM_MANAGED_SERVER_PORT=8001 -e CUSTOM_MANAGED_SERVER_NAME_BASE=MS -e CUSTOM_CONFIGURED_MANAGED_SERVER_COUNT=2 -e CUSTOM_CLUSTER_NAME=clusterdave -e CUSTOM_CLUSTER_TYPE=DYNAMIC -e CUSTOM_PRODUCTION_MODE_ENABLED=true 12214-weblogic-domain-slim
42999c43bffe7bd381031c07567d4aa9893a23247190cbdb18659cae9c228b33
[dave@localhost 12213-domain]$ docker ps
CONTAINER ID        IMAGE                        COMMAND                  CREATED             STATUS              PORTS                                            NAMES
42999c43bffe        12214-weblogic-domain-slim   "/u01/oracle/contain…"   5 seconds ago       Up 3 seconds        0.0.0.0:9002->9002/tcp, 0.0.0.0:9001->7001/tcp   AdminContainer
[dave@localhost 12213-domain]$ pgrep -a java
7367 /usr/java/jdk-8/bin/java -server -Djava.security.egd=file:/dev/./urandom -cp /u01/oracle/wlserver/server/lib/weblogic-launcher.jar -Dlaunch.use.env.classpath=true -Dweblogic.Name=admin -Djava.security.policy=/u01/oracle/wlserver/server/lib/weblogic.policy -Doracle.jdbc.fanEnabled=false -Dweblogic.StdoutDebugEnabled=false -Djava.system.class.loader=com.oracle.classloader.weblogic.LaunchClassLoader -javaagent:/u01/oracle/wlserver/server/lib/debugpatch-agent.jar -da -Dwls.home=/u01/oracle/wlserver/server -Dweblogic.home=/u01/oracle/wlserver/server weblogic.Server
[dave@localhost 12213-domain]$ ls /app/domains/
daveDomain


Deploy the application code using Maven


Set the latest version of weblogic-maven-plugin

 <plugin>
        <groupId>com.oracle.weblogic</groupId>
        <artifactId>weblogic-maven-plugin</artifactId>
        <version>12.2.1-4-0</version>


Maven plugin goals

 https://docs.oracle.com/en/middleware/fusion-middleware/weblogic-server/12.2.1.4/wlprg/maven.html#GUID-CE12CFF4-EB0C-4E92-A13A-676AAD854663

SSH into container to check upload
docker exec -it  2f1af983d72d /bin/bash


Configure upload in Maven weblogic plugin

WAR is uploaded into Docker domain
[oracle@AdminContainer /]$ find . -name "rs-api.war" 2>/dev/null
./u01/oracle/user_projects/domains/base_domain/servers/AdminServer/tmp/_WL_user/rs-api/m49v6j/META-INF/.WL_internal/cache/rs-api.war
./u01/oracle/user_projects/domains/daveDomain/servers/admin/upload/rs-api/app/rs-api.war
./u01/oracle/user_projects/domains/daveDomain/servers/admin/tmp/.appmergegen_1572188440153_rs-api.war/META-INF/.WL_internal/cache/rs-api.war
./u01/oracle/user_projects/domains/daveDomain/servers/admin/tmp/.appmergegen_1572188440153/rs-api.war
./u01/oracle/user_projects/domains/daveDomain/servers/admin/tmp/_WL_user/rs-api/w7yf0e/META-INF/.WL_internal/cache/rs-api.war



Without upload you get following error
ERROR] Failed to execute goal com.oracle.weblogic:weblogic-maven-plugin:12.2.1-4-0:deploy (default) on project rs-api: weblogic.management.ManagementException: [Deployer:149003]Unable to access application source information in "/app/domains/apps/rs-api.war" for application "rs-api". The specific error is: No application files exist.
[ERROR]     at weblogic.deploy.internal.adminserver.operations.OperationHelper.validateSource(OperationHelper.java:358)
[ERROR]     at weblogic.deploy.internal.adminserver.operations.OperationHelper.getArchiveVersionIdFromSource(OperationHelper.java:168)
[ERROR]     at weblogic.deploy.internal.adminserver.operations.OperationHelper.getAndValidateVersionIdWithSrc(OperationHelper.java:206)


in case of unreachable admin you can try to add JAVA Option with the flag “-Dweblogic.rjvm.enableprotocolswitch=true
See also https://github.com/oracle/docker-images/issues/575


<plugin>
        <groupId>com.oracle.weblogic</groupId> 
        <artifactId>weblogic-maven-plugin</artifactId> 
        <version>12.2.1-4-0</version> 
        <!--
        You can find and redefine the following variables in the parent pom file arccording to your environment.
  
        oracleMiddlewareHome
        oracleServerUrl
        oracleUsername
        oraclePassword
        oracleServerName
        -->
        <configuration> 
          <middlewareHome>${oracleMiddlewareHome}</middlewareHome>
        </configuration> 
        <executions>
          <!--Deploy the application to the server-->
          <execution>
            <phase>pre-integration-test</phase> 
            <goals> 
              <goal>deploy</goal> 
            </goals>
            <configuration> 
              <!--The admin URL where the app is deployed. Here use the plugin's default value t3://localhost:7001-->
              <adminurl>${oracleServerUrl}</adminurl>
              <user>${oracleUsername}</user> 
              <password>${oraclePassword}</password>
              <!--The location of the file or directory to be deployed-->
              <source>${project.build.directory}/${project.build.finalName}.${project.packaging}</source>
              <!--The target servers where the application is deployed. Here use the plugin's default value AdminServer-->
              <!--targets>${oracleServerName}</targets-->
              <verbose>true</verbose> 
              <!--The deployment name of the application-->
              <name>${project.build.finalName}</name>
              <upload>true</upload>
            </configuration> 
          </execution> 
        </executions>
      </plugin>


 

Deploy the app into Docker Weblogic domain

Sample application code is here https://github.com/dveselka/weblogic/tree/master/rs-api

dave@localhost rs-api]$ mvn clean package pre-integration-test
[INFO] Scanning for projects...
[INFO] 
[INFO] --------------------------< com.dave:rs-api >---------------------------
[INFO] Building rs-api 1.0-SNAPSHOT
[INFO] --------------------------------[ war ]---------------------------------
[INFO] 
[INFO] --- maven-clean-plugin:2.5:clean (default-clean) @ rs-api ---
[INFO] Deleting /git/weblogic/rs-api/target
[INFO] 
[INFO] --- maven-resources-plugin:2.6:resources (default-resources) @ rs-api ---
[WARNING] Using platform encoding (UTF-8 actually) to copy filtered resources, i.e. build is platform dependent!
[INFO] skip non existing resourceDirectory /git/weblogic/rs-api/src/main/resources
[INFO] 
[INFO] --- maven-compiler-plugin:2.3.2:compile (default-compile) @ rs-api ---
[WARNING] File encoding has not been set, using platform encoding UTF-8, i.e. build is platform dependent!
[INFO] Compiling 4 source files to /git/weblogic/rs-api/target/classes
[INFO] 
[INFO] --- maven-resources-plugin:2.6:testResources (default-testResources) @ rs-api ---
[WARNING] Using platform encoding (UTF-8 actually) to copy filtered resources, i.e. build is platform dependent!
[INFO] skip non existing resourceDirectory /git/weblogic/rs-api/src/test/resources
[INFO] 
[INFO] --- maven-compiler-plugin:2.3.2:testCompile (default-testCompile) @ rs-api ---
[INFO] No sources to compile
[INFO] 
[INFO] --- maven-surefire-plugin:2.12.4:test (default-test) @ rs-api ---
[INFO] No tests to run.
[INFO] 
[INFO] --- maven-war-plugin:2.1.1:war (default-war) @ rs-api ---
[INFO] Packaging webapp
[INFO] Assembling webapp [rs-api] in [/git/weblogic/rs-api/target/rs-api]
[INFO] Processing war project
[INFO] Copying webapp resources [/git/weblogic/rs-api/src/main/webapp]
[INFO] Webapp assembled in [15 msecs]
[INFO] Building war: /git/weblogic/rs-api/target/rs-api.war
[INFO] WEB-INF/web.xml already added, skipping
[INFO] 
[INFO] --- maven-resources-plugin:2.6:resources (default-resources) @ rs-api ---
[WARNING] Using platform encoding (UTF-8 actually) to copy filtered resources, i.e. build is platform dependent!
[INFO] skip non existing resourceDirectory /git/weblogic/rs-api/src/main/resources
[INFO] 
[INFO] --- maven-compiler-plugin:2.3.2:compile (default-compile) @ rs-api ---
[WARNING] File encoding has not been set, using platform encoding UTF-8, i.e. build is platform dependent!
[INFO] Compiling 4 source files to /git/weblogic/rs-api/target/classes
[INFO] 
[INFO] --- maven-resources-plugin:2.6:testResources (default-testResources) @ rs-api ---
[WARNING] Using platform encoding (UTF-8 actually) to copy filtered resources, i.e. build is platform dependent!
[INFO] skip non existing resourceDirectory /git/weblogic/rs-api/src/test/resources
[INFO] 
[INFO] --- maven-compiler-plugin:2.3.2:testCompile (default-testCompile) @ rs-api ---
[INFO] No sources to compile
[INFO] 
[INFO] --- maven-surefire-plugin:2.12.4:test (default-test) @ rs-api ---
[INFO] No tests to run.
[INFO] Skipping execution of surefire because it has already been run for this configuration
[INFO] 
[INFO] --- maven-war-plugin:2.1.1:war (default-war) @ rs-api ---
[INFO] Packaging webapp
[INFO] Assembling webapp [rs-api] in [/git/weblogic/rs-api/target/rs-api]
[INFO] Processing war project
[INFO] Copying webapp resources [/git/weblogic/rs-api/src/main/webapp]
[INFO] Webapp assembled in [2 msecs]
[INFO] Building war: /git/weblogic/rs-api/target/rs-api.war
[INFO] WEB-INF/web.xml already added, skipping
[INFO] 
[INFO] --- weblogic-maven-plugin:12.2.1-4-0:deploy (default) @ rs-api ---
[INFO] Command flags are: -noexit -deploy -username myusername -password ******* -name rs-api -source /git/weblogic/rs-api/target/rs-api.war -upload -verbose -adminurl t3://localhost:9001
weblogic.Deployer invoked with options:  -noexit -deploy -username myusername -name rs-api -source /git/weblogic/rs-api/target/rs-api.war -upload -verbose -adminurl t3://localhost:9001
<Oct 27, 2019 2:12:33 PM CET> <Info> <J2EE Deployment SPI> <BEA-260121> <Initiating deploy operation for application, rs-api [archive: /git/weblogic/rs-api/target/rs-api.war], to configured targets.> 
Task 5 initiated: [Deployer:149026]deploy application rs-api on admin.
Task 5 completed: [Deployer:149026]deploy application rs-api on admin.
Target state: deploy completed on Server admin

Target Assignments:
+ rs-api  admin
[INFO] ------------------------------------------------------------------------
[INFO] BUILD SUCCESS
[INFO] ------------------------------------------------------------------------
[INFO] Total time:  4.768 s
[INFO] Finished at: 2019-10-27T14:12:34+01:00
[INFO] ------------------------------------------------------------------------

Check the running domain

[dave@localhost rs-api]$ docker ps
CONTAINER ID        IMAGE                           COMMAND                  CREATED             STATUS              PORTS                                            NAMES
2f1af983d72d        12214-weblogic-domain-generic   "/u01/oracle/contain…"   22 minutes ago      Up 22 minutes       0.0.0.0:9002->9002/tcp, 0.0.0.0:9001->7001/tcp   AdminContainer
[dave@localhost rs-api]$ pgrep -a java
25383 /usr/java/jdk-8/bin/java -Djava.security.manager -Djava.security.policy=/u01/oracle/wlserver/common/derby/derbyServer.policy -Dderby.system.home=/u01/oracle/user_projects/domains/daveDomain/common/db -classpath /u01/oracle/wlserver/common/derby/lib/derby.jar:/u01/oracle/wlserver/common/derby/lib/derbynet.jar:/u01/oracle/wlserver/common/derby/lib/derbytools.jar:/u01/oracle/wlserver/common/derby/lib/derbyoptionaltools.jar:/u01/oracle/wlserver/common/derby/lib/derbyclient.jar org.apache.derby.drda.NetworkServerControl start
25384 /usr/java/jdk-8/bin/java -server -Djava.security.egd=file:/dev/./urandom -cp /u01/oracle/wlserver/server/lib/weblogic-launcher.jar -Dlaunch.use.env.classpath=true -Dweblogic.Name=admin -Djava.security.policy=/u01/oracle/wlserver/server/lib/weblogic.policy -Doracle.jdbc.fanEnabled=false -Dweblogic.StdoutDebugEnabled=false -Dweblogic.rjvm.enableprotocolswitch=true -Djava.system.class.loader=com.oracle.classloader.weblogic.LaunchClassLoader -javaagent:/u01/oracle/wlserver/server/lib/debugpatch-agent.jar -da -Dwls.home=/u01/oracle/wlserver/server -Dweblogic.home=/u01/oracle/wlserver/server weblogic.Server

Test the app


[dave@localhost rs-api]$ curl http://localhost:9001/rs-api/resources/persons
[{"age":50,"name":"dave"},{"age":30,"name":"abc"}



Saturday, October 26, 2019

Create microservices multimodule OpenLiberty project using Maven

Multimodule project guide
https://openliberty.io/guides/maven-multimodules.html

Sample multimodule project
https://github.com/Yavin/maven-ear-example

Get the code

[dave@localhost git]$ git clone https://github.com/openliberty/guide-maven-multimodules.git
Cloning into 'guide-maven-multimodules'... 

Project structure

[dave@localhost finish]$ find
.
./ear
./ear/pom.xml
./ear/src
./ear/src/main
./ear/src/main/liberty
./ear/src/main/liberty/config
./ear/src/main/liberty/config/server.xml
./ear/src/test
./ear/src/test/java
./ear/src/test/java/it
./ear/src/test/java/it/io
./ear/src/test/java/it/io/openliberty
./ear/src/test/java/it/io/openliberty/guides
./ear/src/test/java/it/io/openliberty/guides/multimodules
./ear/src/test/java/it/io/openliberty/guides/multimodules/Test.java
./war
./war/pom.xml
./war/src
./war/src/main
./war/src/main/java
./war/src/main/java/io
./war/src/main/java/io/openliberty
./war/src/main/java/io/openliberty/guides
./war/src/main/java/io/openliberty/guides/multimodules
./war/src/main/java/io/openliberty/guides/multimodules/web
./war/src/main/java/io/openliberty/guides/multimodules/web/HeightsBean.java
./war/src/main/webapp
./war/src/main/webapp/index.jsp
./war/src/main/webapp/WEB-INF
./war/src/main/webapp/WEB-INF/web.xml
./war/src/main/webapp/heights.jsp
./jar
./jar/pom.xml
./jar/src
./jar/src/main
./jar/src/main/java
./jar/src/main/java/io
./jar/src/main/java/io/openliberty
./jar/src/main/java/io/openliberty/guides
./jar/src/main/java/io/openliberty/guides/multimodules
./jar/src/main/java/io/openliberty/guides/multimodules/lib
./jar/src/main/java/io/openliberty/guides/multimodules/lib/Converter.java
./pom.xml


Build the project using mvn install


[INFO] ------------------------------------------------------------------------
[INFO] Reactor Build Order:
[INFO] 
[INFO] io.openliberty.guides.multimodules.modules                         [pom]
[INFO] io.openliberty.guides.multimodules.jar                             [jar]
[INFO] io.openliberty.guides.multimodules.war                             [war]
[INFO] io.openliberty.guides.multimodules.ear                             [ear]
[INFO] 
[INFO] --< io.openliberty.guides:io.openliberty.guides.multimodules.modules >--
[INFO] Building io.openliberty.guides.multimodules.modules 0.0.1-SNAPSHOT [1/4]
[INFO] --------------------------------[ pom ]---------------------------------
[INFO] 
[INFO] --- maven-install-plugin:2.4:install (default-install) @ io.openliberty.guides.multimodules.modules ---
[INFO] Installing /git/guide-maven-multimodules/finish/pom.xml to /home/dave/.m2/repository/io/openliberty/guides/io.openliberty.guides.multimodules.modules/0.0.1-SNAPSHOT/io.openliberty.guides.multimodules.modules-0.0.1-SNAPSHOT.pom


Start the server using mvn liberty:start-server

INFO] --- liberty-maven-plugin:3.0.M1:start-server (default-cli) @ io.openliberty.guides.multimodules.modules ---
[INFO] CWWKM2102I: Using installDirectory : /git/guide-maven-multimodules/finish/target/liberty/wlp.
[INFO] CWWKM2102I: Using serverName : defaultServer.
[INFO] CWWKM2102I: Using serverDirectory : /git/guide-maven-multimodules/finish/target/liberty/wlp/usr/servers/defaultServer.
[INFO] Installing from Open Liberty repository...
[INFO] Getting: https://public.dhe.ibm.com/ibmdl/export/pub/software/openliberty/runtime/release/info.json
[INFO] To: /home/dave/.m2/repository/wlp-cache/openliberty-versions.json
[INFO] Using runtime version: 2019-10-02_0300
[INFO] Getting: https://public.dhe.ibm.com/ibmdl/export/pub/software/openliberty/runtime/release/2019-10-02_0300/info.json
[INFO] To: /home/dave/.m2/repository/wlp-cache/2019-10-02_0300.json
[INFO] Getting: https://public.dhe.ibm.com/ibmdl/export/pub/software/openliberty/runtime/release/2019-10-02_0300/openliberty-19.0.0.10.zip
[INFO] To: /home/dave/.m2/repository/wlp-cache/2019-10-02_0300/openliberty-19.0.0.10.zip


[INFO] Copying 1 file to /git/guide-maven-multimodules/finish/ear/target/liberty/wlp/usr/servers/defaultServer
[INFO] CWWKM2144I: Update server configuration file server.xml from /git/guide-maven-multimodules/finish/ear/src/main/liberty/config/server.xml.
[INFO] CWWKM2144I: Update server configuration file bootstrap.properties from inlined configuration.
[INFO] CWWKM2001I: server.config.dir is /git/guide-maven-multimodules/finish/ear/target/liberty/wlp/usr/servers/defaultServer.
[INFO] CWWKM2001I: server.output.dir is /git/guide-maven-multimodules/finish/ear/target/liberty/wlp/usr/servers/defaultServer.
[INFO] CWWKM2001I: Invoke command is [/git/guide-maven-multimodules/finish/ear/target/liberty/wlp/bin/server, start, defaultServer].
[INFO] 
[INFO] Starting server defaultServer.
[INFO] Server defaultServer started with process ID 21980.
[INFO] Waiting up to 30 seconds for server confirmation:  CWWKF0011I to be found in /git/guide-maven-multimodules/finish/ear/target/liberty/wlp/usr/servers/defaultServer/logs/messages.log
[INFO] CWWKM2010I: Searching for CWWKF0011I in /git/guide-maven-multimodules/finish/ear/target/liberty/wlp/usr/servers/defaultServer/logs/messages.log. This search will timeout after 30 seconds.
[INFO] CWWKM2015I: Match number: 1 is [10/26/19 12:10:53:843 CEST] 0000001f com.ibm.ws.kernel.feature.internal.FeatureManager            A CWWKF0011I: The defaultServer server is ready to run a smarter planet. The defaultServer server started in 1.067 seconds..

[dave@localhost finish]$ tail -500f /git/guide-maven-multimodules/finish/ear/target/liberty/wlp/usr/servers/defaultServer/logs/messages.log
********************************************************************************
product = Open Liberty 19.0.0.10 (wlp-1.0.33.cl191020191002-0300)
wlp.install.dir = /git/guide-maven-multimodules/finish/ear/target/liberty/wlp/
java.home = /usr/java/jdk1.8.0_231-amd64/jre
java.version = 1.8.0_231
java.runtime = Java(TM) SE Runtime Environment (1.8.0_231-b11)
os = Linux (5.3.6-200.fc30.x86_64; amd64) (en_US)
process = 21980@localhost.localdomain
********************************************************************************
[10/26/19 12:10:52:876 CEST] 00000001 com.ibm.ws.kernel.launch.internal.FrameworkManager           A CWWKE0001I: The server defaultServer has been launched.
[10/26/19 12:10:53:275 CEST] 00000001 com.ibm.ws.kernel.launch.internal.FrameworkManager           I CWWKE0002I: The kernel started after 0.498 seconds
[10/26/19 12:10:53:296 CEST] 0000001f com.ibm.ws.kernel.feature.internal.FeatureManager            I CWWKF0007I: Feature update started.
[10/26/19 12:10:53:457 CEST] 00000015 com.ibm.ws.app.manager.internal.monitor.DropinMonitor        A CWWKZ0058I: Monitoring dropins for applications.
[10/26/19 12:10:53:527 CEST] 00000023 com.ibm.ws.tcpchannel.internal.TCPPort                       E CWWKO0221E: TCP Channel defaultHttpEndpoint initialization did not succeed.  The socket bind did not succeed for host * and port 9080.  The port might already be in use.  Exception Message: Address already in use
[10/26/19 12:10:53:625 CEST] 00000026 com.ibm.ws.app.manager.AppMessageHelper                      I CWWKZ0018I: Starting application io.openliberty.guides.multimodules.ear.
[10/26/19 12:10:53:626 CEST] 00000026 bm.ws.app.manager.ear.internal.EARDeployedAppInfoFactoryImpl I CWWKZ0134I: The io.openliberty.guides.multimodules.ear application is using the loose application definition at the /git/guide-maven-multimodules/finish/ear/target/liberty/wlp/usr/servers/defaultServer/apps/io.openliberty.guides.multimodules.ear-0.0.1-SNAPSHOT.ear.xml location.
[10/26/19 12:10:53:815 CEST] 00000026 com.ibm.ws.session.WASSessionCore                            I SESN8501I: The session manager did not find a persistent storage location; HttpSession objects will be stored in the local application server's memory.
[10/26/19 12:10:53:826 CEST] 00000026 com.ibm.ws.webcontainer.osgi.webapp.WebGroup                 I SRVE0169I: Loading Web Module: Archetype Created Web Application.
[10/26/19 12:10:53:827 CEST] 00000026 com.ibm.ws.webcontainer                                      I SRVE0250I: Web Module Archetype Created Web Application has been bound to default_host.
[10/26/19 12:10:53:830 CEST] 00000026 com.ibm.ws.app.manager.AppMessageHelper                      A CWWKZ0001I: Application io.openliberty.guides.multimodules.ear started in 0.205 seconds.
[10/26/19 12:10:53:842 CEST] 0000001f com.ibm.ws.kernel.feature.internal.FeatureManager            A CWWKF0012I: The server installed the following features: [el-3.0, jsp-2.3, servlet-3.1].
[10/26/19 12:10:53:843 CEST] 0000001f com.ibm.ws.kernel.feature.internal.FeatureManager            I CWWKF0008I: Feature update completed in 0.568 seconds.
[10/26/19 12:10:53:843 CEST] 0000001f com.ibm.ws.kernel.feature.internal.FeatureManager            A CWWKF0011I: The defaultServer server is ready to run a smarter planet. The defaultServer server started in 1.067 seconds.
[10/26/19 12:10:53:847 CEST] 00000029 com.ibm.ws.session.WASSessionCore                            I SESN0176I: A new session context will be created for application key default_host/converter
[10/26/19 12:10:53:861 CEST] 00000029 com.ibm.ws.util                                              I SESN0172I: The session manager is using the Java default SecureRandom implementation for session ID generation.
[10/26/19 12:10:53:868 CEST] 0000002a com.ibm.ws.webcontainer.osgi.mbeans.PluginGenerator          I SRVE9103I: A configuration file for a web server plugin was automatically generated for this server at /git/guide-maven-multimodules/finish/ear/target/liberty/wlp/usr/servers/defaultServer/logs/state/plugin-cfg.xml.


Test the application

Configure development environment for Java Microproflle using OpenLiberty on Fedora

Follow the guide fron OpenLiberty
https://openliberty.io/guides/maven-intro.html

Install latest Maven


https://computingforgeeks.com/installing-latest-apache-maven-on-centos-fedora/

[dave@localhost ~]$ export VER="3.6.2"
[dave@localhost ~]$ curl -O http://www-eu.apache.org/dist/maven/maven-3/${VER}/binaries/apache-maven-${VER}-bin.tar.gz
  % Total    % Received % Xferd  Average Speed   Time    Time     Time  Current
                                 Dload  Upload   Total   Spent    Left  Speed
100 8928k  100 8928k    0     0  9508k      0 --:--:-- --:--:-- --:--:-- 9497k
[dave@localhost ~]$ tar xvf apache-maven-${VER}-bin.tar.gz



[dave@localhost ~]$ sudo mv apache-maven-${VER} /opt/maven
[sudo] password for dave: 
[dave@localhost ~]$ cat <<EOF | sudo tee /etc/profile.d/maven.sh
> export MAVEN_HOME=/opt/maven
> export PATH=\$PATH:\$MAVEN_HOME/bin
> EOF
export MAVEN_HOME=/opt/maven
export PATH=$PATH:$MAVEN_HOME/bin
[dave@localhost ~]$ source /etc/profile.d/maven.sh
[dave@localhost ~]$ echo $MAVEN_HOME
/opt/maven
[dave@localhost ~]$ echo $PATH
/home/dave/.local/bin:/home/dave/bin:/usr/share/Modules/bin:/usr/local/bin:/usr/local/sbin:/usr/bin:/usr/sbin:/opt/maven/bin
[dave@localhost ~]$ mvn --version
Apache Maven 3.6.2 (40f52333136460af0dc0d7232c0dc0bcf0d9e117; 2019-08-27T17:06:16+02:00)
Maven home: /opt/maven
Java version: 1.8.0_232, vendor: Oracle Corporation, runtime: /usr/lib/jvm/java-1.8.0-openjdk-1.8.0.232.b09-0.fc30.x86_64/jre
Default locale: en_US, platform encoding: UTF-8
OS name: "linux", version: "5.3.6-200.fc30.x86_64", arch: "amd64", family: "unix"


Install Oracle JDK


You can also use OpenJDK but I want to run Weblogic on this host so I need Oracle JDK 


[dave@localhost finish]$ sudo dnf install ~/Downloads/jdk-8u231-linux-x64.rpm 
Error: 
 Problem: conflicting requests
  - nothing provides /bin/basename needed by jdk1.8-2000:1.8.0_231-fcs.x86_64
  - nothing provides /bin/cp needed by jdk1.8-2000:1.8.0_231-fcs.x86_64
  - nothing provides /bin/ls needed by jdk1.8-2000:1.8.0_231-fcs.x86_64
  - nothing provides /bin/mkdir needed by jdk1.8-2000:1.8.0_231-fcs.x86_64
  - nothing provides /bin/mv needed by jdk1.8-2000:1.8.0_231-fcs.x86_64
  - nothing provides /bin/pwd needed by jdk1.8-2000:1.8.0_231-fcs.x86_64
  - nothing provides /bin/sort needed by jdk1.8-2000:1.8.0_231-fcs.x86_64
(try to add '--skip-broken' to skip uninstallable packages)


Use direct rpm installation due to missing deps


[dave@localhost Downloads]$ sudo rpm -Uvh  ~/Downloads/jdk-8u231-linux-x64.rpm 
warning: /home/dave/Downloads/jdk-8u231-linux-x64.rpm: Header V3 RSA/SHA256 Signature, key ID ec551f03: NOKEY
Verifying...                          ################################# [100%]
Preparing...                          ################################# [100%]
Updating / installing...
   1:jdk1.8-2000:1.8.0_231-fcs        ################################# [100%]
Unpacking JAR files...
    tools.jar...
    plugin.jar...
    javaws.jar...
    deploy.jar...
    rt.jar...
    jsse.jar...
    charsets.jar...
    localedata.jar...
[dave@localhost Downloads]$ rpm -qi jdk1.8 
Name        : jdk1.8
Epoch       : 2000
Version     : 1.8.0_231
Release     : fcs
Architecture: x86_64
Install Date: Sat 26 Oct 2019 09:50:36 AM CEST
Group       : Development/Tools
Size        : 308047737
License     : https://java.com/bc_license
Signature   : RSA/SHA256, Sat 05 Oct 2019 12:32:51 PM CEST, Key ID 72f97b74ec551f03
Source RPM  : jdk1.8-1.8.0_231-fcs.src.rpm
Build Date  : Sat 05 Oct 2019 12:18:14 PM CEST
Build Host  : java.com
Relocations : /usr/java 
Vendor      : Oracle Corporation
URL         : http://www.oracle.com/technetwork/java/javase/overview/index.html
Summary     : Java Platform Standard Edition Development Kit
Description :
The Java Platform Standard Edition Development Kit (JDK) includes both
the runtime environment (Java virtual machine, the Java platform classes
and supporting files) and development tools (compilers, debuggers,
tool libraries and other tools).

The JDK is a development environment for building applications, applets
and components that can be deployed with the Java Platform Standard
Edition Runtime Environment.


Set new Java home

[dave@localhost Downloads]$ sudo  /usr/sbin/alternatives --config java

There are 2 programs which provide 'java'.

  Selection    Command
-----------------------------------------------
*+ 1           java-1.8.0-openjdk.x86_64 (/usr/lib/jvm/java-1.8.0-openjdk-1.8.0.232.b09-0.fc30.x86_64/jre/bin/java)
   2           /usr/java/jdk1.8.0_231-amd64/jre/bin/java

Enter to keep the current selection[+], or type selection number: 2
[dave@localhost Downloads]$ java -version
java version "1.8.0_231"
Java(TM) SE Runtime Environment (build 1.8.0_231-b11)
Java HotSpot(TM) 64-Bit Server VM (build 25.231-b11, mixed mode)



Get the code for sample


git clone https://github.com/openliberty/guide-maven-intro.git
cd guide-maven-intro/finish
mvn install


Start server

[dave@localhost finish]$           mvn liberty:start-server
[INFO] Scanning for projects...
[WARNING] 
[WARNING] Some problems were encountered while building the effective model for io.openliberty.guides:ServletSample:war:1.0-SNAPSHOT
[WARNING] 'parent.version' is either LATEST or RELEASE (both of them are being deprecated) @ line 8, column 18
[WARNING] 
[WARNING] It is highly recommended to fix these problems because they threaten the stability of your build.
[WARNING] 
[WARNING] For this reason, future Maven versions might no longer support building such malformed projects.
[WARNING] 
[INFO] 
[INFO] ----------------< io.openliberty.guides:ServletSample >-----------------
[INFO] Building ServletSample 1.0-SNAPSHOT
[INFO] --------------------------------[ war ]---------------------------------
[INFO] 
[INFO] --- liberty-maven-plugin:3.0.M1:start-server (default-cli) @ ServletSample ---
[INFO] CWWKM2102I: Using artifact based assembly archive : io.openliberty:openliberty-runtime:null:RELEASE:zip.
[INFO] CWWKM2102I: Using installDirectory : /git/guide-maven-intro/finish/target/liberty/wlp.
[INFO] CWWKM2102I: Using serverName : ServletSampleServer.
[INFO] CWWKM2102I: Using serverDirectory : /git/guide-maven-intro/finish/target/liberty/wlp/usr/servers/ServletSampleServer.
[INFO] CWWKM2112I: Re-using previously installed assembly.
[INFO] Copying 1 file to /git/guide-maven-intro/finish/target/liberty/wlp/usr/servers/ServletSampleServer
[INFO] CWWKM2144I: Update server configuration file server.xml from /git/guide-maven-intro/finish/src/main/liberty/config/server.xml.
[INFO] CWWKM2144I: Update server configuration file bootstrap.properties from inlined configuration.
[INFO] CWWKM2001I: server.config.dir is /git/guide-maven-intro/finish/target/liberty/wlp/usr/servers/ServletSampleServer.
[INFO] CWWKM2001I: server.output.dir is /git/guide-maven-intro/finish/target/liberty/wlp/usr/servers/ServletSampleServer.
[INFO] CWWKM2001I: Invoke command is [/git/guide-maven-intro/finish/target/liberty/wlp/bin/server, start, ServletSampleServer].
[INFO] 
[INFO] Starting server ServletSampleServer.
[INFO] Server ServletSampleServer started with process ID 18867.
[INFO] Waiting up to 30 seconds for server confirmation:  CWWKF0011I to be found in /git/guide-maven-intro/finish/target/liberty/wlp/usr/servers/ServletSampleServer/logs/messages.log
[INFO] CWWKM2010I: Searching for CWWKF0011I in /git/guide-maven-intro/finish/target/liberty/wlp/usr/servers/ServletSampleServer/logs/messages.log. This search will timeout after 30 seconds.
[INFO] CWWKM2015I: Match number: 1 is [10/26/19 10:16:29:999 CEST] 00000020 com.ibm.ws.kernel.feature.internal.FeatureManager            A CWWKF0011I: The ServletSampleServer server is ready to run a smarter planet. The ServletSampleServer server started in 1.286 seconds..
[INFO] ------------------------------------------------------------------------
[INFO] BUILD SUCCESS
[INFO] ------------------------------------------------------------------------
[INFO] Total time:  2.408 s
[INFO] Finished at: 2019-10-26T10:16:30+02:00
[INFO] ------------------------------------------------------------------------


Test server

[dave@localhost finish]$ pgrep -a java
18867 /usr/java/jdk1.8.0_231-amd64/jre/bin/java -javaagent:/git/guide-maven-intro/finish/target/liberty/wlp/bin/tools/ws-javaagent.jar -Djava.awt.headless=true -Djdk.attach.allowAttachSelf=true -jar /git/guide-maven-intro/finish/target/liberty/wlp/bin/tools/ws-server.jar ServletSampleServer


[dave@localhost finish]$ wget -O - http://localhost:9080/ServletSample/servlet
--2019-10-26 10:19:27--  http://localhost:9080/ServletSample/servlet
Resolving localhost (localhost)... ::1, 127.0.0.1
Connecting to localhost (localhost)|::1|:9080... connected.
HTTP request sent, awaiting response... 200 OK
Length: unspecified
Saving to: ‘STDOUT’

-                                          [<=>                                                                         ]       0  --.-KB/s               Hello! How are you today?
-                                          [ <=>                                                                        ]      26  --.-KB/s    in 0s      

2019-10-26 10:19:27 (2.10 MB/s) - written to stdout [26]

Monday, October 14, 2019

JAX-RS read JSON POST body parameters

 Set a Response Body in JAX-RS

https://www.baeldung.com/jax-rs-response

 

 Read JSON directly


    @POST
    @Path("listwrapper/")
    @Consumes({MediaType.APPLICATION_JSON})
    @Produces({MediaType.APPLICATION_JSON})
    public String getListViaWrapperHTTPRequest(List<String> list) {

        System.out.println("getListViaWrapperHTTPRequest");

        for(String param: list){
            System.out.println("param=" + param);
        }
        return "SOME_RESPONSE";
    }




Read HTTP request body


    @POST
    @Path("listraw/")
    @Consumes({MediaType.APPLICATION_JSON})
    @Produces({MediaType.APPLICATION_JSON})
    public String getListViaRawHTTPRequest(@Context HttpServletRequest request, byte[] bodyBytes) {

        System.out.println("getListViaRawHTTPRequest");

        System.out.println("Content-Type: " + request.getContentType().toString());

        String body = new String(bodyBytes);

        System.out.println("body=" + body);

       return "SOME_RESPONSE";

    }

Saturday, October 5, 2019

Creating a RESTful web service using Java Microprofile

 Creating a RESTful web service using Java Microprofile - OpenLiberty guide

https://openliberty.io/guides/rest-intro.html?_ga=2.32933814.922244966.1570259159-606366657.1570259159


Install latest version of Maven  on Centos 7.6 ( sample failed with 3.0.5 default version)
https://www.tecmint.com/install-apache-maven-on-centos-7/

No implementation for org.codehaus.plexus.languages.java.jpms.LocationManager was bound.
  while locating org.apache.maven.plugin.surefire.SurefirePlugin

On Fedora 30 I get following error in Maven
[INFO] ------------------------------------------------------------------------
[ERROR] Failed to execute goal net.wasdev.wlp.maven.plugins:liberty-maven-plugin:2.7:install-server (install-server) on project microprofile: Unable to resolve artifact: io.openliberty:openliberty-runtime:19.0.0.9: Could not transfer artifact io.openliberty:openliberty-runtime:zip:19.0.0.9 from/to central (https://repo.maven.apache.org/maven2): User-specified log class 'org.codehaus.mojo.pluginsupport.logging.DelegatingLog' cannot be found or is not useable. -> [Help 1]
Installing latest version of Maven removed error


Clone the tutorial  sample repo
https://github.com/eugenp/tutorials

Go to Microprofile sample
https://github.com/eugenp/tutorials/tree/master/microprofile

Follow the tutorial article
https://www.baeldung.com/eclipse-microprofile

Change versions to latest in pom.xml - check versions at https://mvnrepository.com/artifact/io.openliberty/openliberty-runtime/

tail pom.xml 
    <properties>
        <app.name>library</app.name>
        <package.file>${project.build.directory}/${app.name}-service.jar</package.file>
        <packaging.type>runnable</packaging.type>
        <microprofile.version>1.2</microprofile.version>
        <liberty-maven-plugin.version>2.7</liberty-maven-plugin.version>
        <openliberty-runtime.version>19.0.0.9</openliberty-runtime.version>
    </properties>

JsonObject - Java EE 7
https://docs.oracle.com/javaee/7/api/javax/json/JsonObject.html

Reader/Writer Java EE7 sample https://github.com/javaee-samples/javaee7-samples/tree/master/jaxrs/readerwriter-json

Compile and start the service
mvn package
java -jar target/library-service.jar


microprofile]$ java -jar target/library-service.jar
Extracting files to /home/centos/wlpExtract/library-service_1453971251685/wlp
Successfully extracted all product files.
Launching defaultServer (Open Liberty 19.0.0.9/wlp-1.0.32.cl190920190905-0148) on OpenJDK 64-Bit Server VM, version 1.8.0_222-b10 (en_US)
[AUDIT   ] CWWKE0001I: The server defaultServer has been launched.
[AUDIT   ] CWWKZ0058I: Monitoring dropins for applications.
[AUDIT   ] CWWKT0016I: Web application available (default_host): http://localhost:9080/
[AUDIT   ] CWWKZ0001I: Application microprofile-1.0-SNAPSHOT started in 1.746 seconds.
[AUDIT   ] CWWKF0012I: The server installed the following features: [cdi-1.2, jaxrs-2.0, jaxrsClient-2.0, jndi-1.0, json-1.0, jsonp-1.0, servlet-3.1].
[AUDIT   ] CWWKF0011I: The defaultServer server is ready to run a smarter planet. The defaultServer server started in 5.136 seconds.


Test the service



curl http://localhost:9080/library/books
[{"id":"0001-201910","isbn":"1","name":"Building Microservice With Eclipse MicroProfile","author":"baeldung","pages":"420"}] 

On Weblogic I got following error
Oct 07, 2019 10:16:16 AM org.glassfish.jersey.message.internal.WriterInterceptorExecutor$TerminalWriterInterceptor aroundWriteTo
SEVERE: MessageBodyWriter not found for media type=application/json, type=class java.util.ArrayList, genericType=class java.util.ArrayList.
<Oct 7, 2019, 10:16:16,652 AM CEST> <Error> <org.glassfish.jersey.message.internal.WriterInterceptorExecutor> <BEA-000000> <MessageBodyWriter not found for media type=application/json, type=class java.util.ArrayList, genericType=class java.util.ArrayList.>
Using this hint from Adam Bien solved the issue http://www.adam-bien.com/roller/abien/entry/jax_rs_returning_a_list
    @GET
    @Produces(MediaType.APPLICATION_JSON)
    public Response getAllBooks() {

        List<Book> books = bookManager.getAll();
        GenericEntity<List<Book>> list = new GenericEntity<List<Book>>(books) {
        };
        return Response.ok(list).build();
        
    }

JAX-RS JAXB JSON - convert POJO to JSON

 Guide to JAXB

https://www.baeldung.com/jaxb

Sample code
 https://github.com/eugenp/tutorials/tree/master/jaxb

Microservice sample
https://www.baeldung.com/eclipse-microprofile

In previous versions before Java EE 7 to  serialize a POJO into JSON using JAXB you  had use a custom JAXB runtime like e.g. EclipseLink MOXy:
http://www.adam-bien.com/roller/abien/entry/jaxb_json_pojo_serialization_example

 Weblogic
http://blog.bdoughan.com/2013/07/oracle-weblogic-1212-now-with.html

 https://stackoverflow.com/questions/46813309/weblogic-12-2-1-3-from-moxy-to-jackson

Java EE 6
 https://docs.oracle.com/javaee/6/tutorial/doc/gkknj.html

Java EE 7
https://docs.oracle.com/javaee/7/tutorial/jaxrs-advanced007.htm

 


Using JSON with JAX-RS and JAXB

JAX-RS can automatically read and write XML using JAXB, but it can also work with JSON data. JSON is a simple text-based format for data exchange derived from JavaScript.

For this data
 
 1
  Mattress
  Queen size mattress
  500
 
The equivalent JSON representation is:
{
    "id":"1",
    "name":"Mattress",
    "description":"Queen size mattress",
    "price":500
}
 
You can add the format application/json to the @Produces annotation in resource methods to produce responses with JSON data:

@GET
@Path("/get")
@Produces({"application/xml","application/json"})
public Product getProduct() { ... }
 
In this example the default response is XML, but the response is a JSON object if the client makes a GET request that includes this header:

Accept: application/json
 
The resource methods can also accept JSON data for JAXB annotated classes:
 
@POST
@Path("/create")
@Consumes({"application/xml","application/json"})
public Response createProduct(Product prod) { ... }
 
The client should include the following header when submitting JSON data with a POST request:

Content-Type: application/json
 
 

Weblogic 12.2.1.2 sample


https://docs.oracle.com/middleware/1221/wls/RESTF/develop-restful-service.htm#RESTF217
 
import javax.ws.rs.GET;
import javax.ws.rs.Produces;
import javax.ws.rs.Path;
...
public class BookmarkResource {
...
    @GET
    @Produces(MediaType.APPLICATION_JSON)
    public JSONObject getBookmark() {
        return asJson();
    }
...
    public JSONObject asJson() {
        try {
            return new JSONObject()
                    .put("userid", bookmarkEntity.getBookmarkEntityPK().getUserid())
                    .put("sdesc", bookmarkEntity.getSdesc())
                    .put("ldesc", bookmarkEntity.getLdesc())
                    .put("uri", bookmarkEntity.getUri());
        } catch (JSONException je){
            return null;
        }
    }
} 
 

Convert Java POJO to JSON- using Response

https://www.baeldung.com/jax-rs-response

@GET
@Path("/pojo")
public Response getPojoResponse() {
    Person person = new Person("Abhinayak", "Nepal");
    return Response
      .status(Response.Status.OK)
      .entity(person)
      .build();
}

https://stackoverflow.com/questions/28079195/how-to-get-json-representation-of-java-objects-in-jax-rs-layer-in-java-ee-7 

@GET
@Path("/books")
@Produces(MediaType.APPLICATION_JSON)
public Response getBooks()  {
    List<Book> listOfBooks = getMiscService().getbooks();
    BooksWrapper result = new BooksWrapper(listOfBooks);
    return Response.status(Response.Status.OK).entity(result).build();
}
 

Convert POJO to JSON using MessageWriter

 

Use MessageBodyWriter - see here https://www.baeldung.com/eclipse-microprofile
 
https://github.com/eugenp/tutorials/blob/master/microprofile/src/main/java/com/baeldung/microprofile/providers/BookMessageBodyWriter.java 


@Provider
@Produces(MediaType.APPLICATION_JSON)
public class BookMessageBodyWriter
  implements MessageBodyWriter {