Skip navigation.
Downloads | Product Documentation | Support

Developing WebLogic Server Applications

# Programming Topics

The following sections contains information on additional WebLogic Server programming topics:

- Compiling Java Code
- Using Threads in WebLogic Server
- Using JavaMail with WebLogic Server Applications
- Programming Applications for WebLogic Server Clusters

# Compiling Java Code

In general, compilers convert information from one form to another. Traditionally, this involves converting information from user readable source to machine readable form. For example, the javac compiler converts .java files to .class files while the appc compiler generates EJBs and JSPs for deployment.

You can also use Ant tasks, which automate the various compile operations that must be performed to build an application, making it simpler to compile (or build) WebLogic Server-specific applications, especially in a development environment. See Using Ant Tasks to Create Compile Scripts.

## javac Compiler

The Sun Microsystems javac compiler reads class and interface definitions, written in the Java programming language and compiles them into the bytecode class files. See javac - Java Programming Language Compiler.

BEA provides the wlcompile Ant task to invoke the javac compiler. See wlcompile Ant Task.

## appc Compiler

To generate JSPs and container-specific EJB classes for deployment, you use the weblogic.appc compiler. The appc compiler also validates the descriptors for compliance with the current specifications at both the individual module level and the application level. The application-level checks include checks between the application-level deployment descriptors and the individual modules as well as validation checks across the modules.

The appc 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.

#### appc Syntax

Use the following syntax to run appc:

>     prompt>java weblogic.appc [options] <ear, jar, or war file or directory>

#### appc Options

The following are the available appc options:

Table 3-1 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 will not be regenerated unless a checksum indicates that it is necessary.
`-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.
-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.
-advanced | Prints advanced usage options.

## Using Ant Tasks to Create Compile Scripts

The preferred BEA method for compiling 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. 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 `samples\domains\examples` directory.

For a complete explanation of ant capabilities, see: http://jakarta.apache.org/ant/manual/index.html

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:

samples\domains\examples\ejb20\basic\beanManaged\build.xml

Also refer to the following WebLogic Server documentation on building examples using Ant

samples\server\examples\src\examples\examples.html

### wlcompile Ant Task

You use the wlcompile Ant task to call the javac compiler to compile your Enterprise application's Java files in a split development directory structure. For more information, refer to Compiling Applications Using wlcompile in Creating WebLogic Server Applications.

### wlappc Ant Task

Use the wlappc Ant task to invoke the appc compiler, which generates JSPs and container-specific EJB classes for deployment.

#### wlappc Ant Task Options

Table 3-2 contains Ant task options specific to wlappc. For the most part, these options are the same as weblogic.appc options. However, there are a few differences.

Note: See appc Compiler for a list of weblogic.appc options.

Table 3-2 wlappc Ant Task 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 will not be regenerated unless a checksum indicates that it is necessary.
`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.
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.
`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.
advanced | Prints advanced usage options.

#### wlappc Ant Task Syntax

The basic syntax for using the wlappc Ant task determines the destination source directory location. This directory contains the files to be compiled by wlappc.

<wlappc source="${dest.dir}" />

The following is an example of a wlappc Ant task command that invokes two options (idl and idlOrverWrite) from Table 3-2.

>     <wlappc source="${dest.dir}"idl="true" idlOrverWrite="true" />

#### Syntax Differences between appc and wlappc

There are some syntax differences between appc and wlappc. For appc, the presence of a flag in the command is a boolean. For wlappc, the presence of a flag in the command means that the argument is required.

To illustrate, the following are examples of the same command, the first being an appc command and the second being a wlappc command:

>     java weblogic.appc -idl foo.ear

>     <wlappc source="${dest.dir}" idl="true"/>

## Setting the Classpath for Compiling Code

Most WebLogic services are based on J2EE standards and are accessed through standard J2EE packages. The Sun, WebLogic, and other Java classes required to compile programs that use WebLogic services are packaged in the `weblogic.jar` file in the `lib` directory of your WebLogic Server installation. In addition to `weblogic.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.

