Buy this Book
Print Book $44.95 Read it Now!
Print Book £31.95
Add to UK Cart
Reprint Licensing

AspectJ Cookbook
AspectJ Cookbook

By Russell Miles
Price: $44.95 USD
£31.95 GBP

Cover | Table of Contents | Colophon


Table of Contents

Chapter 1: Aspect Orientation Overview
This chapter gives a brief overview of aspect orientation. What is discussed here is by no means a definitive description of aspect-oriented concepts, but it should present a flavor of these concepts and the related terminology. This provides a reference that will prove useful as you implement the practical recipes throughout the rest of the book.
Aspect orientation is not a completely new approach to writing software. In much the same way as virtual machine systems were not an entirely new concept when Java became recognized and adopted by the software community, there have been tools and development environments for some time that support some of the capabilities that are now being placed under the banner of aspect orientation. Like Java, aspect orientation is becoming a commonly adopted and de facto approach to practicing older ideas that can be traced to almost the beginning of software development.
Development environments and tools that weave code, pragma instructions, and even debuggers all contain some of the behavior that underlies the aspect-oriented approach. But the significant difference is in the philosophy behind the approach and how that philosophy drives the technology and tools. Aspect orientation is not about any one of these technologies on its own, though it is a new and more modular implementation of the advantages that these technologies have brought to their own domains in the past.
All that said, the philosophical and conceptual underpinnings of aspect orientation are not a subject for this type of book. If you are interested in finding out more about this side of the technology, it's best to search Google for "Aspect-Oriented Software Development." This book focuses on practical approaches to understanding the technology; it is about getting the job done by harnessing the impressive power of aspect-oriented software development.
It is fair to say that the most significant work to date that is actually labeled under the banner of aspect orientation was completed at that historical wellspring of computing innovation, the Xerox Palo Alto Research Center (PARC). Xerox initially invested in producing special-purpose aspect-oriented languages prior to moving to a general-purpose model in Java. AspectJ was the outcome of this effort and is the core development tool for the recipes found throughout this book.
Additional content appearing in this section has been removed.
Purchase this book now or read it online at Safari to get the whole thing!
A Brief History of Aspect Orientation
Aspect orientation is not a completely new approach to writing software. In much the same way as virtual machine systems were not an entirely new concept when Java became recognized and adopted by the software community, there have been tools and development environments for some time that support some of the capabilities that are now being placed under the banner of aspect orientation. Like Java, aspect orientation is becoming a commonly adopted and de facto approach to practicing older ideas that can be traced to almost the beginning of software development.
Development environments and tools that weave code, pragma instructions, and even debuggers all contain some of the behavior that underlies the aspect-oriented approach. But the significant difference is in the philosophy behind the approach and how that philosophy drives the technology and tools. Aspect orientation is not about any one of these technologies on its own, though it is a new and more modular implementation of the advantages that these technologies have brought to their own domains in the past.
All that said, the philosophical and conceptual underpinnings of aspect orientation are not a subject for this type of book. If you are interested in finding out more about this side of the technology, it's best to search Google for "Aspect-Oriented Software Development." This book focuses on practical approaches to understanding the technology; it is about getting the job done by harnessing the impressive power of aspect-oriented software development.
Additional content appearing in this section has been removed.
Purchase this book now or read it online at Safari to get the whole thing!
AspectJ
It is fair to say that the most significant work to date that is actually labeled under the banner of aspect orientation was completed at that historical wellspring of computing innovation, the Xerox Palo Alto Research Center (PARC). Xerox initially invested in producing special-purpose aspect-oriented languages prior to moving to a general-purpose model in Java. AspectJ was the outcome of this effort and is the core development tool for the recipes found throughout this book.
At the time of this writing, AspectJ is a rapidly maturing aspect-oriented development tool with a wealth of examples available. In 2002, Xerox PARC made the important decision of transferring the development of AspectJ to a more open forum on the eclipse.org web site. Current download figures for AspectJ show that interest in the approach is increasing at an exponential rate, and that the software development community is recognizing that aspect orientation is an extremely important evolution in software development. Now is the time to use this book's real-world, aspect-oriented recipes to add this new and powerful tool to your software development repertoire.
Additional content appearing in this section has been removed.
Purchase this book now or read it online at Safari to get the whole thing!
A Definition of Aspect Orientation
Before getting into the actual recipes, it is worth briefly introducing some of the concepts and terms that are used throughout this book.
The basic premise of aspect-oriented programming is to enable developers to express modular cross-cutting concerns in their software. So what does this mean? A cross-cutting concern is behavior, and often data, that is used across the scope of a piece of software. It may be a constraint that is a characteristic of your software or simply behavior that every class must perform.
The most common example of a cross-cutting concern, almost the "Hello World" of the aspect-oriented approach, is that of logging (covered in Chapter 21). Logging is a cross-cutting concern because it affects many areas across the software system and it intrudes on the business logic. Logging is potentially applied across many classes, and it is this form of horizontal application of the logging aspect that gives cross-cutting its name.
An aspect is another term for a cross-cutting concern. In aspect orientation, the aspects provide a mechanism by which a cross-cutting concern can be specified in a modular way. To fully harness the power of aspects, we need to have some basic concepts in place to allow us to specify and apply aspects in a generic manner. We must be able to:
  • Define the aspects in a modular fashion
  • Apply aspects dynamically
  • Apply aspects according to a set of rules
  • Provide a mechanism and a context for specifying the code that will be executed for that particular aspect
