Developing Applications Oracle Weblogic Server
Developing Applications Oracle Weblogic Server
14c (14.1.1.0.0)
F18296-06
June 2021
Oracle Fusion Middleware Developing Applications for Oracle WebLogic Server, 14c (14.1.1.0.0)
F18296-06
This software and related documentation are provided under a license agreement containing restrictions on
use and disclosure and are protected by intellectual property laws. Except as expressly permitted in your
license agreement or allowed by law, you may not use, copy, reproduce, translate, broadcast, modify, license,
transmit, distribute, exhibit, perform, publish, or display any part, in any form, or by any means. Reverse
engineering, disassembly, or decompilation of this software, unless required by law for interoperability, is
prohibited.
The information contained herein is subject to change without notice and is not warranted to be error-free. If
you find any errors, please report them to us in writing.
If this is software or related documentation that is delivered to the U.S. Government or anyone licensing it on
behalf of the U.S. Government, then the following notice is applicable:
U.S. GOVERNMENT END USERS: Oracle programs (including any operating system, integrated software,
any programs embedded, installed or activated on delivered hardware, and modifications of such programs)
and Oracle computer documentation or other Oracle data delivered to or accessed by U.S. Government
end users are "commercial computer software" or "commercial computer software documentation" pursuant
to the applicable Federal Acquisition Regulation and agency-specific supplemental regulations. As such,
the use, reproduction, duplication, release, display, disclosure, modification, preparation of derivative works,
and/or adaptation of i) Oracle programs (including any operating system, integrated software, any programs
embedded, installed or activated on delivered hardware, and modifications of such programs), ii) Oracle
computer documentation and/or iii) other Oracle data, is subject to the rights and limitations specified in the
license contained in the applicable contract. The terms governing the U.S. Government’s use of Oracle cloud
services are defined by the applicable contract for such services. No other rights are granted to the U.S.
Government.
This software or hardware is developed for general use in a variety of information management applications.
It is not developed or intended for use in any inherently dangerous applications, including applications that
may create a risk of personal injury. If you use this software or hardware in dangerous applications, then you
shall be responsible to take all appropriate fail-safe, backup, redundancy, and other measures to ensure its
safe use. Oracle Corporation and its affiliates disclaim any liability for any damages caused by use of this
software or hardware in dangerous applications.
Oracle and Java are registered trademarks of Oracle and/or its affiliates. Other names may be trademarks of
their respective owners.
Intel and Intel Inside are trademarks or registered trademarks of Intel Corporation. All SPARC trademarks are
used under license and are trademarks or registered trademarks of SPARC International, Inc. AMD, Epyc,
and the AMD logo are trademarks or registered trademarks of Advanced Micro Devices. UNIX is a registered
trademark of The Open Group.
This software or hardware and documentation may provide access to or information about content, products,
and services from third parties. Oracle Corporation and its affiliates are not responsible for and expressly
disclaim all warranties of any kind with respect to third-party content, products, and services unless otherwise
set forth in an applicable agreement between you and Oracle. Oracle Corporation and its affiliates will not
be responsible for any loss, costs, or damages incurred due to your access to or use of third-party content,
products, or services, except as set forth in an applicable agreement between you and Oracle.
Contents
Preface
Documentation Accessibility xvi
Conventions xvi
iii
Development Tools 1-17
Java API Reference and the wls-api.jar File 1-17
Using the wls-api.jar File 1-18
Using the weblogic.jar File 1-18
Apache Ant 1-18
Using a Third-Party Version of Ant 1-19
Changing the Ant Heap Size 1-19
Source Code Editor or IDE 1-20
Database System and JDBC Driver 1-20
Web Browser 1-20
Third-Party Software 1-20
New and Changed Features in this Release 1-21
iv
Example libclasspath Ant Task 2-16
v
Source Directory Overview 4-5
Enterprise Application Configuration 4-7
Web Applications 4-7
EJBs 4-8
Important Notes Regarding EJB Descriptors 4-9
Organizing Shared Classes in a Split Development Directory 4-10
Shared Utility Classes 4-10
Third-Party Libraries 4-10
Class Loading for Shared Classes 4-11
Generating a Basic build.xml File Using weblogic.BuildXMLGen 4-11
weblogic.BuildXMLGen Syntax 4-12
Developing Multiple-EAR Projects Using the Split Development Directory 4-13
Organizing Libraries and Classes Shared by Multiple EARs 4-13
Linking Multiple build.xml Files 4-14
Best Practices for Developing WebLogic Server Applications 4-15
vi
7 Developing Applications for Production Redeployment
What is Production Redeployment? 7-1
Supported and Unsupported Application Types 7-1
Additional Application Support 7-2
Programming Requirements and Conventions 7-2
Applications Should Be Self-Contained 7-2
Versioned Applications Access the Current Version JNDI Tree by Default 7-3
Security Providers Must Be Compatible 7-3
Applications Must Specify a Version Identifier 7-3
Applications Can Access Name and Identifier 7-4
Client Applications Use Same Version when Possible 7-4
Assigning an Application Version 7-4
Application Version Conventions 7-4
Upgrading Applications to Use Production Redeployment 7-5
Accessing Version Information 7-5
vii
Injecting a Bean 9-3
Defining the Scope of a Bean 9-4
Overriding the Scope of a Bean at the Point of Injection 9-5
Using Qualifiers 9-5
Defining Qualifiers for Implementations of a Bean Type 9-6
Applying Qualifiers to a Bean 9-7
Injecting a Qualified Bean 9-8
Providing Alternative Implementations of a Bean Type 9-9
Defining an Alternative Implementation of a Bean Type 9-9
Selecting an Alternative Implementation of a Bean Type for an Application 9-10
Applying a Scope and Qualifiers to a Session Bean 9-11
Applying a Scope to a Session Bean 9-11
Applying Qualifiers to a Session Bean 9-11
Using Producer Methods, Disposer Methods, and Producer Fields 9-12
Defining a Producer Method 9-12
Defining a Disposer Method 9-12
Defining a Producer Field 9-13
Initializing and Preparing for the Destruction of a Managed Bean 9-14
Initializing a Managed Bean 9-14
Preparing for the Destruction of a Managed Bean 9-14
Intercepting Method Invocations and Life Cycle Events of Bean Classes 9-15
Defining an Interceptor Binding Type 9-16
Defining an Interceptor Class 9-17
Identifying Methods for Interception 9-18
Enabling an Interceptor 9-19
Applying an Interceptor on a Producer 9-20
Decorating a Managed Bean Class 9-21
Defining a Decorator Class 9-21
Enabling a Decorator Class 9-23
Assigning an EL Name to a CDI Bean Class 9-23
Defining and Applying Stereotypes 9-24
Defining a Stereotype 9-25
Applying Stereotypes to a Bean 9-26
Using Events for Communications Between Beans 9-26
Defining an Event Type 9-27
Sending an Event 9-27
Handling an Event 9-28
Injecting a Predefined Bean 9-29
Injecting and Qualifying Resources 9-30
Using CDI With JCA Technology 9-32
Configuring a CDI Application 9-33
viii
Enabling and Disabling CDI 9-34
Enabling and Disabling CDI for a Domain 9-34
Implicit Bean Discovery 9-35
Enabling and Disabling Implicit Bean Discovery for a Domain 9-35
Supporting Third-Party Portable Extensions 9-36
Using the Built-in Annotation Literals 9-36
Using the Configurator Interfaces 9-37
Bootstrapping a CDI Container 9-38
ix
Application Classloader Hierarchy 12-6
Custom Module Classloader Hierarchies 12-7
Declaring the Classloader Hierarchy 12-8
User-Defined Classloader Restrictions 12-10
Servlet Reloading Disabled 12-10
Nesting Depth 12-10
Module Types 12-10
Duplicate Entries 12-11
Interfaces 12-11
Call-by-Value Semantics 12-11
In-Flight Work 12-11
Development Use Only 12-11
Individual EJB Classloader for Implementation Classes 12-11
Application Classloading and Pass-by-Value or Reference 12-12
Using a Filtering ClassLoader 12-13
What is a Filtering ClassLoader 12-13
Configuring a Filtering ClassLoader 12-14
Resource Loading Order 12-14
Resolving Class References Between Modules and Applications 12-16
About Resource Adapter Classes 12-16
Packaging Shared Utility Classes 12-16
Manifest Class-Path 12-16
Using the Classloader Analysis Tool (CAT) 12-17
Opening the CAT Interface 12-18
How CAT Analyzes Classes 12-18
Identifying Class References through Manifest Hierarchies 12-18
Sharing Applications and Modules By Using Java EE Libraries 12-20
Adding JARs to the Domain /lib Directory 12-20
x
Packaging Shared Java EE Libraries for Distribution and Deployment 13-8
Referencing Shared Java EE Libraries in an Enterprise Application 13-8
Overriding context-roots Within a Referenced Enterprise Library 13-10
URIs for Shared Java EE Libraries Deployed As a Standalone Module 13-11
Referencing Optional Packages from a Java EE Application or Module 13-12
Using weblogic.appmerge to Merge Libraries 13-14
Using weblogic.appmerge from the CLI 13-14
Using weblogic.appmerge as an Ant Task 13-14
Integrating Shared Java EE Libraries with the Split Development Directory
Environment 13-15
Deploying Shared Java EE Libraries and Dependent Applications 13-15
Web Application Shared Java EE Library Information 13-15
Using WebApp Libraries With Web Applications 13-16
Accessing Registered Shared Java EE Library Information with
LibraryRuntimeMBean 13-17
Order of Precedence of Modules When Referencing Shared Java EE Libraries 13-17
Best Practices for Using Shared Java EE Libraries 13-18
xi
16 Programming JavaMail with WebLogic Server
Overview of Using JavaMail with WebLogic Server Applications 16-1
Understanding JavaMail Configuration Files 16-2
Configuring JavaMail for WebLogic Server 16-2
Sending Messages with JavaMail 16-2
Reading Messages with JavaMail 16-3
xii
19 Using the WebSocket Protocol in WebLogic Server
Understanding the WebSocket Protocol 19-2
Limitations of the HTTP Request-Response Model 19-2
WebSocket Endpoints 19-2
Handshake Requests in the WebSocket Protocol 19-3
Messaging and Data Transfer in the WebSocket Protocol 19-3
Understanding the WebLogic Server WebSocket Implementation 19-4
WebSocket Protocol Implementation 19-4
WebLogic WebSocket Java API 19-4
Protocol Fallback for WebSocket Messaging 19-5
Sample WebSocket Applications 19-5
Overview of Creating a WebSocket Application 19-5
Creating an Endpoint 19-5
Creating an Annotated Endpoint 19-6
Creating a Programmatic Endpoint 19-7
Specifying the Path Within an Application to a Programmatic Endpoint 19-7
Handling Life Cycle Events for a WebSocket Connection 19-8
Handling Life Cycle Events in an Annotated WebSocket Endpoint 19-9
Handling a Connection Opened Event 19-10
Handling a Message Received Event 19-10
Handling an Error Event 19-12
Handling a Connection Closed Event 19-12
Handling Life Cycle Events in a Programmatic WebSocket Endpoint 19-13
Defining, Injecting, and Accessing a Resource for a WebSocket Endpoint 19-14
Sending a Message 19-16
Sending a Message to a Single Peer of an Endpoint 19-16
Sending a Message to All Peers of an Endpoint 19-17
Ensuring Thread Safety for WebSocket Endpoints 19-18
Encoding and Decoding a WebSocket Message 19-18
Encoding a Java Object as a WebSocket Message 19-19
Decoding a WebSocket Message as a Java Object 19-21
Specifying a Part of an Endpoint Deployment URI as an Application Parameter 19-23
Maintaining Client State 19-24
Configuring a Server Endpoint Programmatically 19-25
Building Applications that Use the Java API for WebSocket 19-27
Deploying a WebSocket Application 19-27
Monitoring WebSocket Applications 19-29
Using WebSockets with Proxy Servers 19-31
Writing a WebSocket Client 19-31
Writing a Browser-Based WebSocket Client 19-32
xiii
Writing a Java WebSocket Client 19-33
Configuring a WebSocket Client Endpoint Programmatically 19-33
Connecting a Java WebSocket Client to a Server Endpoint 19-35
Setting the Maximum Number of Threads for Dispatching Messages from a
WebSocket Client 19-36
Securing a WebSocket Application 19-37
Applying Verified-Origin Policies 19-37
Authenticating and Authorizing WebSocket Clients 19-38
Authorizing WebSocket Clients 19-39
Establishing Secure WebSocket Connections 19-39
Avoiding Mixed Content 19-40
Specifying Limits for a WebSocket Connection 19-40
Enabling Protocol Fallback for WebSocket Messaging 19-40
Using the JavaScript API for WebSocket Fallback in Client Applications 19-41
Configuring WebSocket Fallback 19-41
Creating a WebSocket Object 19-43
Handling Life Cycle Events for a JavaScript WebSocket Client 19-44
Sending a Message from a JavaScript WebSocket Client 19-46
Packaging and Specifying the Location of the WebSocket Fallback Client
Library 19-47
Enabling WebSocket Fallback 19-47
Migrating an Application to the JSR 356 Java API for WebSocket from the
Deprecated API 19-47
Comparison of the JSR 356 API and Proprietary WebLogic Server WebSocket
API 19-48
Converting a Proprietary WebSocket Server Endpoint to Use the JSR 356 API 19-50
Replacing the /* Suffix in a Path Pattern String 19-52
Replacing a /* Suffix that Represents Variable Path Parameters in an
Endpoint URI 19-52
Replacing a /* Suffix that Represents Additional Data for an Endpoint 19-53
Example of Converting a Proprietary WebSocket Server Endpoint to Use the
JSR 356 API 19-54
Example of Using the Java API for WebSocket with WebLogic Server 19-55
xiv
entity-mapping A-13
jdbc-connection-pool A-14
connection-factory A-15
pool-params A-16
driver-params A-22
security A-24
application-param A-25
classloader-structure A-25
listener A-25
singleton-service A-26
startup A-26
shutdown A-27
work-manager A-27
session-descriptor A-29
library-ref A-31
library-context-root-override A-32
fast-swap A-32
weblogic-application.xml Schema A-33
application.xml Schema A-33
xv
Preface
Preface
This preface describes the document accessibility features and conventions used in
this guide—Developing Applications for Oracle WebLogic Server.
Documentation Accessibility
For information about Oracle's commitment to accessibility, visit the Oracle
Accessibility Program website at http://www.oracle.com/pls/topic/lookup?
ctx=acc&id=docacc.
Conventions
The following text conventions are used in this document:
Convention Meaning
boldface Boldface type indicates graphical user interface elements
associated with an action, or terms defined in text or the glossary.
italic Italic type indicates book titles, emphasis, or placeholder variables
for which you supply particular values.
monospace Monospace type indicates commands within a paragraph, URLs,
code in examples, text that appears on the screen, or text that you
enter.
xvi
1
Overview of WebLogic Server Application
Development
Learn basic concepts about WebLogic Server applications, modules, and deployment
descriptors.
This chapter includes the following sections:
• Document Scope and Audience
• WebLogic Server and the Java EE Platform
• Overview of Java EE Applications and Modules
• Web Application Modules
• Enterprise JavaBean Modules
• Connector Modules
• Enterprise Applications
• WebLogic Web Services
• JMS and JDBC Modules
• WebLogic Diagnostic Framework Modules
• Coherence Grid Archive (GAR) Modules.
• Bean Validation.
• XML Deployment Descriptors
• Deployment Plans
• Development Tools
• New and Changed Features in this Release
1-1
Chapter 1
Overview of Java EE Applications and Modules
1-2
Chapter 1
Web Application Modules
Servlets
Servlets are Java classes that execute in WebLogic Server, accept a request from
a client, process it, and optionally return a response to the client. An HttpServlet
is most often used to generate dynamic Web pages in response to Web browser
requests.
JavaServer Pages
JavaServer Pages (JSPs) are Web pages coded with an extended HTML that makes
it possible to embed Java code in a Web page. JSPs can call custom Java classes,
known as tag libraries, using HTML-like tags. The appc compiler compiles JSPs and
translates them into servlets. WebLogic Server automatically compiles JSPs if the
servlet class file is not present or is older than the JSP source file. See Building
Modules and Applications Using wlappc.
You can also precompile JSPs and package the servlet class in a Web application
(WAR) file to avoid compiling in the server. Servlets and JSPs may require additional
helper classes that must also be deployed with the Web application.
1-3
Chapter 1
Enterprise JavaBean Modules
1-4
Chapter 1
Connector Modules
Connector Modules
Connectors (also known as resource adapters) contain the Java, and if necessary,
the native modules required to interact with an Enterprise Information System (EIS).
A resource adapter deployed to the WebLogic Server environment enables Java EE
applications to access a remote EIS. WebLogic Server application developers can use
HTTP servlets, JavaServer Pages (JSPs), Enterprise JavaBeans (EJBs), and other
APIs to develop integrated applications that use the EIS data and business logic.
To deploy a resource adapter to WebLogic Server, you must first create and configure
WebLogic Server-specific deployment descriptor, weblogic-ra.xml file, and add this to
the deployment directory. Resource adapters can be deployed to WebLogic Server
as standalone modules or as part of an enterprise application. See Enterprise
Applications.
For more information on connectors, see Developing Resource Adapters for Oracle
WebLogic Server.
Enterprise Applications
An enterprise application consists of one or more Web application modules, EJB
modules, and resource adapters. It might also include a client application.
An enterprise application can be optionally defined by an application.xml file, which
was the standard Java EE deployment descriptor for enterprise applications.
1-5
Chapter 1
WebLogic Web Services
1-6
Chapter 1
JMS and JDBC Modules
• A standard for transmitting data and Web service invocation calls between the
Web service and the user of the Web service. WebLogic JAX-WS web services
use Simple Object Access Protocol (SOAP) 1.1 as the message format and HTTP
as the connection protocol.
• A standard for describing the Web service to clients so they can invoke it.
WebLogic Web services use Web services Description Language (WSDL) 1.1,
an XML-based specification, to describe themselves.
• A standard for clients to invoke Web services—JAX-WS. See Developing JAX-WS
Web Services for Oracle WebLogic Server.
WebLogic Server also includes support for RESTful web services. For more
information about RESTful web services, see Developing and Securing RESTful Web
Services for Oracle WebLogic Server.
For more information about WebLogic Web services and the standards that are
supported, see Understanding WebLogic Web Services for Oracle WebLogic Server.
1-7
Chapter 1
Coherence Grid Archive (GAR) Modules
Then place the external diagnostic descriptor file under the URI. Using the example
above, you would place the descriptor file under d:\plan\ META-INF.
Bean Validation
The Bean Validation specification (JSR 380) defines a metadata model and API for
validating data in JavaBeans components. It is supported on both the server and Java
EE 8 client; therefore, instead of distributing validation of data over several layers,
1-8
Chapter 1
XML Deployment Descriptors
such as the browser and the server side, you can define the validation constraints in
one place and share them across the different layers.
Bean validation is not only for validating beans. In fact, it can also be used to validate
any Java object.
Bean Validation and JNDI
Where required by the Java EE specifications, the default Validator and
ValidatorFactory are located using JNDI under the names java:comp/Validator
and java:comp/ValidatorFactory. These two artifacts reflect the validation descriptor
that is in scope.
Bean Validation Configuration
Bean validation can be configured by using XML descriptors or annotation.
• Descriptors:
– Descriptor elements override corresponding annotations.
– Weblogic Server allows one descriptor per module. Therefore, an application
can have several validation descriptors but only one is allowed per module
scope.
– Validation descriptors are named validation.xml and are packaged in the
META-INF directory, except for Web modules, where the descriptor is packaged
in the WEB-INF directory.
• Annotations:
– Injection of the default Validator and ValidatorFactory is requested using
the @Resource annotation. However, not all source files are scanned for this
annotation.
– The WebLogic Connector uses bean validation internally to validate the
connector descriptors.
Once bean validation is configured, the standard set of container managed classes
for a given container will be scanned. For example, for EJBs, bean and interceptor
classes are scanned. Web application classes and ManagedBeans also support the
injection of Validator and ValidatorFactories.
For more information about the classes that support bean validation, please see
the related component specifications for the list of classes that support dependency
injection.
1-9
Chapter 1
XML Deployment Descriptors
the application development process by allowing a developer to specify within the Java
class itself how the component behaves in the container, requests for dependency
injection, and so on. Annotations are an alternative to deployment descriptors that
were required by older versions of Web applications (2.4 and earlier), enterprise
applications (1.4 and earlier), and Enterprise JavaBeans (2.x and earlier). See Using
Java EE Annotations and Dependency Injection.
However, enterprise applications fully support the use of deployment descriptors, even
though the standard Java EE ones are not required. For example, you may prefer to
use the old EJB 2.x programming model, or might want to allow further customizing
of the EJB at a later development or deployment stage; in these cases you can
create the standard deployment descriptors in addition to, or instead of, the metadata
annotations.
Modules and applications have deployment descriptors—XML documents—that
describe the contents of the directory or JAR file. Deployment descriptors are text
documents formatted with XML tags. The Java EE specifications define standard,
portable deployment descriptors for Java EE modules and applications. Oracle
defines additional WebLogic-specific deployment descriptors for deploying a module
or application in the WebLogic Server environment.
Table 1-1 lists the types of modules and applications and their Java EE-standard and
WebLogic-specific deployment descriptors.
Note:
The XML schemas for the WebLogic deployment descriptors listed in
the following table include elements from the http://xmlns.oracle.com/
weblogic/weblogic-javaee/1.7/weblogic-javaee.xsd schema, which
describes common elements shared among all WebLogic-specific
deployment descriptors.
For the most current schema information, see https://www.oracle.com/
webfolder/technetwork/weblogic/wls_14.1.1.0.0.html.
1-10
Chapter 1
XML Deployment Descriptors
1-11
Chapter 1
XML Deployment Descriptors
1-12
Chapter 1
XML Deployment Descriptors
1-13
Chapter 1
XML Deployment Descriptors
1-14
Chapter 1
XML Deployment Descriptors
When you package a module or application, you create a directory to hold the
deployment descriptors—WEB-INF or META-INF—and then create the XML deployment
descriptors in that directory.
1-15
Chapter 1
Deployment Plans
The utility generates the web.xml and weblogic.xml deployment descriptors and
places them in the WEB-INF directory, which DDInit will create if it does not already
exist.
Option Description
-d <dir> Specifies the directory to which descriptors are written.
-help Prints the standard usage message.
-quiet Turns off output messages except error messages.
-verbose Turns on additional output used for debugging.
Deployment Plans
A deployment plan is an XML document that defines an application's WebLogic
Server deployment configuration for a specific WebLogic Server environment. A
deployment plan resides outside of an application's archive file, and can apply
changes to deployment properties stored in the application's existing WebLogic Server
deployment descriptors.
Administrators use deployment plans to easily change an application's WebLogic
Server configuration for a specific environment without modifying existing Java EE or
WebLogic-specific deployment descriptors. Multiple deployment plans can be used to
1-16
Chapter 1
Development Tools
Development Tools
To develop WebLogic Server applications, you need various tools such as Java API
Reference and the wls-api.jar file, source code editor or IDE, database system and
JDBC driver, and Web browser. You also need third party tools such as Apache Ant.
This section describes required and optional tools for developing WebLogic Server
applications.
1-17
Chapter 1
Development Tools
Note:
The wls-api.jar file does not reference any Java EE classes. Oracle
provides the api.jar file with a manifest classpath that includes access to
Java EE JARs.
You may need to include the weblogic.jar file in the classpath of your development
environment to access tools such as WLST, the weblogic.Deployer utilty, and
weblogic.appc.
Apache Ant
The preferred Oracle method for building applications with WebLogic Server is Apache
Ant. Ant is a Java-based build tool. One of the benefits of Ant is that is it is extended
with Java classes, rather than shell-based commands. Oracle provides numerous Ant
extension classes to help you compile, build, deploy, and package applications using
the WebLogic Server split development directory environment.
Another benefit is that Ant is a cross-platform tool. Developers write Ant build
scripts in eXtensible Markup Language (XML). XML tags define the targets to build,
dependencies among targets, and tasks to execute in order to build the targets. Ant
libraries are bundled with WebLogic Server to make it easier for our customers to build
Java applications out of the box.
To use Ant, you must first set your environment by executing either the
setExamplesEnv.cmd (Windows) or setExamplesEnv.sh (UNIX) commands located
in the WL_SERVER\samples\domains\wl_server directory, where WL_SERVER is your
WebLogic Server installation directory.
For a complete explanation of ant capabilities, see: http://jakarta.apache.org/ant/
manual/index.html
1-18
Chapter 1
Development Tools
Note:
The Apache Jakarta Web site publishes online documentation for only the
most current version of Ant, which might be different from the version of
Ant that is bundled with WebLogic Server. Use the following command, after
setting your WebLogic environment, to determine the version of Ant bundled
with WebLogic Server:
prompt> ant -version
To view the documentation for a specific version of Ant, such as the version
included with WebLogic Server, download the Ant zip file from http://
archive.apache.org/dist/ant/binaries/ and extract the documentation.
For more information on using Ant to compile your cross-platform scripts or using
cross-platform scripts to create XML scripts that can be processed by Ant, refer to any
of the WebLogic Server examples, such as ORACLE_HOME/wlserver/samples/server/
examples/src/examples/ejb20/basic/beanManaged/build.xml, where ORACLE_HOME
represents the directory in which you installed WebLogic Server. For more information
about the WebLogic Server code examples, see Sample Applications and Code
Examples in Understanding Oracle WebLogic Server.
Also refer to the following WebLogic Server documentation on
building examples using Ant: ORACLE_HOME/wlserver/samples/server/examples/src/
examples/examples.html.
If you plan to use a different version of Ant, you can replace the appropriate
JAR file in the WL_HOME\server\lib\ant directory with an updated version of the
file (where WL_HOME refers to the main WebLogic installation directory, such as
c:\Oracle\Middleware\Oracle_Home\wlserver) or add the new file to the front of your
CLASSPATH.
If you want to set the heap size permanently, add or update the MEM_ARGS variable in
the scripts that set your environment, start WebLogic Server, and so on, as shown in
the following snippet from a Windows command script that starts a WebLogic Server
instance:
1-19
Chapter 1
Development Tools
See the scripts and commands in WL_HOME/server/bin for examples of using the
MEM_ARGS variable.
Web Browser
Most Java EE applications are designed to be executed by Web browser clients.
WebLogic Server supports the HTTP 1.1 specification and is tested with current
versions of the Firefox and Microsoft Internet Explorer browsers.
When you write requirements for your application, note which Web browser versions
you will support. In your test plans, include testing plans for each supported version.
Be explicit about version numbers and browser configurations. Will your application
support Secure Socket Layers (SSL) protocol? Test alternative security settings in the
browser so that you can tell your users what choices you support.
If your application uses applets, it is especially important to test browser configurations
you want to support because of differences in the JVMs embedded in various
browsers. One solution is to require users to install the Java plug-in so that everyone
has the same Java run-time version.
Third-Party Software
You can use third-party software products to enhance your WebLogic Server
development environment. WebLogic Developer Tools Resources provides developer
tools information for products that support the application servers.
Note:
Check with the software vendor to verify software compatibility with your
platform and WebLogic Server version.
1-20
Chapter 1
New and Changed Features in this Release
1-21
2
Using Ant Tasks to Configure and Use a
WebLogic Server Domain
Learn about how to start and stop WebLogic Server instances and configure WebLogic
Server domains using WebLogic Ant tasks in your development build scripts.
This chapter includes the following sections:
• Overview of Configuring and Starting Domains Using Ant Tasks
• Starting Servers and Creating Domains Using the wlserver Ant Task
• Configuring a WebLogic Server Domain Using the wlconfig Ant Task
• Using the libclasspath Ant Task
2-1
Chapter 2
Starting Servers and Creating Domains Using the wlserver Ant Task
WebLogic Server domain, or you can create a new single-server domain for
development by using the generateconfig=true attribute.
When you use the wlserver task in an Ant script, the task does not return control until
the specified server is available and listening for connections. If you start up a server
instance using wlserver, the server process automatically terminates after the Ant VM
terminates. If you only connect to a currently-running server using the wlserver task,
the server process keeps running after Ant completes.
The wlserver WebLogic Server Ant task extends the standard java Ant task
(org.apache.tools.ant.taskdefs.Java). This means that all the attributes of the java
Ant task also apply to the wlserver Ant task. For example, you can use the output
and error attributes to specify the name of the files to which output and standard
errors of the wlserver Ant task is written, respectively. For full documentation about
the attributes of the standard Java Ant task, see Java on the Apache Ant site (http://
ant.apache.org/manual/Tasks/java.html).
Note:
The wlserver task is predefined in the version of Ant shipped with
WebLogic Server. If you want to use the task with your own Ant
installation, add the following task definition in your build file:
<taskdef name="wlserver" classname="weblogic.ant.taskdefs.management.WLServer"/>
Note:
On UNIX operating systems, the setWLSEnv.sh command does not set
the environment variables in all command shells. Oracle recommends
that you execute this command using the Korn shell or bash shell.
2. Add a call to the wlserver task in the build script to start, shutdown, restart,
or connect to a server. See wlserver Ant Task Reference for information about
wlserver attributes and default behavior.
3. Execute the Ant task or tasks specified in the build.xml file by typing ant in the
staging directory, optionally passing the command a target argument:
prompt> ant
2-2
Chapter 2
Starting Servers and Creating Domains Using the wlserver Ant Task
Use ant -verbose to obtain more detailed messages from the wlserver task.
This target connects to an existing, running server using the indicated connection
parameters and user name/password combination:
<target name="connect-server">
<wlserver host="127.0.0.1" port="7001" username="weblogic" password="weblogic"
action="connect"/>
</target>
This target starts a WebLogic Server instance configured in the config subdirectory:
<target name="start-server">
<wlserver dir="./config" host="127.0.0.1" port="7001" action="start"/>
</target>
This target creates a new single-server domain in an empty directory, and starts the
domain's server instance:
<target name="new-server">
<delete dir="./tmp"/>
<mkdir dir="./tmp"/>
<wlserver dir="./tmp" host="127.0.0.1" port="7001"
generateConfig="true" username="weblogic" password="weblogic" action="start"/>
</target>
2-3
Chapter 2
Starting Servers and Creating Domains Using the wlserver Ant Task
2-4
Chapter 2
Starting Servers and Creating Domains Using the wlserver Ant Task
2-5
Chapter 2
Starting Servers and Creating Domains Using the wlserver Ant Task
<wlserver
host="${wls.host}"
port="${port}"
username="${wls.username}"
password="${wls.password}"
action="shutdown"
forceshutdown="true"/>
2-6
Chapter 2
Configuring a WebLogic Server Domain Using the wlconfig Ant Task
Note:
For equivalent functionality, you should use the WebLogic Scripting Tool
(WLST). See Understanding the WebLogic Scripting Tool.
2-7
Chapter 2
Configuring a WebLogic Server Domain Using the wlconfig Ant Task
• Create new MBeans, optionally storing the new MBean Object Names in Ant
properties.
• Set attribute values on a named MBean available on the Administration Server.
• Create MBeans and set their attributes in one step by nesting set attribute
commands within create MBean commands.
• Query MBeans, optionally storing the query results in an Ant property reference.
• Query MBeans and set attribute values on all matching results.
• Establish a parent/child relationship among MBeans by nesting create commands
within other create commands.
Note:
The wlconfig task is predefined in the version of Ant shipped with
WebLogic Server. If you want to use the task with your own Ant
installation, add the following task definition in your build file:
<taskdef name="wlconfig" classname="weblogic.ant.taskdefs.management.WLConfig"/>
Use ant -verbose to obtain more detailed messages from the wlconfig task.
2-8
Chapter 2
Configuring a WebLogic Server Domain Using the wlconfig Ant Task
Note:
Since WLST is the recommended tool for domain creation scripts, you
should refer to the WLST offline sample scripts that are installed with
the software. The offline scripts demonstrate how to create domains
using the domain templates and are located in the following directory:
WL_HOME\common\templates\scripts\wlst, where WL_HOME refers to the
top-level installation directory for WebLogic Server. For example, the
basicWLSDomain.py script creates a simple WebLogic domain, while
sampleMedRecDomain.py creates a domain that defines resources similar
to those used in the Avitek MedRec sample. See Understanding the
WebLogic Scripting Tool.
Main Attributes
The following table describes the main attributes of the wlconfig Ant task.
2-9
Chapter 2
Configuring a WebLogic Server Domain Using the wlconfig Ant Task
Nested Elements
wlconfig also has several elements that can be nested to specify configuration
options:
• create
• delete
• set
• get
• query
• invoke
create
The create element creates a new MBean in the WebLogic Server domain. The
wlconfig task can have any number of create elements.
A create element can have any number of nested set elements, which set attributes
on the newly-created MBean. A create element may also have additional, nested
create elements that create child MBeans.
2-10
Chapter 2
Configuring a WebLogic Server Domain Using the wlconfig Ant Task
delete
The delete element removes an existing MBean from the WebLogic Server domain.
delete takes a single attribute:
set
The set element sets MBean attributes on a named MBean, a newly-created MBean,
or on MBeans retrieved as part of a query. You can include the set element as a direct
child of the wlconfig task, or nested within a create or query element.
2-11
Chapter 2
Configuring a WebLogic Server Domain Using the wlconfig Ant Task
get
The get element retrieves attribute values from an MBean in the WebLogic Server
domain. The wlconfig task can have any number of get elements.
query
The query elements finds MBean that match a search pattern.
2-12
Chapter 2
Example of Creating a Security Realm with the wlconfig Ant Task
invoke
The invoke element invokes a management operation for one or more MBeans.
For WebLogic Server MBeans, you usually use this command to invoke operations
other than the getAttribute and setAttribute that most WebLogic Server MBeans
provide.
The invoke element has the following attributes.
2-13
Chapter 2
Using the libclasspath Ant Task
2-14
Chapter 2
Using the libclasspath Ant Task
librarydir
The following attribute is required when using this element:
dir—Specifies that all files in this directory are registered as available libraries.
library
The following attribute is required when using this element:
file—Register this file as an available library.
2-15
Chapter 2
Using the libclasspath Ant Task
2-16
3
Using the WebLogic Maven Plug-In
Apache Maven is a software tool for building and managing Java-based projects.
WebLogic Server provides support for Maven through the provisioning of plug-ins that
enable you to perform various operations on WebLogic Server from within a Maven
environment.
The weblogic-maven-plugin provides enhanced functionality to install, start and stop
servers, create domains, execute WLST scripts, and compile and deploy applications.
With the weblogic-maven-plugin, you can install WebLogic Server from within your
Maven environment to fulfill the local WebLogic Server requirement when needed.
The following sections describe using weblogic-maven-plugin:
• Installing Maven
• Configuring the WebLogic Maven Plug-In
• Maven Plug-In Goals
See Building Java EE Projects for WebLogic Server with Maven in Developing
Applications Using Continuous Integration for additional Maven documentation.
Installing Maven
To use the weblogic-maven-plugin plug-in, you must first have a functional Maven
installation and a Maven repository.
A distribution of Maven is included with WebLogic Server in the following location:
ORACLE_HOME\oracle_common\modules\org.apache.maven_relnum. This is a copy of
the standard Maven release, without any modifications. For information about the
specific version of Maven that is included in WebLogic Server, see Third-Party
Products in Oracle Fusion Middleware in Oracle® Fusion Middleware Licensing
Information User Manual.
Run the ORACLE_HOME\wlserver\server\bin\setWLSEnv script to configure Maven.
Alternatively, you can download and install your own copy of Maven from the Maven
Web site: http://maven.apache.org. Make sure you set any required variables as
detailed in that documentation, such as M2_HOME and JAVA_HOME.
Note:
The weblogic-maven-plugin sets the Java protocol handler to
weblogic.net. To use the default JDK protocol handlers, specify the system
property -DUseSunHttpHandler=true in the JVM that executes Maven. To
do this, override the environment variable MAVEN_OPTS inside the mvn.bat or
mvn.sh files to set the appropriate value. For example: set MAVEN_OPTS="-
DUseSunHttpHandler=true".
3-1
Chapter 3
Configuring the WebLogic Maven Plug-In
1. Install the Oracle Maven sync plug-in and run the push goal:
a. Change the directory
to: ORACLE_HOME\oracle_common\plugins\maven\com\oracle\maven\oracle-
maven-sync\14.1.1
b. mvn install:install-file -DpomFile=oracle-maven-sync-14.1.1.pom -
Dfile=oracle-maven-sync-14.1.1.jar
c. mvn com.oracle.maven:oracle-maven-sync:push -
DoracleHome=c:\oracle\middleware\oracle_home\
2. To validate successful installation of the plug-in, use the Maven help:describe
goal. For more information, see the Apache help plug-in describe goal
documentation.
mvn help:describe -DgroupId=com.oracle.weblogic
-DartifactId=weblogic-maven-plugin -Dversion=14.1.1-0-0
3-2
Chapter 3
Configuring the WebLogic Maven Plug-In
If you map multiple goals to the same lifecycle phase, they are typically executed in
the order you list them in the POM.
Example 3-1 Modifying the POM File
<build>
<plugins>
<plugin>
<!-- This is the configuration for the
weblogic-maven-plugin
-->
<groupId>com.oracle.weblogic</groupId>
<artifactId>weblogic-maven-plugin</artifactId>
<version>14.1.1-0-0</version>
<configuration>
<middlewareHome>/fmwhome/wls14110</middlewareHome>
</configuration>
<executions>
<!-- Execute the appc goal during the package phase -->
<execution>
<id>wls-appc</id>
<phase>package</phase>
<goals>
<goal>appc</goal>
</goals>
<configuration>
<source>${project.build.directory}/${project.name}.${project.packaging}</source>
</configuration>
</execution>
<!-- Deploy the application to the WebLogic Server in the
pre-integration-test phase
-->
<execution>
<id>wls-deploy</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>t3://127.0.0.1:7001</adminurl>
<user>weblogic</user>
<password>password</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>AdminServer</targets>
<verbose>true</verbose>
<name>${project.build.finalName}</name>
</configuration>
</execution>
<!-- Stop the application in the pre-integration-test phase -->
<execution>
<id>wls-stop-app</id>
<phase>pre-integration-test</phase>
<goals>
<goal>stop-app</goal>
</goals>
3-3
Chapter 3
Configuring the WebLogic Maven Plug-In
<configuration>
<adminurl>t3://127.0.0.1:7001</adminurl>
<user>weblogic</user>
<password>password</password>
<name>${project.build.finalName}</name>
</configuration>
</execution>
</executions>
</plugin>
</plugins>
</build>
Phase Description
Phase Goal
3-4
Chapter 3
Configuring the WebLogic Maven Plug-In
Phase Goal
verify NA
install NA
deploy NA
1 The integration-test phase has pre sub-phases that are executed before the actual execution of any
integration tests, respectively.
2 The integration-test phase has post sub-phases that are executed after the actual execution of any
integration tests, respectively.
<groupId>demo.sab</groupId>
<artifactId>maven-demo</artifactId>
<version>1.0-SNAPSHOT</version>
<packaging>war</packaging>
<name>maven-demo</name>
<properties>
<endorsed.dir>${project.build.directory}/endorsed</endorsed.dir>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
</properties>
<dependencies>
<dependency>
<groupId>com.oracle.weblogic</groupId>
<artifactId>weblogic-server-pom</artifactId>
<version>14.1.1-0-0</version>
<type>pom</type>
<scope>provided</scope>
</dependency>
</dependencies>
<build>
<plugins>
...
...
3-5
Chapter 3
Maven Plug-In Goals
</plugin>
<configuration>
</configuration>
<executions>
<execution>
<id>wls-appc</id>
<phase>package</phase>
<goals>
<goal>appc</goal>
</goals>
<configuration>
<source>${project.build.directory}/${project.name}.
${project.packaging}</source>
</configuration>
</execution>
</executions>
</plugins>
</build>
</project>
3-6
Chapter 3
Maven Plug-In Goals
appc
Full Name
com.oracle.weblogic:weblogic-maven-plugin:appc
Description
Generates and compiles the classes needed to deploy EJBs and JSPs to WebLogic
Server. Also validates the deployment descriptors for compliance with the current
specifications at both the individual module level and the application level. Does not
require a local server installation.
3-7
Chapter 3
Maven Plug-In Goals
Parameters
3-8
Chapter 3
Maven Plug-In Goals
idlNoAbstractIn boolean false When true, does not generate abstract interfaces
terfaces and methods or attributes that contain them.
Default value is: false
idlNoValueTypes boolean false Does not generate valuetypes or the methods and
attributes that contain them. Default value is:
false
idlOrbix boolean false When true, generates IDL somewhat compatible
with Orbix C++. Default value is: false
idlOverwrite boolean false When true, overwrites existing IDL files. Default
value is: false
idlVerbose boolean false When true, displays additional status information
for IDL generation. Default value is: false
idlVisibroker boolean false When true, generates IDL somewhat compatible
witih Visibroker C++. Default value is: false
ignorePlanValid boolean false When true, ignores the plan file if it does not exist.
ation
iiop boolean false When true, generates CORBA stubs for EJBs.
Default value is: false
iiopDirectory java.lang.Strin false Specifies the directory where IIOP stub files will be
g written. Default: the target directory or JAR
keepgenerated boolean false When true, preserves the generated .java files.
Default value is: false
libraries java.lang.Strin false A comma-separated list of libraries.
g
librarydir java.io.File false Registers all the files in the specified directory as
libraries.
lineNumbers boolean false When true, adds JSP line numbers to generated
class files to aid in debugging. Default value is:
false
manifest java.io.File false This parameter is deprecated in this release. Use
the standard Maven mechanism to specify the
Manifest during packaging.
maxfiles java.lang.Integ false Specifies the maximum number of generated Java
er files to be compiled at one time.
3-9
Chapter 3
Maven Plug-In Goals
noexit boolean false When true, does not exit from the execution of the
appc goal when encountering JSP compile errors.
Default value is: true
normi boolean false This parameter is deprecated in this release.
nowarn boolean false When true, suppresses compiler warnings. Default
value is: false
nowrite boolean false This parameter is deprecated in this release.
optimize boolean false When true, compiles with optimization on. Default
value is: false
output java.io.File false Specifies an alternate output archive or directory.
When not set, the output is placed in the source
archive or directory.
plan java.io.File false Specifies the path to an optional deployment plan.
quiet boolean false When true, turns off output except for errors.
runtimeFlags java.lang.Strin false Passes a list of options to the compiler.
g
serverClasspath java.lang.Strin false This parameter is deprecated in this release and
g ignored. Use the standard Maven dependency
model instead to manipulate the effective
CLASSPATH.
source java.io.File false Specifies the path to the source files. Default value
is: ${project.build.directory}/${project.artifactId}.$
{project.packaging}
sourceVersion java.lang.Strin false Limits the compatibility of the Java files to a
g JDK no higher than specified. For example "1.5".
The default value is the JDK version of the Java
compiler used.
supressCompiler boolean false This parameter is deprecated in this release and
ignored. Use the standard Maven dependency
model instead to add the target classes to the
effective CLASSPATH during a build.
targetVersion java.lang.Strin false Specifies the minimum level of the JVM required
g to run the compiled class files. For example, "1.5".
The default value is the JDK version of the Java
compiler used.
verbose boolean false When true, displays additional status information
during the compilation process. Default value is:
false
verboseJavac boolean false When true, enables verbose output from the Java
compiler. Default value is: false
weblogicHome java.lang.Strin false This parameter is deprecated in this release and
g ignored.
3-10
Chapter 3
Maven Plug-In Goals
Usage Example
The appc goal executes the WebLogic Server application compiler utility to prepare an
application for deployment.
<execution>
<id>wls-appc</id>
<phase>package</phase>
<goals>
<goal>appc</goal>
</goals>
<configuration>
<source>${project.build.directory}/${project.name}.${project.packaging}</source>
</configuration>
</execution>
create-domain
Full Name
com.oracle.weblogic:weblogic-maven-plugin:create-domain
Description
Creates a domain for WebLogic Server using a domain template. This goal supports
specifying the domain directory (the last directory determines the domain name) and
the administrative username and password. For more complex domain creation, use
the wlst goal.
3-11
Chapter 3
Maven Plug-In Goals
Note:
Beginning in version 12.2.1, there is a single unified version of WLST
that automatically includes the WLST environment from all products in the
ORACLE_HOME.
Parameters
Usage Example
Use the create-domain goal to create a WebLogic Server domain from a specified
WebLogic Server installation. You specify the location of the domain using the
domainHome configuration parameter.
3-12
Chapter 3
Maven Plug-In Goals
When creating a domain, a user name and password are required. You can specify
these using the user and password configuration parameters in your POM file or by
specifying them on the command line.
The domain name is taken from the last subdirectory specified in domainHome.
<execution>
<id>wls-create-domain</id>
<phase>pre-integration-test</phase>
<goals>
<goal>create-domain</goal>
</goals>
<configuration>
<middlewareHome>c:/dev/wls14110</middlewareHome>
<domainHome>${project.build.directory}/base_domain</domainHome>
<user>weblogic</user>
<password>password</password>
</configuration>
</execution>
Example 3-4 shows typical command output from the execution of the create-domain
goal.
Example 3-4 create-domain
mvn com.oracle.weblogic:weblogic-maven-plugin:create-domain
-DdomainHome=c:\oracle\middleware\oracle_home\user_projects\domains\maven-domain
-DmiddlewareHome=c:\oracle\middleware\oracle_home -Duser=weblogic -
Dpassword=password
[INFO] Scanning for projects...
[INFO]
[INFO] ------------------------------------------------------------------------
[INFO] Building WebLogic Server Maven Plugin 14.1.1-0-0
[INFO] ------------------------------------------------------------------------
[INFO]
[INFO] --- weblogic-maven-plugin:14.1.1-0-0:create-domain (default-cli) @
weblogic-maven-plugin ---
[INFO] [create-domain]Domain creation script:
readTemplate(r'C:/oracle/middleware/oracle_home/wlserver/common/templates/wls/
wls.jar')
set('Name', 'maven-domain')
cd('/Security/maven-domain/User/weblogic')
set('Name', 'weblogoc')
set('Password', '***')
writeDomain(r'c:/oracle/middleware/oracle_home/user_
projects/domains/maven-domain')
[INFO] [wlst]script temp file = C:/Users/user/AppData/Local/Temp/
test6066166061714573929.py
[INFO] [wlst]Executing: [cmd:[C://windows\\system32\\cmd.exe, /c,
C:\oracle\middleware\oracle_home\wlserver\common\bin\wlst.cmd
C:\Users\user\AppData\Local\Temp\test6066166061714573929.py ]]
[INFO] Process being executed, waiting for completion.
[INFO] [exec]
[INFO] [exec] Initializing WebLogic Scripting Tool (WLST) ...
[INFO] [exec]
[INFO] [exec] Welcome to WebLogic Server Administration Scripting Shell
[INFO] [exec]
[INFO] [exec] Type help() for help on available commands
[INFO] [exec]
[INFO] [wlst][cmd:[C:\\windows\\system32\\cmd.exe, /c,
C:\oracle\middleware\oracle_home\wlserver\common\bin\wlst.cmd
3-13
Chapter 3
Maven Plug-In Goals
deploy
Full Name
com.oracle.weblogic:weblogic-maven-plugin:deploy
Description
Deploys WebLogic Server applications and modules to a running server. Supports all
deployment formats; for example, WAR, JAR, RAR, and such. Does not require a local
server installation.
Parameters
examples boolean false When true, displays examples of how to use this
plug-in.
external_stage boolean false When true, indicates that the user wants to
copy the application in the server staging area
externally or using a third-party tool. When
specified, WebLogic Server looks for the application
under StagingDirectoryName(of target server)/
applicationName. Default value is: false
failOnError boolean false When true, forces the Mojo to fail the build upon
encountering an error if it would otherwise just log
the error. Default value is: true
3-14
Chapter 3
Maven Plug-In Goals
nostage boolean false When true, does not copy the deployment files to
target servers, but leaves them in a fixed location,
specified by the source parameter. By default,
nostage is true for the Administration Server and
stage is true for the Managed Server targets.
noversion boolean false When true, ignores all version related code paths on
the Administration Server. Default value is: false
nowait boolean false When true, initiates multiple tasks and then
monitors them later with the -list action. Default
value is: false
password java.lang.Strin false Specifies the administrative password.
g
plan java.lang.Strin false Specifies the path to the deployment plan.
g
remote boolean false When true, specifies that the plug-in is not running
on the same machine as the Administration Server.
In this case, the source parameter specifies a path on
the server, unless the upload parameter is also used.
Default value is: false
retiretimeout java.lang.Integ false Specifies the number of seconds before WebLogic
er Server undeploys the currently-running version of
this application or module so that clients can start
using a new version. When not specified, a graceful
retirement policy is assumed. Default value is: -1
securityModel java.lang.Strin false Specifies the security model to be used for
g this deployment, overriding the default security
model for the security realm. Possible values are:
DDOnly, CustomRoles, CustomRolesAndPolicies, and
Advanced.
3-15
Chapter 3
Maven Plug-In Goals
source java.lang.Strin false Specifies the address of the artifact to deploy. The
g address can be one of the following:
• A colon (:) separated list of
Maven coordinates of the form:
groupId:artifactId:packaging:classifier:version.
• An archive file or exploded archive directory on
the local system. For example, /home/myhome/
myapps/helloworld.war.
• A remote HTTP URL (http://foo/a/b.ear).
stage boolean false When true, indicates that the application needs
to be copied into the target server staging area
before deployment. By default, nostage is true for
the Administration Server and stage is true for the
Managed Server targets.
submoduletargets java.lang.Strin false Specifies JMS Server targets for resources defined
g within a JMS application module. Possible values
have the form: submod@mod-jms.xml@target or
submoduleName@target.
targets java.lang.Strin false Specifies a comma-separated list of targets for the
g current operation. The default is AdminServer.
3-16
Chapter 3
Maven Plug-In Goals
Usage Example
Use this goal to deploy an application.
<execution>
<id>wls-deploy</id>
<phase>pre-integration-test</phase>
<goals>
<goal>deploy</goal>
</goals>
<configuration>
<adminurl>t3://127.0.0.1:7001</adminurl>
<user>weblogic</user>
<password>password</password>
<source>${project.build.directory}/${project.build.finalName}
.${project.packaging}</source>
<targets>AdminServer</targets>
<verbose>true</verbose>
<name>${project.build.finalName}</name>
</configuration>
</execution>
mvn com.oracle.weblogic:weblogic-maven-plugin:deploy
-Dsource=C:\webservices\MySimpleEjb.jar
-Dpassword=password -Duser=weblogic
[INFO] Scanning for projects...
[INFO]
[INFO]
------------------------------------------------------------------------
[INFO] Building WebLogic Server Maven Plugin 14.1.1-0-0
[INFO]
------------------------------------------------------------------------
[INFO]
[INFO] --- weblogic-maven-plugin:14.1.1-0-0:deploy (default-cli) @
weblogic-mave
n-plugin ---
weblogic.Deployer invoked with options: -noexit -adminurl t3://
localhost:7001 -
3-17
Chapter 3
Maven Plug-In Goals
[INFO]
------------------------------------------------------------------------
[INFO] BUILD SUCCESS
[INFO]
------------------------------------------------------------------------
[INFO] Total time: 9.042s
[INFO] Finished at: Wed Aug 19 13:41:11 EDT 2015
[INFO] Final Memory: 10M/25M
distribute-app
Full Name
com.oracle.weblogic:weblogic-maven-plugin:distribute-app
Description
Prepares deployment files for deployment by copying deployment files to target
servers and validating them. Does not require a local server installation.
Parameters
examples boolean false When true, displays examples of how to use this
plug-in.
3-18
Chapter 3
Maven Plug-In Goals
nostage boolean false When true, does not copy the deployment files to
target servers, but leaves them in a fixed location,
specified by the source parameter. By default,
nostage is true for the Administration Server and
stage is true for the Managed Server targets.
noversion boolean false When true, ignores all version related code paths on
the Administration Server. Default value is: false
nowait boolean false When true, initiates multiple tasks and then
monitors them later with the -list action. Default
value is: false
password java.lang.Str false Specifies the administrative password.
ing
plan java.lang.Str false Specifies the path to the deployment plan.
ing
remote boolean false When true, specifies that the plug-in is not running
on the same machine as the Administration Server.
In this case, the source parameter specifies a path on
the server, unless the upload parameter is also used.
Default value is: false
retiretimeout java.lang.Int false Specifies the number of seconds before WebLogic
eger Server undeploys the currently-running version of
this application or module so that clients can start
using a new version. When not specified, a graceful
retirement policy is assumed. Default value is: -1
securityModel java.lang.Str false Specifies the security model to be used for
ing this deployment, overriding the default security
model for the security realm. Possible values are:
DDOnly, CustomRoles, CustomRolesAndPolicies, and
Advanced.
serverClasspath java.lang.Str false This parameter is deprecated in this release and
ing ignored.
3-19
Chapter 3
Maven Plug-In Goals
3-20
Chapter 3
Maven Plug-In Goals
<execution>
<id>wls-distribute-app</id>
<phase>pre-integration-test</phase>
<goals>
<goal>distribute-app</goal>
</goals>
<configuration>
<adminurl>t3://127.0.0.1:7001</adminurl>
<user>weblogic</user>
<password>password</password>
<source>${project.build.directory}/${project.build.finalName}
.${project.packaging}</source>
<targets>cluster1</targets>
<verbose>true</verbose>
<name>${project.build.finalName}</name>
</configuration>
</execution>
$ mvn com.oracle.weblogic:weblogic-maven-plugin:distribute-app
-Dadminurl=t3://localhost:7001 -Dstage=true -DmiddlewareHome=/maven/
wls14110
-Dname=cluster-test -Duser=weblogic -Dpassword=password -
Dtargets=cluster1
-Dsource=target/cluster-test-1.0-SNAPSHOT.war
[INFO] Scanning for projects...
[INFO]
[INFO]
------------------------------------------------------------------------
[INFO] Building cluster-test 1.0-SNAPSHOT
[INFO]
------------------------------------------------------------------------
[INFO]
[INFO] --- weblogic-maven-plugin:14.1.1-0-0:distribute-app (default-
cli) @
cluster-test ---
weblogic.Deployer invoked with options: -noexit -adminurl t3://
localhost:7001
-distribute -user weblogic -name cluster-test -source
/home/oracle/src/tests/uber-test/cluster-test/
target/cluster-test-1.0-SNAPSHOT.war -targets cluster1 -stage
<Aug 19, 2015> <Info> <J2EE Deployment SPI> <BEA-260121>
<Initiating distribute operation for application, cluster-test
[archive:
/home/oracle/src/tests/uber-test/cluster-test/
target/cluster-test-1.0-SNAPSHOT.war], to cluster1 .>
Task 0 initiated: [Deployer:149026]distribute application cluster-test
on
cluster1.
3-21
Chapter 3
Maven Plug-In Goals
[INFO]
------------------------------------------------------------------------
[INFO] BUILD SUCCESS
[INFO]
------------------------------------------------------------------------
[INFO] Total time: 6.953s
[INFO] Finished at: Wed Aug 19 14:10:00 EST 2015
[INFO] Final Memory: 15M/429M
[INFO]
------------------------------------------------------------------------
install
Full Name
com.oracle.weblogic:weblogic-maven-plugin:install
Description
Installs WebLogic Server from a JAR file.
Parameters
3-22
Chapter 3
Maven Plug-In Goals
quickStartInst boolean false Indicates that this is a quickstart installer. The quickstart
aller installer requires you to specify the artifactLocation and
installDir parameter. All other parameters are ignored
when this parameter is set to true. The default value is
false.
response java.lang.St false Deprecated. Use the responseFile parameter instead.
ring
3-23
Chapter 3
Maven Plug-In Goals
Usage Example
Use this goal to install WebLogic Server into a local directory so it can be used to
execute other goals, as well as to create a WebLogic Server domain for deploying and
testing the application represented as the Maven project.
Note:
The install goal creates a single managed server called myserver, and
does not create a domain. Most other goals, including create-domain, use
a default server name of AdminServer. You therefore need to override the
default AdminServer server name in your POM.
This goal installs WebLogic Server using a specified installation distribution. You
specify the location of the distribution using the artifactLocation configuration
parameter, which can be the location of the distribution as a file on the file system;
an HTTP URL which can be accessed; or a Maven coordinate of the distribution
installed in a Maven repository. Specify the artifactLocation configuration element
in the weblogic-maven-plugin section of the pom.xml file, or by using the –
DartifactLocation property when invoking Maven.
Example 3-7 shows an example of installing WebLogic Server using a JAR file on a
Windows-based system.
Example 3-7 Install From JAR File
mvn com.oracle.weblogic:weblogic-maven-plugin:install
-DartifactLocation=c:\wls-temp\wls_jrf_generic.jar
-DinstallDir=C:\test-maven -DresponseFile=c:\wls-temp\response.txt
[INFO] Scanning for projects...
[INFO]
[INFO]
------------------------------------------------------------------------
[INFO] Building Maven Stub Project (No POM) 1
[INFO]
------------------------------------------------------------------------
[INFO]
[INFO] --- weblogic-maven-plugin:14.1.1-0-0:install (default-cli) @
standalone-p
om ---
[INFO] [install]ORACLE_HOME = C:\test-
3-24
Chapter 3
Maven Plug-In Goals
maven\Oracle\Middleware\Oracle_Home
[INFO] Executing: [cmd:[C:\\Windows\\System32\\cmd.exe, /c,
C:\weblogic\dev\AUT
O_D~1\x86_64\JDK180~3\JDK18~1.0_4\jre\bin\java.exe -Xms1024m -Xmx1024m -
Djava.io
.tmpdir=C:\Users\user\AppData\Local\Temp\ -jar c:\wls-temp\wls_jrf_g
eneric.jar -silent -responseFile c:\wls-temp\response.txt ]]
[INFO] Process being executed, waiting for completion.
[INFO] [exec] Launcher log file is
C:\Users\user\AppData\Local\Temp\OraInsta
ll2015-04-23_09-45-13AM\launcher2015-04-23_09-45-13AM.log.
[INFO] [exec] Extracting
files..................................................
........................................................................
........
...................................
[INFO] [exec] Starting Oracle Universal Installer
[INFO] [exec]
[INFO] [exec] Checking if CPU speed is above 300 MHz. Actual 2491
Passed
[INFO] [exec] Checking swap space: must be greater than 512 MB Passed
[INFO] [exec] Checking if this platform requires a 64-bit JVM. Actual
64 Pa
ssed (64-bit not required)
[INFO] [exec]
[INFO] [exec]
[INFO] [exec] Preparing to launch the Oracle Universal Installer from
C:\Users\
user\AppData\Local\Temp\OraInstall2015-04-23_09-45-13AM
[INFO] [exec] Log:
C:\Users\user\AppData\Local\Temp\OraInstall2015-04-23_09-
45-13AM\install2015-04-23_09-45-13AM.log
[INFO] [exec] Copyright (c) 1996, 2015, Oracle and/or its affiliates.
All rights
reserved.
[INFO] [exec] Reading response file..
[INFO] [exec] -nocheckForUpdates / SKIP_SOFTWARE_UPDATES flag is passed
and henc
e skipping software update
[INFO] [exec] Skipping Software Updates...
[INFO] [exec] Starting check : CertifiedVersions
[INFO] [exec] Expected result: One of 6.1,6.2,6.3
[INFO] [exec] Actual Result: 6.1
[INFO] [exec] Check complete. The overall result of this check is:
Passed
[INFO] [exec] CertifiedVersions Check: Success.
[INFO] [exec] Starting check : CheckJDKVersion
[INFO] [exec] Expected result: 1.8.0_40
[INFO] [exec] Actual Result: 1.8.0_40-ea
[INFO] [exec] Check complete. The overall result of this check is:
Passed
[INFO] [exec] CheckJDKVersion Check: Success.
[INFO] [exec] Validations are enabled for this session.
[INFO] [exec] Verifying data......
[INFO] [exec] Copying Files...
3-25
Chapter 3
Maven Plug-In Goals
Example 3-8 shows an example of installing WebLogic Server using a JAR file and the
installCommand parameter on a Windows-based system.
mvn com.oracle.weblogic:weblogic-maven-plugin:install
-DinstallCommand="@JAVA_HOME@/bin/java -Xms512m -Xmx1024m
-jar @INSTALLER_FILE@ -silent -responseFile c:\wls-temp\response.txt"
-DartifactLocation=c:\wls-temp\wls_jrf_generic.jar
-DresponseFile=c:\wls-temp\response.txt
INFO] Scanning for projects...
[INFO]
[INFO]
------------------------------------------------------------------------
[INFO] Building Maven Stub Project (No POM) 1
[INFO]
------------------------------------------------------------------------
[INFO]
[INFO] --- weblogic-maven-plugin:14.1.1-0-0:install (default-cli) @
standalone-p
om ---
[INFO] [install]ORACLE_HOME = C:\test-
maven\Oracle\Middleware\Oracle_Home
[INFO] Executing: [cmd:[C:\\Windows\\System32\\cmd.exe, /c,
C:\weblogic\dev\AUT
O_D~1\x86_64\JDK180~3\JDK18~1.0_4\jre/bin/java -Xms512m -Xmx1024m -jar
c:\wls-t
emp\wls_jrf_generic.jar -silent -responseFile c:\wls-temp\response.txt]]
[INFO] Process being executed, waiting for completion.
[INFO] [exec] Launcher log file is
C:\Users\user\AppData\Local\Temp\OraInsta
ll2015-04-23_10-58-13AM\launcher2015-04-23_10-58-13AM.log.
[INFO] [exec] Extracting
files..................................................
........................................................................
........
.................
[INFO] [exec] Starting Oracle Universal Installer
3-26
Chapter 3
Maven Plug-In Goals
[INFO] [exec]
[INFO] [exec] Checking if CPU speed is above 300 MHz. Actual 2491
Passed
[INFO] [exec] Checking swap space: must be greater than 512 MB Passed
[INFO] [exec] Checking if this platform requires a 64-bit JVM. Actual
64 Pa
ssed (64-bit not required)
[INFO] [exec]
[INFO] [exec]
[INFO] [exec] Preparing to launch the Oracle Universal Installer from
C:\Users\
user\AppData\Local\Temp\OraInstall2015-04-23_10-58-13AM
[INFO] [exec] Log:
C:\Users\user\AppData\Local\Temp\OraInstall2015-04-23_10-
58-13AM\install2015-04-23_10-58-13AM.log
[INFO] [exec] Copyright (c) 1996, 2015, Oracle and/or its affiliates.
All rights
reserved.
[INFO] [exec] Reading response file..
[INFO] [exec] -nocheckForUpdates / SKIP_SOFTWARE_UPDATES flag is passed
and henc
e skipping software update
[INFO] [exec] Skipping Software Updates...
[INFO] [exec] Starting check : CertifiedVersions
[INFO] [exec] Expected result: One of 6.1,6.2,6.3
[INFO] [exec] Actual Result: 6.1
[INFO] [exec] Check complete. The overall result of this check is:
Passed
[INFO] [exec] CertifiedVersions Check: Success.
[INFO] [exec] Starting check : CheckJDKVersion
[INFO] [exec] Expected result: 1.8.0_40
[INFO] [exec] Actual Result: 1.8.0_40-ea
[INFO] [exec] Check complete. The overall result of this check is:
Passed
[INFO] [exec] CheckJDKVersion Check: Success.
[INFO] [exec] Validations are enabled for this session.
[INFO] [exec] Verifying data......
[INFO] [exec] Copying Files...
[INFO] [exec] -----------20%----------40%----------60%----------80%-----
Visit ht
tp://www.oracle.com/support/policies.html for Oracle Technical Support
policies.
3-27
Chapter 3
Maven Plug-In Goals
[INFO]
------------------------------------------------------------------------
list-apps
Full Name
com.oracle.weblogic:weblogic-maven-plugin:list-apps
Description
Lists the deployment names for applications and standalone modules deployed,
distributed, or installed in the domain. Does not require a local server installation.
Parameters
noversion boolean false When true, ignore all version-related code paths on
the Administration Server. Default value is: false
nowait boolean false When true, initiates multiple tasks and then monitors
them later with the -list action.
password java.lang.Strin false Specifies the administrative password.
g
remote boolean false When true, specifies that the plug-in is not running
on the same machine as the Administration Server.
In this case, the source parameter specifies a path on
the server, unless the upload parameter is also used.
serverClasspat java.lang.Strin false This parameter is deprecated in this release and
h g ignored.
3-28
Chapter 3
Maven Plug-In Goals
3-29
Chapter 3
Maven Plug-In Goals
webFragment
examplesWebApp
mainWebApp
annotation
MySimpleEjb
stockFrontEnd
jsfBeanValidation
programmaticSecurity
entityBeanValidation
faceletsJSF
bookmarkingJSF
stockAdapter
noInterfaceViewInWAR
jdbcDataSource.war
asyncMethodOfEJB
calendarStyledTimer
cdi
jaxrs
criteriaQuery
portableGlobalJNDIName
multipartFileHandling
elementCollection
Number of Applications Found : 27
[INFO] ------------------------------------------------------------------------
[INFO] BUILD SUCCESS
[INFO] ------------------------------------------------------------------------
[INFO] Total time: 8.656s
[INFO] Finished at: Wed Aug 19 11:33:51 EDT 2015
[INFO] Final Memory: 11M/28M
[INFO] ------------------------------------------------------------------------
C:\Oracle\Middleware\Oracle_Home\wlserver\server\lib>
purge-tasks
Full Name
com.oracle.weblogic:weblogic-maven-plugin:purge-tasks
Description
Flushes out retired deployment tasks.
Parameters
3-30
Chapter 3
Maven Plug-In Goals
3-31
Chapter 3
Maven Plug-In Goals
redeploy
Full Name
com.oracle.weblogic:weblogic-maven-plugin:redeploy
Description
Redeploys a running application or part of a running application. Does not require a
local server installation.
Parameters
3-32
Chapter 3
Maven Plug-In Goals
3-33
Chapter 3
Maven Plug-In Goals
3-34
Chapter 3
Maven Plug-In Goals
[INFO] ------------------------------------------------------------------------
[INFO] BUILD SUCCESS
[INFO] ------------------------------------------------------------------------
[INFO] Total time: 6.322s
[INFO] Finished at: Wed Aug 19 11:33:51 EDT 2015
remove-domain
Full Name
com.oracle.weblogic:weblogic-maven-plugin:remove-domain
Description
Removes a domain directory. The domain must not be running for this goal to
succeed. This is a convenience goal for the simple use case. If the domain is already
removed, stdout prints a status message but the goal does not fail.
Parameters
3-35
Chapter 3
Maven Plug-In Goals
start-app
Full Name
com.oracle.weblogic:weblogic-maven-plugin:start-app
Description
Starts an application deployed on WebLogic Server. Does not require a local server
installation.
Parameters
3-36
Chapter 3
Maven Plug-In Goals
submoduletarge java.lang.String false Specifies JMS Server targets for resources defined
ts within a JMS application module. Possible values
have the form: submod@mod-jms.xml@target or
submoduleName@target.
targets java.lang.String false Specifies a comma-separated list of targets for
the current operation. When not specified, all
configured targets are used. For a new application,
the default target is all targets to which the
application is deployed.
timeout java.lang.Intege false Specifies the maximum number of seconds
r WebLogic Server will wait for the deployment task
to complete. The default value of -1 means wait
forever. Default value is: -1
user java.lang.String false Specifies the administrative user name.
userConfigFile java.lang.String false Specifies the location of a user configuration file
to use for the administrative user name and
password instead of specifying the user name and
password directly in plain text.
userKeyFile java.lang.String false Specifies the location of a user key file to use
for encrypting and decrypting the user name and
password stored in the user configuration file.
3-37
Chapter 3
Maven Plug-In Goals
[INFO] ------------------------------------------------------------------------
[INFO] BUILD SUCCESS
[INFO] ------------------------------------------------------------------------
[INFO] Total time: 6.053s
[INFO] Finished at: Wed Aug 19 11:33:51 EDT 2015
[INFO] Final Memory: 10M/26M
[INFO] ------------------------------------------------------------------------
3-38
Chapter 3
Maven Plug-In Goals
start-server
Full Name
com.oracle.weblogic:weblogic-maven-plugin:start-server
Description
Starts WebLogic Server from a script in the current working directory. This is a
convenience goal for the simple use case. If the server is already started, stdout prints
a status message but the goal does not fail.
Parameters
Usage Example
The start-server goal executes a startWebLogic command on a given domain,
starting the WebLogic Server instance.
<execution>
<id>wls-wlst-start-server</id>
<phase>pre-integration-test</phase>
<goals>
<goal>start-server</goal>
</goals>
<configuration>
<domainHome>${project.build.directory}/base_domain</domainHome>
</configuration>
</execution>
3-39
Chapter 3
Maven Plug-In Goals
stop-app
Full Name
com.oracle.weblogic:weblogic-maven-plugin:stop-app
Description
Stops an application. Does not require a local server installation.
Parameters
3-40
Chapter 3
Maven Plug-In Goals
submoduletarge java.lang.String false Specifies JMS Server targets for resources defined
ts within a JMS application module. Possible values
have the form: submod@mod-jms.xml@target or
submoduleName@target.
3-41
Chapter 3
Maven Plug-In Goals
3-42
Chapter 3
Maven Plug-In Goals
@ weblogic-ma
ven-plugin ---
weblogic.Deployer invoked with options: -noexit
-adminurl t3://localhost:7001 -
stop -user weblogic -name ExampleEJB
<Aug 19, 2015> <Info>
<J2EE Deployment SPI> <BEA-260121> <Initiat
ing stop operation for application, ExampleEJB [archive: null],
to configured ta
rgets.>
Task 6 initiated: [Deployer:149026]stop application ExampleEJB on
AdminServer.
Task 6 completed: [Deployer:149026]stop application ExampleEJB on
AdminServer.
Target state: stop completed on Server AdminServer
[INFO] ------------------------------------------------------------------------
[INFO] BUILD SUCCESS
[INFO] ------------------------------------------------------------------------
[INFO] Total time: 6.028s
[INFO] Finished at: Wed Aug 19 11:33:51 EDT 2015
[INFO] Final Memory: 10M/29M
[INFO] ------------------------------------------------------------------------
C:\Oracle\Middleware\Oracle_Home\wlserver\server\lib>
stop-server
Full Name
com.oracle.weblogic:weblogic-maven-plugin:stop-server
Description
Stops WebLogic Server from a script in the current working directory. This is a
convenience goal for the simple use case. If the server is already stopped, stdout
prints a status message but the goal does not fail.
Parameters
3-43
Chapter 3
Maven Plug-In Goals
workingDir java.lang.Strin false Specifies the working directory for the script. If
g you do not specify this attribute, it defaults to
the current working directory. Default value is: $
{project.base.directory}
Usage Example
The stop-server goal stops a server instance using the stopWebLogic script in the
specified domain.
<execution>
<id>wls-wlst-stop-server</id>
<phase>post-integration-test</phase>
<goals>
<goal>stop-server</goal>
</goals>
<configuration>
<domainHome>${project.build.directory}/base_domain</domainHome>
<user>weblogic</user>
<password>password</password>
<adminurl>t3://localhost:7001</adminurl>
</configuration>
</execution>
3-44
Chapter 3
Maven Plug-In Goals
[INFO] ------------------------------------------------------------------------
[INFO]
[INFO] --- weblogic-maven-plugin:14.1.1-0-0:stop-server (default-cli)
@ weblogic
-maven-plugin ---
[INFO] Stop server in domain:
c:\oracle\middleware\oracle_home\user_projects\dom
ains\wl_server
[INFO] Process being executed, waiting for completion.
[INFO] [exec] Stopping Weblogic Server...
[INFO] [exec]
[INFO] [exec] Initializing WebLogic Scripting Tool (WLST) ...
[INFO] [exec]
[INFO] [exec] Welcome to WebLogic Server Administration Scripting Shell
[INFO] [exec]
[INFO] [exec] Type help() for help on available commands
[INFO] [exec]
[INFO] [exec] Connecting to t3://localhost:7001 with userid weblogic ...
[INFO] [exec] Successfully connected to Admin Server "AdminServer" that belongs
to domain "wl_server".
[INFO] [exec]
[INFO] [exec] Warning: An insecure protocol was used to connect to the
[INFO] [exec] server. To ensure on-the-wire security, the SSL port or
[INFO] [exec] Admin port should be used instead.
[INFO] [exec]
[INFO] [exec] Shutting down the server AdminServer with force=false while connec
ted to AdminServer ...
[INFO] [exec] WLST lost connection to the WebLogic Server that you were
[INFO] [exec] connected to, this may happen if the server was shutdown or
[INFO] [exec] partitioned. You will have to re-connect to the server once the
[INFO] [exec] server is available.
[INFO] [exec] Disconnected from weblogic server: AdminServer
[INFO] [exec] Disconnected from weblogic server:
[INFO] [exec]
[INFO] [exec]
[INFO] [exec] Exiting WebLogic Scripting Tool.
[INFO] [exec]
[INFO] [exec] Done
[INFO] [exec] Stopping Derby Server...
[INFO] [exec] Derby server stopped.
[INFO] ------------------------------------------------------------------------
[INFO] BUILD SUCCESS
[INFO] ------------------------------------------------------------------------
[INFO] Total time: 23.270s
[INFO] Finished at: Wed Aug 19 11:33:51 EDT 2015
[INFO] Final Memory: 9M/23M
[INFO] ------------------------------------------------------------------------
undeploy
Full Name
com.oracle.weblogic:weblogic-maven-plugin:undeploy
Description
Undeploys the application from WebLogic Server. Stops the deployment unit and
removes staged files from target servers. Does not require a local server installation.
3-45
Chapter 3
Maven Plug-In Goals
Parameters
ignoresession boolean false When true, ignores pending HTTP sessions during graceful
s shutdown. Can be used only when the graceful
parameter is true. Default value is: false
middlewareHom java.lang.Stri false This parameter is deprecated in this release and ignored.
e ng
name java.lang.Stri false Specifies the deployment name to assign to a newly-
ng deployed application or standalone module.
noversion boolean false When true, ignores all version-related code paths on the
Administration Server. Default value is: false
nowait boolean false When true, initiates multiple tasks and then monitors
them later with the -list action.
password java.lang.Stri false Specifies the administrative password.
ng
planversion java.lang.Stri false Specifies the version of the deployment plan. When not
ng specified, the currently active version of the application's
deployment plan is assumed.
remote boolean false When true, specifies that the plug-in is not running on
the same machine as the Administration Server. In this
case, the source parameter specifies a path on the server,
unless the upload parameter is also used. Default value is:
false
3-46
Chapter 3
Maven Plug-In Goals
3-47
Chapter 3
Maven Plug-In Goals
[INFO] ------------------------------------------------------------------------
[INFO] BUILD SUCCESS
[INFO] ------------------------------------------------------------------------
[INFO] Total time: 6.114s
[INFO] Finished at: Wed Aug 19 11:33:51 EDT 2015
[INFO] Final Memory: 9M/26M
[INFO] ------------------------------------------------------------------------
uninstall
Full Name
com.oracle.weblogic:weblogic-maven-plugin:uninstall
Description
Uninstalls WebLogic Server.
Parameters
3-48
Chapter 3
Maven Plug-In Goals
mvn com.oracle.weblogic:weblogic-maven-plugin:uninstall -
DresponseFile=c:\wls-temp\response.txt
[INFO] Scanning for projects...
[INFO]
[INFO]
------------------------------------------------------------------------
[INFO] Building Maven Stub Project (No POM) 1
[INFO]
------------------------------------------------------------------------
[INFO]
[INFO] --- weblogic-maven-plugin:14.1.1-0-0:uninstall (default-cli) @
standalone
-pom ---
[INFO] [uninstall]ORACLE_HOME = C:\test-
maven\Oracle\Middleware\Oracle_Home
[INFO] [uninstall]ORACLE_HOME = C:\test-
maven\Oracle\Middleware\Oracle_Home
[INFO] Executing: [cmd:[C:\\Windows\\System32\\cmd.exe, /c, C:\test-
maven\Oracl
e\Middleware\Oracle_Home\oui\bin\deinstall.cmd -noconsole -deinstall -
silent -re
sponseFile c:\wls-temp\response.txt]]
[INFO] Process being executed, waiting for completion.
[INFO] Installer exited with code: 0
[INFO]
------------------------------------------------------------------------
[INFO] BUILD SUCCESS
[INFO]
------------------------------------------------------------------------
update-app
Full Name
com.oracle.weblogic:weblogic-maven-plugin:update-app
3-49
Chapter 3
Maven Plug-In Goals
Description
Updates an application's deployment plan by redistributing the plan files and
reconfiguring the application based on the new plan contexts. Does not require a local
server installation.
Parameters
3-50
Chapter 3
Maven Plug-In Goals
submoduletar java.lang.String false Specifies JMS Server targets for resources defined
gets within a JMS application module. Possible values
have the form: submod@mod-jms.xml@target or
submoduleName@target.
targets java.lang.String false The targets on which to update the application or
module. This attribute can be a comma-separated list.
If no targets are specified, all targets are updated.
timeout java.lang.Intege false Specifies the maximum number of seconds WebLogic
r Server will wait for the deployment task to complete.
The default value of -1 means wait forever. Default
value is: -1
upload boolean false When true, copies the source files to the Administration
Server's upload directory prior to deployment. Use this
setting when running the plug-in remotely (using the
remote parameter) and when the user lacks normal
access to the Administration Server's file system. Default
value is: false
user java.lang.String false Specifies the administrative user name.
userConfigFi java.lang.String false Specifies the location of a user configuration file to use
le for the administrative user name and password instead
of specifying the user name and password directly in
plain text.
userKeyFile java.lang.String false Specifies the location of a user key file to use for
encrypting and decrypting the user name and password
stored in the user configuration file.
verbose boolean false When true, displays additional status information.
Default value is: false
version boolean false When true, prints the version information. Default
value is: false
weblogicHome java.lang.String false This parameter is deprecated in this release and
ignored.
3-51
Chapter 3
Maven Plug-In Goals
<goals>
<goal>update-app</goal>
</goals>
<configuration>
<adminurl>t3://127.0.0.1:7001</adminurl>
<user>weblogic</user>
<password>password</password>
<name>${project.build.finalName}</name>
<plan>${basedir}/misc/myplan.xml</plan>
</configuration>
</execution>
[INFO] ------------------------------------------------------------------------
[INFO] BUILD SUCCESS
[INFO] ------------------------------------------------------------------------
[INFO] Total time: 10.651s
[INFO] Finished at: Wed Aug 19 11:33:51 EDT 2015
[INFO] Final Memory: 18M/435M
[INFO] ------------------------------------------------------------------------
wlst
Full Name
com.oracle.weblogic:weblogic-maven-plugin:wlst
Description
This goal is a wrapper for the WLST scripting tool. It requires a server install for WLST
online commands.
3-52
Chapter 3
Maven Plug-In Goals
Parameters
3-53
Chapter 3
Maven Plug-In Goals
Usage Example
The wlst goal enables the WebLogic Scripting Tool (WLST) to be used to execute
scripts that configure resources or perform other operations on a WebLogic Server
domain. The wlst Maven goal uses the WebLogic Server WLST standard environment
so you can use it with all your existing WLST scripts.
You can use the wlst goal to execute an external WLST script specified with the
fileName configuration parameter, or you can specify a sequence of WLST commands
within the pom.xml file using the script configuration element:
<execution>
<id>wls-wlst-server</id>
<phase>post-integration-test</phase>
<goals>
<goal>wlst</goal>
</goals>
<configuration>
<middlewareHome>c:/dev/wls14110</middlewareHome>
<fileName>${project.basedir}/misc/configure_resources.py</fileName>
<args>t3://localhost:7001 weblogic password AdminServer</args>
<script>
print('This is a WLST inline script\n')
print('Next, we run a WLST script to create JMS resources on the server\n')
</script>
<executeScriptBeforeFile>true</executeScriptBeforeFile>
</configuration>
</execution>
3-54
Chapter 3
Maven Plug-In Goals
Name: cp
Driver Name: Oracle JDBC driver
DataSource: oracle.jdbc.xa.client.OracleXADataSource
Properties: {user=demo}
State: Running
[INFO] ------------------------------------------------------------------------
[INFO] BUILD SUCCESS
By default, the wlst goal is bound to the pre-integration-test phase. To override the
default phase binding for a goal, you can explicitly bind plug-in goals to a particular
life cycle phase, for example, to the post-integration-test phase, as shown below. The
pom.xml file binds the wlst goal to both the pre- and post-integration-test phases
(a dual phase target). As shown, you can run different scripts in different phases,
overriding the default settings, and make modifications according to your needs.
Example pom.xml file
3-55
Chapter 3
Maven Plug-In Goals
<project>
....
<executions>
<execution>
<id>WLS_SETUP_RESOURCES</id>
<phase>pre-integration-test</phase>
<goals>
<goal>wlst</goal>
</goals>
<configuration>
<fileName>src/main/wlst/create-datasource.py</fileName>
</configuration>
</execution>
<execution>
<id>WLS_TEARDOWN_RESOURCES</id>
<phase>post-integration-test</phase>
<goals>
<goal>wlst</goal>
</goals>
<configuration>
<fileName>src/main/wlst/remove-datasource.py</fileName>
</configuration>
</execution>
</executions>
....
</project>
wlst-client
Full Name
com.oracle.weblogic:weblogic-maven-plugin:wlst-client
Description
This goal is a WLST wrapper that does not require a local server install for WLST
online commands. If a local server install is not present, this goal supports only WLST
online commands.
Parameters
3-56
Chapter 3
Maven Plug-In Goals
If you use the wlst-client goal to run WLST scripts that contain Fusion Middleware
dependencies, you must first include the com.oracle.fmwshare dependency to pull in
the necessary libraries needed by those scripts.
The com.oracle.fmwshare dependency must be listed before any Fusion Middleware
dependencies.
For example, to run a WLST script for SOA, add a dependency on
com.oracle.fmwshare and SOA, similar to the following:
<plugin>
<groupId>com.oracle.weblogic</groupId>
<artifactId>weblogic-maven-plugin</artifactId>
<version>14.1.1-0-0</version>
3-57
Chapter 3
Maven Plug-In Goals
<executions>
<execution>
<id>soa-wlst-client</id>
<goals>
<goal>wlst-client</goal>
</goals>
<configuration>
<fileName>${project.basedir}/misc/doSoaStuff.py</fileName>
<scriptArgs>
<scriptArg>${adminUserName}</scriptArg>
<scriptArg>${adminPassword}</scriptArg>
<scriptArg>${adminUrl}</scriptArg>
</scriptArgs>
</configuration>
</execution>
</executions>
<dependencies>
<dependency>
<groupId>com.oracle.fmwshare</groupId>
<artifactId>fmwshare-wlst-dependencies</artifactId>
<version>14.1.1-0-0</version>
<type>pom</type>
</dependency>
<dependency>
<groupId>com.oracle.soa</groupId>
<artifactId>soa-wlst-dependencies</artifactId>
<version>14.1.1-0-0</version>
<type>pom</type>
</dependency>
</dependencies>
</plugin>
Usage Example
The wlst-client goal enables the WebLogic Scripting Tool (WLST) to be used to
execute scripts that configure resources or perform other operations on a WebLogic
Server domain. The wlst-client goal does not require a local server install for WLST
online commands.
The wlst-client Maven goal uses the WebLogic Server WLST standard environment
so you can use it with all your existing WLST scripts.
You can use the wlst-client goal to execute an external WLST script specified
with the fileName configuration parameter, you can specify a sequence of WLST
commands within the pom.xml file using the script configuration element, or you can
use both mechanisms.
For example:
<execution>
<id>wls-wlst-server</id>
<phase>post-integration-test</phase>
<goals>
<goal>wlst-client</goal>
</goals>
<configuration>
<fileName>${project.basedir}/misc/configure_resources.py</fileName>
<args>t3://some-host:7001 weblogic password AdminServer</args>
<script>
print('This is a WLST inline script\n')
3-58
Chapter 3
Maven Plug-In Goals
Name: cp
Driver Name: Oracle JDBC driver
DataSource: oracle.jdbc.xa.client.OracleXADataSource
Properties: {user=demo}
State: Running
3-59
Chapter 3
Maven Plug-In Goals
[INFO] ------------------------------------------------------------------------
[INFO] BUILD SUCCESS
As another example, assume that you have the following simple WLST script:
try:
connect('weblogic','password','t3://10.151.69.120:7001')
listApplications()
print('TEST PASS')
except:
print('TEST FAIL')
You can supply this WLST script with the fileName configuration parameter, as shown
in Example 3-22.
Example 3-22 wlst-client Script Example
C:\Oracle\Middleware\Oracle_Home\oracle_common\plugins\maven\com\oracle\maven\or
acle-maven-sync\14.1.1>mvn com.oracle.weblogic:weblogic-maven-plugin:wlst-client
-DfileName=test.py
[INFO] Scanning for projects...
[INFO]
[INFO] ------------------------------------------------------------------------
[INFO] Building Maven Stub Project (No POM) 1
[INFO] ------------------------------------------------------------------------
[INFO]
[INFO] --- weblogic-maven-plugin:14.1.1-0-0:wlst-client (default-cli) @ standalo
ne-pom ---
[INFO] [wlst-client]No middlewareHome specified.
Connecting to t3://10.151.69.120:7001 with userid weblogic ...
Successfully connected to Admin Server "AdminServer" that belongs to domain "bas
e_domain".
jaxwsejb30ws
TEST PASS
[INFO] ------------------------------------------------------------------------
[INFO] BUILD SUCCESS
[INFO] ------------------------------------------------------------------------
[INFO] Total time: 29.197s
[INFO] Finished at: Wed Aug 19 11:33:51 EDT 2020
[INFO] Final Memory: 18M/45M
By default, the wlst goal is bound to the pre-integration-test phase. To override the
default phase binding for a goal, you can explicitly bind plug-in goals to a particular
life cycle phase, for example, to the post-integration-test phase, as shown below. The
pom.xml file binds the wlst goal to both the pre- and post-integration-test phases
(a dual phase target). As shown, you can run different scripts in different phases,
overriding the default settings, and make modifications according to your needs.
Example pom.xml file
<project>
....
<executions>
<execution>
<id>WLS_SETUP_RESOURCES</id>
<phase>pre-integration-test</phase>
3-60
Chapter 3
Maven Plug-In Goals
<goals>
<goal>wlst</goal>
</goals>
<configuration>
<fileName>src/main/wlst/create-datasource.py</fileName>
</configuration>
</execution>
<execution>
<id>WLS_TEARDOWN_RESOURCES</id>
<phase>post-integration-test</phase>
<goals>
<goal>wlst</goal>
</goals>
<configuration>
<fileName>src/main/wlst/remove-datasource.py</fileName>
</configuration>
</execution>
</executions>
....
</project>
exit() is Trapped
exit() exits WLST from the user session and closes the scripting shell. By default,
WLST calls System.exit(0) for the current WLST JVM when exiting WLST. Because
wlst-client runs inside the same JVM as the Maven build process, the entire Maven
build process would exit. To provide for this, the Maven implementation traps WLST
exit() calls and throws an exception.
jaxwsejb30ws
TEST FAIL
[INFO] ------------------------------------------------------------------------
[INFO] BUILD SUCCESS
[INFO] ------------------------------------------------------------------------
[INFO] Total time: 29.250s
[INFO] Finished at: Wed Aug 19 11:33:51 EDT 2020
3-61
Chapter 3
Maven Plug-In Goals
ws-clientgen
Deprecated
This goal is deprecated in this release.
Full Name
com.oracle.weblogic:weblogic-maven-plugin:ws-clientgen
Description
Parameters
Table 3-22 briefly describes the ws-clientgen parameters. These parameters are
more fully described in Table 2-3 WebLogic-specific Attributes of the clientgen Ant
Task in WebLogic Web Services Reference for Oracle WebLogic Server.
3-62
Chapter 3
Maven Plug-In Goals
includeJavaR boolean false Specifies whether to include the default run-time libraries
untime from the executing VM in the classpath.
jmstransport JMSTransportCli false Invoking a WebLogic Web service using JMS transport.
client ent Table 3-25 describes the parameters of the
jmstransportclient parameter.
packageName java.lang.Strin false Specifies the package name into which the generated client
g interfaces and stub files are packaged.
3-63
Chapter 3
Maven Plug-In Goals
destinationType java.lang.Stri false Valid values include: QUEUE or TOPIC. Default value is
ng QUEUE.
replyToName java.lang.Stri false JNDI name of the JMS destination to which the response
ng message is sent.
3-64
Chapter 3
Maven Plug-In Goals
Usage Example
The ws-clientgen goal generates client Web service artifacts from a WSDL.
3-65
Chapter 3
Maven Plug-In Goals
<goals>
<goal>ws-clientgen</goal>
</goals>
<configuration>
<wsdl>${basedir}/AddNumbers.wsdl</wsdl>
<dest${project.build.outputDirectory}</destDir>
<packageName>maven_plugin.simple.client</packageName>
</configuration>
</execution>
</executions>
</plugin>
</plugins>
</build>
</project>
3-66
Chapter 3
Maven Plug-In Goals
wsgen
Full Name
com.oracle.weblogic:weblogic-maven-plugin:wsgen
Description
Maven goal that reads a JAX-WS service endpoint implementation class and
generates all of the portable artifacts for a JAX-WS Web service. Use the wsgen goal
when you are starting from Java classes.
You can then package the service endpoint interface and implementation class, value
types, and generated classes, if any, into a WAR file, and deploy the WAR to a Web
container.
The wsgen goal provides a wrapper for the JAX-WS Maven wsgen plug-in goal.
Parameters
Table 3-26 describes the wsgen parameters.
3-67
Chapter 3
Maven Plug-In Goals
Usage Example
The wsgen goal reads a JAX-WS service endpoint implementation class and generates
all of the portable artifacts for a JAX-WS Web service.
Specify the Maven process-classes life cycle phase. Then, run mvn process-classes
in the same directory of the POM file.
3-68
Chapter 3
Maven Plug-In Goals
To do this, modify the pom.xml file to specify the process-classes life cycle phase,
the wsgen goal, and include any parameters you need to set. Consider the following
example:
3-69
Chapter 3
Maven Plug-In Goals
target
classes
3-70
Chapter 3
Maven Plug-In Goals
META-INF
wsdl
IPInfoService.wsdl
IPInfoService_schema1.xsd
myexample
IPInfo.class
generated-sources
wsdl
IPInfoService.wsdl
IPInfoService_schema1.xsd
wsgen
myexample
jaxws
GetIpAddress.java
GetIpAddressResponse.java
wsgenoutput
myexample
jaxws
GetIpAddress.class
GetIpAddressResponse.class
wsimport
Full Name
com.oracle.weblogic:weblogic-maven-plugin:wsimport
Description
Maven goal that parses a WSDL and binding files and generates the Java code
needed to access it. Use the wsimport goal when you are starting from a WSDL.
The wsimport goal provides a wrapper for the JAX-WS Maven wsimport goal.
Parameters
Table 3-27 describes the wsimport parameters.
3-71
Chapter 3
Maven Plug-In Goals
3-72
Chapter 3
Maven Plug-In Goals
...
<configuration>
<wsdlDirectory>src/mywsdls</
wsdlDirectory>
<wsdlFiles>
<wsdlFile>a.wsdl</wsdlFile>
<wsdlFile>b/b.wsdl</wsdlFile>
<wsdlFile>${basedir}/src/mywsdls/
c.wsdl</wsdlFile>
</wsdlFiles>
<wsdlLocation>http://example.com/
mywebservices/*</wsdlLocation>
</configuration>
...
3-73
Chapter 3
Maven Plug-In Goals
Usage Example
The wsimport goal parses a WSDL and binding files and generates Java code needed
to access the Web service.
You can use the wsimport goal in two ways:
• To generate the client-side artifacts. Then, implement the client to invoke the Web
service.
• To create your own implementation of the Web service. Use wsimport goal with
the genJWS parameter to generate portable artifacts and a stubbed implementation
file. You then implement the service endpoint.
Specify the Maven generate-sources life cycle phase. Then, run mvn generate-
sources in the same directory of the POM file.
Assume that you want to import the WSDL shown in Example 3-25.
Example 3-25 WSDL to Import
3-74
Chapter 3
Maven Plug-In Goals
<soapjms:jndiInitialContextFactory>weblogic.jndi.WLInitialContextFactory
</soapjms:jndiInitialContextFactory>
<soapjms:jndiConnectionFactoryName>com.oracle.webservices.api.jms.Connec
tionFactory</soapjms:jndiConnectionFactoryName>
<soapjms:jndiUrl>t3://localhost:7001</soapjms:jndiUrl>
<soapjms:bindingVersion>SOAP_JMS_1_0</soapjms:bindingVersion>
<soapjms:destinationName>com.oracle.webservices.api.jms.RequestQueue</
soapjms:destinationName>
<soapjms:targetService>SampleWs</soapjms:targetService>
<soapjms:timeToLive>180000</soapjms:timeToLive>
<soapjms:deliveryMode>PERSISTENT</soapjms:deliveryMode>
<soapjms:priority>0</soapjms:priority>
<soapjms:messageType>BYTES</soapjms:messageType>
<soapjms:destinationType>QUEUE</soapjms:destinationType>
<soap:binding transport="http://www.w3.org/2010/soapjms/"
style="document"/>
<operation name="hello">
<soap:operation soapAction=""/>
<input>
<soap:body use="literal"/>
</input>
<output>
3-75
Chapter 3
Maven Plug-In Goals
<soap:body use="literal"/>
</output>
</operation>
</binding>
<service name="SampleWs">
<port name="SampleWsPort" binding="tns:SampleWsPortBinding">
<soap:address
location="jms:jndi:com.oracle.webservices.api.jms.RequestQueue?
targetService=Sampl
eWs&jndiURL=t3://
localhost:7001&messageType=BYTES&deliveryMode=PERSISTENT"/>
</port>
</service>
</definitions>
To import this WSDL, modify the pom.xml file to specify the generate-sources life
cycle phase, the wsimport goal, the WSDL location, and include any parameters you
need to set. This example uses a local WSDL file for demonstration purposes.
Consider the following example:
3-76
Chapter 3
Maven Plug-In Goals
Generating code...
[INFO]
------------------------------------------------------------------------
[INFO] BUILD SUCCESS
[INFO]
------------------------------------------------------------------------
[INFO] Total time: 20.888s
[INFO] Finished at: Finished at: Wed Aug 19 11:33:51 EDT 2015
[INFO] Final Memory: 7M/23M
[INFO]
------------------------------------------------------------------------
org
my
wls
web
ws
SampleWs_SampleWsPortImpl.java
target
classes
3-77
Chapter 3
Maven Plug-In Goals
generated-sources
wsimport
org
my
wls
web
ws
Hello.java
HelloResponse.java
ObjectFactory.java
package-info.java
SampleWs.java
SampleWs_Service.java
jaxws
stale
.2b48c6ef28bc8a45aa2da4246c0c4ac90cf82c57
ws-wsdlc
Deprecated
This goal is deprecated in this release.
Full Name
com.oracle.weblogic:weblogic-maven-plugin:ws-wsdlc
Description
Maven goal to generate a set of artifacts and a partial Java implementation of the Web
service from a WSDL.
The ws-wsdlc goal provides a Maven wrapper for the wsdlc Ant task, which is
described in WebLogic Web Services Reference for Oracle WebLogic Server.
Parameters
Table 3-28 briefly describes the ws-wsdlc parameters. These parameters are more
fully described in Table 2-3 WebLogic-specific Attributes of the clientgen Ant Task in
WebLogic Web Services Reference for Oracle WebLogic Server.
3-78
Chapter 3
Maven Plug-In Goals
destJavadocD java.lang.Stri false Specifies the directory into which the Javadoc that
ir ng describes the JWS interface is generated.
destJwsDir java.lang.Stri true Specifies the directory into which the JAR file that contains
ng the JWS interface and data binding artifacts should be
generated.
explode boolean false Specifies the flag to set if you want exploded output.
Defaults to true.
failOnError boolean false Specifies whether the ws-clientgen goal continues
executing in the event of an error. The default value is
true
fork boolean false Specifies whether to execute javac using the JDK compiler
externally. The default value is false.
includeAntRu boolean false Specifies whether to include the Ant run-time libraries in
ntime the classpath. The default value is true.
includeJavaR boolean false Specifies whether to include the default run-time libraries
untime from the executing VM in the classpath. The default value
is false.
optimize boolean false Specifies the flag to set if you want optimization. Defaults
to true.
packageName java.lang.Stri false Specifies the package into which the generated JWS
ng interface and implementation files should be generated.
srcPortName java.lang.Stri false Specifies the name of the WSDL port from which the JWS
ng interface file should be generated. Set the value of this
parameter to the value of the name parameter of the port
parameter that corresponds to the Web service port for
which you want to generate a JWS interface file.
The port parameter is a child of the service parameter
in the WSDL file. If you do not specify this attribute,
ws-wsdlc generates a JWS interface file from the service
specified by srcServiceName.
srcServiceNa java.lang.Stri false Specifies the name of the Web service from which the JWS
me ng interface file should be generated.
srcWsdl java.lang.Stri true Specifies the name of the WSDL from which to generate
ng the JAR file that contains the JWS interface and data
binding artifacts.
verbose boolean false Specifies the flag to set if you want verbose output. Default
value is false.
3-79
Chapter 3
Maven Plug-In Goals
Usage Example
The ws-wsdlc goal generates a set of artifacts and a partial Java implementation of the
Web service from a WSDL.
This goal benefits from the convention-over-configuration approach, allowing you to
execute it using the defaults of the project.
There are two ways to run the ws-wsdlc goal:
• From the command line. For example, after you define an alias:
mvn –DvariableName1=value1 –DvariableName2=value2
com.oracle.weblogic:weblogic-maven-plugin:ws-wsdlc
• By specifying the Maven generate-resources life cycle phase.
To do this, modify the pom.xml file to specify the generate-resources life cycle
phase, the ws-wsdlc goal, and include any parameters you need to set. Then run
mvn generate-resources in the same directory of pom.xml.
3-80
Chapter 3
Maven Plug-In Goals
ws-jwsc
Deprecated
This goal is deprecated in this release.
Full Name
com.oracle.weblogic:weblogic-maven-plugin:ws-jwsc
Description
Maven goal to build a JAX-WS web service.
The ws-jwsc goal provides a Maven wrapper for the jwsc Ant task, which is described
in WebLogic Web Services Reference for Oracle WebLogic Server.
Note:
The ws-jwsc goal does not work with the JAX-RPC-only JWS annotations
described in WebLogic-Specific Annotations
3-81
Chapter 3
Maven Plug-In Goals
<module>
<name>pocreate</name>
<contextPath>mypub</contextPath>
<compiledWsdl>D:\maven-test\order_wsdl.jar</
compiledWsdl >
<jws>
<file>examples/wsee/jwsc/POCreateImpl.java</file>
<transportType>
<type>WLHttpTransport</type>
<serviceUri>POCreate</serviceUri>
<portName>POCreatePort</portName>
</transportType>
</jws>
<jws>
…
</jws>
<descriptors>
<descriptor>"resources/web.xml"<descriptor/>
<descriptor>"resources/weblogic.xml"<descriptor />
3-82
Chapter 3
Maven Plug-In Goals
</descriptors>
</module>
<module>
…
</module>
</modules>
</configuration>
</execution>
</executions>
</plugin>
</plugins>
</build>
</project>
These nested configuration elements for ws-jwsc have the following conditions:
• You must use at least one of the following elements: jws, jwses, module, or
modules.
• Collection elements such as jwses and modules elements can be omitted.
• If there is only one child element within the collection element, the collection
element can also be removed.
For example, if there is only one jws element, use jws. If there are multiple jws
elements, add all of the jws elements under a jwses element.
• As with the JWSC ant task, if module has only one jws child element, then other
sub elements of module can be nested into jwsc and jwsc/transportType.
Example 3-29 shows an example without a module element in which the jws
parameter is a child of ws-jwsc.
3-83
Chapter 3
Maven Plug-In Goals
${project.build.finalName}</destDir>
<jws> <!-- no parent <module> -->
<file>examples/wsee/jwsc/POCreateImpl.java</file>
<compiledWsdl>${project.build.directory}/
purchaseorder_wsdl.jar>
<transportType>
<type>WLHttpTransport</type>
</transportType>
</jws>
</configuration>
</execution>
</executions>
</plugin>
</plugins>
</build>
</project>
ws-jwsc Parameters
Table 3-29 briefly describes the ws-jwsc parameters. These parameters are more
fully described in Table 2-3 WebLogic-specific Attributes of the clientgen Ant Task in
WebLogic Web Services Reference for Oracle WebLogic Server.
3-84
Chapter 3
Maven Plug-In Goals
srcEncoding java.lang.Str false Specifies the character encoding of the input files, such as the
ing JWS file or configuration XML files.
Examples of character encodings are SHIFT-JIS and UTF-8. The
default value of this attribute is the character encoding set for
the JVM.
verbose boolean false Specifies verbose output
jws Parameter
As described in jws, the jws parameter specifies the name of a JWS file that
implements your Web service and for which the ws-jwsc goal should generate Java
code and supporting artifacts, and then package them into a deployable WAR file
inside of an Enterprise Application.
You can specify the jws parameter in two ways:
• An immediate child element of the ws-jwsc goal. In this case, ws-jwsc generates
a separate WAR file for each JWS file. You typically use this method if you are
specifying just one JWS file to the ws-jwsc goal.
• A child element of the module parameter, which in turn is a child of the ws-jwsc
goal. In this case, ws-jwsc generates a single WAR file that includes all the
generated code and artifacts for all the JWS files grouped within the module
parameter.
This method is useful if you want all JWS files to share supporting files, such as
common Java data types.
Table 3-30 describes the child parameters of the jws parameter. The description
specifies whether the parameter applies in the case that jws is a child of the ws-jwsc
goal, is a child of module, or both.
3-85
Chapter 3
Maven Plug-In Goals
explode boolean false Specifies the flag to set when you want ws-jwsc
exploded output. Defaults to true.
file java.lang.St true The name of the JWS file that you want to both
ring compile. The ws-jwsc goal looks for the file in
the srcdir directory.
generateWsdl boolean true Specifies whether the generated WAR file both
includes the WSDL file in the WEB-INF
directory. Default value is false.
jmstransports boolean false Use JMS transport for Web services. It can be ws-jwsc
ervice omitted. See Table 3-34 for a description of
jmstransportservice parameters.
name java.lang.St false Specifies the name of the generated WAR file ws-jwsc
ring (or exploded directory, if the explode attribute
is set to true) that contains the deployable Web
service.
transportType transportTyp false Used when it contains only one transport type both
e element. It can be omitted.
See Table 3-33 for a description of
transportType parameters.
transportType transportTyp false Used when it contains more than one transport both
s e type element. It can be omitted.
See Table 3-33 for a description of
transportType parameters.
wsdlOnly boolean false Specifies that only a WSDL file should be ws-jwsc
generated for this JWS file. The default value
is false.
module Parameters
As described in module, the module parameter groups one or more jws parameters
together so that their generated code and artifacts are packaged in a single Web
application (WAR) file. The module parameter is a child of the ws-jwsc goal.
3-86
Chapter 3
Maven Plug-In Goals
contextPath java.lang.Str false Specifies the deployed context of the Web service.
ing
descriptor java.lang.Str false Specifies the web.xml descriptor to use if a new one should
ing not be generated. The path should be fully qualified. The files
should be separated by ", ".
ejbWsInWar boolean false Specifies whether to package EJB-based Web services in a
WAR file instead of a JAR file.
explode boolean false Specifies the flag to set when you want exploded output.
Defaults to true.
FileSet FileSet false Used when it contains one FileSet element. It can be omitted.
FileSets FileSet false Used when it contains more than one FileSet element. It can
be omitted.
generateWsd boolean true Specifies whether the generated WAR file includes the WSDL
l file in the WEB-INF directory. Default value is false.
jws Jws false Used when it contains one jws element. It can be omitted.
jwses Jws false Used when it contains more than one jws element. It can be
omitted.
name java.lang.Str false Specifies the name of the WAR to use when evaluating the ear
ing file.
wsdlOnly boolean false Specifies that only a WSDL file should be generated for this
JWS file. The default value is false.
zipfileset java.lang.Str false There is only one <zipfileset> element.
ing
FileSet Parameters
As described in jwsfileset, the FileSet parameter specifies one or more directories in
which the ws-jwsc goal searches for JWS files to compile. The list of JWS files that
ws-jwsc finds is then treated as if each file had been individually specified with the jws
parameter of module.
3-87
Chapter 3
Maven Plug-In Goals
TransportType Parameters
As described in WLHttpTransport, WLHttpsTransport, and WLJMSTransport, you use
transport parameters to specify the transport type, context path, and service URI
sections of the URL used to invoke the Web service, as well as the name of the port in
the generated WSDL.
The ws-jwsc goal combines these transport parameters into one, TransportType.
destinationType java.lang.S false Valid values include: QUEUE or TOPIC. Default value is
tring QUEUE.
replyToName java.lang.S false JNDI name of the JMS destination to which the response
tring message is sent.
3-88
Chapter 3
Maven Plug-In Goals
mdbPerDestinatio boolean false Boolean flag that specifies whether to create one
n listening message-driven bean (MDB) for each requested
destination. Default value is true.
activationConfig java.lang.S false Activation configuration properties passed to the JMS
tring provider.
3-89
Chapter 3
Maven Plug-In Goals
Usage Example
The ws-jwsc goal builds a JAX-WS web service.
To do this, modify the pom.xml file to specify the generate-resources phase, the ws-
jwsc goal, and include any pa parameters you need to set. Then run mvn generate-
resources in the same directory of pom.xml.
3-90
Chapter 3
Maven Plug-In Goals
</executions>
</plugin>
</plugins>
</build>
</project>
[INFO]
------------------------------------------------------------------------
[INFO] Building maven_plugin_simple 1.0
[INFO]
------------------------------------------------------------------------
[INFO]
[INFO] --- weblogic-maven-plugin:14.1.1-0-0:ws-jwsc (jwsc) @
maven_plugin_simple ---
[INFO] Executing standalone...
3-91
4
Creating a Split Development Directory
Environment
To create a WebLogic Server split development directory that you can use to develop
a Java EE application or module, you have to organize the Java EE components and
shared classes, generate a basic build.xml file, and develop multiple EAR projects.
This chapter includes the following sections:
• Overview of the Split Development Directory Environment
• Using the Split Development Directory Structure: Main Steps
• Organizing Java EE Components in a Split Development Directory
• Organizing Shared Classes in a Split Development Directory
• Generating a Basic build.xml File Using weblogic.BuildXMLGen
• Developing Multiple-EAR Projects Using the Split Development Directory
• Best Practices for Developing WebLogic Server Applications
4-1
Chapter 4
Overview of the Split Development Directory Environment
source files, editable descriptor files, JSPs, static content, and so forth. You create
the source directory for an application by following the directory structure guidelines
described in Organizing Java EE Components in a Split Development Directory.
The top level of the source directory always represents an enterprise application (.ear
file), even if you are developing only a single Java EE module. Subdirectories beneath
the top level source directory contain:
• Enterprise Application Modules (EJBs and Web applications)
Note:
The split development directory structure does not provide support for
developing new Resource Adapter components.
Editable Deployment
Descriptors
Third-Party
JAR Files
The build directory contains only those files generated during the build process. The
combination of files in the source and build directories form a deployable Java EE
application.
The build and source directory contents can be place in any directory of your choice.
However, for ease of use, the directories are commonly placed in directories named
source and build, within a single project directory (for example, \myproject\build
and \myproject\source).
4-2
Chapter 4
Overview of the Split Development Directory Environment
Deploy
Editable Deployment
Descriptors .beabuild.txt
Third-Party
JAR Files
4-3
Chapter 4
Using the Split Development Directory Structure: Main Steps
• wlcompile—This Ant task compiles the contents of the source directory into
subdirectories of the build directory. wlcompile compiles Java classes and also
processes annotated .ejb files into deployment descriptors, as described in
Compiling Applications Using wlcompile.
• wlappc—This Ant task invokes the appc compiler, which generates JSPs and
container-specific EJB classes for deployment. See Building Modules and
Applications Using wlappc.
• wldeploy—This Ant task deploys any format of Java EE applications (exploded
or archived) to WebLogic Server. To deploy directly from the split development
directory environment, you specify the build directory of your application. See
wldeploy Ant Task Reference.
• wlpackage—This Ant task uses the contents of both the source and build
directories to generate an EAR file or exploded EAR directory that you can give to
others for deployment.
Note:
On UNIX operating systems, the setWLSEnv.sh command does not set
the environment variables in all command shells. Oracle recommends
that you execute this command using the Korn shell or bash shell.
5. Use the weblogic.BuildXMLGen utility to generate a default build.xml file for use
with your project. Edit the default property values as needed for your environment.
See Generating a Basic build.xml File Using weblogic.BuildXMLGen.
4-4
Chapter 4
Organizing Java EE Components in a Split Development Directory
6. Use the default targets in the build.xml file to build, deploy, and package your
application. See Generating a Basic build.xml File Using weblogic.BuildXMLGen
for a list of default targets.
Note:
If your project requires multiple EARs, see also Developing Multiple-EAR
Projects Using the Split Development Directory.
The following sections describe the basic conventions for staging the following module
types in the split development directory structure:
• Enterprise Application Configuration
• Web Applications
• EJBs
• Shared Utility Classes
• Third-Party Libraries
The directory examples are taken from the splitdir sample application installed
in ORACLE_HOME\wlserver\samples\src\examples\splitdir, where ORACLE_HOME
represents the directory in which the WebLogic Server code examples are configured.
For more information about the WebLogic Server code examples, see Sample
Applications and Code Examples in Understanding Oracle WebLogic Server.
4-5
Chapter 4
Organizing Java EE Components in a Split Development Directory
Source
helloWorldEar
build.xml
META-INF
application.xml
weblogic-application.xml
helloWebApp
hello.jsp
WEB-INF
web.xml
weblogic.xml
src
static
HTML, Graphics,
Static files*
helloEJB
META-INF
weblogic-ejb-jar.xml
ejb-jar.xml*
appUtils
APP-INF
lib
4-6
Chapter 4
Organizing Java EE Components in a Split Development Directory
Source Build
helloWorldEar helloWorldEar
helloEJB helloEJB
META-INF* META-INF
ejb-jar.xml* ejb-jar.xml
weblogic-ejb-jar.xml* weblogic-ejb-jar.xml
Key
The enterprise application directory will also have one or more subdirectories to hold
a Web application, EJB, utility class, and/or third-party Jar file, as described in the
following sections.
Web Applications
Web applications use the basic source directory layout shown in the figure below.
4-7
Chapter 4
Organizing Java EE Components in a Split Development Directory
Source Build
helloWorldEar helloWorldEar
hellowebApp hellowebApp
hello.jsp WEB-INF
WEB-INF classes
src jsp_servlet
static*
HTML, Graphics,
Static files
Key
The key directories and files for the Web application are:
• helloWebApp\ —The top level of the Web application module can contain JSP files
and static content such as HTML files and graphics used in the application. You
can also store static files in any named subdirectory of the Web application (for
example, helloWebApp\graphics or helloWebApp\static.)
• helloWebApp\WEB-INF\ —Store the Web application's editable deployment
descriptor files (web.xml and weblogic.xml) in the WEB-INF subdirectory.
• helloWebApp\WEB-INF\src —Store Java source files for Servlets in package
subdirectories under WEB-INF\src.
When you build a Web application, the appc Ant task and jspc compiler compile
JSPs into package subdirectories under helloWebApp\WEB-INF\classes\jsp_servlet
in the build directory. Editable deployment descriptors are not copied during the build
process.
EJBs
EJBs use the source directory layout shown in the figure below.
4-8
Chapter 4
Organizing Java EE Components in a Split Development Directory
Editable Deployment
Descriptors
Third-Party
JAR Files
4-9
Chapter 4
Organizing Shared Classes in a Split Development Directory
Source Build
helloWorldEar helloWorldEar
appUtils APP-INF
Place the source for Java utility classes in a named subdirectory of the top-level
enterprise application directory. Beneath the named subdirectory, use standard
package subdirectory conventions.
During the build process, the wlcompile Ant task invokes the javac compiler and
compiles Java classes into the APP-INF/classes/ directory under the build directory.
This ensures that the classes are available to other modules in the deployed
application.
Third-Party Libraries
You can extend an enterprise application to use third-party .jar files by placing the
files in the APP-INF\lib\ directory, as shown below:
4-10
Chapter 4
Generating a Basic build.xml File Using weblogic.BuildXMLGen
Source
helloWorldEar
APP-INF
lib
Third-party JARs are generally not compiled, but may be versioned using the
source control system for your application code. For example, XML parsers, logging
implementations, and Web application framework JAR files are commonly used in
applications and maintained along with editable source code.
During the build process, third-party JAR files are not copied to the build directory, but
remain in the source directory for deployment.
4-11
Chapter 4
Generating a Basic build.xml File Using weblogic.BuildXMLGen
</wlappc>
</target>
The compile and appc tasks for modules also use the lib\echolib\echolib.jar
library.
weblogic.BuildXMLGen Syntax
The syntax for weblogic.BuildXMLGen is as follows:
java weblogic.BuildXMLGen [options] <source directory>
In particular, make sure you edit the tmp.dir property to point to the build directory
you want to use. By default, the build.xml file builds projects into a subdirectory
tmp.dir named after the application (/tmp/helloWorldEar in the above listing).
The following listing shows the default main targets created in the build.xml file. You
can view these targets at the command prompt by entering the ant -projecthelp
command in the EAR source directory.
4-12
Chapter 4
Developing Multiple-EAR Projects Using the Split Development Directory
Note:
The following sections refer to the MedRec sample application, which
consists of three separate enterprise applications as well as shared
utility classes, third-party JAR files, and dedicated client applications. The
MedRec source and build directories are installed under ORACLE_HOME/
user_projects/domain/medrec, where ORACLE_HOME is the directory you
specified as Oracle Home when you installed Oracle WebLogic Server.
For more information about the WebLogic Server samples, see Sample
Applications and Code Examples in Understanding Oracle WebLogic Server.
4-13
Chapter 4
Developing Multiple-EAR Projects Using the Split Development Directory
third-party JAR files in the APP-INF/lib directory of each EAR source directory. This
introduces multiple copies of the source JAR files, increases the possibility of some
JAR files being at different versions, and requires additional space in your source
control system.
To address these problems, consider editing your build script to copy third-party JAR
files into the APP-INF/lib directory of the build directory for each EAR that requires
the libraries. This allows you to maintain a single copy and version of the JAR files in
your source control system, yet it enables each EAR in your project to use the JAR
files.
The MedRec sample application installed with WebLogic Server uses this strategy, as
shown in the following figure.
build build
medrecEar physicianEar
APP-INF APP-INF
lib lib
commons-*.jar commons-*.jar
exceptions.jar exceptions.jar
struts.jar struts.jar
utils.jar utils.jar
value.jar value.jar
MedRec takes a similar approach to utility classes that are shared by multiple EARs in
the project. Instead of including the source for utility classes within the scope of each
ear that needs them, MedRec keeps the utility class source independent of all EARs.
After compiling the utility classes, the build script archives them and copies the JARs
into the build directory under the APP-INF/LIB subdirectory of each EAR that uses the
classes, as shown in figure Figure 4-9.
Ant provides a core task (named ant) that allows you to execute other project build
files within a main build.xml file. The following line from the MedRec main build file
shows its usage:
4-14
Chapter 4
Best Practices for Developing WebLogic Server Applications
The above task instructs Ant to execute the file named build.xml in the /startupEar
subdirectory. The inheritAll parameter instructs Ant to pass only user properties
from the main build file to the build.xml file in /startupEar.
MedRec uses multiple tasks similar to the above to build the startupEar, medrecEar,
and physicianEar applications, as well as building common utility classes and client
applications.
4-15
5
Building Applications in a Split
Development Directory
To build WebLogic Server Java EE applications in WebLogic split development
directory environment you have to compile applications using wlcompile and build
modules and applications using wlappc.
This chapter includes the following sections:
• Compiling Applications Using wlcompile
• Building Modules and Applications Using wlappc
Note:
Deployment descriptors are no longer mandatory as of Java EE 5; therefore,
exploded module directories must indicate the module type by using the .war
or .jar suffix when there is no deployment descriptor in these directories.
The suffix is required so that wlcompile can recognize the modules.
The .war suffix indicates the module is a Web application module and
the .jar suffix indicates the module is an EJB module.
The following is the order in which events occur using this task:
1. wlcompile compiles the Java components into an output directory:
ORACLE_HOMEwlserver\samples\server\examples\build\helloWorldEar\APP-
INF\classes\
where ORACLE_HOME represents the directory in which the WebLogic Server code
examples are configured. For more information about the WebLogic Server code
examples, see Sample Applications and Code Examples in Understanding Oracle
WebLogic Server.
2. wlcompile builds the EJBs and automatically includes the previously built Java
modules in the compiler's classpath. This allows the EJBs to call the Java modules
without requiring you to manually edit their classpath.
5-1
Chapter 5
Compiling Applications Using wlcompile
3. Finally, wlcompile compiles the Java components in the Web application with
the EJB and Java modules in the compiler's classpath. This allows the Web
applications to refer to the EJB and application Java classes without requiring you
to manually edit the classpath.
Attribute Description
srcdir The source directory.
destdir The build/output directory.
classpath Allows you to change the classpath used by wlcompile.
includes Allows you to include specific directories from the build.
excludes Allows you to exclude specific directories from the build.
librarydir Specifies a directory of shared Java EE libraries to add to the
classpath. See Creating Shared Java EE Libraries and Optional
Packages.
5-2
Chapter 5
Building Modules and Applications Using wlappc
compile programs that use WebLogic services are packaged in the wls-api.jar file
in the lib directory of your WebLogic Server installation. In addition to wls-api.jar,
include the following in your compiler's CLASSPATH:
• The lib\tools.jar file in the JDK directory, or other standard Java classes
required by the Java Development Kit you use.
• The examples.property file for Apache Ant (for examples environment). This file
is discussed in the WebLogic Server documentation on building examples using
Ant located at: samples\server\examples\src\examples\examples.html
• Classes for third-party Java tools or services your programs import.
• Other application classes referenced by the programs you are compiling.
The name and version information are specified as attributes to the library element,
described in Table 5-2.
Attribute Description
file Required filename of a Java EE library
name The optional name of a required Java EE
library.
specificationversion An optional specification version required
for the library.
implementationversion An optional implementation version
required for the library.
5-3
Chapter 5
Building Modules and Applications Using wlappc
Note:
See weblogic.appc Reference for a list of weblogic.appc options.
Option Description
print Prints the standard usage message.
version Prints appc version information.
output <file> Specifies an alternate output archive or directory. If
not set, the output is placed in the source archive or
directory.
forceGeneration Forces generation of EJB and JSP classes. Without
this flag, the classes may not be regenerated (if
determined to be unnecessary).
lineNumbers Adds line numbers to generated class files to aid in
debugging.
writeInferredDescriptors Specifies that the application or module
contains deployment descriptors with annotation
information.
basicClientJar Does not include deployment descriptors in client
JARs generated for EJBs.
idl Generates IDL for EJB remote interfaces.
idlOverwrite Always overwrites existing IDL files.
idlVerbose Displays verbose information for IDL generation.
idlNoValueTypes Does not generate valuetypes and the methods/
attributes that contain them.
5-4
Chapter 5
Building Modules and Applications Using wlappc
Option Description
idlNoAbstractInterfaces Does not generate abstract interfaces and methods/
attributes that contain them.
idlFactories Generates factory methods for valuetypes.
idlVisibroker Generates IDL somewhat compatible with
Visibroker 4.5 C++.
idlOrbix Generates IDL somewhat compatible with Orbix
2000 2.0 C++.
idlDirectory <dir> Specifies the directory where IDL files will be
created (default: target directory or JAR)
idlMethodSignatures <> Specifies the method signatures used to trigger IDL
code generation.
iiop Generates CORBA stubs for EJBs.
iiopDirectory <dir> Specifies the directory where IIOP stub files will be
written (default: target directory or JAR)
keepgenerated Keeps the generated .java files.
librarydir Specifies a directory of shared Java EE libraries to
add to the classpath. See Creating Shared Java EE
Libraries and Optional Packages.
compiler <java.jdt> Selects the Java compiler to use. Defaults to JDT.
debug Compiles debugging information into a class file.
optimize Compiles with optimization on.
nowarn Compiles without warnings.
verbose Compiles with verbose output.
deprecation Warns about deprecated calls.
normi Passes flags through to Symantec's sj.
runtimeflags Passes flags through to Java runtime
classpath <path> Selects the classpath to use during compilation.
clientJarOutputDir <dir> Specifies a directory to place generated client jar
files. If not set, generated jar files are placed into the
same directory location where the JVM is running.
advanced Prints advanced usage options.
The following is an example of a wlappc Ant task command that invokes two options
(idl and idlOrverWrite) from Table 5-3.
<wlappc source="${dest.dir}"idl="true" idlOrverWrite="true" />
5-5
Chapter 5
Building Modules and Applications Using wlappc
weblogic.appc Reference
The following sections describe how to use the command-line version of the appc
compiler. The weblogic.appc command-line compiler reports any warnings or errors
encountered in the descriptors and compiles all of the relevant modules into an EAR
file, which can be deployed to WebLogic Server.
weblogic.appc Syntax
Use the following syntax to run appc:
prompt>java weblogic.appc [options] <ear, jar, or war file or directory>
weblogic.appc Options
The following are the available appc options:
Option Description
-print Prints the standard usage message.
-version Prints appc version information.
-output <file> Specifies an alternate output archive or directory. If not
set, the output is placed in the source archive or directory.
-forceGeneration Forces generation of EJB and JSP classes. Without this flag,
the classes may not be regenerated (if determined to be
unnecessary).
-library A comma-separated list of shared Java EE libraries.
<file[[@name=<string>] Optional name and version string information must be
[@libspecver=<version>] specified in the format described in Referencing Shared
[@libimplver=<version| Java EE Libraries in an Enterprise Application.
string>]]>
- Specifies that the application or module contains
writeInferredDescriptors deployment descriptors with annotation information.
-lineNumbers Adds line numbers to generated class files to aid in
debugging.
-basicClientJar Does not include deployment descriptors in client JARs
generated for EJBs.
-idl Generates IDL for EJB remote interfaces.
5-6
Chapter 5
Building Modules and Applications Using wlappc
Option Description
-idlOverwrite Always overwrites existing IDL files.
-idlVerbose Displays verbose information for IDL generation.
-idlNoValueTypes Does not generate valuetypes and the methods/attributes
that contain them.
-idlNoAbstractInterfaces Does not generate abstract interfaces and methods/
attributes that contain them.
-idlFactories Generates factory methods for valuetypes.
-idlVisibroker Generates IDL somewhat compatible with Visibroker 4.5
C++.
-idlOrbix Generates IDL somewhat compatible with Orbix 2000 2.0
C++.
-idlDirectory <dir> Specifies the directory where IDL files will be created
(default: target directory or JAR)
-idlMethodSignatures <> Specifies the method signatures used to trigger IDL code
generation.
-iiop Generates CORBA stubs for EJBs.
-iiopDirectory <dir> Specifies the directory where IIOP stub files will be
written (default: target directory or JAR)
-keepgenerated Keeps the generated .java files.
-compiler <javac> Selects the Java compiler to use.
-g Compiles debugging information into a class file.
-O Compiles with optimization on.
-nowarn Compiles without warnings.
-verbose Compiles with verbose output.
-deprecation Warns about deprecated calls.
-normi Passes flags through to Symantec's sj.
-J<option> Passes flags through to Java runtime.
-classpath <path> Selects the classpath to use during compilation.
-clientJarOutputDir Specifies a directory to place generated client jar files.
<dir> If not set, generated jar files are placed into the same
directory location where the JVM is running.
-advanced Prints advanced usage options.
5-7
6
Deploying and Packaging from a Split
Development Directory
To deploy and package WebLogic Server Java EE applications in WebLogic split
development directory environment use wldeploy and wlpackage tasks.
This chapter includes the following sections:
• Deploying Applications Using wldeploy
• Packaging Applications Using wlpackage
6-1
Chapter 6
Packaging Applications Using wlpackage
You can also package applications in a single archived file, which is convenient for
packaging modules and applications for distribution. Archive files are easier to copy,
they use up fewer file handles than an exploded directory, and they can save disk
space with file compression.
The Java classloader can search for Java class files (and other file types) in a JAR file
the same way that it searches a directory in its classpath. Because the classloader can
search a directory or a JAR file, you can deploy Java EE modules on WebLogic Server
in either a JAR (archived) file or an exploded (unarchived) directory.
6-2
7
Developing Applications for Production
Redeployment
You can program and maintain applications with WebLogic Server using the
production redeployment strategy.
This chapter includes the following sections:
• What is Production Redeployment?
• Supported and Unsupported Application Types
• Programming Requirements and Conventions
• Assigning an Application Version
• Upgrading Applications to Use Production Redeployment
• Accessing Version Information
7-1
Chapter 7
Programming Requirements and Conventions
7-2
Chapter 7
Programming Requirements and Conventions
Note:
Set weblogic.jndi.WLContext.RELAX_VERSION_LOOKUP to true only if you
are certain that the newer and older version of the resource that you are
looking up are compatible with one another.
7-3
Chapter 7
Assigning an Application Version
7-4
Chapter 7
Upgrading Applications to Use Production Redeployment
For example, the following manifest file content describes an application with version
"v920.beta":
Manifest-Version: 1.0
Created-By: 1.4.1_05-b01 (Sun Microsystems Inc.)
Weblogic-Application-Version: v920.beta
7-5
Chapter 7
Accessing Version Information
7-6
8
Using Java EE Annotations and
Dependency Injection
Learn about Java EE MetaData annotations and dependency injection (DI) in
WebLogic Server.
This chapter includes the following sections:
• Annotation Processing
• Dependency Injection of Resources
• Standard JDK Annotations
• Standard Security-Related JDK Annotations
Annotation Processing
Annotations simplify the application development process by allowing developers
to specify within the Java class itself how the application component behaves in
the container, requests for dependency injection, and so on. Annotations are an
alternative to deployment descriptors that were required by older versions of enterprise
applications (Java EE 1.4 and earlier).
With Java EE annotations, the standard application.xml and web.xml deployment
descriptors are optional. The Java EE programming model uses the JDK annotations
feature for Web containers, such as EJBs, servlets, Web applications, and JSPs (see
https://javaee.github.io/javaee-spec/javadocs/).
Annotation Parsing
The application components can use annotations to define their needs. Annotations
reduce or eliminate the need to deal with deployment descriptors. Annotations simplify
the development of application components. The deployment descriptor can still
override values defined in the annotation. One usage of annotations is to define
fields or methods that need Dependency Injection (DI). Annotations are defined on
the POJO (plain old Java object) component classes like the EJB or the servlet.
An annotation on a field or a method can declare that fields/methods need injection,
as described in Dependency Injection of Resources. Annotations may also be applied
to the class itself. The class-level annotations declare an entry in the application
component's environment but do not cause the resource to be injected. Instead, the
application component is expected to use JNDI or component context lookup method
to lookup the entry. When the annotation is applied to the class, the JNDI name and
the environment entry type must be specified explicitly.
8-1
Chapter 8
Dependency Injection of Resources
deployment descriptors. Assuming that it has some classes that have been declared
as EJBs using annotations, a user of Session Helper will still be able to deal
with the module as if it had the deployment descriptor. So the developer can
modify the configuration information and it will be written out in a deployment plan.
During deployment, such a plan will be honored and will override information from
annotations.
8-2
Chapter 8
Standard JDK Annotations
…..
}
In the above code the @Resource annotation has not specified a name; therefore, the
container would look for an env-entry name called <class-name>/maxExemptions and
inject the value of that entry into the maxExemptions variable. The field or method may
have any access qualifier (public, private, etc.). For all classes except application client
main classes, the fields or methods must not be static. Because application clients use
the same life cycle as Java EE applications, no instance of the application client main
class is created by the application client container. Instead, the static main method is
invoked. To support injection for the application client main class, the fields or methods
annotated for injection must be static.
The order in which the methods are called matches the order of the class hierarchy,
with methods on a superclass being called before methods on a subclass. From the
Java EE side only the application client container is involved in invoking these life
cycle methods for Java EE clients. The life cycle methods for Java EE clients must be
static. The Java EE client just supports the @PostConstruct callback.
8-3
Chapter 8
Standard JDK Annotations
• javax.annotation.Resource
• javax.annotation.Resources
For information about EJB-specific annotations for WebLogic Server Enterprise
JavaBeans, see Developing Enterprise JavaBeans for Oracle WebLogic Server.
For information about Web component-specific annotations WebLogic Server
applications, see WebLogic Annotation for Web Components in Developing Web
Applications, Servlets, and JSPs for Oracle WebLogic Server.
javax.annotation.PostConstruct
Target: Method
Specifies the life cycle callback method that the application component should execute
before the first business method invocation and after dependency injection is done to
perform any initialization. This method will be called after all injections have occurred
and before the class is put into service. This method will be called even if the class
doesn't request any resources to be injected.
You must specify a @PostConstruct method in any component that includes
dependency injection.
Only one method in the component can be annotated with this annotation.
The method annotated with @PostConstruct must follow these requirements:
• The method must not have any parameters, except in the case of EJB
interceptors, in which case it takes an javax.interceptor.InvocationContext object
as defined by the EJB specification.
• The return type of the method must be void.
• The method must not throw a checked exception.
• The method may be public, protected, package private or private.
• The method must not be static except for the application client.
• The method may be final or non-final, except in the case of EJBs where it must
be non-final.
• If the method throws an unchecked exception, the class must not be put into
service. In the case of EJBs, the method annotated with PostConstruct can handle
exceptions and cleanup before the bean instance is discarded.
This annotation does not have any attributes.
javax.annotation.PreDestroy
Target: Method
Specifies the life cycle callback method that signals that the application component is
about to be destroyed by the container. You typically apply this annotation to methods
that release resources that the class has been holding.
Only one method in the bean class can be annotated with this annotation.
The method annotated with @PreDestroy must follow these requirements:
8-4
Chapter 8
Standard JDK Annotations
• The method must not have any parameters, except in the case of EJB
interceptors, in which case it takes an javax.interceptor.InvocationContext object
as defined by the EJB specification.
• The return type of the method must be void.
• The method must not throw a checked exception.
• The method may be public, protected, package private or private.
• The method must not be static except for the application client.
• The method may be final or non-final, except in the case of EJBs where it must
be non-final.
• If the method throws an unchecked exception, the class must not be put into
service. In the case of EJBs, the method annotated with PreDestroy can handle
exceptions and cleanup before the bean instance is discarded.
This annotation does not have any attributes.
javax.annotation.Resource
Target: Class, Method, Field
Specifies a dependence on an external resource, such as a JDBC data source or a
JMS destination or connection factory.
If you specify the annotation on a field or method, the application component injects
an instance of the requested resource into the bean when the bean is initialized. If you
apply the annotation to a class, the annotation declares a resource that the component
will look up at runtime.
Attributes
8-5
Chapter 8
Standard JDK Annotations
javax.annotation.Resources
Target: Class
Specifies an array of @Resource annotations. Since repeated annotations are
not allowed, the Resources annotation acts as a container for multiple resource
declarations.
Attributes
8-6
Chapter 8
Standard Security-Related JDK Annotations
javax.annotation.security.DeclareRoles
Target: Class
Defines the security roles that will be used in the Java EE container.
You typically use this annotation to define roles that can be tested from within the
methods of the annotated class, such as using the isUserInRole method. You can
also use the annotation to explicitly declare roles that are implicitly declared if you use
the @RolesAllowed annotation on the class or a method of the class.
You create security roles in WebLogic Server using the WebLogic Server
Administration Console. For information about security, see Manage Security Roles.
Attributes
javax.annotation.security.DenyAll
Target: Method
Specifies that no security role is allowed to access the annotated method, or in other
words, the method is excluded from execution in the Java EE container.
This annotation does not have any attributes.
javax.annotation.security.PermitAll
Target: Method
Specifies that all security roles currently defined for WebLogic Server are allowed to
access the annotated method.
This annotation does not have any attributes.
8-7
Chapter 8
Standard Security-Related JDK Annotations
javax.annotation.security.RolesAllowed
Target: Class, Method
Specifies the list of security roles that are allowed to access methods in the Java EE
container.
If you specify it at the class-level, then it applies to all methods in the application
component. If you specify it at the method-level, then it only applies to that method.
If you specify the annotation at both the class- and method-level, the method value
overrides the class value.
You create security roles in WebLogic Server using the WebLogic Server
Administration Console. For information about security, see Manage Security Roles.
Attributes
javax.annotation.security.RunAs
Target: Class
Specifies the security role which actually executes the Java EE container.
The security role must exist in the WebLogic Server security realm and map to a user
or group. For information about security, see Manage Security Roles.
Attributes
8-8
9
Using Contexts and Dependency Injection
for the Java EE Platform
WebLogic Server provides an implementation of the Contexts and Dependency
Injection (CDI) specification. The CDI specification defines a set of services for using
injection to specify dependencies in an application. CDI provides contextual life cycle
management of beans, type-safe injection points, a loosely coupled event framework,
loosely coupled interceptors and decorators, alternative implementations of beans,
bean navigation through the Unified Expression Language (EL), and a service provider
interface (SPI) that enables CDI extensions to support third-party frameworks or future
Java EE components.
This chapter includes the following sections:
• About CDI for the Java EE Platform
• Defining a Managed Bean
• Injecting a Bean
• Defining the Scope of a Bean
• Overriding the Scope of a Bean at the Point of Injection
• Using Qualifiers
• Providing Alternative Implementations of a Bean Type
• Applying a Scope and Qualifiers to a Session Bean
• Using Producer Methods_ Disposer Methods_ and Producer Fields
• Initializing and Preparing for the Destruction of a Managed Bean
• Intercepting Method Invocations and Life Cycle Events of Bean Classes
• Decorating a Managed Bean Class
• Assigning an EL Name to a CDI Bean Class
• Defining and Applying Stereotypes
• Using Events for Communications Between Beans
• Injecting a Predefined Bean
• Injecting and Qualifying Resources
• Using CDI With JCA Technology
• Configuring a CDI Application
• Supporting Third-Party Portable Extensions
• Enabling and Disabling CDI
• Enabling and Disabling Implicit Bean Discovery
9-1
Chapter 9
About CDI for the Java EE Platform
9-2
Chapter 9
Defining a Managed Bean
8\cdi where ORACLE_HOME represents the directory in which you installed WebLogic
Server. See Sample Applications and Code Examples in Understanding Oracle
WebLogic Server.
Note:
No special declaration, such as an annotation, is required to define a
managed bean. To make the managed beans of an application available
for injection, you must configure the application as explained in Configuring a
CDI Application.
Injecting a Bean
To use the beans that you define, inject them into another bean that an application
such as a JavaServer Faces can use.
See Injecting Beans in The Java EE 8 Tutorial.
CDI ensures type-safe injection of beans by selecting the bean class on the basis
of the Java type that is specified in the injection point, not the bean name. CDI also
determines where to inject a bean from the Java type in the injection point.
In this respect, CDI bean injection is different than the resource injection that was
introduced in the Java EE 5 specification, which selects the resource to inject from
the string name of the resource. For example, a data source that is injected with the
javax.annotation.Resource annotation is identified by its string name.
9-3
Chapter 9
Defining the Scope of a Bean
To inject a bean, obtain an instance of the bean by creating an injection point in the
class that is to use the injected bean. Create the injection point by annotating one of
the following program elements with the javax.inject.Inject annotation:
• @RequestScoped
• @SessionScoped
• @ApplicationScoped
• @ConversationScoped
• @Dependent
For information about these scopes, see Using Scopes in The Java EE 8 Tutorial.
If you do not define the scope of a bean, the scope of the bean is @Dependent by
default. The @Dependent scope specifies that the bean's life cycle is the life cycle of the
object into which the bean is injected.
The predefined scopes except @Dependent are contextual scopes. CDI places beans
of contextual scope in the context whose life cycle is defined by the Java EE
specifications. For example, a session context and its beans exist during the lifetime
of an HTTP session. Injected references to the beans are contextually aware. The
references always apply to the bean that is associated with the context for the thread
that is making the reference. The CDI container ensures that the objects are created
and injected at the correct time as determined by the scope that is specified for these
objects.
Example 9-2 shows how to define the scope of a bean.
9-4
Chapter 9
Overriding the Scope of a Bean at the Point of Injection
The Accountant class in this example is qualified by the @BeanCounter qualifier. For
more information, see Using Qualifiers.
package com.example.managers;
import javax.enterprise.context.RequestScoped;
@RequestScoped
@BeanCounter
public class Accountant implements Manager
{
...
}
Note:
The effects of overriding the scope of a bean may be unpredictable and
undesirable, particularly if the overridden scope is @Request or @Session.
To override the scope of a bean at the point of injection, inject the bean by using
the javax.enterprise.inject.New annotation instead of the @Inject annotation. For
more information about the @Inject annotation, see Injecting a Bean.
Using Qualifiers
Qualifiers enable you to provide more than one implementation of a particular bean
type.
When you use qualifiers, you select between implementations at development time.
See Using Qualifiers in The Java EE 8 Tutorial.
Note:
To select between alternative implementations at deployment time, use
alternatives as explained in Providing Alternative Implementations of a Bean
Type.
9-5
Chapter 9
Using Qualifiers
Using qualifiers involves the tasks that are explained in the following sections:
• Defining Qualifiers for Implementations of a Bean Type
• Applying Qualifiers to a Bean
• Injecting a Qualified Bean
Note:
CDI does not require a qualifier to be unique to a particular bean. You can
define a qualifier to use for more than one bean type.
To define a qualifier:
1. Define a Java annotation type to represent the qualifier.
2. Annotate the declaration of the annotation type with the javax.inject.Qualifier
annotation.
3. Specify that the qualifier is to be retained by the virtual machine at run time.
Use the java.lang.annotation.Retention(RUNTIME) meta-annotation for this
purpose.
4. Specify that the qualifier may be applied to the program elements METHOD, FIELD,
PARAMETER, and TYPE.
Use the java.lang.annotation.Target({METHOD, FIELD, PARAMETER, TYPE})
meta-annotation for this purpose.
The following examples show how to define qualifiers @BeanCounter and
@PeopleManager for different implementations of the same bean type.
import java.lang.annotation.Retention;
import java.lang.annotation.Target;
9-6
Chapter 9
Using Qualifiers
import javax.inject.Qualifier;
@Qualifier
@Retention(RUNTIME)
@Target({METHOD, FIELD, PARAMETER, TYPE})
public @interface BeanCounter {}
import java.lang.annotation.Retention;
import java.lang.annotation.Target;
import javax.inject.Qualifier;
@Qualifier
@Retention(RUNTIME)
@Target({METHOD, FIELD, PARAMETER, TYPE})
public @interface PeopleManager {}
Note:
CDI does not require a qualifier to be unique to a particular bean. You can
apply the same qualifier to different types of beans in the set of beans that
are available in the application.
To apply qualifiers to a bean, annotate the class declaration of the bean with each
qualifier to apply. Any qualifier that you apply to a bean must be defined as explained
in Defining Qualifiers for Implementations of a Bean Type.
The following examples show how to apply the qualifiers @BeanCounter and
@PeopleManager to different implementations of the Manager bean type.
9-7
Chapter 9
Using Qualifiers
package com.example.managers;
...
@BeanCounter
public class Accountant implements Manager
{...}
9-8
Chapter 9
Providing Alternative Implementations of a Bean Type
import javax.inject.Inject;
...
public class PennyPincher {
@Inject @BeanCounter Manager accountant;
...
}
Note:
To select between alternative implementations at development time, use
qualifiers as explained in Using Qualifiers.
Providing alternative implementations of a bean type involves the tasks that are
explained in the following sections:
• Defining an Alternative Implementation of a Bean Type
• Selecting an Alternative Implementation of a Bean Type for an Application
9-9
Chapter 9
Providing Alternative Implementations of a Bean Type
Note:
To ensure that the primary implementation is selected by default, do
not annotate the class declaration of the primary implementation with
@Alternative.
The following examples show the declaration of the primary implementation and an
alternative implementation of a bean type. The alternative implementation is a mock
implementation that is intended for use in testing.
Example 9-8 Declaring a Primary Implementation of a Bean Type
This example declares the primary implementation OrderImpl of the bean type Order.
package com.example.orderprocessor;
...
public class OrderImpl implements Order {
...
}
@Alternative
public class MockOrderImpl implements Order {
...
}
Example 9-16 shows a class element in the beans.xml file for selecting an alternative
implementation of a bean type.
Example 9-10 Selecting an Alternative Implementation of a Bean Type
This example selects the alternative implementation
com.example.orderprocessor.MockOrderImpl.
9-10
Chapter 9
Applying a Scope and Qualifiers to a Session Bean
...
<alternatives>
<class>com.example.orderprocessor.MockOrderImpl</class>
</alternatives>
...
For more information about scopes in CDI, see Defining the Scope of a Bean.
When CDI injects a reference to a stateful session bean, CDI creates the bean, injects
the bean's fields, and manages the stateful session bean according to its scope. When
the context is destroyed, CDI calls the stateful session bean's remove method to
remove the bean.
9-11
Chapter 9
Using Producer Methods, Disposer Methods, and Producer Fields
If the producer method sometimes returns null, set the scope of the method to
dependent.
Note:
Calling a producer method directly in application code does not invoke CDI.
9-12
Chapter 9
Using Producer Methods, Disposer Methods, and Producer Fields
A disposer method matches a producer method when the disposed object's injection
point matches both the type and qualifiers of the producer method. You can define one
disposer method to match to several producer methods in the class.
Example 9-11 shows how to use the @Produces annotation to define a producer
method and the @Disposes annotation to define a disposer method.
The producer method connect returns an object of type Connection. In the disposer
method close, the parameter connection is the disposed parameter. This parameter
is of type Connection to match the return type of the producer method.
At run time, the CDI framework creates an instance of SomeClass and then calls
the producer method. Therefore, the CDI framework is responsible for injecting the
parameters that are passed to the producer method.
The scope of the producer method is @RequestScoped. When the request context is
destroyed, if the Connection object is in the request context, CDI calls the disposer
method for this object. In the call to the disposer method, CDI passes the Connection
object as a parameter.
import javax.enterprise.inject.Produces;
import javax.enterprise.inject.Disposes;
import javax.enterprise.context.RequestScoped;
If the producer field may contain a null when accessed, set the scope of the field to
dependent.
9-13
Chapter 9
Initializing and Preparing for the Destruction of a Managed Bean
Note:
Using a producer field directly in application code does not invoke CDI.
Note:
As mandated by JSR 250, if the annotated method is declared in a
superclass, the method is called unless a subclass of the declaring class
overrides the method.
9-14
Chapter 9
Intercepting Method Invocations and Life Cycle Events of Bean Classes
In this method, perform any cleanup that is required before the bean is destroyed,
such a releasing resources that the bean has been holding.
2. Annotate the declaration of the method with the javax.annotation.PreDestroy
annotation.
CDI calls the method before starting the logic for destroying the bean.
Note:
As mandated by JSR 250, if the annotated method is declared in a
superclass, the method is called unless a subclass of the declaring class
overrides the method.
Note:
The programming model for interceptor classes is optimized for operations
that are separate from the business logic of the application. To intercept
methods that perform operations with business semantics, use a decorator
class as explained in Decorating a Managed Bean Class.
The interceptors that were introduced in the Java EE 5 specification are specific to
EJB components. For more information about Java EE 5 interceptors, see Specifying
Interceptors for Business Methods or Life Cycle Callback Events in Developing
Enterprise JavaBeans for Oracle WebLogic Server.
CDI enables you to use interceptors with the following types of Java EE managed
objects:
• CDI managed beans
• EJB session beans
• EJB message-driven beans
9-15
Chapter 9
Intercepting Method Invocations and Life Cycle Events of Bean Classes
Note:
You cannot use interceptors with EJB entity beans because CDI does not
support EJB entity beans.
Note:
CDI does not require an interceptor binding type to be unique to a particular
interceptor class. You can define an interceptor binding type to use for more
than one interceptor class.
9-16
Chapter 9
Intercepting Method Invocations and Life Cycle Events of Bean Classes
import java.lang.annotation.Retention;
import java.lang.annotation.Target;
import javax.interceptor.InterceptorBinding;
@InterceptorBinding
@Target({METHOD, TYPE})
@Retention(RUNTIME)
public @interface Transactional {}
Note:
CDI does not require an interceptor binding type to be unique to
a particular interceptor class. You can apply the same interceptor
binding type to multiple interceptor classes.
9-17
Chapter 9
Intercepting Method Invocations and Life Cycle Events of Bean Classes
Note:
An interceptor class can have multiple interceptor methods. However, an
interceptor class can have no more than one interceptor method of a
given type.
import javax.annotation.Resource;
import javax.interceptor.*;
...
@Transactional @Interceptor
public class TransactionInterceptor {
@Resource UserTransaction transaction;
@AroundInvoke
public Object manageTransaction(InvocationContext ctx)
throws Exception {
...
}
}
9-18
Chapter 9
Intercepting Method Invocations and Life Cycle Events of Bean Classes
Note:
An implementation of a Java EE 5 interceptor must be declared in the
annotation on the method that is to be intercepted. A CDI interceptor uses
an interceptor binding to identify an interceptor method and to relate an
intercepted method to its interceptor method. Both the intercepted method
and the interceptor method must be annotated with the binding. In this way,
the intercepted method and the interceptor are related to each other only
through the interceptor binding.
@Transactional
public class ShoppingCart {
...
}
Enabling an Interceptor
By default, an interceptor is disabled. If you require an interceptor to be interposed in
method invocations and events, you must enable the interceptor explicitly.
To enable an interceptor:
1. Add a class element for the interceptor to the interceptors element in the
beans.xml file.
2. In the class element, provide the fully qualified class name of the interceptor.
Ensure that the order of t he class elements in the beans.xml file matches the
order in which the interceptors are to be invoked.
CDI interceptors are invoked in the order in which they are declared in the
beans.xml file. Interceptors that are defined in the ejb-jar.xml file or by
the javax.interceptor.Interceptors annotation are called before the CDI
interceptors. Interceptors are called before CDI decorators.
9-19
Chapter 9
Intercepting Method Invocations and Life Cycle Events of Bean Classes
Note:
Java EE 5 interceptors are invoked in the order in which they are
annotated on an intercepted method.
For more information about the beans.xml file, see Configuring a CDI Application.
Example 9-16 shows a class element in the beans.xml file for enabling an interceptor
class.
Example 9-16 Enabling an Interceptor Class
This example enables the interceptor class
com.example.billpayment.interceptor.TransactionInterceptor. The interceptor
class is defined in Example 9-13.
...
<interceptors>
<class>com.example.billpayment.interceptor.TransactionInterceptor</class>
</interceptors>
...
publicinterfaceInterceptionFactory<T> {
InterceptionFactory<T> ignoreFinalMethods();
AnnotatedTypeConfigurator<T> configure();
T createInterceptedInstance(T instance);
}
@Produces
@RequestScoped
public Product createInterceptedProduct(InterceptionFactory<Product>
interceptionFactory) {
interceptionFactory.configure().add(ActionBinding.Literal.INSTANCE);
return interceptionFactory.createInterceptedInstance(new Product());
}
See Using Interceptors in CDI Applications in Java EE 8 Tutorial for more information
about using interceptors.
9-20
Chapter 9
Decorating a Managed Bean Class
Note:
The programming model for decorator classes is optimized for operations
that perform the business logic of the application. To intercept methods that
are separate from the business logic of an application, use an interceptor
class as explained in Intercepting Method Invocations and Life Cycle Events
of Bean Classes.
9-21
Chapter 9
Decorating a Managed Bean Class
A decorator class must contain exactly one delegate injection point. A delegate
injection point injects a delegate object, which is an instance of the decorated
class, into the decorator object.
You can customize how any method in the decorator object handles the
implementation of the decorated method. CDI allows but does not require the
decorator object to invoke the corresponding delegate object. Therefore, you are
free to choose whether the decorator object invokes the corresponding delegate
object.
a. In the decorator class, inject an instance of the bean class that you are
decorating.
b. Annotate the injection point with the javax.decorator.Delegate annotation.
c. Apply qualifiers that you require to the injection point, if any.
If you apply qualifiers to the injection point, the decorator applies only to beans
whose bean class matches the qualifiers of the injection point.
Note:
No special declaration, such as an annotation, is required to define a
decorated bean class. An enabled decorator class applies to any bean class
or session bean that matches the bean type and qualifiers of the delegate
injection point.
Because only some methods of the decorated class are to be intercepted, the class is
declared as an abstract class. This class injects a delegate instance delegate of the
decorated implementation of the DataAcess bean type.
import javax.decorator.*;
import javax.inject.Inject;
import java.lang.Override;
...
@Decorator
public abstract class DataAccessAuthDecorator
implements DataAccess {
@Override
public void delete(Object object) {
authorize(SecureAction.DELETE, object);
delegate.delete(object);
}
9-22
Chapter 9
Assigning an EL Name to a CDI Bean Class
Note:
Any interceptor classes that are defined for an application are invoked before
the application's decorator classes.
For more information about the beans.xml file, see Configuring a CDI Application.
Example 9-18 shows a class element in the beans.xml file for enabling a decorator
class.
Example 9-18 Enabling a Decorator Class
This example enables the decorator class
com.example.billpayment.decorator.DataAccessAuthDecorator.
...
<decorators>
<class>com.example.billpayment.decorator.DataAccessAuthDecorator</class>
</decorators>
...
9-23
Chapter 9
Defining and Applying Stereotypes
If you do not specify a name, the EL name is the unqualified class name with the first
character in lower case. For example, if the unqualified class name is ShoppingCart,
the EL name is shoppingCart.
To specify a name, set the value element of the @Named annotation to the name that
you require.
Note:
To assign an EL name to a CDI bean class, you must annotate the bean
class declaration with the @Named annotation. If the class is not annotated
with @Named, the CDI bean class does not have an EL name.
The following example shows how to use the @Named annotation to assign an EL name
to a CDI bean class. This example assigns the EL name cart to the ShoppingCart
class.
import javax.enterprise.context.SessionScoped;
@SessionScoped
@Named("cart")
public class ShoppingCart {
public String getTotal() {
...
}
...
}
Any bean that a JSP page or JSF page accesses must conform to the JavaBeans
standard. To access a CDI managed bean from a JSP page or JSF page through the
bean's EL name, use a syntax that is similar to the syntax for JavaBeans components.
The following example shows how an instance of the ShoppingCart class is accessed
in a JSF page through the EL name that is assigned to the class.
Example 9-19 Accessing a Bean Through its EL Name
This example accesses an instance of the ShoppingCart class to display the value of
its total property in a JSF page.
This property is returned by the getTotal getter method of the ShoppingCart class.
...
<h:outputText value="#{cart.total}"/>
...
9-24
Chapter 9
Defining and Applying Stereotypes
You can then use the stereotype to guarantee that the same set of annotations is
applied to all bean classes that require the annotations. See Using Stereotypes in The
Java EE 8 Tutorial.
Defining and applying stereotypes involves the tasks that are explained in the following
sections:
• Defining a Stereotype
• Applying Stereotypes to a Bean
Defining a Stereotype
A stereotype is an application-defined annotation type that incorporates other
annotation types.
To define a stereotype:
1. Define a Java annotation type to represent the stereotype.
2. Annotate the declaration of the annotation type with the following annotations:
• javax.enterprise.inject.Stereotype
• The other annotation types that you want the stereotype to incorporate
You can specify the following annotation types in a stereotype:
– A default scope—see Defining the Scope of a Bean
– @Alternative—see Providing Alternative Implementations of a Bean Type
– One or more interceptor bindings—see Intercepting Method Invocations
and Life Cycle Events of Bean Classes
– @Named—see Assigning an EL Name to a CDI Bean Class
3. Specify that the stereotype is to be retained by the virtual machine at run time.
Use the java.lang.annotation.Retention(RUNTIME) meta-annotation for this
purpose.
4. Specify that the stereotype may be applied to the program element TYPE.
Use the java.lang.annotation.Target(TYPE) meta-annotation for this purpose.
The following example shows the definition of a stereotype.
Example 9-20 Defining a Stereotype
This example defines the stereotype @Action, which specifies the following for each
bean that the stereotype annotates:
• The default scope is request scope unless the scope is overridden with a scope
annotation.
• The default EL name is assigned to the bean unless the name is overridden with
the @Named annotation.
• The interceptor bindings @Secure and @Transactional are applied to the bean.
The definition of these interceptor bindings is beyond the scope of this example.
import javax.enterprise.inject.Stereotype;
import javax.inject.Named;
import javax.enterprise.context.RequestScoped;
9-25
Chapter 9
Using Events for Communications Between Beans
@RequestScoped
@Secure
@Transactional
@Named
@Stereotype
@Target(TYPE)
@Retention(RUNTIME)
public @interface Action {}
9-26
Chapter 9
Using Events for Communications Between Beans
Sending an Event
To communicate a change that occurs in response to an operation, your application
must send an event of the correct type when performing the operation. CDI provides a
predefined event dispatcher object that enables application code to send an event and
select the associated qualifiers at run time.
To send an event:
1. Obtain an instance of the event type to send.
2. Call methods of the event instance to populate the event payload of the event
object that you are sending.
3. Inject an instance of the parameterized javax.enterprise.event.Event interface.
If you are sending a qualified event, annotate the injection point with the event
qualifier.
4. Call the fire method of the injected Event instance.
• In the call to the fire method, pass as a parameter the event instance that
you are sending. This method fires the event synchronously and notifies any
observer methods.
9-27
Chapter 9
Using Events for Communications Between Beans
@SessionScoped
public class Login implements Serializable {
if (user != null) {
userLoggedInEvent.fire(user);
}
}
...
}
Handling an Event
Any CDI managed bean class can handle events.
To handle an event:
1. In your bean class, define a method to handle the event.
Note:
If qualifiers are applied to an event type, define one method for each
qualified type.
2. In the signature of the method, define a parameter for passing the event to the
method.
Ensure that the type of the parameter is the same as the Java type of the event.
3. Annotate the parameter in the method signature with the
javax.enterprise.event.Observes annotation.
If necessary,
• set elements of the @Observes annotation to specify whether the method is
conditional or transactional. See Using Observer Methods to Handle Events in
The Java EE 8 Tutorial.
9-28
Chapter 9
Injecting a Predefined Bean
• set the observer method order using @Priority annotation to specify the
order in which the observer methods for an event are invoked. See Observer
Method Ordering in The Java EE 8 Tutorial.
4. If the event type is qualified, apply the qualifier to the annotated parameter.
5. In the method body, provide code for handling the event payload of the event
object.
Example 9-23 shows how to declare an observer method for receiving qualified events
of a particular type. Example 9-24 shows how to declare an observer method for
receiving all events of a particular type.
Example 9-23 Handling a Qualified Event of a Particular Type
This example declares the afterLogin method in which the parameter user is
annotated with the @Observes annotation and the @LoggedIn qualifier. This method
is called when an event of type User with the qualifier @LoggedIn is sent.
import javax.enterprise.event.Observes;
javax.transaction.UserTransaction
Java Transaction API (JTA) user transaction.
java.security.Principal
The abstract notion of a principal, which represents any entity, such as an individual, a
corporation, and a login ID.
The principal represents the identity of the current caller. Whenever the injected
principal is accessed, it always represents the identity of the current caller.
For example, a principal is injected into a field at initialization. Later, a method that
uses the injected principal is called on the object into which the principal was injected.
In this situation, the injected principal represents the identity of the current caller when
the method is run.
9-29
Chapter 9
Injecting and Qualifying Resources
javax.validation.Validator
Validator for bean instances.
The bean that implements this interface enables a Validator object for the default
bean validation ValidatorFactory object to be injected.
javax.validation.ValidatorFactory
Factory class for returning initialized Validator instances.
The bean that implements this interface enables the default bean validation
ValidatorFactory object to be injected.
For more information about injecting resources, see Resource Injection in The Java
EE 8 Tutorial.
Example 9-25 shows how to use the @Resource annotation to inject a predefined bean.
9-30
Chapter 9
Injecting and Qualifying Resources
For more information about producer fields, see Defining a Producer Field.
The following example shows how to use Java EE 5 annotations to inject resources.
import javax.annotation.Resource;
import javax.persistence.PersistenceContext;
import javax.persistence.PersistenceUnit;
import javax.ejb.EJB;
import javax.xml.ws.WebServiceRef;
...
public class SomeClass {
@WebServiceRef(lookup="java:app/service/PaymentService")
PaymentService paymentService;
@EJB(ejbLink="../payment.jar#PaymentService")
PaymentService paymentService;
@Resource(lookup="java:global/env/jdbc/CustomerDatasource")
Datasource customerDatabase;
@PersistenceContext(unitName="CustomerDatabase")
EntityManager customerDatabasePersistenceContext;
@PersistenceUnit(unitName="CustomerDatabase")
EntityManagerFactory customerDatabasePersistenceUnit;
...
}
The following example shows how to inject the same set of resources by combining
Java EE 5 resource injection with CDI producer fields.
The declaration of the SomeClass class is annotated with @ApplicationScoped to set
the scope of this bean to application. The @Dependent scope is implicitly applied to the
producer fields.
import javax.enterprise.context.ApplicationScoped;
import javax.enterprise.inject.Produces;
import javax.annotation.Resource;
import javax.persistence.PersistenceContext;
import javax.persistence.PersistenceUnit;
import javax.ejb.EJB;
javax.xml.ws.WebServiceRef;
...
@ApplicationScoped
public class SomeClass {
@Produces
@WebServiceRef(lookup="java:app/service/PaymentService")
PaymentService paymentService;
@Produces
@EJB(ejbLink="../their.jar#PaymentService")
PaymentService paymentService;
@Produces @CustomerDatabase
@Resource(lookup="java:global/env/jdbc/CustomerDatasource")
Datasource customerDatabase;
@Produces @CustomerDatabase
@PersistenceContext(unitName="CustomerDatabase")
9-31
Chapter 9
Using CDI With JCA Technology
EntityManager customerDatabasePersistenceContext;
@Produces @CustomerDatabase
@PersistenceUnit(unitName="CustomerDatabase")
EntityManagerFactory customerDatabasePersistenceUnit;
...
}
CDI enables you to use Java EE resources in CDI applications in a way that is
consistent with CDI. To use Java EE resources in this way, inject the resources as CDI
beans into other beans.
The following example shows how to inject a Java EE resource as a CDI bean into
another bean.
This example injects a persistence unit resource into a request-scoped bean.
import javax.enterprise.context.RequestScoped;
import javax.enterprise.inject.Inject;
@RequestScoped
public class SomeOtherClass {
...
@Inject @CustomerDatabase
private EntityManagerFactory emf;
...
}
For more information about the beans.xml file, see Configuring a CDI Application.
All classes in the resource adapter are available for injection. All classes in the
resource adapter can be CDI managed beans except for the following classes:
• Resource adapter beans. These beans are classes that are annotated with
the javax.resource.spi.Connector annotation or are declared as corresponding
elements in the resource adapter deployment descriptor ra.xml.
• Managed connection factory beans. These beans are classes that are
annotated with the javax.resource.spi.ConnectionDefinition annotation or
9-32
Chapter 9
Configuring a CDI Application
If your application does not use any alternatives, interceptors, or decorators, the
beans.xml file can be empty. However, you must provide the beans.xml file even if the
file is empty.
If your CDI application uses alternatives, interceptors, or decorators, you must enable
these items by declaring them in the beans.xml file. For more information, see:
• For a Web application, the beans.xml file must be in the WEB-INF directory.
• For an EJB module, resource archive (RAR) file, application client JAR file, or
library JAR file, the beans.xml file must be in the META-INF directory.
You can provide CDI bean archives in the lib directory of an EJB module. You must
provide a beans.xml file in the META-INF directory of each CDI bean archive the lib
directory of an EJB module.
Example 9-26 shows a beans.xml file for configuring a CDI application.
9-33
Chapter 9
Enabling and Disabling CDI
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/beans_1_1.xsd">
<alternatives>
<class>com.example.orderprocessor.MockOrderImpl</class>
</alternatives>
<interceptors>
<class>com.example.billpayment.interceptor.TransactionInterceptor</class>
</interceptors>
<decorators>
<class>com.example.billpayment.decorator.DataAccessAuthDecorator</class>
</decorators>
</beans>
<domain>
<cdi-container>
<policy>Disabled</policy>
</cdi-container>
<domain>
You can use the WLST scripting tool to enable or disable CDI for a domain. The
following examples demonstrate how to use WLST to enable and disable CDI for a
domain whether you are online or offline.
Example 9-27 Enabling CDI While Online
In the following example, WebLogic Server is running. The arguments username
and password represent the credentials for the user who is connecting WLST to the
server, and url represents the listen address and listen port of the server instance (for
example, localhost:7001). Also note that domain represents the domain name.
connect('user','password','url')
domainConfig()
edit()
cd('CdiContainer/mydomain')
9-34
Chapter 9
Implicit Bean Discovery
startEdit()
set('Policy','Enabled') // 'Enabled' or 'Disabled'
validate()
save()
activate(block="true")
readDomain('domain')
create('mydomain','CdiContainer')
cd('CdiContainer/mydomain')
set('Policy','Enabled') // 'Enabled' or 'Disabled'
updateDomain()
closeDomain()
You control whether implicit bean discovery is enabled in the domain by setting
the implicit-bean-discovery-enabled parameter on the CDI container. When this
parameter is set to 1, implicit bean discovery is enabled for all applications in the
domain. When the implicit-bean-discovery-enabled parameter is set to 0, implicit
bean discovery is disabled for all applications in the domain.
You can disable implicit bean discovery only for a domain.
<domain>
<cdi-container>
<implicit-bean-discovery-enabled>false</implicit-bean-discobery-enabled>
</cdi-container>
<domain>
You can use WLST scripting too to enable or disable this feature. The following
examples demonstrate how to use WLST to enable and disable implicit bean
discovery for a domain whether you are online or offline.
9-35
Chapter 9
Supporting Third-Party Portable Extensions
Code in CDI extensions can handle events that are sent by the CDI framework.
For more information, see "Portable extensions" in JSR 365: Contexts and
Dependency Injection for the Java EE platform.
9-36
Chapter 9
Using the Configurator Interfaces
Classes Package
Any javax.enterprise.inject
Default javax.enterprise.inject
New javax.enterprise.inject
Specialized javax.enterprise.inject
Veteod javax.enterprise.inject
Alternative javax.enterprise.inject
Typed javax.enterprise.inject
Nonbinding javax.enterprise.util
Initialized javax.enterprise.context
Destroyed javax.enterprise.context
RequestScoped javax.enterprise.context
SessionScoped javax.enterprise.context
ApplicationScoped javax.enterprise.context
Dependent javax.enterprise.context
ConversationScoped javax.enterprise.context
Syntax
Example 9-31 Built-in Annotation Literals
9-37
Chapter 9
Bootstrapping a CDI Container
See Configuring the CDI Container in Java EE 8 Tutorial for more information.
9-38
10
Java API for JSON Processing
WebLogic Server supports the Java API for JSON Processing 1.1 (JSR 374) by
including the JSR-374 reference implementation for use with applications deployed
on a WebLogic Server instance.
This chapter includes the following sections:
• About JavaScript Object Notation (JSON)
• Object Model API
• Streaming API
• New Features for JSON Processing
To learn more about JSON concepts, see Java API for JSON Processing in the Java
EE 8 Tutorial.
10-1
Chapter 10
Object Model API
from the rest of the data. The streaming model generates JSON output to a given
stream by making a function call with one element at a time.
For information about using the streaming model, see Streaming API.
These object models can also be created from an input source using the
javax.json.JsonReader interface. Similarly, these object models can be written to an
output source using the javax.json.JsonWriter interface.
The following sections show examples of using the object model API:
• Creating an Object Model from JSON Data
• Creating an Object Model from Application Code
• Navigating an Object Model
• Writing an Object Model to a Stream
The object reference jsonst can be either of type JsonObject or of type JsonArray,
depending on the contents of the file. JsonObject and JsonArray are subtypes of
JsonStructure. This reference represents the top of the tree and can be used to
navigate the tree or to write it to a stream as JSON data.
10-2
Chapter 10
Object Model API
The object reference model represents the top of the tree, which is created by nesting
invocations to the add methods and is built by invoking the build method. The
javax.json.JsonObjectBuilder interface contains the following add methods:
JsonObjectBuilder add(String name, BigDecimal value)
JsonObjectBuilder add(String name, BigInteger value)
JsonObjectBuilder add(String name, boolean value)
JsonObjectBuilder add(String name, double value)
JsonObjectBuilder add(String name, int value)
JsonObjectBuilder add(String name, JsonArrayBuilder builder)
JsonObjectBuilder add(String name, JsonObjectBuilder builder)
JsonObjectBuilder add(String name, JsonValue value)
JsonObjectBuilder add(String name, long value)
JsonObjectBuilder add(String name, String value)
JsonObjectBuilder addNull(String name)
The resulting tree represents the JSON data from JSON Syntax.
10-3
Chapter 10
Object Model API
case ARRAY:
System.out.println("ARRAY");
JsonArray array = (JsonArray) tree;
for (JsonValue val : array)
navigateTree(val, null);
break;
case STRING:
JsonString st = (JsonString) tree;
System.out.println("STRING " + st.getString());
break;
case NUMBER:
JsonNumber num = (JsonNumber) tree;
System.out.println("NUMBER " + num.toString());
break;
case TRUE:
case FALSE:
case NULL:
System.out.println(tree.getValueType().toString());
break;
}
}
The navigateTree method can be used with the models shown in Creating an Object
Model from JSON Data and Creating an Object Model from Application Code as
follows:
navigateTree(model, null);
The navigateTree method takes two arguments: a JSON element and a key. The key
is used only to help print the key-value pairs inside objects. Elements in a tree are
represented by the JsonValue type. If the element is an object or an array, a new
invocation to this method is made for every element contained in the object or array. If
the element is a value, it is printed to standard output.
The JsonValue.getValueType method identifies the element as an object, an array,
or a value. For objects, the JsonObject.keySet method returns a set of strings
that contains the keys in the object, and the JsonObject.get(String name) method
returns the value of the element whose key is name. For arrays, JsonArray implements
the List<JsonValue> interface. You can use enhanced for loops with the Set<String>
instance returned by JsonObject.keySet and with instances of JsonArray, as shown
in this example.
The navigateTree method for the model shown in Creating an Object Model from
Application Code produces the following output:
OBJECT
Key firstName: STRING Duke
Key lastName: STRING Java
Key age: NUMBER 18
Key streetAddress: STRING 100 Internet Dr
Key city: STRING JavaTown
Key state: STRING JA
Key postalCode: STRING 12345
Key phoneNumbers: ARRAY
OBJECT
Key type: STRING mobile
Key number: STRING 111-111-1111
OBJECT
Key type: STRING home
Key number: STRING 222-222-2222
10-4
Chapter 10
Streaming API
Streaming API
The streaming API is a low-level API designed to process large amounts of JSON data
efficiently.
This API consists of the following interfaces:
Interface Description
javax.json.stream.JsonParser Contains methods to parse JSON in a streaming way.
This interface provides forward, read-only access to
JSON data using the pull parsing programming model. In
this model the application code controls the thread and
calls methods in the parser interface to move the parser
forward or to obtain JSON data from the current state of
the parser.
javax.json.stream.JsonGenerator Contains methods to write JSON to an output source in a
streaming way.
This interface provides methods to write JSON to an
output source. The generator writes name-value pairs in
JSON objects and values in JSON arrays.
10-5
Chapter 10
Streaming API
For VALUE_NUMBER events, you can also use the following methods:
START_OBJECT
KEY_NAME firstName - VALUE_STRING Duke
KEY_NAME lastName - VALUE_STRING Java
KEY_NAME age - VALUE_NUMBER 18
KEY_NAME streetAddress - VALUE_STRING 100 Internet Dr
KEY_NAME city - VALUE_STRING JavaTown
10-6
Chapter 10
New Features for JSON Processing
10-7
Chapter 10
New Features for JSON Processing
JSON Pointer
JSON Pointer defines a string syntax for referencing a location in the target.
A JSON Pointer, when applied to a target JsonValue, defines a reference location in
the target. An empty JSON Pointer string defines a reference to the target itself.
JsonPointer provides the following methods:
/*add*/
JsonPointer pointer = Json.createPointer("/email");
contacts =
pointer.add(contacts,Json.createValue("duke@example.com"));
/*containsValue*/
JsonPointer pName = Json.createPointer("/firstName");
boolean exist = pName.containsValue(“John”);
/*getValue*/
JsonPointer pPhone = Json.createPointer("/phoneNumber/0");
Jsonvalue mobileNumber = (pPhone.getValue(contacts);
/*remove*/
JsonPointer pRemove = Json.createPointer("/phoneNumber/0");
contacts = pRemove.remove(contacts);
10-8
Chapter 10
New Features for JSON Processing
/*replace*/
JsonPointer pAge = Json.createPointer("/age");
pAge.replace(contacts,30);
The following is the resultant JSON document after running the JSON Pointer
examples:
{
"firstName": "Duke",
"lastName": "Java",
"age": 30,
"email": "duke@example.com",
"streetAddress": "100 Internet Dr",
"city": "JavaTown",
"state": "JA",
"postalCode": "12345",
"phoneNumbers": [
{ "Home": "222-222-2222" }
]
}
JSON Patch
JSON Patch defines a format for expressing a sequence of operations to be applied to
a JSON document.
JsonPatch mainly consists of two interfaces:
• JsonPatch - Provides apply(), toJsonArray() methods.
• JsonPatchBuilder - Provides add(), copy(), move(), replace(), remove(), and
test() methods.
A JsonPatch can be constructed using the following approaches:
• Constructing a JSON Patch with JsonPatchBuilder
10-9
Chapter 10
New Features for JSON Processing
JsonArray
patch=Json.createArrayBuilder().add(Json.createObjectBuilder()
.add("op","replace")
.add("path","/age")
.add("value", 30))
.build();
JsonPatch jsonPatch = Json.createPatch(patch);
JsonObject result1 = jsonPatch.apply(buildPerson());
command: [{"op":"replace","path":"/age","value":30}
10-10
Chapter 10
New Features for JSON Processing
directory, where ORACLE_HOME represents the directory in which you installed WebLogic
Server.
10-11
11
Java API for JSON Binding
JSON Binding (JSON-B) is a standard binding layer for converting Java objects to
or from JSON messages. Oracle WebLogic Server 14.1.1.0.0 supports the Java API
for JSON Binding 1.0 (JSR 367) specification by including the JSR-367 reference
implementation for use with applications deployed on a WebLogic Server instance.
JSON-B defines a default mapping algorithm for converting existing Java classes to
JSON, while enabling developers to customize the mapping process through the use
of Java annotations. For more information, see:
• JSON Binding in The Java EE 8 Tutorial.
• JSON Binding 1.0 Users Guide
• JSON Binding package summary
This chapter includes the following sections:
• About Default Mapping
• About Customized Mapping
• Standard Support to Handle Application or JSON Media Type for JAX-RS
The main entry point in JSON-B is the Jsonb class. It provides a set of overloaded
toJson and fromJson methods to serialize Java objects to JSON documents and
deserialize them back. Jsonb instances are thread safe and can be reused. It is
recommended to have a single instance per configuration type.
You can map an object, a collection, or a generic collection:
• Mapping an object
To map an object, you must first create a Jsonb instance, and use the toJson
method to serialize to JSON and the fromJson method to deserialize back to an
object.
• Mapping a collection or a generic collection
JSON-B supports collections and generic collections handling. For proper
deserialization, the runtime type of the resulting object needs to be passed to
JSON-B during deserialization.
For more information about default mapping, see:
• Default Mapping in JSON Binding 1.0 Users Guide
11-1
Chapter 11
About Customized Mapping
Note:
If both JSON-B and JSON-P are supported in the same environment, entity
providers for JSON-B take precedence over those for JSON-P, for all types
except JsonValue and its sub-types. Note the precedence with JSON-P.
If you selected to install the WebLogic Server Examples, you'll find an example that
demonstrates how to use the Java API for JSON Binding with JAX-RS in the
ORACLE_HOME\wlserver\samples\server\examples\src\examples\javaee8\jsonb\ja
xrs directory of your WebLogic Server distribution, where ORACLE_HOME represents the
directory in which you installed WebLogic Server. For more information about the
11-2
Chapter 11
Standard Support to Handle Application or JSON Media Type for JAX-RS
WebLogic Server code examples, see Sample Applications and Code Examples in
Understanding Oracle WebLogic Server.
11-3
12
Understanding WebLogic Server
Application Classloading
Java classloader is a part of the Java virtual machine (JVM) that loads classes into
memory. WebLogic Server Java EE application classloading enables WebLogic Server
to host multiple isolated applications within the same JVM.
This chapter includes the following sections:
• Java Classloading
• WebLogic Server Application Classloading
• Resolving Class References Between Modules and Applications
• Using the Classloader Analysis Tool (CAT)
• Sharing Applications and Modules By Using Java EE Libraries
• Adding JARs to the Domain /lib Directory
Java Classloading
Classloaders are a fundamental module of the Java language. A classloader is a
part of the Java virtual machine (JVM) that loads classes into memory; a classloader
is responsible for finding and loading class files at run time. Every successful Java
programmer needs to understand classloaders and their behavior.
• Java Classloader Hierarchy
• Loading a Class
• prefer-web-inf-classes Element
• Changing Classes in a Running Program
• Class Caching With the Policy Class Loader
• Class Caching With Application Class Data Sharing
12-1
Chapter 12
Java Classloading
However, anything in the extensions directory must be self-contained and can only
refer to classes in the extensions directory or JDK classes.
The system classpath classloader extends the JDK extensions classloader. The
system classpath classloader loads the classes from the classpath of the JVM.
Application-specific classloaders (including WebLogic Server classloaders) are
children of the system classpath classloader.
Note:
What Oracle refers to as a "system classpath classloader" is often referred
to as the "application classloader" in contexts outside of WebLogic Server.
When discussing classloaders in WebLogic Server, Oracle uses the term
"system" to differentiate from classloaders related to Java EE applications or
libraries (which Oracle refers to as "application classloaders").
Loading a Class
Classloaders use a delegation model when loading a class. The classloader
implementation first checks its cache to see if the requested class has already been
loaded. This class verification improves performance in that its cached memory copy
is used instead of repeated loading of a class from disk. If the class is not found in its
cache, the current classloader asks its parent for the class. Only if the parent cannot
load the class does the classloader attempt to load the class. If a class exists in both
the parent and child classloaders, the parent version is loaded. This delegation model
is followed to avoid multiple copies of the same form being loaded. Multiple copies of
the same class can lead to a ClassCastException.
Classloaders ask their parent classloader to load a class before attempting to load
the class themselves. Classloaders in WebLogic Server that are associated with Web
applications can be configured to check locally first before asking their parent for the
class. This allows Web applications to use their own versions of third-party classes,
which might also be used as part of the WebLogic Server product. The prefer-web-inf-
classes Element section discusses this in more detail.
prefer-web-inf-classes Element
The weblogic.xml Web application deployment descriptor contains a <prefer-web-
inf-classes> element (a sub-element of the <container-descriptor> element). By
default, this element is set to False. Setting this element to True subverts the
classloader delegation model so that class definitions from the Web application are
loaded in preference to class definitions in higher-level classloaders. This allows a
Web application to use its own version of a third-party class, which might also be part
of WebLogic Server. See weblogic.xml Deployment Descriptor Elements.
When using this feature, you must be careful not to mix instances created from the
Web application's class definition with instances created from the server's definition. If
such instances are mixed, a ClassCastException results.
12-2
Chapter 12
Java Classloading
12-3
Chapter 12
Java Classloading
Note:
If you want to disable the Policy Class Loader and use the standard system
class loader in JVM, set USE_JVM_SYSTEM_LOADER=true when you run the
startWebLogic script.
./startWebLogic.sh generateClassList
When you use class caching with AppCDS, the Policy Class Loader (PCL) will be
disabled.
./generateArchive.sh
APPCDS_CLASS_LIST=my.classlist APPCDS_ARCHIVE=myArchive.jsa ./
generateArchive.sh
12-4
Chapter 12
WebLogic Server Application Classloading
./startWebLogic.sh useArchive
You can change the default location of the AppCDS archive by setting the value of
APPCDS_ARCHIVE when starting the WebLogic Server. For example:
AppCDS is not compatible with Policy Class Loader. Therefore, Policy Class Loader
will be disabled.
12-5
Chapter 12
WebLogic Server Application Classloading
Note:
See the following sections for more information:
– For information on resource adapters and classloading, see About
Resource Adapter Classes.
– For information on overriding generic application files while
classloading, see Generic File Loading Overrides in Deploying
Applications to Oracle WebLogic Server.
If you deploy an EJB and a Web application separately, they are considered two
applications. If they are deployed together within an EAR file, they are one application.
You deploy modules together in an EAR file for them to be considered part of the same
application.
Every application receives its own classloader hierarchy; the parent of this hierarchy
is the system classpath classloader. This isolates applications so that application A
cannot see the classloaders or classes of application B. In hierarchy classloaders, no
sibling or friend concepts exist. Application code only has visibility to classes loaded
by the classloader associated with the application (or module) and classes that are
loaded by classloaders that are ancestors of the application (or module) classloader.
This allows WebLogic Server to host multiple isolated applications within the same
JVM.
12-6
Chapter 12
WebLogic Server Application Classloading
WebLogic Server
Application 1 Application 2
Note:
The Web application classloader contains all classes for the Web application
except for the JSP class. The JSP class obtains its own classloader, which is
a child of the Web application classloader. This allows JSPs to be individually
reloaded.
12-7
Chapter 12
WebLogic Server Application Classloading
The following diagram illustrates how classloaders are organized by default for
WebLogic applications. An application level classloader exists where all EJB classes
are loaded. For each Web module, there is a separate child classloader for the classes
of that module.
For simplicity, JSP classloaders are not described in the following diagram.
Application Classloader
[EJB 1] [EJB 2]
12-8
Chapter 12
WebLogic Server Application Classloading
Note:
JSP classloaders are not included in this definition scheme. JSPs are always
loaded into a classloader that is a child of the classloader associated with the
Web module to which it belongs.
For more information on the DTD elements, refer to Enterprise Application Deployment
Descriptor Elements.
The following is an example of a classloader declaration (defined in the classloader-
structure element in weblogic-application.xml):
<classloader-structure>
<module-ref>
<module-uri>ejb1.jar</module-uri>
</module-ref>
<module-ref>
<module-uri>web3.war</module-uri>
</module-ref>
<classloader-structure>
<module-ref>
<module-uri>web1.war</module-uri>
</module-ref>
</classloader-structure>
<classloader-structure>
<module-ref>
<module-uri>ejb3.jar</module-uri>
</module-ref>
<module-ref>
<module-uri>web2.war</module-uri>
</module-ref>
<classloader-structure>
<module-ref>
<module-uri>web4.war</module-uri>
</module-ref>
</classloader-structure>
<classloader-structure>
<module-ref>
<module-uri>ejb2.jar</module-uri>
</module-ref>
</classloader-structure>
</classloader-structure>
</classloader-structure>
The organization of the nesting indicates the classloader hierarchy. The above stanza
leads to a hierarchy shown in the following diagram.
12-9
Chapter 12
WebLogic Server Application Classloading
Application Classloader
[EJB 1] [WEB 3]
[WEB 4] [EJB 2]
Nesting Depth
Nesting is limited to three levels (including the application classloader). Deeper
nestings lead to a deployment exception.
Module Types
Custom classloader hierarchies are currently restricted to Web and EJB modules.
12-10
Chapter 12
WebLogic Server Application Classloading
Duplicate Entries
Duplicate entries lead to a deployment exception.
Interfaces
The standard WebLogic Server classloader hierarchy makes EJB interfaces available
to all modules in the application. Thus other modules can invoke an EJB, even though
they do not include the interface classes in their own module. This is possible because
EJBs are always loaded into the root classloader and all other modules either share
that classloader or have a classloader that is a child of that classloader.
With the custom classloader feature, you can configure a classloader hierarchy so that
a callee's classes are not visible to the caller. In this case, the calling module must
include the interface classes. This is the same requirement that exists when invoking
on modules in a separate application.
Call-by-Value Semantics
The standard classloader hierarchy provided with WebLogic Server allows for calls
between modules within an application to use call-by-reference semantics. This is
because the caller is always using the same classloader or a child classloader of
the callee. With this feature, it is possible to configure the classloader hierarchy so
that two modules are in separate branches of the classloader tree. In this case,
call-by-value semantics are used.
In-Flight Work
Be aware that the classloader switch required for reloading is not atomic across
modules. In fact, updates to applications in general are not atomic. For this reason,
it is possible that different in-flight operations (operations that are occurring while
a change is being made) might end up accessing different versions of classes
depending on timing.
12-11
Chapter 12
WebLogic Server Application Classloading
Module Classloader
Foo.class Bar.class
FooHome.class BarHome.class
Foolmpl.class Barlmpl.class
To perform a partial update of files relative to the root of the exploded application, use
the following command line:
Example 12-2 Performing a Partial File Update
java weblogic.Deployer -adminurl url -user user -password password
-name myapp -redeploy myejb/foo.class
After the -redeploy command, you provide a list of files relative to the root of the
exploded application that you want to update. This might be the path to a specific
element (as above) or a module (or any set of elements and modules). For example:
Example 12-3 Providing a List of Relative Files for Update
java weblogic.Deployer -adminurl url -user user -password password
-name myapp -redeploy mywar myejb/foo.class anotherejb
Given a set of files to be updated, the system tries to figure out the minimum set of
things it needs to redeploy. Redeploying only an EJB impl class causes only that class
to be redeployed. If you specify the whole EJB (in the above example, anotherejb)
or if you change and update the EJB home interface, the entire EJB module must be
redeployed.
Depending on the classloader hierarchy, this redeployment may lead to other modules
being redeployed. Specifically, if other modules share the EJB classloader or are
loaded into a classloader that is a child to the EJB's classloader (as in the WebLogic
Server standard classloader module) then those modules are also reloaded.
12-12
Chapter 12
WebLogic Server Application Classloading
the actual object is passed to the method. Pass by reference improves performance
because it avoids copying objects, but it also allows a method to modify the state of a
passed parameter.
WebLogic Server includes an optimization to improve the performance of Remote
Method Interface (RMI) calls within the server. Rather than using pass by value and
the RMI subsystem's marshalling and unmarshalling facilities, the server makes a
direct Java method call using pass by reference. This mechanism greatly improves
performance and is also used for EJB 2.0 local interfaces.
RMI call optimization and call by reference can only be used when the caller and
callee are within the same application. As usual, this is related to classloaders.
Because applications have their own classloader hierarchy, any application class has
a definition in both classloaders and receives a ClassCastException error if you try to
assign between applications. To work around this, WebLogic Server uses call-by-value
between applications, even if they are within the same JVM.
Note:
Calls between applications are slower than calls within the same application.
Deploy modules together as an EAR file to enable fast RMI calls and use of
the EJB 2.0 local interfaces.
12-13
Chapter 12
WebLogic Server Application Classloading
is not recommended that you filter out API classes, like classes in javax packages or
weblogic packages.
The FilteringClassLoader sits between the application classloader and the system
classloader. It is a child of the system classloader and the parent of the
application classloader. The FilteringClassLoader intercepts the loadClass(String
className) method and compares the className with a list of packages specified
in weblogic-application.xml file. If the package matches the className, the
FilteringClassLoader throws a ClassNotFoundException. This exception notifies the
application classloader to load this class from the application.
You can specify that a certain package be loaded for a WAR file included within an
EAR file by configuring the FilteringClassLoader in the weblogic.xml file of the
WAR file.
For example, A.ear contains B.war. A.ear defines the FilteringClassLoader in
weblogic-application.xml, and B.war defines a different FilteringClassLoader in
weblogic.xml. When you deploy A.ear, B.war loads the package defined in the
FilteringClassLoader in weblogic.xml. The WAR-level FilteringClassLoader has
priority over the EAR-level FilteringClassLoader for this WAR file.
For aid in configuring filtering classloaders, see Using the Classloader Analysis Tool
(CAT).
12-14
Chapter 12
WebLogic Server Application Classloading
Note:
The resources are returned in the default Java EE delegation model beneath
the FilteringClassLoader. Only the resources from the parent of the
FilteringClassLoader are appended to the end of the enumeration being
returned.
When filtering is enabled, the resources from the child of the FilteringClassLoader
(an application classloader) down to the calling classloader are returned before the
ones from the system classloader. In Example 12-5, if the same resource existed in all
the classloaders (D), (B) and (A) one would get them in the following order if requested
by the Web classloader:
META-INF/foo.xml - from the App ClassLoader (B)
META-INF/foo.xml - from the Web ClassLoader (A)
META-INF/foo.xml - from the System ClassLoader (D)
If the application classloader requested the same resource, the following order would
be obtained.
META-INF/foo.xml - from the App ClassLoader (B)
META-INF/foo.xml - from the System ClassLoader (D)
12-15
Chapter 12
Resolving Class References Between Modules and Applications
Manifest Class-Path
The Java EE specification provides the manifest Class-Path entry as a means for a
module to specify that it requires an auxiliary JAR of classes. You only need to use
12-16
Chapter 12
Using the Classloader Analysis Tool (CAT)
this manifest Class-Path entry if you have additional supporting JAR files as part of
your EJB JAR or WAR file. In such cases, when you create the JAR or WAR file, you
must include a manifest file with a Class-Path element that references the required
JAR files.
The following is a simple manifest file that references a utility.jar file:
Manifest-Version: 1.0 [CRLF]
Class-Path: utility.jar [CRLF]
In the first line of the manifest file, you must always include the Manifest-Version
attribute, followed by a new line (CR | LF |CRLF) and then the Class-Path
attribute. More information about the manifest format can be found at: https://
docs.oracle.com/en/java/javase/11/docs/specs/jar/jar.html
The manifest Class-Path entries refer to other archives relative to the current archive
in which these entries are defined. This structure allows multiple WAR files and EJB
JAR files to share a common library JAR. For example, if a WAR file contains a
manifest entry of y.jars, this entry should be next to the WAR file (not within it) as
follows:
/<directory>/x.war
/<directory>/y.jars
See http://docs.oracle.com/javase/tutorial/deployment/jar/
manifestindex.html.
Note:
CAT is not supported on IBM SDK for Java because some functions of the
CAT application depend on HotSpot implementation.
12-17
Chapter 12
Using the Classloader Analysis Tool (CAT)
12-18
Chapter 12
Using the Classloader Analysis Tool (CAT)
cat4mf.ear
+- ejb.jar
+- web-mf-in-root.war
+- lib
+- applib.jar
+- apputil_1.jar
+- apputil_1_1.jar
+- apputil_1_1_1.jar
+- apputil_1_2.jar
+- apputil_1_2_1.jar
+- ejbutil_1.jar
+- ejbutil_1_1.jar
+- ejbutil_1_2.jar
+- ejbutil_1_2_1.jar
+- webutil_1.jar
+- webutil_1_1.jar
+- webutil_1_1_1.jar
+- webutil_2.jar
+- webutil_2_1.jar
12-19
Chapter 12
Sharing Applications and Modules By Using Java EE Libraries
path/to/user_projects/applications/cat4mf/y79s0z/ejbutil_1_2.jar
path/to/user_projects/applications/cat4mf/y79s0z/ejbutil_1_2_1.jar
The lib subdirectory is intended for JAR files that change infrequently and are
required by all or most applications deployed in the server. For example, you might
use the lib directory to store third-party utility classes that are required by all Java EE
deployments in a domain. Third-party utility classes will be made available because
the domain /lib classloader will be the parent of any Java EE application.
12-20
Chapter 12
Adding JARs to the Domain /lib Directory
Note:
WebLogic Server must have read access to the lib directory during
startup.
The Administration Server does not automatically copy files in the
lib directory to Managed Servers on remote machines. If you have
Managed Servers that do not share the same physical domain directory
as the Administration Server, you must manually copy JAR file(s) to the
domain_name/lib directory on the Managed Server machines.
3. Start the Administration Server and all Managed Servers in the domain.
12-21
13
Creating Shared Java EE Libraries and
Optional Packages
You can share components and classes among applications using shared Java EE
libraries and optional packages supported in WebLogic Server.
This chapter includes the following sections:
• Overview of Shared Java EE Libraries and Optional Packages
• Creating Shared Java EE Libraries
• Referencing Shared Java EE Libraries in an Enterprise Application
• Referencing Optional Packages from a Java EE Application or Module
• Using weblogic.appmerge to Merge Libraries
• Integrating Shared Java EE Libraries with the Split Development Directory
Environment
• Deploying Shared Java EE Libraries and Dependent Applications
• Web Application Shared Java EE Library Information
• Using WebApp Libraries With Web Applications
• Accessing Registered Shared Java EE Library Information with
LibraryRuntimeMBean
• Order of Precedence of Modules When Referencing Shared Java EE Libraries
• Best Practices for Using Shared Java EE Libraries
13-1
Chapter 13
Overview of Shared Java EE Libraries and Optional Packages
Oracle recommends that you package a shared Java EE library into its appropriate
archive file (EAR, JAR, or WAR). However, for development purposes, you may
choose to deploy shared Java EE libraries as exploded archive directories to facilitate
repeated updates and redeployments.
After the shared Java EE library has been registered, you can deploy enterprise
applications that reference the library. Each referencing application receives a
reference to the required library on deployment, and can use the modules that make
up the library as if they were packaged as part of the referencing application itself.
The library classes are added to the class path of the referencing application, and the
primary deployment descriptors of the referencing application or module are merged
(in memory) with those of the modules that make up the shared Java EE library.
In general, this topic discusses shared Java EE libraries that can be referenced only
by enterprise applications. You can also create libraries that can be referenced only
by another Web application. The functionality is very similar to application libraries,
although the method of referencing them is slightly different. See Web Application
Shared Java EE Library Information for details.
Note:
WebLogic Server also provides a simple way to add one or more JAR files
to the WebLogic Server System classpath, using the lib subdirectory of the
domain directory. See Adding JARs to the Domain /lib Directory.
Optional Packages
WebLogic Server supports optional packages as described at https://
docs.oracle.com/javase/8/docs/technotes/guides/extensions/extensions.html
with versioning described in Optional Package Versioning (see https://
docs.oracle.com/javase/8/docs/technotes/guides/extensions/versioning.html).
Optional packages provide similar functionality to Java EE libraries, allowing you to
easily share a single JAR file among multiple applications. As with Java EE libraries,
optional packages must first be registered with WebLogic Server by deploying the
associated JAR file as an optional package. After registering the package, you can
deploy Java EE modules that reference the package in their manifest files.
Optional packages are also supported as Java EE shared libraries in
weblogic.BuildXMLGen, whereby all manifests of an application and its modules are
scanned to look for optional package references. If optional package references are
found they are added to the wlcompile and appc tasks in the generated build.xml file.
Optional packages differ from Java EE libraries because optional packages can be
referenced from any Java EE module (EAR, JAR, WAR, or RAR archive) or exploded
archive directory. Java EE libraries can be referenced only from a valid enterprise
application.
For example, third-party Web application Framework classes needed by multiple Web
applications can be packaged and deployed in a single JAR file, and referenced by
multiple Web application modules in the domain. Optional packages, rather than Java
EE libraries, are used in this case, because the individual Web application modules
must reference the shared JAR file. (With Java EE libraries, only a complete enterprise
application can reference the library).
13-2
Chapter 13
Overview of Shared Java EE Libraries and Optional Packages
Note:
Oracle documentation and WebLogic Server utilities use the term library to
refer to both Java EE libraries and optional packages. Optional packages are
called out only when necessary.
Library Directories
The Java EE platform provides several mechanisms for applications to use optional
packages and shared libraries. Libraries can be bundled with an application or may
be installed separately for use by any application. An EAR file may contain a directory
that contains libraries packaged in JAR files. The library-directory element of the
EAR file's deployment descriptor contains the name of this directory. If a library-
directory element isn't specified, or if the EAR file does not contain a deployment
descriptor, the directory named lib is used. An empty library-directory element
may be used to specify that there is no library directory. All files in this directory (but
not in subdirectories) with a .jar extension must be made available to all components
packaged in the EAR file, including application clients. These libraries may reference
other libraries, either bundled with the application or installed separately.
This feature is similar to the APP-INF/lib feature supported in WebLogic Server.
If both APP-INF/lib and library-directory exist, then the jars in the library-
directory would take precedence; that is, they would be placed before the APP-
INF/lib jar files in the classpath. For more information on APP-INF/lib, see Resolving
Class References Between Modules and Applications and Organizing Shared Classes
in a Split Development Directory.
13-3
Chapter 13
Overview of Shared Java EE Libraries and Optional Packages
13-4
Chapter 13
Creating Shared Java EE Libraries
Note:
Oracle documentation and WebLogic Server utilities use the term shared
Java EE library to refer to both libraries and optional packages. Optional
packages are called out only when necessary.
Additional Information
For information about deploying and managing shared Java EE libraries, optional
packages, and referencing applications from the administrator's perspective, see
Deploying Shared Java EE Libraries and Dependent Applications in Deploying
Applications to Oracle WebLogic Server.
13-5
Chapter 13
Creating Shared Java EE Libraries
• You must ensure that context roots in Web application modules of the shared
Java EE library do not conflict with context roots in the referencing enterprise
application. If necessary, you can configure referencing applications to override a
library's context root. See Referencing Shared Java EE Libraries in an Enterprise
Application.
• Shared Java EE libraries cannot be nested. For example, if you are deploying
an EAR as a shared Java EE library, the entire EAR must be designated as
the library. You cannot designate individual Java EE modules within the EAR as
separate, named libraries.
• As with any other Java EE module or enterprise application, a shared Java
EE library must be configured for deployment to the target servers or clusters
in your domain. This means that a library requires valid Java EE deployment
descriptors as well as WebLogic Server-specific deployment descriptors and an
optional deployment plan. See Deploying Applications to Oracle WebLogic Server.
Oracle recommends packaging shared Java EE libraries as enterprise applications,
rather than as standalone Java EE modules. This is because the URI of a standalone
module is derived from the deployment name, which can change depending on how
the module is deployed. By default, WebLogic Server uses the deployment archive
filename or exploded archive directory name as the deployment name. If you redeploy
a standalone shared Java EE library from a different file or location, the deployment
name and URI also change, and referencing applications that use the wrong URI
cannot access the deployed library.
If you choose to deploy a shared Java EE library as a standalone Java EE module,
always specify a known deployment name during deployment and use that name as
the URI in referencing applications.
13-6
Chapter 13
Creating Shared Java EE Libraries
Attribute Description
Extension-Name An optional string value that identifies the name of the shared Java EE library.
Referencing applications must use the exact Extension-Name value to use the
library.
As a best practice, always specify an Extension-Name value for each library. If
you do not specify an extension name, one is derived from the deployment name
of the library. Default deployment names are different for archive and exploded
archive deployments, and they can be set to arbitrary values in the deployment
command.
Specification- An optional String value that defines the specification version of the shared
Version Java EE library. Referencing applications can optionally specify a required
Specification-Version for a library; if the exact specification version is not
available, deployment of the referencing application fails.
The Specification-Version uses the following format:
Major/minor version format, with version and revision numbers separated by
periods (such as "9.0.1.1")
Referencing applications can be configured to require either an exact version of
the shared Java EE library, a minimum version, or the latest available version.
The specification version for a shared Java EE library can also be set at the
command-line when deploying the library, with some restrictions. See Deploying
Shared Java EE Libraries and Dependent Applications.
Implementation- An optional String value that defines the code implementation version of the
Version shared Java EE library. You can provide an Implementation-Version only if you
have also defined a Specification-Version.
Implementation-Version uses the following formats:
• Major/minor version format, with version and revision numbers separated
by periods (such as "9.0.1.1")
• Text format, with named versions (such as "9011Beta" or "9.0.1.1.B")
If you use the major/minor version format, referencing applications can be
configured to require either an exact version of the shared Java EE library, a
minimum version, or the latest available version. If you use the text format,
referencing applications must specify the exact version of the library.
The implementation version for a shared Java EE library can also be set at the
command-line when deploying the library, with some restrictions. See Deploying
Shared Java EE Libraries and Dependent Applications.
13-7
Chapter 13
Referencing Shared Java EE Libraries in an Enterprise Application
2. In the text editor, add a string value to specify the name of the shared Java EE
library. For example:
Extension-Name: myExtension
Applications that reference the library must specify the exact Extension-Name in
order to use the shared files.
3. As a best practice, enter the optional version information for the shared Java EE
library. For example:
Extension-Name: myExtension
Specification-Version: 2.0
Implementation-Version: 9.0.0
Using the major/minor format for the version identifiers provides the most flexibility
when referencing the library from another application (see Table 13-2)
Note:
Although you can optionally specify the Specification-Version and
Implementation-Version at the command line during deployment, Oracle
recommends that you include these strings in the MANIFEST.MF file.
Including version strings in the manifest ensures that you can deploy
new versions of the library alongside older versions. See Deploying
Shared Java EE Libraries and Dependent Applications.
Table 13-2 describes the XML elements that define a library reference.
13-8
Chapter 13
Referencing Shared Java EE Libraries in an Enterprise Application
Element Description
library-ref library-ref is the parent element in which you define a reference to a shared Java
EE library. Enclose all other elements within library-ref.
library-name A required string value that specifies the name of the shared Java EE library to use.
library-name must exactly match the value of the Extension-Name attribute in the
library's manifest file. (See Table 13-2.)
specification- An optional String value that defines the required specification version of the
version shared Java EE library. If this element is not set, the application uses a matching
library with the highest specification version. If you specify a string value using
major/minor version format, the application uses a matching library with the
highest specification version that is not below the configured value. If all available
libraries are below the configured specification-version, the application cannot
be deployed. The required version can be further constrained by using the exact-
match element, described below.
If you specify a String value that does not use major/minor versioning conventions
(for example, 9.2BETA) the application requires a shared Java EE library having the
exact same string value in the Specification-Version attribute in the library's
manifest file. (See Table 13-2.)
implementation- An optional String value that specifies the required implementation version of
version the shared Java EE library. If this element is not set, the application uses a
matching library with the highest implementation version. If you specify a string
value using major/minor version format, the application uses a matching library
with the highest implementation version that is not below the configured value.
If all available libraries are below the configured implementation-version, the
application cannot be deployed. The required implementation version can be
further constrained by using the exact-match element, described below.
If you specify a String value that does not use major/minor versioning conventions
(for example, 9.2BETA) the application requires a shared Java EE library having the
exact same string value in the Implementation-Version attribute in the library's
manifest file. (See Table 13-2.)
exact-match An optional Boolean value that determines whether the application should use a
shared Java EE library with a higher specification or implementation version than
the configured value, if one is available. By default this element is false, which
means that WebLogic Server uses higher-versioned libraries if they are available.
Set this element to true to require the exact matching version as specified in the
specification-version and implementation-version elements.
context-root An optional String value that provides an alternate context root to use for a Web
application shared Java EE library. Use this element if the context root of a library
conflicts with the context root of a Web application in the referencing Java EE
application.
Web application shared Java EE library refers to special kind of library: a Web
application that is referenced by another Web application. See Web Application
Shared Java EE Library Information.
13-9
Chapter 13
Referencing Shared Java EE Libraries in an Enterprise Application
In the above example, WebLogic Server attempts to find a library name myLibrary
when deploying the dependent application. If more than one copy of myLibrary is
registered, WebLogic Server selects the library with the highest specification version. If
multiple copies of the library use the selected specification version, WebLogic Server
selects the copy having the highest implementation version.
This example references a shared Java EE library with a requirement for the
specification version:
<library-ref>
<library-name>myLibrary</library-name>
<specification-version>2.0</specification-version>
</library-ref>
In the above example, WebLogic Server looks for matching libraries having a
specification version of 2.0 or higher. If multiple libraries are at or above version
2.0, WebLogic Server examines the selected libraries that use Float values for their
implementation version and selects the one with the highest version. Note that
WebLogic Server ignores any selected libraries that have a non-Float value for the
implementation version.
This example references a shared Java EE library with both a specification version
and a non-Float value implementation version:
<library-ref>
<library-name>myLibrary</library-name>
<specification-version>2.0</specification-version>
<implementation-version>81Beta</implementation-version>
</library-ref>
In the above example, WebLogic Server searches for a library having a specification
version of 2.0 or higher, and having an exact match of 81Beta for the implementation
version.
The following example requires an exact match for both the specification and
implementation versions:
<library-ref>
<library-name>myLibrary</library-name>
<specification-version>2.0</specification-version>
<implementation-version>8.1</implementation-version>
<exact-match>true</exact-match>
</library-ref>
The following example specifies a context-root with the library reference. When a
WAR library reference is made from weblogic-application.xml, the context-root
may be specified with the reference:
<library-ref>
<library-name>myLibrary</library-name>
<context-root>mywebapp</context-root>
</library-ref>
13-10
Chapter 13
Referencing Shared Java EE Libraries in an Enterprise Application
Element Description
context-root An optional String value that overrides the context-root elements declared in libraries.
In the absence of this element, the library's context-root is used.
Only a referencing application (for example, a user application) can override the
context-root elements declared in its libraries.
override- An optional String value that specifies the value of the library-context-root-
value override element when overriding the context-root elements declared in libraries. In
the absence of these elements, the library's context-root is used.
In the above example, the current application refers to myLibrary, which contains
a Web application with a context-root of webapp. The only way to override this
reference is to declare a library-context-root-override that maps webapp to
mywebapp.
13-11
Chapter 13
Referencing Optional Packages from a Java EE Application or Module
Attribute Description
Extension-List A required String value that defines a logical name for an optional
logical_name [...] package dependency. You can use multiple values in the Extension-
List attribute to designate multiple optional package dependencies. For
example:
Extension-List: dependency1 dependency2
[logical_name-]Extension- A required string value that identifies the name of an optional package
Name dependency. This value must match the Extension-Name attribute
defined in the optional package's manifest file.
If you are referencing multiple optional packages from a single archive,
prepend the appropriate logical name to the Extension-Name attribute.
For example:
dependency1-Extension-Name: myOptPkg
[logical_name-]Specificatio An optional String value that defines the required specification version
n-Version of an optional package. If this element is not set, the archive uses a
matching package with the highest specification version. If you include
a specification-version value using the major/minor version format,
the archive uses a matching package with the highest specification
version that is not below the configured value. If all available package
are below the configured specification-version, the archive cannot be
deployed.
If you specify a String value that does not use major/minor
versioning conventions (for example, 9.2BETA) the archive requires a
matching optional package having the exact same string value in the
Specification-Version attribute in the package's manifest file. (See
Table 13-2.)
If you are referencing multiple optional packages from a single archive,
prepend the appropriate logical name to the Specification-Version
attribute.
13-12
Chapter 13
Referencing Optional Packages from a Java EE Application or Module
Attribute Description
[logical_name-]Implementati An optional String value that specifies the required implementation
on-Version version of an optional package. If this element is not set, the archive
uses a matching package with the highest implementation version. If you
specify a string value using the major/minor version format, the archive
uses a matching package with the highest implementation version that
is not below the configured value. If all available libraries are below
the configured implementation-version, the application cannot be
deployed.
If you specify a String value that does not use major/minor
versioning conventions (for example, 9.2BETA) the archive requires a
matching optional package having the exact same string value in the
Implementation-Version attribute in the package's manifest file. (See
Table 13-2.)
If you are referencing multiple optional packages from a single archive,
prepend the appropriate logical name to the Implementation-Version
attribute.
For example, this simple entry in the manifest file for a dependent archive references
two optional packages, myAppPkg and my3rdPartyPkg:
Extension-List: internal 3rdparty
internal-Extension-Name: myAppPkg
3rdparty-Extension-Name: my3rdPartyPkg
This example requires a specification version of 2.0 or higher for myAppPkg, and an
exact match for the implementation version of my3rdPartyPkg:
Extension-List: internal 3rdparty
internal-Extension-Name: myAppPkg
3rdparty-Extension-Name: my3rdPartyPkg
internal-Specification-Version: 2.0
3rdparty-Implementation-Version: 8.1GA
13-13
Chapter 13
Using weblogic.appmerge to Merge Libraries
Option Comment
-help Print the standard usage message.
-version Print version information.
-output <file> Specifies an alternate output archive or directory. If not set, output is
placed in the source archive or directory.
-plan <file> Specifies an optional deployment plan.
-verbose Provide more verbose output.
-library <file> Comma-separated list of libraries. Each library may optionally set its name
and versions, if not already set in its manifest, using the following syntax:
<file> [@name=<string>@libspecver=<version>
@libimplver=<version|string>].
-librarydir <dir> Registers all files in specified directory as libraries.
- Specifies that the application or module contains deployment descriptors
writeInferredDescriptors with annotation information.
Example:
$ java weblogic.appmerge -output CompleteSportsApp.ear -library
Weather.war,Calendar.ear SportsApp.ear
13-14
Chapter 13
Integrating Shared Java EE Libraries with the Split Development Directory Environment
<library file="Calendar.ear"/>
</appmerge>
13-15
Chapter 13
Using WebApp Libraries With Web Applications
Web application. The functionality is very similar to application libraries, although the
method of referencing them is slightly different.
Note:
For simplicity, this section uses the term Web application library when
referring to a shared Java EE library that is referenced only by another Web
application.
In particular:
• Web application libraries can only be referenced by other Web applications.
• Rather than update the weblogic-application.xml file, Web applications
reference Web application libraries by updating the weblogic.xml deployment
descriptor file. The elements are almost the same as those described in
Referencing Shared Java EE Libraries in an Enterprise Application; the only
difference is that the <context-root> child element of <library-ref> is ignored in
this case.
• You cannot reference any other type of shared Java EE library (EJB, enterprise
application, or plain JAR file) from the weblogic.xml deployment descriptor file of
a Web application.
Other than these differences in how they are referenced, the way to create, package,
and deploy a Web application library is the same as that of a standard shared Java EE
library.
The first step in using a WebApp library is to register a Web application as a webapp-
library. This can be accomplished by deploying a Web application using either the
WebLogic Server Administration Console or the weblogic.Deployer tool as a library.
To make other Web applications refer to this library, their weblogic.xml file must have
a library-ref element pointing to the webapp-library, as follows:
<library-ref>
<library-name>BaseWebApp</library-name>
<specification-version>2.0</specification-version>
<implementation-version>8.1beta</implementation-version>
<exact-match>false</exact-match>
</library-ref>
13-16
Chapter 13
Accessing Registered Shared Java EE Library Information with LibraryRuntimeMBean
When multiple libraries are present, the CLASSPATH/resource path precedence order
follows the order in which the library-refs elements appear in the weblogic.xml file.
13-17
Chapter 13
Best Practices for Using Shared Java EE Libraries
module called myEJB, and both the myLibA and myLibB applications include an EJB
module called myOtherEJB.
Further assume that once the myApp application is deployed, a client invokes, via
the myApp application, the myEJB module. In this case, WebLogic Server actually
invokes the EJB in the myApp application (rather than the one in myLibA) because
modules in the referencing application have higher precedence over modules in the
referenced applications. If a client invokes the myOtherEJB EJB, then WebLogic Server
invokes the one in myLibA, because the library is referenced first in the weblogic-
application.xml file of myApp, and thus has precedence over the EJB with the same
name in the myLibB application.
13-18
Chapter 13
Best Practices for Using Shared Java EE Libraries
13-19
14
Programming Application Life Cycle Events
Learn how to create applications that respond to WebLogic Server application life
cycle events.
This chapter includes the following sections:
• Understanding Application Life Cycle Events
• Registering Events in weblogic-application.xml
• Programming Basic Life Cycle Listener Functionality
• Examples of Configuring Life Cycle Events with and without the URI Parameter
• Understanding Application Life Cycle Event Behavior During Re-deployment
• Programming Application Version Life Cycle Events
Note:
Application-scoped startup and shutdown classes have been deprecated
as of release 9.0 of WebLogic Server. The information in this chapter
about startup and shutdown classes is provided only for backwards
compatibility. Instead, you should use life cycle listener events in your
applications.
14-1
Chapter 14
Registering Events in weblogic-application.xml
The postStop event is the end of the remove phase, or the end of the
application removal or undeployment process.
• Shutdown classes only get postStop events.
Note:
Application-scoped shutdown classes have been deprecated as of
release 9.0 of WebLogic Server. Use life cycle listeners instead.
Note:
Application-scoped shutdown classes have been deprecated as of
release 9.0 of WebLogic Server. Use life cycle listeners instead.
For Startup and Shutdown classes, you only implement a main{}
method. If you implement any of the methods provided for Listeners,
they are ignored.
No remove{} method is provided in the ApplicationLifecycleListener,
because the events are only fired at startup time during deployment
(prestart and poststart) and shutdown during undeployment (prestop and
poststop).
14-2
Chapter 14
Programming Basic Life Cycle Listener Functionality
• postStart{}
• preStop{}
• postStop{}
Example 14-1 illustrates how you override the ApplicationLifecycleListener. In this
example, the public class MyListener extends ApplicationLifecycleListener.
Example 14-1 MyListener
import weblogic.application.ApplicationLifecycleListener;
import weblogic.application.ApplicationLifecycleEvent;
public class MyListener extends ApplicationLifecycleListener {
public void preStart(ApplicationLifecycleEvent evt) {
System.out.println
("MyListener(preStart) -- we should always see you..");
} // preStart
public void postStart(ApplicationLifecycleEvent evt) {
System.out.println
("MyListener(postStart) -- we should always see you..");
} // postStart
public void preStop(ApplicationLifecycleEvent evt) {
System.out.println
("MyListener(preStop) -- we should always see you..");
} // preStop
public void postStop(ApplicationLifecycleEvent evt) {
System.out.println
("MyListener(postStop) -- we should always see you..");
} // postStop
public static void main(String[] args) {
System.out.println
("MyListener(main): in main .. we should never see you..");
} // main
}
Example 14-2 illustrates how you implement the shutdown class. The shutdown class
is attachable to preStop and postStop events. In this example, the public class
MyShutdown does not extend ApplicationLifecycleListener because a shutdown
class declared in the weblogic-application.xml deployment descriptor does not
need to depend on any WebLogic Server-specific interfaces.
Example 14-2 MyShutdown
import weblogic.application.ApplicationLifecycleListener;
import weblogic.application.ApplicationLifecycleEvent;
public class MyShutdown {
public static void main(String[] args) {
System.out.println
("MyShutdown(main): in main .. should be for post-stop");
} // main
}
Example 14-3 illustrates how you implement the startup class. The startup class
is attachable to preStart and postStart events. In this example, the public class
MyStartup does not extend ApplicationLifecycleListener because a startup class
declared in the weblogic-application.xml deployment descriptor does not need to
depend on any WebLogic Server-specific interfaces.
14-3
Chapter 14
Examples of Configuring Life Cycle Events with and without the URI Parameter
The following examples illustrate how you configure application life cycle events in
the weblogic-application.xml deployment descriptor file. The URI parameter is not
required. You can place classes anywhere in the application $CLASSPATH. However,
you must ensure that the class locations are defined in the $CLASSPATH. You can place
listeners in APP-INF/classes or APP-INF/lib, if these directories are present in the
EAR. In this case, they are automatically included in the $CLASSPATH.
The following example illustrates how you configure application life cycle events using
the URI parameter. In this case, the archive foo.jar contains the classes and exists at
the top level of the EAR file. For example: myEar/foo.jar.
Example 14-4 Configuring Application Life Cycle Events Using the URI
Parameter
<listener>
<listener-class>MyListener</listener-class>
<listener-uri>foo.jar</listener-uri>
14-4
Chapter 14
Understanding Application Life Cycle Event Behavior During Redeployment
</listener>
<startup>
<startup-class>MyStartup</startup-class>
<startup-uri>foo.jar</startup-uri>
</startup>
<shutdown>
<shutdown-class>MyShutdown</shutdown-class>
<shutdown-uri>foo.jar</shutdown-uri>
</shutdown>
The following example illustrates how you configure application life cycle events
without using the URI parameter.
Example 14-5 Configuring Application Life Cycle Events without Using the URI
Parameter
<listener>
<listener-class>MyListener</listener-class>
</listener>
<startup>
<startup-class>MyStartup</startup-class>
</startup>
<shutdown>
<shutdown-class>MyShutdown</shutdown-class>
</shutdown>
14-5
Chapter 14
Programming Application Version Life Cycle Events
Note:
A postDelete event is only fired after the entire application version is
completely removed. It does not include a partial undeploy, such as
undeploying a module or from a subset of targets.
14-6
Chapter 14
Programming Application Version Life Cycle Events
Table 14-1 Sequence of Deployment Actions and Application Version Life Cycle Events
14-7
Chapter 14
Programming Application Version Life Cycle Events
Table 14-1 (Cont.) Sequence of Deployment Actions and Application Version Life Cycle Events
14-8
15
Programming Context Propagation
Learn how to use the context propagation APIs in WebLogic Server applications.
This chapter includes the following sections:
• Understanding Context Propagation
• Programming Context Propagation: Main Steps
• Programming Context Propagation in a Client
• Programming Context Propagation in an Application
15-1
Chapter 15
Programming Context Propagation: Main Steps
Table 15-1 Interfaces and classes of the WebLogic Context Propagation API
For the complete API documentation about context propagation, see the
weblogic.workarea Javadocs.
15-2
Chapter 15
Programming Context Propagation in a Client
3. Update your application (EJB, Web service, servlet, and so on) to also create a
WorkContextMap and then get the context and user data that you added from the
client application.
See Programming Context Propagation in an Application.
Note:
See Developing JAX-WS Web Services for Oracle WebLogic Server for
information on creating Web services and client applications that invoke
them.
package examples.workarea.client;
import java.rmi.RemoteException;
import javax.xml.rpc.ServiceException;
import javax.xml.rpc.Stub;
import javax.naming.InitialContext;
import javax.naming.NamingException;
import weblogic.workarea.WorkContextMap;
import weblogic.workarea.WorkContext;
import weblogic.workarea.PrimitiveContextFactory;
import weblogic.workarea.PropagationMode;
import weblogic.workarea.PropertyReadOnlyException;
/**
* This is a simple standalone client application that invokes the
* the <code>sayHello</code> operation of your WorkArea Web service.
*
*/
public class Main {
public final static String SESSION_ID= "session_id_key";
public static void main(String[] args)
throws ServiceException, RemoteException, NamingException,
PropertyReadOnlyException{
YourWorkAreaService service = new YourWorkAreaService(args[0] + "?WSDL");
YourWorkAreaPortType port = service.getWorkAreaPort();
WorkContextMap map = (WorkContextMap)new
InitialContext().lookup("java:comp/WorkContextMap");
WorkContext stringContext = PrimitiveContextFactory.create("A String
Context");
// Put a string context
map.put(SESSION_ID, stringContext, PropagationMode.SOAP);
try {
15-3
Chapter 15
Programming Context Propagation in an Application
import weblogic.workarea.WorkContextMap;
import weblogic.workarea.WorkContext;
import weblogic.workarea.PrimitiveContextFactory;
import weblogic.workarea.PropagationMode;
import weblogic.workarea.PropertyReadOnlyException;
• Substitute your implementation of the WorkArea service and port for your Web
service for YourWorkAreaService and YourWorkAreaPortType.
• The following code shows how to create a WorkContextMap by doing
a JNDI lookup of the context propagation-specific JNDI name java:comp/
WorkContextMap:
WorkContextMap map = (WorkContextMap)
new InitialContext().lookup("java:comp/WorkContextMap");
• The following code shows how to create a WorkContext by using the
PrimitiveContextFactory. In this example, the WorkContext consists of the
simple String value A String Context. This String value is the user data that
is passed to the invoked Web service.
WorkContext stringContext =
PrimitiveContextFactory.create("A String Context");
• The following code saves the stringContext under the SESSION_ID key in the
WorkContextMap. Specifying the propagation mode of SOAP causes the propagation
of the stringContext along any SOAP message sent to servers supporting context
propagation.
map.put(SESSION_ID, stringContext, PropagationMode.SOAP);
15-4
Chapter 15
Programming Context Propagation in an Application
Note:
See Developing JAX-WS Web Services for Oracle WebLogic Server for
information on creating Web services and client applications that invoke
them.
package examples.workarea;
import javax.naming.InitialContext;
// Import the Context Propagation classes
import weblogic.workarea;
import weblogic.workarea.WorkContextMap;
import weblogic.workarea.WorkContext;
import javax.jws.WebMethod;
import javax.jws.WebService;
import weblogic.jws.WLHttpTransport;
@WebService(name="WorkAreaPortType",
serviceName="WorkAreaService",
targetNamespace="http://example.org")
@WLHttpTransport(contextPath="workarea",
serviceUri="WorkAreaService",
portName="WorkAreaPort")
/**
* This JWS file forms the basis of simple WebLogic
* Web service with a single operation: sayHello
*
*/
public class WorkContextAwareWebService {
public final static String SESSION_ID = "session_id_key";
@WebMethod()
public String sayHello(String message) {
try {
WorkContextMap map = (WorkContextMap) new
InitialContext().lookup("java:comp/WorkContextMap");
WorkContext localwc = map.get(SESSION_ID);
WorkContext modifiedLocalWC =
PrimitiveContextFactory.create(localwc.get() + " could be replaced by a
new value...");
map.put(SESSION_ID, newLocalWC, PropagationMode.SOAP);
System.out.println("local context: " + localwc);
System.out.println("sayHello: " + message);
return "The server received message: " + message + ", with SESSION_ID: " +
localwc;
} catch (Throwable t) {
return "error";
}
}
}
15-5
Chapter 15
Programming Context Propagation in an Application
15-6
16
Programming JavaMail with WebLogic
Server
Learn how to program JavaMail with WebLogic Server to add email capabilities to your
WebLogic Server applications.
This chapter includes the following sections:
• Overview of Using JavaMail with WebLogic Server Applications
• Understanding JavaMail Configuration Files
• Configuring JavaMail for WebLogic Server
• Sending Messages with JavaMail
• Reading Messages with JavaMail
• javax.mail
• javax.mail.event
• javax.mail.internet
• javax.mail.search
The weblogic.jar also contains the Java Activation Framework (JAF) package, which
JavaMail requires.
The javax.mail package includes providers for Internet Message Access protocol
(IMAP) and Simple Mail Transfer Protocol (SMTP) mail servers. There is a separate
POP3 provider for JavaMail, which is not included in weblogic.jar. You can
download the POP3 provider at https://maven.java.net/content/repositories/
releases/com/sun/mail/pop3 and add it to the WebLogic Server classpath if you want
to use it.
16-1
Chapter 16
Understanding JavaMail Configuration Files
16-2
Chapter 16
Reading Messages with JavaMail
3. If you need to override the properties you set for the Session in the WebLogic
Server Administration Console, create a java.util.Properties object and add
the properties you want to override. Then call getInstance() to get a new Session
object with the new properties.
Properties props = new Properties();
props.put("mail.transport.protocol", "smtp");
props.put("mail.smtp.host", "mailhost");
// use mail address from HTML form for from address
props.put("mail.from", emailAddress);
Session session2 = session.getInstance(props);
4. Construct a MimeMessage. In the following example, to, subject, and messageTxt
are String variables containing input from the user.
Message msg = new MimeMessage(session2);
msg.setFrom();
msg.setRecipients(Message.RecipientType.TO,
InternetAddress.parse(to, false));
msg.setSubject(subject);
msg.setSentDate(new Date());
// Content is stored in a MIME multi-part message
// with one body part
MimeBodyPart mbp = new MimeBodyPart();
mbp.setText(messageTxt);
Multipart mp = new MimeMultipart();
mp.addBodyPart(mbp);
msg.setContent(mp);
5. Send the message.
Transport.send(msg);
The JNDI lookup can throw a NamingException on failure. JavaMail can throw
a MessagingException if there are problems locating transport classes or if
communications with the mail host fails. Be sure to put your code in a try block and
catch these exceptions.
16-3
Chapter 16
Reading Messages with JavaMail
Here are steps to read incoming messages on a POP3 server from within a WebLogic
Server module:
1. Import the JNDI (naming), JavaBean Activation, and JavaMail packages. You will
also need to import java.util.Properties:
import java.util.*;
import javax.activation.*;
import javax.mail.*;
import javax.mail.internet.*;
import javax.naming.*;
2. Look up the Mail Session in JNDI:
InitialContext ic = new InitialContext();
Session session = (Session) ic.lookup("myMailSession");
3. If you need to override the properties you set for the Session in the WebLogic
Server Administration Console, create a Properties object and add the properties
you want to override. Then call getInstance() to get a new Session object with
the new properties:
Properties props = new Properties();
props.put("mail.store.protocol", "pop3");
props.put("mail.pop3.host", "mailhost");
Session session2 = session.getInstance(props);
4. Get a Store object from the Session and call its connect() method to connect to
the mail server. To authenticate the connection, you need to supply the mailhost,
user name, and password in the connect method:
Store store = session.getStore();
store.connect(mailhost, username, password);
5. Get the default folder, then use it to get the INBOX folder:
Folder folder = store.getDefaultFolder();
folder = folder.getFolder("INBOX");
6. Read the messages in the folder into an array of Messages:
Message[] messages = folder.getMessages();
7. Operate on messages in the Message array. The Message class has methods that
allow you to access the different parts of a message, including headers, flags, and
message contents.
Reading messages from an IMAP server is similar to reading messages from a
POP3 server. With IMAP, however, the JavaMail API provides methods to create and
manipulate folders and transfer messages between them. If you use an IMAP server,
you can implement a full-featured, Web-based mail client with much less code than if
you use a POP3 server. With POP3, you must provide code to manage a message
store via WebLogic Server, possibly using a database or file system to represent
folders.
16-4
17
Threading and Clustering Topics
Learn how to use threads in WebLogic Server as well as how to program applications
for use in WebLogic Server clusters.
This chapter includes the following sections:
• Using Threads in WebLogic Server
• Using the Work Manager API for Lower-Level Threading
• Programming Applications for WebLogic Server Clusters
17-1
Chapter 17
Using the Work Manager API for Lower-Level Threading
independent, isolated tasks, such as conversing with an external service with a TCP/IP
connection or, with proper locking, reading or writing to files. A short-lived thread that
accomplishes a single purpose and ends (or returns to the thread pool) is less likely to
interfere with other threads.
Avoid creating daemon threads in modules that are packaged in applications deployed
on WebLogic Server. When you create a daemon thread in an application module such
as a servlet, you will not be able to redeploy the application because the daemon
thread created in the original deployment will remain running.
Be sure to test multithreaded code under increasingly heavy loads, adding clients
even to the point of failure. Observe the application performance and WebLogic Server
behavior and then add checks to prevent failures from occurring in production.
17-2
18
Developing OSGi Bundles for WebLogic
Server Applications
Learn about the OSGi environment in WebLogic Server and how to deploy OSGi
bundles to WebLogic Server. Developers who want to use OSGi in their applications
can easily share OSGi facilities, such as the OSGi service registry, class loaders, and
other OSGi services.
For general information about OSGi, see http://www.osgi.org.
Understanding OSGi
OSGi is a Java modularity system developed and maintained by the OSGi Alliance, of
which Oracle is a member.
The OSGi specifications and related Javadoc together describe a comprehensive
operating environment for Java applications:
• You can download the OSGi Service Platform Core Specification from https://
docs.osgi.org/specification/.
• The OSGi Javadoc is available from https://docs.osgi.org/specification/.
As described on the OSGi Alliance Web page, "The OSGi Alliance is a worldwide
consortium of technology innovators that advances a proven and mature process to
create open specifications that enable the modular assembly of software built with
Java technology. Modularity reduces software complexity; OSGi is the best model to
modularize Java.."
The OSGi Architecture Web page further describes the OSGi technology as "...a set of
specifications that define a dynamic component system for Java. These specifications
enable a development model where applications are (dynamically) composed of
many different (reusable) components. The OSGi specifications enable components
to hide their implementations from other components while communicating through
services, which are objects that are specifically shared between components. This
18-1
Chapter 18
Features Provided in WebLogic Server OSGi Implementation
surprisingly simple model has far reaching effects for almost any aspect of the
software development process."
OSGi offers you the following benefits:
• Versioning of package wiring, for both implementors and users of interfaces.
• The "uses" directive allows for intelligent wiring of class loaders and helps ensure
a consistent class space.
• Flexible and dynamic security.
• Dynamic service wiring through an active registry.
• Various standard OSGi specifications provided by multiple vendors.
18-2
Chapter 18
Configuring the OSGi Framework
Note:
WebLogic Server supports only the Felix framework. Other OSGi
Frameworks are not supported and have not been tested.
18-3
Chapter 18
Configuring the OSGi Framework
Attribute Usage
Target This attribute is required. You must select a target (servers or
clusters) on which an MBean will be deployed from the list of
servers or clusters in the current domain on which this item can
be deployed.
Name The name of the framework instance. The name of a given
framework instance must be unique within a WebLogic Server
server instance.
Implementation The name of the framework implementation class
Class for the org.osgi.framework.launch.FrameworkFactory
class. The default value is
org.apache.felix.framework.FrameworkFactory.
Deploy Installation Determines whether OSGi bundles are installed in the framework.
Bundles This attribute is "populate" by default. See Parameter Required for
Installing Bundles in the Framework for more information.
Dynamically Determines whether the MBean is created dynamically or is
Created persisted to config.xml. The configuration is always persisted
if you use the WebLogic Server Administration Console and this
attribute is not displayed.
Init Properties The standard Felix properties to be used when initializing the
framework. All standard properties and all properties specific to
the framework can be set.
See Example 18-3 for an example of setting the Init Properties from
a Java program.
The Apache Felix Framework Configuration
Properties are described in http://
felix.apache.org/documentation/subprojects/apache-
felix-framework/apache-felix-framework-configuration-
properties.html.
Framework Boot The name of the org.osgi.framework.bootdelegation property.
delegation Note that this value, if set, will take precedence over anything
specified in the init-properties.
Framework System The name of the org.osgi.framework.system.packages.extra
Packages Extra property. Note that this value, if set, will take precedence over
anything specified in the init-properties.
Register Global Boolean. Returns true if global data sources should be added to the
Data Sources OSGi service registry.
Register Global Boolean. Returns true if global work managers should be added to
Work Managers the OSGi service registry.
18-4
Chapter 18
Configuring the OSGi Framework
If you need to add multiple OSGi framework instances, add multiple <osgi-framework>
elements. Remember that each <name> element must be unique within the server.
After you add this element, you must reboot the WebLogic Server instance.
Example 18-1 Configuring OSGi Framework Instance From config.xml
<osgi-framework>
<name>test-osgi-frame</name>
<target>AdminServer</target>
</osgi-framework>
connect('weblogic', 'password')
edit()
startEdit()
wls:/mydomain/edit !> cmo.createOsgiFramework('test-osgi-frame')
[MBeanServerInvocationHandler]com.bea:Name=test-osgi-frame,Type=OsgiFramework
targetServer=cmo.lookupServer('AdminServer')
cd('OsgiFrameworks')
cd('test-osgi-frame')
cmo.addTarget(targetServer)
wls:/mydomain/edit !> save()
wls:/mydomain/edit !> activate()
18-5
Chapter 18
Configuring the OSGi Framework
wls:/mydomain/edit/OsgiFrameworks> ls('a')
drw- test-osgi-frame
wls:/mydomain/edit/OsgiFrameworks> cd('test-osgi-frame')
wls:/mydomain/edit/OsgiFrameworks/test-osgi-frame> ls('a')
-rw- DeployInstallationBundles populate
-rw- DeploymentOrder 1000
-r-- DynamicallyCreated false
-rw- FactoryImplementationClass org.apache.felix.framework.F
rameworkFactory
-r-- Id 0
-rw- InitProperties null
-rw- Name test-osgi-frame
-rw- Notes null
-rw- OrgOsgiFrameworkBootdelegation null
-rw- OrgOsgiFrameworkSystemPackagesExtra null
-rw- RegisterGlobalDataSources true
-rw- RegisterGlobalWorkManagers true
-r-- Type OsgiFramework
/**
* Create a fresh framework
*
* @param isRegisterGlobalWorkManagers
* @param isRegisterGlobalDataSources
* @param deployInstallationBundles
* @param orgOsgiFrameworkBootdelegation
18-6
Chapter 18
Configuring the OSGi Framework
* @param orgOsgiFrameworkSystemPackagesExtra
*/
protected void createOSGiFrameworkInstance(String frameworkName,
Properties initProp,
String isRegisterGlobalWorkManagers,
String isRegisterGlobalDataSources,
String deployInstallationBundles,
String orgOsgiFrameworkBootdelegation,
String orgOsgiFrameworkSystemPackagesExtra) {
frameworkInstances.add(frameworkName);
if (initProp == null) {
initProp = new Properties();
}
initProp.setProperty("wlstest.framework.instance.name", frameworkName);
//initProp.setProperty("felix.cache.locking", "false");
//initProp.setProperty("org.osgi.framework.storage.clean", "onFirstInit");
try {
if (osgiFrameworkMBean != null) {
log("Will destroy the framework instance: " + osgiFrameworkMBean);
connection.invoke(osgiFrameworkMBean,
"removeTarget",
new Object[] { serverMBean },
new String[] { "javax.management.ObjectName" });
connection.invoke(domainMBean,
"destroyOsgiFramework",
new Object[] { osgiFrameworkMBean },
new String[] { "javax.management.ObjectName" });
18-7
Chapter 18
Configuring the OSGi Framework
if (isRegisterGlobalDataSources != null) {
Attribute attr = new Attribute("RegisterGlobalDataSources",
Boolean.parseBoolean(isRegisterGlobalDataSources));
connection.setAttribute(osgiFrameworkMBean, attr);
}
if (deployInstallationBundles != null) {
Attribute attr = new Attribute("DeployInstallationBundles", deployInstallationBundles);
connection.setAttribute(osgiFrameworkMBean, attr);
}
if (orgOsgiFrameworkBootdelegation != null) {
Attribute attr = new Attribute("OrgOsgiFrameworkBootdelegation",
orgOsgiFrameworkBootdelegation);
connection.setAttribute(osgiFrameworkMBean, attr);
}
if (orgOsgiFrameworkSystemPackagesExtra != null) {
Attribute attr = new Attribute("OrgOsgiFrameworkSystemPackagesExtra",
orgOsgiFrameworkSystemPackagesExtra);
connection.setAttribute(osgiFrameworkMBean, attr);
}
MBeanInfo mi = connection.getMBeanInfo(osgiFrameworkMBean);
log("Attributes are as below:");
for (MBeanAttributeInfo mai : mi.getAttributes()) {
Object value = connection.getAttribute(osgiFrameworkMBean, mai.getName());
System.out.printf(" %-40s = %s\n", mai.getName(), value);
}
18-8
Chapter 18
Configuring the OSGi Framework
• ignore — None of the bundles in this directory are installed and started.
• populate — The bundles are installed and started if possible. This is the default.
Furthermore, a few extra packages are added to the boot delegation classpath
parameters in order to enable the bundles in the osgi-lib directory if they are not
already there.
It is not be considered a failure that causes the system to not boot if these bundles
do not properly resolve and therefore cannot be started.
18-9
Chapter 18
Creating OSGi Bundles
18-10
Chapter 18
Deploying OSGi Bundles
Before you do this, you must first specify which OSGi framework you want your bundle
to use, and identity the bundle to WebLogic Server.
Note:
If the OSGi framework instance you specify does not exist on the target
server, the OSGi bundle fails to deploy.
How you do this depends on whether your bundle is inside a WAR file or an EAR file:
• WAR — The framework instance and bundle name must be in an element in the
Web application's weblogic.xml deployment descriptor file.
• EAR — The framework instance and bundle name must be in an element in the
application's weblogic-application.xml deployment descriptor file.
If the EAR file contains WAR files, then the bundles inside the WAR files are
deployed using the weblogic.xml deployment descriptor file from the embedded
WAR files.
The sections that follow describe the required steps in detail.
For more information about WebLogic Server deployment descriptors, see Deploying
Applications to Oracle WebLogic Server.
The stanza in Example 18-4 tells the WebLogic Server to attach to the OSGi
framework named "test-osgi-frame" and to find the bundle in that server with the
symbolic name com.oracle.weblogic.test.client in order to find classes from that
OSGi framework.
18-11
Chapter 18
Deploying OSGi Bundles
The stanza in Example 18-4 tells the WebLogic Server to attach to the OSGi
framework named "test-osgi-frame" and to find the bundle in that server with the
symbolic name com.oracle.weblogic.test.client in order to find classes from that
OSGi framework.
18-12
Chapter 18
Deploying OSGi Bundles
Note:
The OsgiFrameWorkMBean MBean Deploy Installation Bundles attribute
controls whether or not bundles present in the osgi-lib directory are
actually installed, as described in Parameter Required for Installing Bundles
in the Framework. This attribute is true by default, and the bundles are
installed.
18-13
Chapter 18
Accessing Deployed Bundle Objects From JNDI
Any files in this directory that end with .jar, .ear, or .war are considered an OSGi
bundle to be installed into a framework when it starts.
WL_HOME/server/osgi-lib is consulted only when the server first boots, and is not
monitored for changes thereafter. If you add a new OSGi bundle to the WL_HOME/
server/osgi-lib directory and want to deploy it, you must reboot WebLogic Server.
try {
Context initCtx = new InitialContext();
bundle = (Bundle) initCtx.lookup(Constants.BUNDLE_JNDI_NAME);
} catch (NamingException e) {
errorMessages.add(e.toString());
System.out.println("Failed to lookup bundle from JNDI due to " + e);
}
if (bundle != null) {
BundleContext bc = bundle.getBundleContext();
if (bc != null) {
18-14
Chapter 18
Accessing Deployed Bundle Objects From JNDI
info.setAllInstalledBundles(allInstalledBundles);
info.setAllActivatedBundles(allActivatedBundles);
info.setRegisteredServices(services);
info.setStartLevels(startLevels);
18-15
Chapter 18
Using OSGi Logging Via WebLogic Server
}
}
return info;
18-16
Chapter 18
Configuring a Filtering ClassLoader for OSGi Bundles
Table 18-2 (Cont.) OSGi and WebLogic Server Logging Severity Mapping
OSGI Example
WebLogic Server includes two simple example OSGi bundles: client and server. The
server bundle (ServerBundle) exports a packet that the client bundle (ClientBundle)
imports. The example produces an HTML page that displays the deployed OSGi
bundles.
WebLogic Server includes an example that demonstrates how to deploy OSGi
bundles to WebLogic Server. If you installed the WebLogic Server examples, the
OSGi example source code is available in ORACLE_HOMEwl_server/examples/src/
examples/osgi/osgiApp, where ORACLE_HOME represents the directory in which the
WebLogic Server code examples are configured. For more information about the
WebLogic Server code examples, see Sample Applications and Code Examples in
Understanding Oracle WebLogic Server.
18-17
19
Using the WebSocket Protocol in
WebLogic Server
WebLogic Server supports the WebSocket protocol (RFC 6455), which provides full-
duplex communications between two peers over the TCP protocol. The WebLogic
Server implementation of the WebSocket protocol and its accompanying API
enable you to develop and deploy applications that communicate bidirectionally with
clients. Although you can use the WebSocket protocol for any type of client-server
communication, the implementation is most commonly used to communicate with
browsers running Web pages that use the World Wide Web Consortium (W3C)
JavaScript WebSocket API. The WebLogic Server implementation of the WebSocket
protocol also supports Java clients.
This chapter includes the following sections:
• Understanding the WebSocket Protocol
• Understanding the WebLogic Server WebSocket Implementation
• Overview of Creating a WebSocket Application
• Creating an Endpoint
• Handling Life Cycle Events for a WebSocket Connection
• Defining_ Injecting_ and Accessing a Resource for a WebSocket Endpoint
• Sending a Message
• Encoding and Decoding a WebSocket Message
• Specifying a Part of an Endpoint Deployment URI as an Application Parameter
• Maintaining Client State
• Configuring a Server Endpoint Programmatically
• Building Applications that Use the Java API for WebSocket
• Deploying a WebSocket Application
• Using WebSockets with Proxy Servers
• Writing a WebSocket Client
• Securing a WebSocket Application
• Enabling Protocol Fallback for WebSocket Messaging
• Migrating an Application to the JSR 356 Java API for WebSocket from the
Deprecated API
• Example of Using the Java API for WebSocket with WebLogic Server
19-1
Chapter 19
Understanding the WebSocket Protocol
WebSocket Endpoints
In a WebSocket application, the server publishes a WebSocket endpoint and the
client uses the endpoint's URI to connect to the server.
A WebSocket endpoint is represented by a URI in one of the following formats:
ws://host:port/path?query
wss://host:port/path?query
host
The host as defined in [RFC3986], Section 3.2.2.
port
Optional. The port as defined in [RFC3986], Section 3.2.3. The default port number is
80 for unencrypted connections and 443 for encrypted connections.
path
The path as defined in [RFC3986], Section 3.3. In a WebSocket endpoint, the path
indicates the location of the endpoint within a server.
19-2
Chapter 19
Understanding the WebSocket Protocol
query
Optional. A query as defined in [RFC3986], Section 3.4.
The server applies a known operation to the value of the Sec-WebSocket-Key header
to generate the value of the Sec-WebSocket-Accept header. The client applies the
same operation to the value of the Sec-WebSocket-Key header. If the result matches
the value received from the server, the connection is established successfully. The
client and the server can send messages to each other after a successful handshake.
19-3
Chapter 19
Understanding the WebLogic Server WebSocket Implementation
Note:
The proprietary WebLogic Server WebSocket API that was introduced
in release 12.1.2 is deprecated but remains supported for backward
compatibility.
Although the JSR 356 Java API for WebSocket coexists with the proprietary
WebLogic Server WebSocket API, an application cannot contain calls to both
APIs. Only one of the APIs can be used in an application.
Information about how to use the deprecated API is available in the
documentation for Oracle WebLogic Server 12c (12.1.2) in Chapter 17,
Using WebSockets in WebLogic Server in Developing Applications for Oracle
WebLogic Server 12c (12.1.2).
javax.websocket.server
This package contains annotations, classes, and interfaces to create and configure
server endpoints.
19-4
Chapter 19
Overview of Creating a WebSocket Application
javax.websocket
This package contains annotations, classes, interfaces, and exceptions that are
common to client and server endpoints.
The API reference documentation for these packages is available in the following
sections of the Java EE 8 Specification APIs:
• Package javax.websocket
• Package javax.websocket.server
Creating an Endpoint
The container creates one instance of an endpoint for each connection to its
deployment URI. Each instance retains user state for each connection and simplifies
development.
The Java API for WebSocket enables you to create the following kinds of endpoints:
• Annotated endpoints
19-5
Chapter 19
Creating an Endpoint
• Programmatic endpoints
The process is different for programmatic endpoints and annotated endpoints. In most
cases, it is easier to create and deploy an annotated endpoint than a programmatic
endpoint.
Note:
As opposed to servlets, WebSocket endpoints are instantiated multiple
times. The container creates one instance of an endpoint for each
connection to its deployment URI. Each instance is associated with one and
only one connection. This behavior facilitates keeping user state for each
connection and simplifies development because only one thread is executing
the code of an endpoint instance at any given time.
19-6
Chapter 19
Creating an Endpoint
Example 19-5 shows how to declare a programmatic endpoint class. For an example
of how to declare an annotated endpoint class to represent the same endpoint, see
Example 19-3.
Example 19-5 Declaring a Programmatic Endpoint Class
This example declares the programmatic endpoint class EchoEndpoint. For an
example that shows how to specify the path within an application to this endpoint,
see Example 19-6.
import javax.websocket.Endpoint;
...
public class EchoEndpoint extends Endpoint {
...
}
19-7
Chapter 19
Handling Life Cycle Events for a WebSocket Connection
host
The host on which the application is running.
port
The port on which WebLogic Server listens for client requests.
application
The name with which the application is deployed.
path
The path that you specified in the invocation of the create method.
For example, the URI to the endpoint at the /echo path relative to the /echoapp
application running on the local host is ws://localhost:8890/echoapp/echo.
Example 19-6 shows how to perform this task in a single line of Java code.
Example 19-6 Specifying the Path Within an Application to a Programmatic
Endpoint
This example specifies /echo as the path within an application to the programmatic
endpoint EchoEndpoint from Example 19-5.
import javax.websocket.server.ServerEndpointConfig.Builder;
...
ServerEndpointConfig.Builder.create(EchoEndpoint.class, "/echo").build();
...
19-8
Chapter 19
Handling Life Cycle Events for a WebSocket Connection
For details about the combinations of parameters that are allowed by an annotation,
see the API reference documentation for the annotation.
Error OnError
@OnError
public void error(Session session,
Throwable error)
{ }
19-9
Chapter 19
Handling Life Cycle Events for a WebSocket Connection
Message Type Data Type of the Parameter for Receiving the Message
Text Any one of the following data types depending on how the message
is to be received:
• To receive the whole message: java.lang.String
• To receive the whole message converted to a Java primitive or
class equivalent to that type: the primitive or class equivalent
• To receive the message in parts: String and boolean pair
• To receive the whole message as a blocking stream:
java.io.Reader
• To receive the message encoded as a Java
object: any type for which the endpoint has
a text decoder (javax.websocket.Decoder.Text or
javax.websocket.Decoder.TextStream)
19-10
Chapter 19
Handling Life Cycle Events for a WebSocket Connection
Message Type Data Type of the Parameter for Receiving the Message
Binary Any one of the following data types depending on how the message
is to be received:
• To receive the whole message: byte array or
java.nio.ByteBuffer
• To receive the message in parts: byte array and boolean pair,
or ByteBuffer and boolean pair
• To receive the whole message as a blocking stream:
java.io.InputStream
• To receive the message encoded as a Java object:
any object type for which the endpoint has a
binary decoder (javax.websocket.Decoder.Binary or
javax.websocket.Decoder.BinaryStream)
Pong javax.websocket.PongMessage
Note:
For an annotated endpoint, you add methods for handling incoming
messages to your endpoint class. You are not required to create a separate
message handler class. However, for a programmatic endpoint, you must
create a separate message handler class.
To compare how to handle incoming messages for an annotated endpoint
and a programmatic endpoint, see Example 19-8 and Example 19-12.
import javax.websocket.OnMessage;
import javax.websocket.Session;
...
@OnMessage
public String onMessage(String msg) throws IOException {
return msg;
}
...
19-11
Chapter 19
Handling Life Cycle Events for a WebSocket Connection
import javax.websocket.OnMessage;
import javax.websocket.PongMessage;
import javax.websocket.Session;
...
@OnMessage
public void textMessage(Session session, String msg) {
System.out.println("Text message: " + msg);
}
@OnMessage
public void binaryMessage(Session session, ByteBuffer msg) {
System.out.println("Binary message: " + msg.toString());
}
@OnMessage
public void pongMessage(Session session, PongMessage msg) {
System.out.println("Pong message: " +
msg.getApplicationData().toString());
}
...
...
@OnError
public void error(Session session, Throwable t) {
t.printStackTrace();
...
}
19-12
Chapter 19
Handling Life Cycle Events for a WebSocket Connection
such as the ID, or any application data that the session holds before the data becomes
unavailable after the connection is closed.
To handle a connection closed event, annotate the method for handling the event with
the OnClose annotation.
Example 19-12 shows how handle incoming text messages for a programmatic
endpoint by handling connection opened events and message received events.
19-13
Chapter 19
Defining, Injecting, and Accessing a Resource for a WebSocket Endpoint
The Session parameter represents a conversation between this endpoint and the
remote endpoint. The addMessageHandler method registers message handlers, and
the getBasicRemote method returns an object that represents the remote endpoint.
19-14
Chapter 19
Defining, Injecting, and Accessing a Resource for a WebSocket Endpoint
The following examples show how to define, inject, and access a resource for a
WebSocket endpoint:
• Example 19-13
• Example 19-14
Example 19-13 Defining a Managed Bean for a WebSocket Endpoint
This example defines the managed bean class InjectedSimpleBean.
import javax.annotation.PostConstruct;
@PostConstruct
public void postConstruct() {
postConstructCalled = true;
}
import javax.annotation.PostConstruct;
import javax.inject.Inject;
@ServerEndpoint(value = "/simple")
public class SimpleEndpoint {
@Inject
InjectedSimpleBean bean;
@OnMessage
public String echo(String message) {
return postConstructCalled ?
String.format("%s%s", message, bean.getText()) :
"PostConstruct was not called";
}
@PostConstruct
public void postConstruct() {
19-15
Chapter 19
Sending a Message
postConstructCalled = true;
}
Sending a Message
The Java API for WebSocket enables you to send text messages, binary messages,
and ping frames from an endpoint to its connected peers.
• Text messages
• Binary messages
• Ping frames
19-16
Chapter 19
Sending a Message
import javax.websocket.OnMessage;
import javax.websocket.Session;
...
@OnMessage
public void onMessage(Session session, String msg) {
try {
session.getBasicRemote().sendText(msg);
} catch (IOException e) { ... }
}
...
19-17
Chapter 19
Encoding and Decoding a WebSocket Message
import javax.websocket.OnMessage;
import javax.websocket.Session;
import javax.websocket.server.ServerEndpoint;
...
@ServerEndpoint("/echoall")
public static class EchoAllEndpoint {
@OnMessage
public void messageReceived(Session session, String msg) {
for (Session sess : session.getOpenSessions()) {
try {
sess.getBasicRemote().sendText(msg);
} catch (IOException e) {
// handle exception
}
}
}
}
19-18
Chapter 19
Encoding and Decoding a WebSocket Message
simplifies WebSocket applications because it decouples the business logic from the
serialization and deserialization of objects.
An encoder takes a Java object and produces a representation that can be transmitted
as a WebSocket text message or binary message. For example, encoders typically
produce JavaScript Object Notation (JSON), Extensible Markup Language (XML), or
binary representations. A decoder performs the reverse function: it reads a WebSocket
message and creates a Java object.
Note:
If you want to send and receive multiple Java types as the same type
of WebSocket message, define the types to extend a common class. For
example, if you want to send and receive the Java types MessageA and
MessageB as text messages, define the types to extend the common class
Message.
Defining the types in this way enables you to implement a single decoder
class for multiple types.
19-19
Chapter 19
Encoding and Decoding a WebSocket Message
• Example 19-18
• Example 19-19
Example 19-17 Implementing an Encoder Interface
This example implements the Encoder.Text<MessageA> interface.
package com.example.game.encoder;
import javax.websocket.EncodeException;
import javax.websocket.Encoder;
import javax.websocket.EndpointConfig;
import com.example.game.message.MessageA;
...
public class MessageATextEncoder implements Encoder.Text<MessageA> {
@Override
public void init(EndpointConfig ec) { }
@Override
public void destroy() { }
@Override
public String encode(MessageA msgA) throws EncodeException {
// Access msgA's properties and convert to JSON text...
return msgAJsonString;
}
...
}
import javax.websocket.server.ServerEndpoint;
import com.example.game.encoder.MessageATextEncoder;
import com.example.game.encoder.MessageBTextEncoder;
...
@ServerEndpoint(
value = "/myendpoint",
encoders = { MessageATextEncoder.class, MessageBTextEncoder.class }
...
)
public class EncEndpoint { ... }
19-20
Chapter 19
Encoding and Decoding a WebSocket Message
• Example 19-20
• Example 19-21
• Example 19-22
These examples assume that the Java types
com.example.game.message.MessageA and com.example.game.message.MessageB
extend the com.example.game.message.Message class.
Because only one decoder for text messages is allowed for an endpoint, the
implementation is a decoder for the Message superclass. This decoder is used for
decoding the subclasses of Message.
package com.example.game.decoder;
19-21
Chapter 19
Encoding and Decoding a WebSocket Message
import javax.websocket.DecodeException;
import javax.websocket.Decoder;
import javax.websocket.EndpointConfig;
import com.example.game.message.Message;
import com.example.game.message.MessageA;
import com.example.game.message.MessageB;
...
For completeness, this example also includes the definitions of the encoder classes
MessageATextEncoder.class and MessageBTextEncoder.class from Example 19-18.
package com.example.game;
import javax.websocket.server.ServerEndpoint;
import com.example.game.encoder.MessageATextEncoder;
import com.example.game.encoder.MessageBTextEncoder;
import com.example.game.decoder.MessageTextDecoder;
...
@ServerEndpoint(
value = "/myendpoint",
encoders = { MessageATextEncoder.class, MessageBTextEncoder.class },
decoders = { MessageTextDecoder.class }
)
public class EncEndpoint { ... }
19-22
Chapter 19
Specifying a Part of an Endpoint Deployment URI as an Application Parameter
import com.example.game.message.Message;
import com.example.game.message.MessageA;
import com.example.game.message.MessageB;
...
@OnMessage
public void message(Session session, Message msg) {
if (msg instanceof MessageA) {
// We received a MessageA object...
else if (msg instanceof MessageB) {
// We received a MessageB object...
}
}
19-23
Chapter 19
Maintaining Client State
import javax.websocket.EndpointConfig;
import javax.websocket.OnOpen;
import javax.websocket.Session;
import javax.websocket.server.PathParam;
import javax.websocket.server.ServerEndpoint;
@ServerEndpoint("/chatrooms/{room-name}")
public class ChatEndpoint {
@OnOpen
public void open(Session session,
EndpointConfig c,
@PathParam("room-name") String roomName) {
// Add the client to the chat room of their choice ...
}
...
}
Code in the body of the open method to expand the {room-name} variable is not shown
in this example.
If the endpoint is deployed inside a web application called chatapp at a local Java
EE server in port 8080, clients can connect to the endpoint using any of the following
URIs:
http://localhost:8080/chatapp/chatrooms/currentnews
http://localhost:8080/chatapp/chatrooms/music
http://localhost:8080/chatapp/chatrooms/cars
http://localhost:8080/chatapp/chatrooms/technology
@ServerEndpoint("/delayedecho")
public class DelayedEchoEndpoint {
@OnOpen
public void open(Session session) {
session.getUserProperties().put("previousMsg", " ");
}
@OnMessage
19-24
Chapter 19
Configuring a Server Endpoint Programmatically
3. In the server endpoint class, set the configurator element of the ServerEndpoint
annotation to the configurator class.
The following examples show how to configure a server endpoint programmatically:
• Example 19-25
19-25
Chapter 19
Configuring a Server Endpoint Programmatically
• Example 19-26
Example 19-25 Extending the ServerEndpointConfig.Configurator Class
This example extends the ServerEndpointConfig.Configurator class to make the
handshake request object available to endpoint instances.
import javax.websocket.HandshakeResponse;
import javax.websocket.server.ServerEndpointConfig.Configurator;
import javax.websocket.server.HandshakeRequest;
...
public class CustomConfigurator extends ServerEndpointConfig.Configurator {
@Override
public void modifyHandshake(ServerEndpointConfig conf,
HandshakeRequest req,
HandshakeResponse resp) {
conf.getUserProperties().put("handshakereq", req);
}
...
}
The custom configurator enables instances of the server endpoint class to access the
handshake request object. The server endpoint class uses the handshake request
object to access the details of the handshake request, such as its headers or the
HttpSession object.
import javax.websocket.EndpointConfig;
import javax.websocket.HandshakeResponse;
import javax.websocket.OnOpen;
import javax.websocket.Session;
import javax.websocket.server.HandshakeRequest;
import javax.websocket.server.ServerEndpoint;
import java.util.List;
import java.util.Map;
...
@ServerEndpoint(
value = "/myendpoint",
configurator = CustomConfigurator.class
)
public class MyEndpoint {
@OnOpen
public void open(Session s, EndpointConfig conf) {
HandshakeRequest req = (HandshakeRequest) conf.getUserProperties()
.get("handshakereq");
Map<String,List<String>> headers = req.getHeaders();
...
}
}
19-26
Chapter 19
Building Applications that Use the Java API for WebSocket
19-27
Chapter 19
Deploying a WebSocket Application
Example 19-27 shows how to set context initialization properties for a WebSocket
application.
Example 19-27 Setting Context Initialization Properties for a WebSocket
Application
This example sets context initialization parameters for a WebSocket application as
follows:
• The maximum underlying buffer size for receiving messages is set to 16777227
bytes.
• The maximum period after which an idle connection times out is set to 60,000
milliseconds, which corresponds to 1 minute.
• Enable WebSocket cluster using managed Coherence server to establish
communication among all members.
Note:
Clustering requires a managed Coherence server with local storage
enabled. See, Configure Coherence Cluster Member Storage Settings
in Administering Clusters for Oracle WebLogic Server.
19-28
Chapter 19
Monitoring WebSocket Applications
19-29
Chapter 19
Monitoring WebSocket Applications
19-30
Chapter 19
Using WebSockets with Proxy Servers
19-31
Chapter 19
Writing a WebSocket Client
Most browsers support the W3C WebSocket API that can be used to create and work
with the WebSocket protocol. For information about the W3C WebSocket API, see:
http://www.w3.org/TR/websockets/.
ws.onmessage = function(event) {
msg = event.data
document.getElementById("short_msg").innerHTML =
event.data;
}
3. The client sends messages to the server over the WebSocket object as needed by
the application.
function sendMsg() {
// Check if connection is open before sending
if(ws == null || ws.readyState != 1) {
document.getElementById("reason").innerHTML
= "Not connected can't send msg"
} else {
ws.send(document.getElementById("name").value);
}
}
19-32
Chapter 19
Writing a WebSocket Client
Table 19-4 HTTP Proxy Configuration Properties for a Java WebSocket Client
weblogic.websocket.cl String Optional. The user name for logging in to the proxy
ient.PROXY_PASSWORD host.
19-33
Chapter 19
Writing a WebSocket Client
Table 19-5 (Cont.) SSL Configuration Properties for a Java WebSocket Client
Note:
Configure a client endpoint before connecting the client to its server
endpoint.
19-34
Chapter 19
Writing a WebSocket Client
19-35
Chapter 19
Writing a WebSocket Client
import javax.websocket.CloseReason;
import javax.websocket.ContainerProvider;
import javax.websocket.Session;
import javax.websocket.WebSocketContainer;
...
19-36
Chapter 19
Securing a WebSocket Application
• In the java command to launch your client application, set the system property
weblogic.websocket.client.max-aio-threads to the number that you require.
Example 19-30 shows how to set the maximum number of threads for dispatching
messages from a WebSocket client.
Example 19-30 Setting the Maximum Number of Threads for Dispatching
Messages from a WebSocket Client
This example sets the maximum number of threads for dispatching messages from the
WebSocket client ClientExample to 50.
java -Dweblogic.websocket.client.max-aio-threads=50 ClientExample
19-37
Chapter 19
Securing a WebSocket Application
@Override
public boolean checkOrigin(String originHeaderValue) {
return ORIGIN.equals(originHeaderValue)
}
}
...
Note:
Nonbrowser clients (for example, Java clients) are not required to send
an Origin HTTP header with the WebSocket handshake request. If a
WebSocket handshake request does not include an Origin header, then
the request is from a nonbrowser client; if a handshake request includes
an Origin header, then the request may be from either a browser or a
nonbrowser client.
Because nonbrowser clients can send arbitrary Origin headers, the browser
origin security model is not recommended for nonbrowser clients.
19-38
Chapter 19
Securing a WebSocket Application
<login-config>
<auth-method>FORM</auth-method>
<form-login-config>
<form-login-page>/login.jsp</form-login-page>
<form-error-page>/error.jsp</form-error-page>
</form-login-config>
</login-config>
<security-role>
<role-name>user</role-name>
</security-role>
19-39
Chapter 19
Enabling Protocol Fallback for WebSocket Messaging
<role-name>user</role-name>
</auth-constraint>
<user-data-constraint>
<transport-guarantee>CONFIDENTIAL</transport-guarantee>
</user-data-constraint>
</security-constraint>
For more information about mixed content, see "Web Security Context: User Interface
Guidelines" at http://www.w3.org/TR/wsc-ui/#securepage.
19-40
Chapter 19
Enabling Protocol Fallback for WebSocket Messaging
Note:
To support WebSocket fallback, the server must use the JSR 356 Java API
for WebSocket, not the proprietary WebLogic Server WebSocket API.
When you use the standard W3C WebSocket JavaScript API, code your application
without regard to whether the WebSocket protocol is supported.
transport string none The enforced transport, which can be one of the
following transports:
• WebSocket
• XMLHttpRequest
19-41
Chapter 19
Enabling Protocol Fallback for WebSocket Messaging
19-42
Chapter 19
Enabling Protocol Fallback for WebSocket Messaging
19-43
Chapter 19
Enabling Protocol Fallback for WebSocket Messaging
Note:
The creation of the ws WebSocket object in the examples is shown in
Example 19-32.
19-44
Chapter 19
Enabling Protocol Fallback for WebSocket Messaging
19-45
Chapter 19
Enabling Protocol Fallback for WebSocket Messaging
...
ws.onerror = function(error)
{
if (nbMessReceived === 0)
statusFld.innerHTML = "";
statusFld.innerHTML += ((nbMessReceived === 0?"":"<br>") + "<small>" +
(new Date()).format("d-M-Y H:i:s._ Z") +
"</small>:<font color='red'>" + error.err + "</
font>");
statusFld.scrollTop = statusFld.scrollHeight;
nbMessReceived++;
};
...
The creation of the ws WebSocket object in this example is shown in Example 19-32.
...
var send = function(mess)
{
ws.send(mess);
19-46
Chapter 19
Migrating an Application to the JSR 356 Java API for WebSocket from the Deprecated API
};
...
In the client application, add the following script element to specify the location of
orasocket.min.js.
<script type="text/javascript" src="scripts/orasocket.min.js"></script>
19-47
Chapter 19
Migrating an Application to the JSR 356 Java API for WebSocket from the Deprecated API
Table 19-9 Comparison of the JSR 356 API and Proprietary WebLogic Server
WebSocket API
19-48
Chapter 19
Migrating an Application to the JSR 356 Java API for WebSocket from the Deprecated API
Table 19-9 (Cont.) Comparison of the JSR 356 API and Proprietary WebLogic
Server WebSocket API
19-49
Chapter 19
Migrating an Application to the JSR 356 Java API for WebSocket from the Deprecated API
Table 19-9 (Cont.) Comparison of the JSR 356 API and Proprietary WebLogic
Server WebSocket API
19-50
Chapter 19
Migrating an Application to the JSR 356 Java API for WebSocket from the Deprecated API
Note:
If the pathPatterns element of your existing endpoint contains
the /* suffix, you must rewrite your code to achieve the same result
as the /* suffix. For more information, see Replacing the /* Suffix in
a Path Pattern String.
2. Annotate the declaration of each method for handling a life cycle event with the
annotation that designates the event that the method handles.
For more information, see Handling Life Cycle Events in an Annotated WebSocket
Endpoint.
3. Replace each reference to the weblogic.websocket.WebSocketConnection
interface with a reference to the javax.websocket.Session interface.
4. Replace each method invocation on the WebSocketConnection object with an
invocation of the corresponding method on the Session object.
For example, the close method of a WebSocketConnection object takes
a weblogic.websocket.ClosingMessage object as a parameter. In the
close method of a Session object the corresponding parameter is a
javax.websocket.CloseReason object.
5. Change each method invocation on a Session object to send a message as
follows:
a. Add an invocation of the getBasicRemote method or getAsyncRemote method
to obtain a reference to the object that represents the peer of this endpoint.
b. Replace the method in the deprecated API for sending the message with the
corresponding method in the JSR 356 API.
The method of the JSR 356 API is a method
of the javax.websocket.RemoteEndpoint.Basic object or
javax.websocket.RemoteEndpoint.Async object to which you obtained a
reference in the previous step.
For more information, see Sending a Message.
19-51
Chapter 19
Migrating an Application to the JSR 356 Java API for WebSocket from the Deprecated API
No equivalent to the /* suffix exists in the JSR 356 API. If your existing endpoint relies
on the /* suffix, you must rewrite your code to achieve the same result as the /* suffix.
How to rewrite your code depends on whether the /* suffix represents variable path
parameters in an endpoint URI or additional data for an endpoint.
The URI /ws/test matches the template in the preceding example. The param1
variable is expanded to test.
Similarly, if two variable path parameters replace the /* suffix in your existing endpoint,
define a URI template similar to the following example:
/ws/{param1}/{param2}
The URI /ws/test/chat matches the template in the preceding example. The param1
variable is expanded to test and the param2 variable is expanded to chat.
19-52
Chapter 19
Migrating an Application to the JSR 356 Java API for WebSocket from the Deprecated API
The JSR 356 specification does not forbid or restrict the use of query parameters in
any way. Therefore, you can use a query parameter to transfer any data provided that
the following conditions are met:
• URLs are shorter than their maximum allowed length.
• All data is properly encoded.
To obtain an endpoint's query parameters, invoke the method of the endpoint's
Session object that obtains the parameters in the required format:
• To obtain the parameters as a single string that contains the entire query, invoke
the getQueryString method. See Example 19-39.
• To obtain the parameters as a map that contains a list of query parameters, invoke
the getRequestParameterMap method. See Example 19-40.
Example 19-39 Obtaining Query Parameters as a Single String
This example obtains the query parameters in the request
URI /echo?foo=bar,baz,mane,padme,hum as the application output
"# foo=bar,baz,mane,padme,hum".
import javax.websocket.OnOpen;
import javax.websocket.Session;
import javax.websocket.server.ServerEndpoint;
...
@ServerEndpoint("/echo")
public class EchoEndpoint {
@OnOpen
public void onOpen(Session session) throws IOException {
System.out.println("# " + session.getQueryString());
}
// ...
}
19-53
Chapter 19
Migrating an Application to the JSR 356 Java API for WebSocket from the Deprecated API
@OnOpen
public void onOpen(Session session) throws IOException {
System.out.println("# " + session.getRequestParameterMap().get("foo"));
}
// ...
}
import java.io.IOException;
//@WebSocket( Deprecated
// timeout = -1, Deprecated
// pathPatterns = {"/ws"} Deprecated
//)
@ServerEndpoint("/ws") //JSR 356
//public class MessageListener extends WebSocketAdapter { Deprecated
public class MessageListener {
//@Override Not required. Replaced by @OnMessage in a POJO class
@OnMessage //JSR 356
//public void onMessage(WebSocketConnection connection, String payload)
{ Deprecated
public void onMessage(Session connection, String payload) //JSR 356
throws IOException { //JSR 356
// Sends message from the browser back to the client.
String msgContent = "Message \"" + payload + "\" has been received by
server.";
try {
// connection.send(msgContent); Deprecated
connection.getBasicRemote().sendText(msgContent); //JSR 356
19-54
Chapter 19
Example of Using the Java API for WebSocket with WebLogic Server
} catch (IOException e) {
// connection.close(ClosingMessage.SC_GOING_AWAY); Deprecated
connection.close(new //JSR 356
CloseReason(CloseReason.CloseCodes.GOING_AWAY, "Going away.")); //JSR 356
}
}
}
import java.io.IOException;
import javax.websocket.OnError;
import javax.websocket.OnMessage;
import javax.websocket.OnOpen;
import javax.websocket.Session;
import javax.websocket.server.ServerEndpoint;
@ServerEndpoint("/echo")
public class EchoEndpoint {
@OnOpen
public void onOpen(Session session) throws IOException {
session.getBasicRemote().sendText("onOpen is invoked.");
}
@OnMessage
public String echo(String message) {
return message + " (from server)";
}
@OnError
public void onError(Throwable t) {
t.printStackTrace();
}
19-55
A
Enterprise Application Deployment
Descriptor Elements
Learn about enterprise application deployment descriptors such as application.xml
(a Java EE standard deployment descriptor) and weblogic-application.xml (a
WebLogic-specific application deployment descriptor).
With Java EE annotations, the standard application.xml deployment descriptor
is optional. Annotations simplify the application development process by allowing
developers to specify within the Java class itself how the application component
behaves in the container, requests for dependency injection, and so on. Annotations
are an alternative to deployment descriptors that were required by older versions of
enterprise applications (Java EE 1.4 and earlier). See Using Java EE Annotations and
Dependency Injection.
The weblogic-application.xml file is also optional if you are not using any WebLogic
Server extensions.
This chapter includes the following sections:
• weblogic-application.xml Deployment Descriptor Elements
• weblogic-application.xml Schema
• application.xml Schema
weblogic-application
The weblogic-application element is the root element of the application deployment
descriptor.
The following table describes the elements you can define within a weblogic-
application element.
A-1
Appendix A
weblogic-application.xml Deployment Descriptor Elements
A-2
Appendix A
weblogic-application.xml Deployment Descriptor Elements
<application-param>
<param-name>webapp.encoding.default
</param-name>
<param-value>UTF8</param-value>
</application-param>
A-3
Appendix A
weblogic-application.xml Deployment Descriptor Elements
<classloader-structure>
<module-ref>
<module-uri>ejb1.jar</module-uri>
</module-ref>
</classloader-structure>
<classloader-structure>
<module-ref>
<module-uri>ejb2.jar</module-uri>
</module-ref>
</classloader-structure>
A-4
Appendix A
weblogic-application.xml Deployment Descriptor Elements
<module>
<name>Workflows</name>
<type>JMS</type>
<path>jms/Workflows-jms.xml</path>
</module>
A-5
Appendix A
weblogic-application.xml Deployment Descriptor Elements
A-6
Appendix A
weblogic-application.xml Deployment Descriptor Elements
A-7
Appendix A
weblogic-application.xml Deployment Descriptor Elements
A-8
Appendix A
weblogic-application.xml Deployment Descriptor Elements
ejb
The following table describes the elements you can define within an ejb element.
A-9
Appendix A
weblogic-application.xml Deployment Descriptor Elements
<entity-cache>
<entity-cache-name>ExclusiveCache</entity-
cache-name>
<max-cache-size>
<megabytes>50</megabytes>
</max-cache-size>
</entity-cache>
entity-cache
The following table describes the elements you can define within a entity-cache
element.
A-10
Appendix A
weblogic-application.xml Deployment Descriptor Elements
A-11
Appendix A
weblogic-application.xml Deployment Descriptor Elements
max-cache-size
The following table describes the elements you can define within a max-cache-size
element.
xml
The following table describes the elements you can define within an xml element.
A-12
Appendix A
weblogic-application.xml Deployment Descriptor Elements
parser-factory
The following table describes the elements you can define within a parser-factory
element.
entity-mapping
The following table describes the elements you can define within an entity-mapping
element.
A-13
Appendix A
weblogic-application.xml Deployment Descriptor Elements
jdbc-connection-pool
Note:
The jdbc-connection-pool element is deprecated. To define a data source
in your enterprise application, you can package a JDBC module with the
application. See Configuring JDBC Application Modules for Deployment in
Administering JDBC Data Sources for Oracle WebLogic Server.
The following table describes the elements you can define within a jdbc-connection-
pool element.
A-14
Appendix A
weblogic-application.xml Deployment Descriptor Elements
connection-factory
The following table describes the elements you can define within a connection-
factory element.
A-15
Appendix A
weblogic-application.xml Deployment Descriptor Elements
pool-params
The following table describes the elements you can define within a pool-params
element.
A-16
Appendix A
weblogic-application.xml Deployment Descriptor Elements
A-17
Appendix A
weblogic-application.xml Deployment Descriptor Elements
A-18
Appendix A
weblogic-application.xml Deployment Descriptor Elements
A-19
Appendix A
weblogic-application.xml Deployment Descriptor Elements
A-20
Appendix A
weblogic-application.xml Deployment Descriptor Elements
A-21
Appendix A
weblogic-application.xml Deployment Descriptor Elements
driver-params
The following table describes the elements you can define within a driver-params
element.
A-22
Appendix A
weblogic-application.xml Deployment Descriptor Elements
A-23
Appendix A
weblogic-application.xml Deployment Descriptor Elements
security
The following table describes the elements you can define within a security element.
<security-role-assignment>
<role-name>
PayrollAdmin
</role-name>
<principal-name>
Tanya
</principal-name>
<principal-name>
Fred
</principal-name>
<principal-name>
system
</principal-name>
</security-role-assignment>
A-24
Appendix A
weblogic-application.xml Deployment Descriptor Elements
application-param
The following table describes the elements you can define within a application-param
element.
classloader-structure
The following table describes the elements you can define within a classloader-
structure element.
listener
The following table describes the elements you can define within a listener element.
A-25
Appendix A
weblogic-application.xml Deployment Descriptor Elements
singleton-service
The following table describes the elements you can define within a singleton-service
element.
startup
The following table describes the elements you can define within a startup element.
A-26
Appendix A
weblogic-application.xml Deployment Descriptor Elements
Note:
Application-scoped startup and shutdown classes have been deprecated as
of release 9.0 of WebLogic Server. Instead, you should use lifecycle listener
events in your applications. For details, see Programming Application Life
Cycle Events.
shutdown
The following table describes the elements you can define within a shutdown element.
Note:
Application-scoped startup and shutdown classes have been deprecated as
of release 9.0 of WebLogic Server. Instead, you should use lifecycle listener
events in your applications. For details, see Programming Application Life
Cycle Events.
<shutdown-uri> Optional 1 Defines a JAR file within the EAR that contains the
shutdown-class. If you do not define the shutdown-uri
element, it is assumed that the class is visible to the
application.
work-manager
The following table describes the elements you can define within a work-manager
element.
See Using Work Managers to Optimize Scheduled Work for examples and information
on Work Managers.
A-27
Appendix A
weblogic-application.xml Deployment Descriptor Elements
A-28
Appendix A
weblogic-application.xml Deployment Descriptor Elements
session-descriptor
The following table describes the elements you can define within a session-descriptor
element.
A-29
Appendix A
weblogic-application.xml Deployment Descriptor Elements
A-30
Appendix A
weblogic-application.xml Deployment Descriptor Elements
library-ref
The following table describes the elements you can define within a library-ref
element.
See Creating Shared Java EE Libraries and Optional Packages, for additional
information and examples.
A-31
Appendix A
weblogic-application.xml Deployment Descriptor Elements
library-context-root-override
The following table describes the elements you can define within a library-context-
root-override element to override context-root elements within a referenced EAR
library. See library-ref.
See Creating Shared Java EE Libraries and Optional Packages, for additional
information and examples.
fast-swap
The following table describes the elements you can define within a fast-swap element.
For more information about FastSwap Deployment, see Using FastSwap Deployment
to Minimize Redeployment in Deploying Applications to Oracle WebLogic Server.
A-32
Appendix A
weblogic-application.xml Schema
weblogic-application.xml Schema
See http://xmlns.oracle.com/weblogic/weblogic-application/1.6/weblogic-
application.xsd for the XML Schema of the weblogic-application.xml deployment
descriptor file.
application.xml Schema
For more information about application.xml deployment descriptor elements,
see the Java EE 6 schema available at http://www.oracle.com/webfolder/
technetwork/jsc/xml/ns/javaee/application_7.xsd.
A-33
B
wldeploy Ant Task Reference
Learn about the different tools to deploy applications and standalone modules to
WebLogic Server.
This chapter includes the following sections:
• Overview of the wldeploy Ant Task
• Basic Steps for Using wldeploy
• Sample build.xml Files for wldeploy
• wldeploy Ant Task Attribute Reference
B-1
Appendix B
Sample build.xml Files for wldeploy
Note:
On UNIX operating systems, the setWLSEnv.sh command does not set
the environment variables in all command shells. Oracle recommends
that you execute this command using the Korn shell or bash shell.
2. In the staging directory, create the Ant build file (build.xml by default). If you want
to use an Ant installation that is different from the one installed with WebLogic
Server, start by defining the wldeploy Ant task definition:
<taskdef name="wldeploy"
classname="weblogic.ant.taskdefs.management.WLDeploy"/>
3. If necessary, add task definitions and calls to the wlserver and wlconfig tasks
in the build script to create and start a new WebLogic Server domain. See Using
Ant Tasks to Configure and Use a WebLogic Server Domain, for information about
wlserver and wlconfig.
4. Add a call to wldeploy to deploy your application to one or more WebLogic Server
instances or clusters. See Sample build.xml Files for wldeploy and wldeploy Ant
Task Attribute Reference.
5. Execute the Ant task or tasks specified in the build.xml file by typing ant in the
staging directory, optionally passing the command a target argument:
prompt> ant
The following example shows a corresponding task to undeploy the application; the
example shows that when you undeploy or redeploy an application, you do not specify
the source archive file or exploded directory, but rather, just its deployed name:
<target name="undeploy">
<wldeploy
action="undeploy" verbose="true" debug="true"
name="DeployExample"
user="weblogic" password="weblogic"
adminurl="t3://localhost:7001" targets="myserver"
failonerror="false" />
</target>
B-2
Appendix B
wldeploy Ant Task Attribute Reference
The following example shows how to perform a partial redeploy of the application; in
this case, just a single WAR file in the application is redeployed:
<target name="redeploy_partial">
<wldeploy
action="redeploy" verbose="true"
name="DeployExample"
user="weblogic" password="weblogic"
adminurl="t3://localhost:7001" targets="myserver"
deltaFiles="examples/general/redeploy/SimpleImpl.war" />
</target>
The following example uses the nested <files> child element of wldeploy to specify a
particular file in the application that should be undeployed:
<target name="undeploy_partial">
<wldeploy
action="undeploy" verbose="true" debug="true"
name="DeployExample"
user="weblogic" password="weblogic"
adminurl="t3://localhost:7001" targets="myserver"
failonerror="false">
<files
dir="${current-dir}/output/redeployEAR/examples/general/redeploy"
includes="SimpleImpl.jsp" />
</wldeploy>
</target>
The following example shows how to deploy a Java EE library called myLibrary whose
source files are located in the output/myLibrary directory:
<target name="deploy">
<wldeploy action="deploy" name="myLibrary"
source="output/myLibrary" library="true"
user="weblogic" password="weblogic"
verbose="true" adminurl="t3://localhost:7001"
targets="myserver" />
</target>
Main Attributes
The following table describes the main attributes of the wldeploy Ant task.
B-3
Appendix B
wldeploy Ant Task Attribute Reference
B-4
Appendix B
wldeploy Ant Task Attribute Reference
B-5
Appendix B
wldeploy Ant Task Attribute Reference
B-6
Appendix B
wldeploy Ant Task Attribute Reference
B-7
Appendix B
wldeploy Ant Task Attribute Reference
B-8
Appendix B
wldeploy Ant Task Attribute Reference
Note:
Use of <files> to redeploy a list of files in an application has been
deprecated as of release 9.0 of WebLogic Server. Instead, use the
deltaFiles attribute of wldeploy.
The <files> element works the same as the standard <fileset> Ant task (except
for the difference in actual task name). Therefore, see the Apache Ant Web
site at http://ant.apache.org/manual/Types/fileset.html for detailed reference
information about the attributes you can specify for the <files> element.
B-9