# Using Threads in WebLogic Server

WebLogic Server is a sophisticated, multi-threaded application server and it carefully manages resource allocation, concurrency, and thread synchronization for the modules it hosts. To obtain the greatest advantage from WebLogic Server's architecture, construct your application modules created according to the standard J2EE APIs.

In most cases, avoid application designs that require creating new threads in server-side modules:

- Applications that create their own threads do not scale well. Threads in the JVM are a limited resource that must be allocated thoughtfully. Your applications may break or cause WebLogic Server to thrash when the server load increases. Problems such as deadlocks and thread starvation may not appear until the application is under a heavy load.
- Multithreaded modules are complex and difficult to debug. Interactions between application-generated threads and WebLogic Server threads are especially difficult to anticipate and analyze.

In some situations, creating threads may be appropriate, in spite of these warnings. For example, an application that searches several repositories and returns a combined result set can return results sooner if the searches are done asynchronously using a new thread for each repository instead of synchronously using the main client thread.

If you must use threads in your application code, create a pool of threads so that you can control the number of threads your application creates. Like a JDBC connection pool, you allocate a given number of threads to a pool, and then obtain an available thread from the pool for your runnable class. If all threads in the pool are in use, wait until one is returned. A thread pool helps avoid performance issues and allows you to optimize the allocation of threads between WebLogic Server execution threads and your application.

Be sure you understand where your threads can deadlock and handle the deadlocks when they occur. Review your design carefully to ensure that your threads do not compromise the security system.

To avoid undesirable interactions with WebLogic Server threads, do not let your threads call into WebLogic Server modules. For example, do not use enterprise beans or servlets from threads that you create. Application threads are best used for 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.

If you create an InitialContext in the threads, ensure that you explicitly close `InitialContext` to release resources immediately and avoid any potential memory leaks. See Closing the Context in Programming WebLogic JNDI for more information.

# Using JavaMail with WebLogic Server Applications

WebLogic Server includes the JavaMail API version 1.1.3 reference implementation from Sun Microsystems. Using the JavaMail API, you can add email capabilities to your WebLogic Server applications. JavaMail provides access from Java applications to Internet Message Access Protocol (IMAP)- and Simple Mail Transfer Protocol (SMTP)-capable mail servers on your network or the Internet. It does not provide mail server functionality; you must have access to a mail server to use JavaMail.

Complete documentation for using the JavaMail API is available on the JavaMail page on the Sun Web site at. This section describes how you can use JavaMail in the WebLogic Server environment.