The aspect-oriented approach provides a set of semantics and syntactical constructs to meet these demands so that aspects can be applied generically regardless of the type of software being written. These constructs are advice, join points, and pointcuts.
Additional content appearing in this section has been removed.
Purchase this book now or read it online at Safari to get the whole thing!
Where to Go for More Information
For more detailed information on the concepts and philosophy behind aspect orientation, check out the following web sites:
http://www.parc.xerox.com/research/csl/projects/aspectj/default.html
The official information on the AspectJ project at Xerox PARC.
http://www.eclipse.org/aspectj
The official AspectJ development technologies download site with links to support tools.
http://www.eclipse.org/ajdt
Eclipse has a set of AspectJ Development Tools collected as a downloadable feature using the built-in update site mechanism from the listed web site.
http://sourceforge.net/projects/aspectj4jbuildr/
A plug-in for Borland JBuilder that allows integration with AspectJ is available at this site.
http://sourceforge.net/projects/aspectj4netbean/
A plug-in for NetBeans to support AspectJ development is available from this web site.
Additional content appearing in this section has been removed.
Purchase this book now or read it online at Safari to get the whole thing!
Chapter 2: Getting Started with AspectJ
This chapter contains recipes for getting started in developing your own aspect-oriented code using AspectJ. Beginning with the task of getting a build environment set up and moving through the different types of builds and targets, this chapter provides a tutorial in the basics of AspectJ development.
With an understanding of the fundamental concepts in aspect orientation, this chapter first covers getting your fingers dirty using AspectJ's development environment. At the core of AspectJ is its build support for weaving aspects into your Java code. This is currently done using a compiler, ajc, that interacts with the existing Java compiler, javac. Working within the constraints of the Java compilation process ensures that your aspect-oriented programs produce standard Java classes that can be run by any Java Virtual Machine (JVM). ajc simply automates the mapping of your aspects onto your Java classes.
The ajc tool is used for compile-time weaving of aspects either from the command line or within an IDE or other build tool, but there is also an alternative weaving method supported in AspectJ, load-time weaving. As its title suggests, load-time weaving supports the weaving of aspects into your application at the time when the Java class loader is loading the application into the JVM. This is a fairly new feature of AspectJ and is briefly described in this chapter with the caveat that the current methods by which load-time weaving is achieved using AspectJ may change in the future as this facility matures.
Once you have got the hang of using the ajc command-line compiler then it's time to move on to installing and using some of the capabilities available to the AspectJ developer within the Eclipse development environment. These include how to set up an Eclipse project with an AspectJ Nature using the new project creation wizards and using Eclipse to vary the aspects that are actually built into a single project using AspectJ build configuration files.
Additional content appearing in this section has been removed.
Purchase this book now or read it online at Safari to get the whole thing!
Introduction
This chapter contains recipes for getting started in developing your own aspect-oriented code using AspectJ. Beginning with the task of getting a build environment set up and moving through the different types of builds and targets, this chapter provides a tutorial in the basics of AspectJ development.
With an understanding of the fundamental concepts in aspect orientation, this chapter first covers getting your fingers dirty using AspectJ's development environment. At the core of AspectJ is its build support for weaving aspects into your Java code. This is currently done using a compiler, ajc, that interacts with the existing Java compiler, javac. Working within the constraints of the Java compilation process ensures that your aspect-oriented programs produce standard Java classes that can be run by any Java Virtual Machine (JVM). ajc simply automates the mapping of your aspects onto your Java classes.
The ajc tool is used for compile-time weaving of aspects either from the command line or within an IDE or other build tool, but there is also an alternative weaving method supported in AspectJ, load-time weaving. As its title suggests, load-time weaving supports the weaving of aspects into your application at the time when the Java class loader is loading the application into the JVM. This is a fairly new feature of AspectJ and is briefly described in this chapter with the caveat that the current methods by which load-time weaving is achieved using AspectJ may change in the future as this facility matures.
Once you have got the hang of using the ajc command-line compiler then it's time to move on to installing and using some of the capabilities available to the AspectJ developer within the Eclipse development environment. These include how to set up an Eclipse project with an AspectJ Nature using the new project creation wizards and using Eclipse to vary the aspects that are actually built into a single project using AspectJ build configuration files.
Additional content appearing in this section has been removed.
Purchase this book now or read it online at Safari to get the whole thing!
Installing AspectJ
You want to set up an AspectJ build environment.
At its simplest, AspectJ installation is a four-step process:
  1. Download the AspectJ tools from http://www.aspectj.org.
  2. Install the downloaded JAR files by double-clicking on them. This will create an aspectj1.2 directory on your machine.
  3. Test your environment with the following command:
    > ajc
    AspectJ Compiler
    
            Usage: <options> <source file | @argfile>..
    
    AspectJ-specific options:
            ... Listed compiler options
    
    
    1 fail|abort
  4. Don't worry about the 1 fail | abort message here; if you get the output shown above, then the AspectJ tools have been successfully installed and located and are available for use.
  5. Copy aspectj1.2/lib/aspectjrt.jar to a library directory of your JRE. Typical locations for this directory are %JAVA_HOME%\jre\lib\ext for Windows and /Library/Java/Extensions for Mac OS X.
