Por Isaac Ruiz
Publicado en Julio 2016
El presente documento destalla los pasos necesarios para crear un proyecto JEE compatible con WLS 12.2.1 usando el plugin de Maven para Weblogic Server 12.2.1
Se creará un proyecto usando el arquetipo: com.oracle.weblogic.archetype:basic-webservice
El cual genera un proyecto para desplegar un WS-SOAP usando Jax-WS.
El documento asume que se cumplen con los siguientes requerimientos:
Si aún no se tiene instalado el plugin, en este link se puede ver la guía de instalación:
Weblogic 12.2.1. Instalación del plugin Maven
Si aún no tienes instalado un dominio puedes leer alguno de estos documentos:
Para este ejercicio asumimos que tenemos un Dominio básico, así que solo existe un servidor el AdminServer.
URL |
http://localhost:7001/console |
User |
weblogic |
Pwd |
welcome1 |
Servidor |
AdminServer |
Debe tener a la mano estos datos según su propia instalación.
Para crear el proyecto usaremos el procedimiento asistido proporcionado por maven.
Debemos posicionarnos en la carpeta dónde queremos crear nuestro proyecto.
Para este ejercicio usaremos como carpeta de trabajo:
C:\Workarea\spsolutions
La línea para iniciar la creación asistida:
C:\Workarea\spsolutions> mvn archetype:generate |
Esto mostrará el listado de arquetipos registrados local mente en el esquipo y, si el plugin de Maven está registrado adecuadamente, debemos ver estos arquetipos:
PS C:\Workarea\spsolutions> mvn archetype:generate [INFO] Scanning for projects... [INFO] [INFO] ------------------------------------------------------------------------ [INFO] Building Maven Stub Project (No POM) 1 [INFO] ------------------------------------------------------------------------ [INFO] [INFO] >>> maven-archetype-plugin:2.4:generate (default-cli) > generate-sources @ standalone-pom >>> [INFO] [INFO] <<< maven-archetype-plugin:2.4:generate (default-cli) < generate-sources @ standalone-pom <<< [INFO] [INFO] --- maven-archetype-plugin:2.4:generate (default-cli) @ standalone-pom --- [INFO] Generating project in Interactive mode [INFO] No archetype defined. Using maven-archetype-quickstart (org.apache.maven.archetypes:maven-archetype-quickstart:1.0) Choose archetype: 1: remote -> am.ik.archetype:maven-reactjs-blank-archetype (Blank Project for React.js) 2: remote -> am.ik.archetype:msgpack-rpc-jersey-blank-archetype (Blank Project for Spring Boot + Jersey) 3: remote -> am.ik.archetype:mvc-1.0-blank-archetype (MVC 1.0 Blank Project) ... ... 1592: remote -> us.fatehi:schemacrawler-archetype-plugin-dbconnector (-) 1593: remote -> us.fatehi:schemacrawler-archetype-plugin-lint (-) 1594: local -> com.oracle.adf.archetype:oracle-adffaces-ejb (adfFusionWebapp) 1595: local -> com.oracle.coherence.archetype:gar-maven-archetype (maven-gar-archetype) 1596: local -> com.oracle.wcportal.archetype:wsrp-portlet (wsrp-portlet) 1597: local -> com.oracle.weblogic.archetype:basic-mdb (basicMDB) 1598: local -> com.oracle.weblogic.archetype:basic-serversentevent (cdi) 1599: local -> com.oracle.weblogic.archetype:basic-webapp (basicJsf) 1600: local -> com.oracle.weblogic.archetype:basic-webapp-ejb (cdi) 1601: local -> com.oracle.weblogic.archetype:basic-webservice (basicWebservice) 1602: local -> com.oracle.weblogic.archetype:basic-websocket (cdi) 1603: local -> com.oracle.weblogic.archetype:basic-websocket-emulation (cdi) Choose a number or apply filter (format: [groupId:]artifactId, case sensitive contains): 780: |
El prompt queda en espera del número de arquetipo que queremos utilizar; para nuestro ejemplo usaremos el 1601:
1601: local -> com.oracle.weblogic.archetype:basic-webservice (basicWebservice)
basicWebservice es el nombre que tendrá nuestro war final.
Una vez elegido, el promtp inicia una serie de preguntas que debemos responder para terminar de crear el proyecto.
Define value for property 'groupId': : mx.com.spsolutions.test01 Define value for property 'artifactId': : ws01example Define value for property 'version': 1.0-SNAPSHOT: : 1.0 Define value for property 'package': mx.com.spsolutions.test01: : Confirm properties configuration: groupId: mx.com.spsolutions.test01 artifactId: ws01example version: 1.0 package: mx.com.spsolutions.test01 Y: : |
Confirmamos los datos que hemos dado de entrada:
Confirm properties configuration: groupId: mx.com.spsolutions.test01 artifactId: ws01example version: 1.0 package: mx.com.spsolutions.test01 Y: : Y |
La confirmación nos nuestra un resumen del proyecto recién creado:
Y: : Y [INFO] ---------------------------------------------------------------------------- [INFO] Using following parameters for creating project from Archetype: basic-webservice:12.2.1-0-0 [INFO] ---------------------------------------------------------------------------- [INFO] Parameter: groupId, Value: mx.com.spsolutions.test01 [INFO] Parameter: artifactId, Value: ws01example [INFO] Parameter: version, Value: 1.0 [INFO] Parameter: package, Value: mx.com.spsolutions.test01 [INFO] Parameter: packageInPathFormat, Value: mx/com/spsolutions/test01 [INFO] Parameter: package, Value: mx.com.spsolutions.test01 [INFO] Parameter: version, Value: 1.0 [INFO] Parameter: groupId, Value: mx.com.spsolutions.test01 [INFO] Parameter: artifactId, Value: ws01example [INFO] project created from Archetype in dir: C:\Workarea\spsolutions\ws01example [INFO] ------------------------------------------------------------------------ [INFO] BUILD SUCCESS [INFO] ------------------------------------------------------------------------ [INFO] Total time: 09:04 min [INFO] Finished at: 2016-05-13T11:05:44-05:00 [INFO] Final Memory: 13M/203M [INFO] ------------------------------------------------------------------------ |
Podemos ejecutar el comando <tree> (Windows 10 lo soporta) para ver el detalle de las carpetas creadas:
PS C:\Workarea\spsolutions> tree |
El siguiente paso es realizar unas modificaciones en el POM de este proyecto. Si lo abrimos veremos lo que contiene por default.
<?xml version="1.0" encoding="UTF-8"?> <project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd"> <modelVersion>4.0.0</modelVersion> <groupId>mx.com.spsolutions.test01</groupId> <artifactId>ws01example</artifactId> <version>1.0</version> <packaging>war</packaging> <name>basicWebservice</name> <!-- Start elements of Oracle products and licenses --> ……. <!-- End elements of Oracle products and licenses --> <parent> <groupId>com.oracle.weblogic.archetype</groupId> <artifactId>wls-common</artifactId> <version>12.2.1-0-0</version> </parent> <properties> <web-context-root>basicWebservice</web-context-root> <packageUrl>mx/com/spsolutions/test01</packageUrl> </properties> <build> <finalName>basicWebservice</finalName> <plugins> <plugin> <groupId>org.apache.maven.plugins</groupId> <artifactId>maven-compiler-plugin</artifactId> <version>2.3.2</version> <configuration> <source>1.6</source> <target>1.6</target> </configuration> </plugin> <plugin> <groupId>org.apache.maven.plugins</groupId> <artifactId>maven-war-plugin</artifactId> <version>2.1.1</version> <configuration> <!--Use the created web.xml--> <failOnMissingWebXml>false</failOnMissingWebXml> <!--Create the war file based on the resources created by ws-jwsc goal--> <webappDirectory>${basedir}/target/generated-${project.artifactId}</webappDirectory> </configuration> </plugin> <plugin> <groupId>com.oracle.weblogic</groupId> <artifactId>weblogic-maven-plugin</artifactId> <version>12.2.1-0-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> <!--Run ws-jwsc goal to build the JAX-WS web service--> <execution> <phase>compile</phase> <goals> <goal>ws-jwsc</goal> </goals> <configuration> <jws> <!--The web service file--> <file>SayHello.java</file> <!--Output will be a directory instead of a war file--> <explode>true</explode> <!--The name of the output directory or war file(if explode is false)--> <name>generated-${project.artifactId}</name> <contextPath>${web-context-root}</contextPath> </jws> <!--The destination directory that contains the output--> <destDir>${project.build.directory}</destDir> <!--The source directory that contains the webservice file--> <srcDir>${basedir}/src/main/java/${packageUrl}</srcDir> </configuration> </execution> <!--Deploy the application to the server--> <execution> <id>deployApp</id> <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> </configuration> </execution> </executions> </plugin> </plugins> </build> </project> |
En la tarea "compile" se puede observar la configuración que utiliza el POM para realizar el compilado de las clases usando ws-jwsc, este tipo de configuraciones son las que trae el arquetipo y ayudan a agilizar todo el ciclo de desarrollo.
El proyecto tiene solo una clase, pero es suficiente para probar el deploy en el WLS 12.2.1
Podemos observar que, el goal “deploy” está listo ya para desplegar sobre un servidor, el POM solo espera que las siguientes propiedades tengan valores:
La propiedad ${oracleServerUrl) puede omitirse si nuestro dominio escucha en el puerto por default: 7001.
Estas variables bien pueden pasarse al momento de invocar la tarea, pero, también puede definirse dentro del POM y agilizar con esto la ejecución de la tarea.
Existe un tag especial para establecer variables de entorno.
Para este ejercicio, definiremos los valores dentro del POM.
Dentro del POM agregaremos valores para ${oracleUsername} y ${oraclePassword} , adicionalmente agregaremos la propiedad ${oracleServerName} en la zona de propiedades.
Así, el tag de propiedades queda como sigue:
<properties> <web-context-root>basicWebservice</web-context-root> <packageUrl>mx/com/spsolutions/test01</packageUrl> <oracleUsername>weblogic</oracleUsername> <oraclePassword>welcome1</oraclePassword> <oracleServerName>AdminServer</oracleServerName> </properties> |
Los valores deben coincidir con los que tengan definiditos para el dominio propio.
En este ejemplo, el deploy se hará sobre el Adminserver, si se requiere realizar sobre otro servidor (o incluso un cluster) es necesario colocar el nombre que aparece en la consola web.
Ya solo falta agregar un nodo más a nuestro POM, este nodo es: <distributionManagement>
Este nodo nos ayuda a definir la ubicación del repositorio en donde debe de desplegarse nuestro proyecto, para este ejercicio seguiremos asumiendo que nuestro scope es la maquina local.
<distributionManagement> <repository> <uniqueVersion>false</uniqueVersion> <id>corp1</id> <name>SPS LOCAL</name> <url>file:///C:/Users/SP%20Solutions/.m2/repository/</url> <layout>default</layout> </repository> </distributionManagement> |
El valor más importante es la ubicación del repositorio , el valor está dado por una URL, por lo que, dado que nuestro repositorio es local, usamos el protocolo file:///
Si quieres conocer más sobre la configuración de este tag puedes revisar: https://maven.apache.org/pom.html#Distribution_Management
En este ejemplo, nuestro repositorio local se encuentra en:
C:/Users/SP Solutions/
Nuestro POM, después de estas modificaciones queda de la siguiente manera:
<?xml version="1.0" encoding="UTF-8"?> <project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd"> <modelVersion>4.0.0</modelVersion> <groupId>mx.com.spsolutions.test01</groupId> <artifactId>ws01example</artifactId> <version>1.0</version> <packaging>war</packaging> <name>basicWebservice</name> <!-- Start elements of Oracle products and licenses --> <!-- End elements of Oracle products and licenses --> <parent> <groupId>com.oracle.weblogic.archetype</groupId> <artifactId>wls-common</artifactId> <version>12.2.1-0-0</version> </parent> <properties> <web-context-root>basicWebservice</web-context-root> <packageUrl>mx/com/spsolutions/test01</packageUrl> <oracleUsername>weblogic</oracleUsername> <oraclePassword>welcome1</oraclePassword> <oracleServerName>AdminServer</oracleServerName> </properties> <distributionManagement> <repository> <uniqueVersion>false</uniqueVersion> <id>corp1</id> <name>SPS LOCAL</name> <url>file:///C:/Users/SP%20Solutions/.m2/repository/</url> <layout>default</layout> </repository> </distributionManagement> <build> <finalName>basicWebservice</finalName> <plugins> <plugin> <groupId>org.apache.maven.plugins</groupId> <artifactId>maven-compiler-plugin</artifactId> <version>2.3.2</version> <configuration> <source>1.6</source> <target>1.6</target> </configuration> </plugin> <plugin> <groupId>org.apache.maven.plugins</groupId> <artifactId>maven-war-plugin</artifactId> <version>2.1.1</version> <configuration> <!--Use the created web.xml--> <failOnMissingWebXml>false</failOnMissingWebXml> <!--Create the war file based on the resources created by ws-jwsc goal--> <webappDirectory>${basedir}/target/generated-${project.artifactId}</webappDirectory> </configuration> </plugin> <plugin> <groupId>com.oracle.weblogic</groupId> <artifactId>weblogic-maven-plugin</artifactId> <version>12.2.1-0-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> <!--Run ws-jwsc goal to build the JAX-WS web service--> <execution> <phase>compile</phase> <goals> <goal>ws-jwsc</goal> </goals> <configuration> <jws> <!--The web service file--> <file>SayHello.java</file> <!--Output will be a directory instead of a war file--> <explode>true</explode> <!--The name of the output directory or war file(if explode is false)--> <name>generated-${project.artifactId}</name> <contextPath>${web-context-root}</contextPath> </jws> <!--The destination directory that contains the output--> <destDir>${project.build.directory}</destDir> <!--The source directory that contains the webservice file--> <srcDir>${basedir}/src/main/java/${packageUrl}</srcDir> </configuration> </execution> <!--Deploy the application to the server--> <execution> <id>deployApp</id> <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> </configuration> </execution> </executions> </plugin> </plugins> </build> </project> |
En este punto ya podemos probar el deploy desde el plugin, para ello, nos colocamos en el directorio donde se encuentre el POM de nuestro proyecto recién creado.
(El dominio debe estar ya en RUNNING y asumimos que estamos en la misma maquina donde está en ejecución el servidor).
PS C:\Workarea\spsolutions\ws01example> pwd Path ---- C:\Workarea\spsolutions\ws01example PS C:\Workarea\spsolutions\ws01example> ls Directorio: C:\Workarea\spsolutions\ws01example Mode LastWriteTime Length Name ---- ------------- ------ ---- d----- 13/05/2016 11:05 src d----- 13/05/2016 12:02 target -a---- 13/05/2016 12:17 9671 pom.xml |
y ejecutamos:
mvn compile package deploy: |
La salida que obtendremos será similar a la siguiente:
PS C:\Workarea\spsolutions\ws01example> mvn clean package deploy [INFO] Scanning for projects... [INFO] [INFO] ------------------------------------------------------------------------ [INFO] Building basicWebservice 1.0 [INFO] ------------------------------------------------------------------------ [INFO] [INFO] --- maven-clean-plugin:2.5:clean (default-clean) @ ws01example --- [INFO] Deleting C:\Workarea\spsolutions\ws01example\target [INFO] [INFO] --- maven-resources-plugin:2.6:resources (default-resources) @ ws01example --- [WARNING] Using platform encoding (Cp1252 actually) to copy filtered resources, i.e. build is platform dependent! [INFO] skip non existing resourceDirectory C:\Workarea\spsolutions\ws01example\src\main\resources [INFO] [INFO] --- maven-compiler-plugin:2.3.2:compile (default-compile) @ ws01example --- [WARNING] File encoding has not been set, using platform encoding Cp1252, i.e. build is platform dependent! [INFO] Compiling 1 source file to C:\Workarea\spsolutions\ws01example\target\classes [INFO] [INFO] --- weblogic-maven-plugin:12.2.1-0-0:ws-jwsc (default) @ ws01example --- [JAM] Warning: failed to resolve class org.apache.xmlbeans.XmlObject [JAM] Warning: failed to resolve class com.bea.xml.XmlObject [JAM] Warning: failed to resolve class javax.xml.rpc.holders.Holder [EarFile] Application File : C:\Workarea\spsolutions\ws01example\target\META-INF\application.xml [INFO] [INFO] --- maven-resources-plugin:2.6:testResources (default-testResources) @ ws01example --- [WARNING] Using platform encoding (Cp1252 actually) to copy filtered resources, i.e. build is platform dependent! [INFO] skip non existing resourceDirectory C:\Workarea\spsolutions\ws01example\src\test\resources [INFO] [INFO] --- maven-compiler-plugin:2.3.2:testCompile (default-testCompile) @ ws01example --- [INFO] No sources to compile [INFO] [INFO] --- maven-surefire-plugin:2.12.4:test (default-test) @ ws01example --- [INFO] No tests to run. [INFO] [INFO] --- maven-war-plugin:2.1.1:war (default-war) @ ws01example --- [INFO] Packaging webapp [INFO] Assembling webapp [ws01example] in [C:\Workarea\spsolutions\ws01example\target\generated-ws01example] [INFO] Processing war project [INFO] Webapp assembled in [80 msecs] [INFO] Building war: C:\Workarea\spsolutions\ws01example\target\basicWebservice.war [INFO] [INFO] --- maven-resources-plugin:2.6:resources (default-resources) @ ws01example --- [WARNING] Using platform encoding (Cp1252 actually) to copy filtered resources, i.e. build is platform dependent! [INFO] skip non existing resourceDirectory C:\Workarea\spsolutions\ws01example\src\main\resources [INFO] [INFO] --- maven-compiler-plugin:2.3.2:compile (default-compile) @ ws01example --- [INFO] Nothing to compile - all classes are up to date [INFO] [INFO] --- weblogic-maven-plugin:12.2.1-0-0:ws-jwsc (default) @ ws01example --- [JAM] Warning: failed to resolve class org.apache.xmlbeans.XmlObject [JAM] Warning: failed to resolve class com.bea.xml.XmlObject [JAM] Warning: failed to resolve class javax.xml.rpc.holders.Holder [EarFile] Application File : C:\Workarea\spsolutions\ws01example\target\META-INF\application.xml [INFO] [INFO] --- maven-resources-plugin:2.6:testResources (default-testResources) @ ws01example --- [WARNING] Using platform encoding (Cp1252 actually) to copy filtered resources, i.e. build is platform dependent! [INFO] skip non existing resourceDirectory C:\Workarea\spsolutions\ws01example\src\test\resources [INFO] [INFO] --- maven-compiler-plugin:2.3.2:testCompile (default-testCompile) @ ws01example --- [INFO] No sources to compile [INFO] [INFO] --- maven-surefire-plugin:2.12.4:test (default-test) @ ws01example --- [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) @ ws01example --- [INFO] Packaging webapp [INFO] Assembling webapp [ws01example] in [C:\Workarea\spsolutions\ws01example\target\generated-ws01example] [INFO] Processing war project [INFO] Webapp assembled in [24 msecs] [INFO] Building war: C:\Workarea\spsolutions\ws01example\target\basicWebservice.war [INFO] [INFO] --- weblogic-maven-plugin:12.2.1-0-0:deploy (deployApp) @ ws01example --- [INFO] Command flags are: -noexit -deploy -username weblogic -password ******* -name basicWebservice -source Target Assignments: + basicWebservice AdminServer [INFO] [INFO] --- maven-install-plugin:2.4:install (default-install) @ ws01example --- [INFO] Installing C:\Workarea\spsolutions\ws01example\target\basicWebservice.war to C:\Users\SP Solutions\.m2\repository\mx\com\spsolutions\test01\ws01example\1.0\ws01 [INFO] Installing C:\Workarea\spsolutions\ws01example\pom.xml to C:\Users\SP Solutions\.m2\repository\mx\com\spsolutions\test01\ws01example\1.0\ws01example-1.0.pom [INFO] [INFO] --- maven-deploy-plugin:2.7:deploy (default-deploy) @ ws01example --- Uploading: |
Listo, hemos realizado un deploy directamente a nuestro dominio, específicamente al AdminServer usando el plugin de Maven,
Si entramos en nuestro server debemos ver que nuestro proyecto (basicWebservice) se encuentra desplegado.
Con esto hemos cubierto el uso básico para desplegar un proyecto usando el plugin de Maven.
Si quisiéramos deployar en un servidor que no se encuentre en http://localhost:7001, podemos agregar la propiedad: oracleServerUrl a nuestra lista de propiedades.
Por ejemplo:
<properties> <web-context-root>basicWebservice</web-context-root> <packageUrl>mx/com/spsolutions</packageUrl> <oracleMiddlewareHome></oracleMiddlewareHome> <oracleServerUrl>http://localhost:7001</oracleServerUrl> <oracleUsername>weblogic</oracleUsername> <oraclePassword>welcome1</oraclePassword> <oracleServerName>AdminServer</oracleServerName> </properties> |
Weblogic server 12c incluye nuevas herramientas para aumentar el desempeño desde la perspectiva del desarrollador JEE, tener finalmente un repositorio oficial de artefactos y tener un plugin que nos permita interactuar directamente tanto con un proyecto JEE como con el dominio que lo contiene, sin duda permitirán tener ambientes de desarrollo mucho más ágiles y sobre todo tenemos ya un mecanismo que permite la integración de otro tipo de herramientas que buscan en su conjunto incluir al WLS en el mundo de la integración continua.
Isaac Ruiz Guerra (@rugi), es programador Java yConsultor TI. Especializado en integración de sistemas, fundamentalmente relacionados con el sector financiero. Actualmente forma parte del equipo de S&P Solutions. Escribe en su blog personal xhubacubi.blogspot.com, pero también participa y pertenece a www.javahispano.org y a www.javamexico.org
Este artículo ha sido revisado por el equipo de productos Oracle y se encuentra en cumplimiento de las normas y prácticas para el uso de los productos Oracle.