The `weblogic.jar` file contains the `javax.mail` and `javax.mail.internet` packages from Sun. `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. Sun has a separate POP3 provider for JavaMail, which is not included in `weblogic.jar`. You can download the POP3 provider from Sun and add it to the WebLogic Server classpath if you want to use it.

## About JavaMail Configuration Files

JavaMail depends on configuration files that define the mail transport capabilities of the system. The `weblogic.jar` file contains the standard configuration files from Sun, which enable IMAP and SMTP mail servers for JavaMail and define the default message types JavaMail can process.

Unless you want to extend JavaMail to support additional transports, protocols, and message types, you do not have to modify any JavaMail configuration files. If you do want to extend JavaMail, download JavaMail from Sun and follow Sun's instructions for adding your extensions. Then add your extended JavaMail package in the WebLogic Server classpath in front of `weblogic.jar.`

## Configuring JavaMail for WebLogic Server

To configure JavaMail for use in WebLogic Server, you create a Mail Session in the WebLogic Server Administration Console. This allows server-side modules and applications to access JavaMail services with JNDI, using Session properties you preconfigure for them. For example, by creating a Mail Session, you can designate the mail hosts, transport and store protocols, and the default mail user in the Administration Console so that modules that use JavaMail do not have to set these properties. Applications that are heavy email users benefit because WebLogic Server creates a single Session object and makes it available via JNDI to any module that needs it.

1. In the Administration Console, click on the Mail node in the left pane of the Administration Console.
2. Click Create a New Mail Session.
3. Complete the form in the right pane, as follows:

- In the Name field, enter a name for the new session.
- In the JNDIName field, enter a JNDI lookup name. Your code uses this string to look up the `javax.mail.Session` object.
- In the Properties field, enter properties to configure the Session. The property names are specified in the JavaMail API Design Specification. JavaMail provides default values for each property, and you can override the values in the application code. The following table lists the properties you can set in this field.

Property | Description | Default
--- | --- | ---
`mail.store.protocol` | Protocol for retrieving email. Example: `mail.store.protocol=imap` | The bundled JavaMail library is IMAP.
> `mail.transport.protocol` | Protocol for sending email. Example:
>     mail.transport.protocol=smtp
| The bundled JavaMail library has supports for SMTP.
> `mail.host` | The name of the mail host machine. Example:
>     mail.host=mailserver
| Local machine.
> `mail.user` | Name of the default user for retrieving email. Example:
>     mail.user=postmaster
| Value of the `user.name` Java system property.
> `mail.``protocol``.host` | Mail host for a specific protocol. For example, you can set mail.SMTP.host and mail.IMAP.host to different machine names. Examples:
>     mail.smtp.host=mail.mydom.com
>     mail.imap.host=localhost
| Value of the mail.host property.
> `mail.``protocol``.user` | Protocol-specific default user name for logging into a mailer server. Examples:
>     mail.smtp.user=weblogic
>     mail.imap.user=appuser
| Value of the mail.user property.
> `mail.from` | The default return address. Examples:
>     mail.from=master@mydom.com
| `username@host`
`mail.debug` | Set to True to enable JavaMail debug output. | False

You can override any properties set in the Mail Session in your code by creating a `Properties` object containing the properties you want to override. See Sending Messages with JavaMail. Then, after you look up the Mail Session object in JNDI, call the `Session.getInstance()` method with your `Properties` object to get a customized Session.

## Sending Messages with JavaMail

Here are the steps to send a message with JavaMail 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 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.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.

## Reading Messages with JavaMail

The JavaMail API allows you to connect to a message store, which could be an IMAP server or POP3 server. Messages are stored in folders. With IMAP, message folders are stored on the mail server, including folders that contain incoming messages and folders that contain archived messages. With POP3, the server provides a folder that stores messages as they arrive. When a client connects to a POP3 server, it retrieves the messages and transfers them to a message store on the client.

Folders are hierarchical structures, similar to disk directories. A folder can contain messages or other folders. The default folder is at the top of the structure. The special folder name INBOX refers to the primary folder for the user, and is within the default folder. To read incoming mail, you get the default folder from the store, and then get the INBOX folder from the default folder.

The API provides several options for reading messages, such as reading a specified message number or range of message numbers, or pre-fetching specific parts of messages into the folder's cache. See the JavaMail API for more information.

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 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, username, 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.

# Programming Applications for WebLogic Server Clusters

JSPs and Servlets that will be deployed to a WebLogic Server cluster must observe certain requirements for preserving session data. See Requirements for HTTP Session State Replication in Using WebLogic Server Clusters for more information.

EJBs deployed in a WebLogic Server cluster have certain restrictions based on EJB type. See Increased Reliability and Availability for Clustered EJBs in Programming WebLogic Enterprise JavaBeans for information about the capabilities of different EJB types in a cluster. EJBs can be deployed to a cluster by setting clustering properties in the EJB deployment descriptor.

If you are developing either EJBs or custom RMI objects for deployment in a cluster, also refer to Using WebLogic JNDI in a Clustered Environment in Programming WebLogic JNDI to understand the implications of binding clustered objects in the JNDI tree.