The first step in preparing to develop using aspects is to download the appropriate support tools for your environment. In the case of AspectJ, this involves downloading the AspectJ libraries and tools. These tools can be obtained by accessing http://www.aspectj.org and following the links to Downloads.
Once the appropriate AspectJ development kits have been downloaded, they can be installed by double-clicking on the downloaded .jar file. After installation, you will find a directory named aspectj1.2 (if the default installation options were accepted).
The AspectJ installer specifies some important instructions at the end of the installation process. These instructions include setting up your search path so that the AspectJ tools are available from the command line and adding the AspectJ Java libraries to your Java classpath. It's worth taking care to follow those instructions to make things as easy as possible when setting up your AspectJ development environment.
Additional content appearing in this section has been removed.
Purchase this book now or read it online at Safari to get the whole thing!
Developing a Simple Aspect
You want to write a simple aspect.
First, write your business logic classes, as shown in Example 2-1.
Example 2-1. A simple business logic Java class
package com.oreilly.aspectjcookbook;

public class MyClass
{
        public void foo(int number, String name)
        {
                System.out.println("Inside foo (int, String)");
        }

        public static void main(String[] args)
        {
                // Create an instance of MyClass
                MyClass myObject = new MyClass( );
                // Make the call to foo
                myObject.foo(1, "Russ Miles");
        }
}
Define an aspect that will be applied to this class. The aspect in Example 2-2 parodies the traditional "Hello World" for AspectJ by providing an aspect that captures all calls to the void foo(int, String) method in the MyClass class.
Example 2-2. A simple HelloWorld aspect in AspectJ
package com.oreilly.aspectjcookbook;

public aspect HelloWorld 
{
   pointcut callPointcut( ) : 
      call(void com.oreilly.aspectjcookbook.MyClass.foo(int, String));

   before( ) : callPointcut( )
   {
      System.out.println(
         "Hello World");
      System.out.println(
         "In the advice attached to the call pointcut");
   }
}
Save this file in the same directory as your business logic class as HelloWorld.aj or HelloWorld.java. Run the ajc command to compile this simple application and produce the byte code .class files for both the aspect and the class:
> ajc -classpath %MY_CLASSPATH% -d %MY_DESTINATION_DIRECTORY% com/oreilly/
aspectjcookbook/MyClass.java com/oreilly/aspectjcookbook/HelloWorld.java
If you get the following message then you will need to add the aspectjrt.jar to your classpath:
warning couldn't find aspectjrt.jar on classpath, checked: 

error can't find type org.aspectj.lang.JoinPoint

1 error, 1 warning
Additional content appearing in this section has been removed.
Purchase this book now or read it online at Safari to get the whole thing!
Compiling an Aspect and Multiple Java Files
You want to conveniently compile a selection of aspects that are to be applied to multiple Java classes.
Create an AspectJ build configuration file titled <appname> .lst containing the names of all of the class files and aspects to be included in the compilation, similar to the example .lst file in Example 2-4.
Example 2-4. The contents of an example AspectJ build configuration .lst file
// File files.lst
com/oreilly/aspectjcookbook/MyClass.java
com/oreilly/aspectjcookbook/MyAspect.java
com/oreilly/aspectjcookbook/AnotherClass.java
com/oreilly/aspectjcookbook/AnotherAspect.java
Use the following command to instruct the ajc compiler to apply the aspects to the classes:
> ajc -argfile files.lst -classpath %MY_CLASSPATH% -d %MY_DESTINATION_DIRECTORY%
The process by which the ajc tool completes the compilation of aspects and classes is largely transparent to the developer and can be treated as a black box. You shouldn't really worry about the interim steps that may be taking place inside the AspectJ compiler, short of a desire to get into development work on ajc itself.
It is important to consider the inputs to the build process; this is handled through the creation of the .lst build configuration file. The ajc compiler does not search the source or class path for files to compile; it must be told which files are to be involved in the compilation. This means that all of your source that is to be compiled with aspects must be fed directly to the ajc compiler. There are three ways to supply the files to be compiled to the ajc compiler (two of which are semantically equivalent):
The -argfile option
You can supply all the files within a .lst file by specifying the filename on the
Additional content appearing in this section has been removed.
Purchase this book now or read it online at Safari to get the whole thing!
Weaving Aspects into Jars
Your want to weave your aspects into code that has already been compiled and collected into a .jar file.
Use the -inpath command-line option when running the ajc command.
The ajc command weaves aspects into Java byte code which can reside in .class files, within a Java .jar library file or a mixture of the two. The following instructions show you how to take the code from Recipe 2.2 and package the MyClass class in a .jar file before weaving the HelloWorld aspect into the library:
  1. Compile the MyClass class using the traditional javac command:
    > javac -classpath %MY_CLASSPATH% -d %MY_DESTINATION_DIRECTORY% com/oreilly/
    aspectjcookbook/MyClass.java
  2. Package the generated MyClass.class file into a .jar file titled MyApp.jar:
    > jar -cvf MyApp.jar com/oreilly/aspectjcookbook/MyClass.class
  3. Compile the HelloWorld.java aspect using the ajc command, specifying the new MyApp.jar on the command line using the -inpath option:
    > ajc -classpath %MY_CLASSPATH% -d %MY_DESTINATION_DIRECTORY% -inpath MyApp.jar 
    com/oreilly/aspectjcookbook/HelloWorld.java
    The -inpath option forces the ajc compiler to extract the Java byte code from the supplied .jar files into the destination directory as specified by the -d option. The ajc compiler then includes that extracted byte code in the aspect weaving process.
  4. If no errors occur during compilation with ajc then you will have successfully woven the classes contained within the MyApp.jar file with the HelloWorld aspect. Because the ajc command extracts the classes from the .jar files supplied to the -inpath option, they are no longer needed to run the application. However, you can optionally re-package your new application in a
Additional content appearing in this section has been removed.
Purchase this book now or read it online at Safari to get the whole thing!
Weaving Aspects at Load Time
You want to postpone the decision as to whether an aspect should be applied to a particular application until the application is being loaded into the Java Virtual Machine.
Use the new load-time weaving features of AspectJ 1.2.
Using the code shown in Recipe 2.2, the following instructions show you how to apply the HelloWorld aspect to the MyClass class at load time:
  1. Compile the MyClass class using the traditional javac command:
    > javac -classpath %MY_CLASSPATH% -d %MY_DESTINATION_DIRECTORY% com/oreilly/
    aspectjcookbook/MyClass.java
    By using the javac command, you are completely avoiding weaving any aspects into your application at compile time. If you have some aspects that you want to include at compile time, you can use the ajc command and list the aspects to be included at that point in the AspectJ build configuration file, not specifying any aspects you intend to only weave at load time.
  2. You can now check to ensure that the MyClass class has been compiled without any aspects by running the application using the java command:
    > java com.oreilly.aspectjcookbook.MyClass
    Inside foo (int, String)
  3. Compile the HelloWorld aspect into an aspect library .jar file using the ajc command:
    > ajc -outjar helloworldlibrary.jar -d %MY_DESTINATION_DIRECTORY% com/oreilly/
    aspectjcookbook/HelloWorld.java
    You may find that you get the following warning stating that there is no match to the pointcut logic declared in your HelloWorld aspect:
    warning no match for this type name: com$oreilly$aspectjcookbook$MyClass [Xlint:
    invalidAbsoluteTypeName]
    call(void com.oreilly.aspectjcookbook.MyClass.foo(int, String));
              ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
Additional content appearing in this section has been removed.
Purchase this book now or read it online at Safari to get the whole thing!
Generating Javadoc Documentation
You want to generate javadoc format documentation for your AspectJ application.
Use the ajdoc tool from the command line or from within Eclipse.
Java developers have used the javadoc tool for generating comprehensive documentation for their Java applications since Java 1.1. The javadoc tool was never designed to handle the new language constructs that AspectJ introduces and is not able to generate documentation for an AspectJ application. To meet this problem, the developers of AspectJ created ajdoc, a tool that extends javadoc so that it can correctly and usefully document the aspect-oriented structures in your application.
Providing your environment has been set up correctly, as shown in Recipe 2.1, the ajdoc tool can be accessed from the command line by typing the following command:
> ajdoc -sourcepath <The root location of you code> -d <The 
directory in which you want your documentation to be placed> <The 
file locations of each of the classes aspects and classes to include in 
the generated documentation>
The ajdoc tool provides the -argfile parameter so that you can provide an explicit AspectJ build configuration .lst file, as mentioned in Recipe 2.3. A .lst file contains the build configuration for a set of classes and aspects in your application for which documentation should be produced.
Using ajdoc means that you can now document your pointcuts, advice, and aspects as shown in Example 2-5.
Example 2-5. Applying javadoc tags to the aspects, pointcuts, and advice
package com.oreilly.aspectjcookbook;

/**
 * A simple aspect to weave in a HelloWorld message when foo(int,name) 
 * is called on objects of the MyClass class.
 * @author russellmiles
 * @version 1.0
 *
 */
public aspect HelloWorld 
{
   /**
    * Selects join points on calls to the MyClass.foo(int,String) method.
    */
   pointcut callPointCut( ) : 
      call(void com.oreilly.aspectjcookbook.MyClass.foo(int, String));
   
   /**
    * Simple before advice that prints HelloWorld to the standard output.
    */
   before( ) : callPointCut( )
   {
      System.out.println(
      "Hello World");
      System.out.println(
      "In the advice attached to the call point cut");
   }
}
Additional content appearing in this section has been removed.
Purchase this book now or read it online at Safari to get the whole thing!
Compiling an AspectJ Project Using Eclipse
You want to compile your AspectJ project using Eclipse.
Download and install the AspectJ Development Tools (AJDT) plug-in into Eclipse.
AspectJ is run under the same open source collective as the Eclipse project and provides the most advanced AspectJ plug-in for an IDE. The AspectJ Eclipse plug-in can be downloaded by following the instructions available at http://www.eclipse.org/ajdt.
It's a good rule of thumb to download the latest version of AspectJ, the corresponding latest version of the AJDT, and then download the supported version of Eclipse just in case the Eclipse tool is a step or so ahead of the AspectJ development. If you are ever confused by the options available, there is a compatibility table available on the AJDT downloads page to point you in the right direction.
To check that the plug-in has been correctly installed, click on File New Project... on the Eclipse menu bar. When the New Project dialog appears, the AspectJ project option should be available, as shown in Figure 2-1.
Figure 2-1: Creating a new AspectJ project
By default, early milestone builds of Eclipse 3 hid all additional wizards. To see the New AspectJ Project option, you may have to select the Show All Wizards checkbox.
Highlighting the AspectJ Project option, click on Next in the New Project dialog and complete the next few steps to set up the new AspectJ project.
Additional content appearing in this section has been removed.
Purchase this book now or read it online at Safari to get the whole thing!
Selecting the Aspects That Are Woven in a Build Within Eclipse
You want to vary the aspects that are woven into your application when developing in Eclipse.
Create a separate AspectJ build configuration for each different selection of aspects that you want to weave into your application. Eclipse then allows you to select the current build configuration it will use to build your AspectJ project so you can easily select the set of aspects you want to apply for a particular build.
Recipe 2.3 showed that the AspectJ compiler can use a build confiuguration .lst file to select the classes and aspects it will include in its aspect weaving. By default, an AspectJ project in Eclipse has a single .lst file, naturally called default.lst, that lists all the of the files in your project. Using this default, the AspectJ compile will apply all the aspects to all of classes where indicated by the pointcut logic in those aspects.
For many applications, this default behavior is fine but there are times when you may want to vary the aspects that are applied to a particular application depending on such things as deployment target or feature selection. AspectJ provides a neat way of varying the selection of aspects to be applied using a custom build configuration .lst file that excludes or includes the aspects you wish to apply.
Eclipse provides the means by which a custom AspectJ build configuration can be created and used for a particular project.
When the project created in Recipe 2.7 is run, the output produced on the Console in Eclipse is:
MyAspect before( ) advice
In the advice attached to the call point cut
Inside foo (int, String)
The following steps create a new build configuration that will exclude the single MyAspect aspect in the project from the build and therefore change the behavior of the application as shown by the amended output on the Console.
Additional content appearing in this section has been removed.
Purchase this book now or read it online at Safari to get the whole thing!
Building an AspectJ Project Using Ant
You want to compile an AspectJ project using Ant.
Use the tasks included in the AspectJ toolkit to build your project using Ant.
The Ant build.xml configuration file in Example 2-6 shows an example for how to call upon the additional AspectJ Ant tasks.
Example 2-6. An Ant configuration file that uses the AspectJ tasks
<?xml version="1.0" encoding="UTF-8"?>
<project basedir="." default="compile" name="test">
    <property name="src" value="src"/>
    <property name="build" value="build"/>
    <taskdef resource="org/aspectj/tools/ant/taskdefs/aspectjTaskdefs.
       properties">
        <classpath>
            <pathelement location="%ASPECTJ_INSTALLATION%/lib/
               aspectjtools.jar"/>
        </classpath>
    </taskdef>
    <target name="compile">
        <mkdir dir="${build}"/>
        <iajc destdir="${build}" sourceroots="${src}">
            <classpath>
                <pathelement location="%ASPECTJ_INSTALLATION%/
                   lib/aspectjrt.jar"/>
            </classpath>
        </iajc>
    </target>
</project>
Here is what Example 2-6 does:
  1. Defines a new task using the AspectJ task properties
  2. Specifies the location of the aspectjtools.jar
  3. Declares a build target that compiles the project using the iajc task that in turn relies upon the aspectjrt.jar to execute
Ant: The Definitive Guide by Jesse Tilly and Eric M. Burke (O'Reilly); the Jakarta Ant online manual at http://jakarta.apache.org/ant/manual/index.html.
Additional content appearing in this section has been removed.
Purchase this book now or read it online at Safari to get the whole thing!
Chapter 3: Deploying AspectJ Applications
Whatever the applications are that you develop with AspectJ, you will usually want to deploy your application to a target environment so it can be made available to your users. Java application deployment can range from being as complex as providing context-specific runtime wrappers and scripts to run your application, or as simple as providing a double-clickable .jar or executable. So, deployment can often be a real headache for developers.
To add to this mix, AspectJ adds some additional requirements to your application deployment. The recipes in this chapter describe in detail those additional requirements that an AspectJ application imposes on a traditional Java application and some of the tools support that you have at your disposal to help you in the deployment process.
AspectJ is definitely not limited to just regular Java applications. You can deploy AspectJ applications into many different target runtime environments including Java Servlets and Java Server Pages inside Tomcat and Axis Web Services. These more complicated deployment environments often offer several different ways of deploying the same application. Some of these options are better suited to AspectJ than others and so this chapter focuses on describing the easiest routes to application deployment to these target environments.
As you work through the recipes in this chapter, it's worth remembering that many of the manual steps could be automated using Apache Ant or even command-line scripts and batch files. However, the recipes here deliberately walk you through all of the manual steps required to deploy into the various target environments to keep you in touch with what is going on at all times.
You want to deploy a simple AspectJ application to be deployed and then run from the command line.
A straightforward Java application usually requires nothing more than a Java Runtime Environment on the target machine and the classes of your application added to the Java classpath before you can run your application.
Additional content appearing in this section has been removed.
Purchase this book now or read it online at Safari to get the whole thing!
Introduction
Whatever the applications are that you develop with AspectJ, you will usually want to deploy your application to a target environment so it can be made available to your users. Java application deployment can range from being as complex as providing context-specific runtime wrappers and scripts to run your application, or as simple as providing a double-clickable .jar or executable. So, deployment can often be a real headache for developers.
To add to this mix, AspectJ adds some additional requirements to your application deployment. The recipes in this chapter describe in detail those additional requirements that an AspectJ application imposes on a traditional Java application and some of the tools support that you have at your disposal to help you in the deployment process.
AspectJ is definitely not limited to just regular Java applications. You can deploy AspectJ applications into many different target runtime environments including Java Servlets and Java Server Pages inside Tomcat and Axis Web Services. These more complicated deployment environments often offer several different ways of deploying the same application. Some of these options are better suited to AspectJ than others and so this chapter focuses on describing the easiest routes to application deployment to these target environments.
As you work through the recipes in this chapter, it's worth remembering that many of the manual steps could be automated using Apache Ant or even command-line scripts and batch files. However, the recipes here deliberately walk you through all of the manual steps required to deploy into the various target environments to keep you in touch with what is going on at all times.
Additional content appearing in this section has been removed.
Purchase this book now or read it online at Safari to get the whole thing!
Deploying a Command-Line AspectJ Application
You want to deploy a simple AspectJ application to be deployed and then run from the command line.
A straightforward Java application usually requires nothing more than a Java Runtime Environment on the target machine and the classes of your application added to the Java classpath before you can run your application.
AspectJ requires that the Java Runtime Environment be at Version 1.1 or later, and it needs the additional aspectjrt.jar library added to the classpath to support the aspect-oriented features of your AspectJ application.
Using the simple application developed in Recipe 2.2, the following steps create a directory containing all of the necessary deployment files needed to run your AspectJ application:
  1. Create a new directory to contain your runtime deployment that is separate from your source directories. For this example, name the directory deployment.
  2. Create a subdirectory of the top-level deployment directory and name it classes.
  3. Place all of your application's compiled .class files in the classes directory, taking care to maintain your package directory structure. For this example, the code from Recipe 2.2 is being used, so the directory structure should look like Figure 3-1.
    Figure 3-1: The directory structure after you have placed the .class files within your deployment area
    You can perform this by either manually copying each of the packages of .class files or by building your application with the ajc tool with the destination flag, -d, set to the classes directory:
    > ajc -classpath %MY_CLASSPATH% -d %PROJECT_ROOT_DIRECTORY%/deployment/classes
    com/oreilly/aspectjcookbook/MyClass.java com/oreilly/aspectjcookbook/HelloWorld.
    java
Additional content appearing in this section has been removed.
Purchase this book now or read it online at Safari to get the whole thing!
Deploying an AspectJ Application as a Fully Contained Executable JAR File
You want to deploy an AspectJ application to be run as an executable JAR file.
Unpack the contents of the aspectjrt.jar file and then repack the AspectJ classes with your own application's classes into a single JAR file. To make the single JAR file executable, an appropriate manifest file should be included that lists the class that contains the standard public static void main(String[]) method entry point for running Java applications.
Creating an executable JAR file is a popular way of deploying conventional Java applications. The JAR file format, by default, contains all of the necessary classes for a software component, and it has the potential to be configured as a packaged Java application that can be run simply by double-clicking on the file within most popular operating systems.
The following steps manually create an executable JAR file for the application shown in Recipe 2.2:
  1. Take a copy of the deployment directory as it was created in Recipe 2.1.
  2. Unjar the contents of the aspectjrt.jar that is stored in the deployment/lib directory using the jar tool from the command line:
    jar -xvf aspectjrt.jar
  3. After the jar extraction has completed, you will find that two folders have been extracted within the deployment/lib directory, META-INF and org. The META-INF directory contains a MANIFEST.MF file containing the manifest information for the aspectjrt.jar. The org directory contains the .class files needed by the aspect-oriented mechanisms within your application to run when it is deployed.
  4. Copy the deployment/lib/org directory and all of its contents into the deployment/classes directory
Additional content appearing in this section has been removed.
Purchase this book now or read it online at Safari to get the whole thing!
Deploying a Java Servlet That Uses AspectJ
You want to deploy a servlet that has been developed using AspectJ into Apache Tomcat.
Compile your Java Servlet from the command line using the ajc command or inside an Eclipse AspectJ project. Under the webapps directory inside Apache Tomcat, set up a new web application directory and WEB-INF subdirectory. Make the appropriate amendments to the server.xml file in the Tomcat configuration to enable your web application.
Copy the compiled Java Servlet .class files and corresponding aspect .class files into the webapps/%YOUR_APPLICATION_DIRECTORY%/WEB-INF/classes. Copy the aspectjrt.jar file into the webapps/%YOUR_APPLICATION_DIRECTORY%/WEB-INF/lib so the aspect-oriented features of your software can find the support components they need.
Amend your web application's webapps/%YOUR_APPLICATION_DIRECTORY/WEB-INF/web.xml file to support access to the new Java Servlet. Finally, restart Tomcat to activate your web application.
The following steps show how to create, compile, and deploy a simple Java Servlet that uses AspectJ:
  1. Create a Java Servlet and corresponding aspect similar to the ones shown in Examples Example 3-2 and Example 3-3.
    Example 3-2. A simple HelloWorld Java Servlet
    package com.oreilly.aspectjcookbook;
    
    import java.io.IOException;
    
    import javax.servlet.ServletException;
    import javax.servlet.ServletOutputStream;
    import javax.servlet.http.HttpServlet;
    import javax.servlet.http.HttpServletRequest;
    import javax.servlet.http.HttpServletResponse;
    
    public class AOHelloWorldServlet extends HttpServlet
    {
       public void doGet (HttpServletRequest request, HttpServletResponse response)
          throws ServletException, IOException
       {
          ServletOutputStream out = response.getOutputStream( );
          out.println("<h1>Hello World from an aspect-oriented Servlet!</h1>");
       }
       
       public String getServletInfo( ) 
       {
          return "Create a page that says <i>Hello World</i> and send it back";
       }
    }
Additional content appearing in this section has been removed.
Purchase this book now or read it online at Safari to get the whole thing!
Deploying a JSP That Uses AspectJ
You want to build and deploy a JSP that uses AspectJ into Apache Tomcat.
Create a Java Servlet from your JSP using the tools supplied with Tomcat. Compile your Java Servlet from the command line using the ajc command or inside an Eclipse AspectJ project.
Set up a directory structure from which to deploy your complete JSP application, including the aspectjrt.jar support library and the .class files that were compiled by the ajc command-line tool.
Copy the deployment directory entirely to the %TOMCAT_INSTALL_DIRECTORY%/webapps directory. Make the appropriate amendments to the server.xml file in the Tomcat configuration to enable your web application. Finally, restart Tomcat to activate your web application.
Java Server Pages are trickier than Java Servlets when it comes to using a custom compiler such as AspectJ because a JSP is traditionally compiled into a Java Servlet transparently by the Servlet containers like Apache Tomcat.
The following steps describe how to build and deploy a simple JSP that uses AspectJ into Apache Tomcat:
  1. Create a directory in your project area called jsp.
  2. Create a file in the jsp directory called simple.jsp that has the following contents:
    <html>
    <body bgcolor="white">
    <h1> Request Information </h1>
    <font size="4">
    JSP Request Method: <%= request.getMethod( ) %>
    <br>
    Request URI: <%= request.getRequestURI( ) %>
    <br>
    Request Protocol: <%= request.getProtocol( ) %>
    <br>
    Servlet path: <%= request.getServletPath( ) %>
    <br>
    </font>
    </body>
    </html>
  3. Create a directory in your project area called source to hold your aspect and preprocessed JSP source code.
  4. Create a directory in your project area called myjspapplication and a subdirectory called
Additional content appearing in this section has been removed.
Purchase this book now or read it online at Safari to get the whole thing!
Deploying an Axis Web Service That Uses AspectJ
You want to deploy an aspect-oriented Apache Axis web service that has been created using AspectJ.
Create and compile your web service Java class with your aspects using the ajc command line tool or in AspectJ project in Eclipse. Copy your application's .class files to the %AXIS_INSTALLATION_IN_TOMCAT%/WEB-INF/classes directory and the aspectjrt.jar to %AXIS_INSTALLATION_IN_TOMCAT%/WEB-INF/lib.
Create an Apache Axis deployment configuration file and use the org.apache.axis.client.AdminClient command-line tool to register your new web service with Apache Axis.
Apache Axis is rapidly becoming one of the most popular web service implementations for Java developers. Not only is it open source but, thanks to its very active supporting developer base, it also has a high degree of success in interoperability with web services developed using other web service frameworks such as .NET.
Once you have Apache Axis running within Tomcat on your machine, you can use the following steps to compile a simple aspect-oriented web service and deploy it within Apache Axis:
  1. Create a directory within your project area called source, and within that new directory, create a file called MyWebService.java that contains:
    package com.oreilly.aspectjcookbook;
    
    public class MyWebService
    {
       public String echo(String message)
       {
          return message;
       }
    }
  2. Create another file in the source directory called AddMessageHeaderAspect.java that contains:
    package com.oreilly.aspectjcookbook;
    
    public aspect AddMessageHeaderAspect 
    {
       public pointcut captureEcho(String message) : 
          execution(public void MyWebService.echo(String)) && 
          args(message);
       
       Object around(String message) : captureEcho(message)
       {
          return "Your original message was: " + message;
       }
    }
Additional content appearing in this section has been removed.
Purchase this book now or read it online at Safari to get the whole thing!
Chapter 4: Capturing Joing Points on Methods
A join point is a specific point at which advice can be woven into the code of an application. Pointcuts provide logical definitions for picking the join points that will invoke a piece of advice.
The next nine chapters correspond to the types of Java language constructs that contain join points that can be captured using pointcut declarations in AspectJ. This chapter focuses on pointcuts that can capture the selection of join points that are available on Java methods.
The before( ) form of advice is used for most of these pointcut-based recipes that make up the next eight chapters to avoid confusing things by using different types of advice. Where it's unavoidable, other forms of advice may have to be used, so it might be helpful to refer to Chapter 9 to understand the implications that the different forms of advice bring to the solutions provided.
Once you have grasped the different types of pointcut that AspectJ provides in Chapter 4 through Chapter 12, check out Mik Kersten's standard pointcut idioms by going to http://www.eclipse.org/aspectj and then by clicking on Documentation standard pointcut idioms. These reusable pointcut definitions provide some great tools with which to construct your own pointcut logic.
You want to capture when calls are made to methods that match a specific signature.
Use the call(Signature) pointcut. The syntax of the call(Signature) pointcut is:
pointcut <pointcut name>(<any values to be picked up>) : 
   call(<optional modifier> <return type> <class>.<method>(<paramater types>));
In contrast to Java method parameters, whitespace in the Signature parameter is important as it is used to separate out the different components.
Additional content appearing in this section has been removed.
Purchase this book now or read it online at Safari to get the whole thing!
Introduction
Content preview·Buy PDF of this chapter|