aboutsummaryrefslogtreecommitdiffstats
path: root/documentation/articles/OptimizingTheWidgetSet.asciidoc
blob: b06823ddf40b8ef302b7f24b1b831534c43d9c87 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
---
title: Optimizing The Widget Set
order: 29
layout: page
---

[[optimizing-the-widget-set]]
= Optimizing the widget set

Vaadin contains a lot of components and most of those components
contains a client side part which is executed in the browser. Together
all the client side implementations sum up to a big amount of data the
enduser needs to download to the browser even if he might never use all
the components.

For that reason Vaadin uses three strategies for downloading the
components:

[[eager]]
Eager
+++++

What eager means is that the client implementation for the component is
included in the payload that is initially downloaded when the
application starts. The more components that is made eager the more will
need to be downloaded before the initial view of the application is
shown. By default Vaadin puts most components here since Vaadin does not
know which components will be used in the first view and cannot thus
optimize any further. You would have noticed this if you ever made a
Hello World type of application and wondered why Vaadin needed to
download so much for such a simple application.

[[deferred]]
Deferred
++++++++

When marking a component as deferred it means that its client side
implementation will be downloaded right after the initial rendering of
the application is done. This can be useful if you know for instance
that a component will soon be used in that application but is not
displayed in the first view.

[[lazy]]
Lazy
++++

Lazy components client side implementation doesn't get downloaded until
the component is shown. This will sometimes mean that a view might take
a bit longer to render if several components client side implementation
needs to first be downloaded. This strategy is useful for components
that are rarely used in the application which everybody might not see.
`RichTextArea` and `ColorPicker` are examples of components in Vaadin that by
default are Lazy.

[[optimizing-the-loading-of-the-widgets]]
Optimizing the loading of the widgets
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^

Now that we know what Vaadin provides, lets see how we can modify how a
component is loaded to provide the best experience for our application.

Lets say we want to build a HelloWorld application which only needs a
few components. Specifically these components will be shown on the
screen:

* UI - The UI of the application.
* VerticalLayout - The Vertical layout inside the UI where the message
is shown
* Label - A label with the text "Hello World"

All other Vaadin components provided by Vaadin we don't want to load. To
do this we are going to mark those three components as Eager (initially
loaded) and all the rest as Lazy.

To do that we need to implement our own `ConnectorBundleLoaderFactory`.
Here is my example one:

[source,java]
....
public class MyConnectorBundleLoaderFactory extends
    ConnectorBundleLoaderFactory {
  private static final List<Class> eagerComponents = new
    LinkedList<Class>();

  static {
    eagerComponents.add(UI.class);
    eagerComponents.add(VerticalLayout.class);
    eagerComponents.add(Label.class);
  }

  @Override
  protected LoadStyle getLoadStyle(JClassType connectorType){
    Connect annotation = connectorType.getAnnotation(Connect.class);
    Class componentClass = annotation.value();

    // Load eagerly marked connectors eagerly
    if(eagerComponents.contains(componentClass)) {
      return LoadStyle.EAGER;
    }

    //All other components should be lazy
    return LoadStyle.LAZY;
  }
}
....

We also need to add our factory to the widgetset by adding the following
to our <widgetset>.gwt.xml:

[source,xml]
....
<generate-with class="com.example.widgetsetoptimization.MyConnectorBundleLoaderFactory">
  <when-type-assignable class="com.vaadin.client.metadata.ConnectorBundleLoader" />
</generate-with>
....

If you are using the Eclipse Plugin to compile the widgetset you will
also want to add the following meta data for the compiler so it does not
overwrite our generator setting:

[source,xml]
....
<!-- WS Compiler: manually edited -->
....

If you have used the Maven archetype for setting up your project, you
might need to add vaadin-client-compiler as a dependency in your project
as it is by default only used when actually starting the widgetset
compiler. See http://dev.vaadin.com/ticket/11533 for more details.

Finally, here is my simple test application UI for which I have
optimized the widgetset:

[source,java]
....
public class HelloWorldUI extends UI {

  @Override
  protected void init(VaadinRequest request) {
    VerticalLayout layout = new VerticalLayout();
    layout.addComponent(new Label("Hello world"));
    setContent(layout);
  }
}
....

Now, all I have to do is recompile the widgetset for the new load
strategy to take effect.

If you now check the network traffic when you load the application you
will notice a *huge difference*. Using the default widgetset with the
default loading strategy our Hello World application will load over *1
Mb* of widgetset data. If you then switch to using our own widgetset
with our own custom loader factory the widgetset will only be about *375
kb*. That is over *60% less!*

Using your own custom widgetset loader factory is highly recommended in
all projects.

[[finding-out-which-components-are-loaded-by-a-view]]
Finding out which components are loaded by a View
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^

So you want to start optimizing your widgetset but how do you find out
which components are needed for the initial view so you can make them
eager while keeping everything else deferred or lazy? Fortunately there
is an addon
https://vaadin.com/directory#addon/widget-set-optimizer[WidgetSetOptimizer]
for doing just this.

To use it you download this addon and add it to your project.

Add the following to the <widgetset>.gwt.xml:

[source,xml]
....
<inherits name="org.vaadin.artur.widgetsetoptimizer.WidgetSetOptimizerWidgetSet" />
....

You will also need to add the following to your UI classes init method

[source,java]
....
new WidgetSetOptimizer().extend(this);
....

Finally compile the widgetset and run the application with the &debug
parameter. In the debug window there will be a new button "OWS" which by
pressing you will get the Generator class automatically generated for
you. The generated generator class will mark the currently displayed
components as Eager while loading everything else as Deferred. More
information about the addon and its usage can be found on the Addon page
in the directory.
old } /* Name.Exception */ .highlight .nf { color: #0066bb; font-weight: bold } /* Name.Function */ .highlight .nl { color: #336699; font-style: italic } /* Name.Label */ .highlight .nn { color: #bb0066; font-weight: bold } /* Name.Namespace */ .highlight .py { color: #336699; font-weight: bold } /* Name.Property */ .highlight .nt { color: #bb0066; font-weight: bold } /* Name.Tag */ .highlight .nv { color: #336699 } /* Name.Variable */ .highlight .ow { color: #008800 } /* Operator.Word */ .highlight .w { color: #bbbbbb } /* Text.Whitespace */ .highlight .mb { color: #0000DD; font-weight: bold } /* Literal.Number.Bin */ .highlight .mf { color: #0000DD; font-weight: bold } /* Literal.Number.Float */ .highlight .mh { color: #0000DD; font-weight: bold } /* Literal.Number.Hex */ .highlight .mi { color: #0000DD; font-weight: bold } /* Literal.Number.Integer */ .highlight .mo { color: #0000DD; font-weight: bold } /* Literal.Number.Oct */ .highlight .sa { color: #dd2200; background-color: #fff0f0 } /* Literal.String.Affix */ .highlight .sb { color: #dd2200; background-color: #fff0f0 } /* Literal.String.Backtick */ .highlight .sc { color: #dd2200; background-color: #fff0f0 } /* Literal.String.Char */ .highlight .dl { color: #dd2200; background-color: #fff0f0 } /* Literal.String.Delimiter */ .highlight .sd { color: #dd2200; background-color: #fff0f0 } /* Literal.String.Doc */ .highlight .s2 { color: #dd2200; background-color: #fff0f0 } /* Literal.String.Double */ .highlight .se { color: #0044dd; background-color: #fff0f0 } /* Literal.String.Escape */ .highlight .sh { color: #dd2200; background-color: #fff0f0 } /* Literal.String.Heredoc */ .highlight .si { color: #3333bb; background-color: #fff0f0 } /* Literal.String.Interpol */ .highlight .sx { color: #22bb22; background-color: #f0fff0 } /* Literal.String.Other */ .highlight .sr { color: #008800; background-color: #fff0ff } /* Literal.String.Regex */ .highlight .s1 { color: #dd2200; background-color: #fff0f0 } /* Literal.String.Single */ .highlight .ss { color: #aa6600; background-color: #fff0f0 } /* Literal.String.Symbol */ .highlight .bp { color: #003388 } /* Name.Builtin.Pseudo */ .highlight .fm { color: #0066bb; font-weight: bold } /* Name.Function.Magic */ .highlight .vc { color: #336699 } /* Name.Variable.Class */ .highlight .vg { color: #dd7700 } /* Name.Variable.Global */ .highlight .vi { color: #3333bb } /* Name.Variable.Instance */ .highlight .vm { color: #336699 } /* Name.Variable.Magic */ .highlight .il { color: #0000DD; font-weight: bold } /* Literal.Number.Integer.Long */
[[ajc]]
= `ajc`, the AspectJ compiler/weaver

== Name

`ajc` - compiler and bytecode weaver for the AspectJ and Java languages

== Synopsis

[subs=+quotes]
 ajc [_option_...] [_file_... | @_file_... | -argfile _file_...]

== Description

The `ajc` command compiles and weaves AspectJ and Java source and .class
files, producing .class files compliant with any Java VM (1.1 or later).
It combines compilation and bytecode weaving and supports incremental
builds; you can also weave bytecode at run-time using xref:ltw.adoc#ltw[Load-Time Weaving].

The arguments after the options specify the source file(s) to compile.
To specify source classes, use `-inpath` (below). Files may be listed
directly on the command line or in a file. The `-argfile file` and
`@file` forms are equivalent, and are interpreted as meaning all the
arguments listed in the specified file.

`Note:` You must explicitly pass `ajc` all necessary sources. Be sure to
include the source not only for the aspects or pointcuts but also for
any affected types. Specifying all sources is necessary because, unlike
javac, ajc does not search the sourcepath for classes. (For a discussion
of what affected types might be required, see
xref:../progguide/implementation.adoc[The AspectJ Programming Guide,
Implementation Appendix].)

To specify sources, you can list source files as arguments or use the
options `-sourceroots` or `-inpath`. If there are multiple sources for
any type, the result is undefined since ajc has no way to determine
which source is correct. (This happens most often when users include the
destination directory on the inpath and rebuild.)

[[ajc_options]]
=== Options

`-injars <JarList>`::
  deprecated: since 1.2, use `-inpath`, which also takes directories.
`-inpath <Path>`::
  Accept as source bytecode any .class files in the .jar files or
  directories on Path. The output will include these classes, possibly
  as woven with any applicable aspects. Path is a single argument
  containing a list of paths to zip files or directories, delimited by
  the platform-specific path delimiter.
`-aspectpath <Path>`::
  Weave binary aspects from jar files and directories on path into all
  sources. The aspects should have been output by the same version of
  the compiler. When running the output classes, the run classpath
  should contain all aspectpath entries. Path, like classpath, is a
  single argument containing a list of paths to jar files, delimited by
  the platform-specific classpath delimiter.
`-argfile <File>`::
  The file contains a line-delimited list of arguments. Each line in the
  file should contain one option, filename, or argument string (e.g., a
  classpath or inpath). Arguments read from the file are inserted into
  the argument list for the command. Relative paths in the file are
  calculated from the directory containing the file (not the current
  working directory). Comments, as in Java, start with `//` and extend
  to the end of the line. Options specified in argument files may
  override rather than extending existing option values, so avoid
  specifying options like `-classpath` in argument files unlike the
  argument file is the only build specification. The form `@file` is the
  same as specifying `-argfile file`.
`-outjar <output.jar>`::
  Put output classes in zip file output.jar.
`-outxml`::
  Generate aop.xml file for load-time weaving with default name.
`-outxmlfile <custom/aop.xml>`::
  Generate aop.xml file for load-time weaving with custom name.
`-incremental`::
  Run the compiler continuously. After the initial compilation, the
  compiler will wait to recompile until it reads a newline from the
  standard input, and will quit when it reads a 'q'. It will only
  recompile necessary components, so a recompile should be much faster
  than doing a second compile. This requires `-sourceroots`.
`-sourceroots <DirPaths>`::
  Find and build all .java or .aj source files under any directory
  listed in DirPaths. DirPaths, like classpath, is a single argument
  containing a list of paths to directories, delimited by the platform-specific
  classpath delimiter. Required by `-incremental`.

`-xmlConfigured <files>`::
+
--
Configure the compile-time weaving (CTW) process, if you wish to impose non-standard limitations, e.g. a list of aspects
to use (if not all), global and per-aspect scopes for the weaver (target packages and classes to exclude or include).
This option also needs an .xml file on the command line, optionally multiple ones to be logically merged into one weaver
configuration. Example:

[source, xml]
....
<aspectj>
  <!-- From all aspects found, only use the ones listed here -->
  <aspects>
    <!-- Only weave class org.acme.app.B -->
    <aspect name="a.b.OneAspect" scope="org.acme.app.B"/>
    <!-- Only weave classes in package org.acme and its sub-packages -->
    <aspect name="c.d.TwoAspect" scope="org.acme..*"/>
    <!-- Weave all classes, unless globally excluded -->
    <aspect name="e.f.ThreeAspect"/>
    <!-- Weave all classes below org.acme.service, but not in the audit sub-package -->
    <aspect name="e.f.FourAspect" scope="org.acme.service..* AND !*..audit.*"/>
    <!-- Weave all controllers and services -->
    <aspect name="e.f.FiveAspect" scope="*..*Controller || *..*Service"/>
  </aspects>
  <weaver>
    <!-- Globally exclude classes in package org.acme.internal and its sub-packages from weaving -->
    <exclude within="org.acme.internal..*"/>
    <!-- This has **no effect**, use per-aspect scopes instead -->
    <include within="com.xyz..*"/>
  </weaver>
</aspectj>
....

Please note, that `-xmlConfigured` works similarly to load-time weaving (LTW) configuration with _aop.xml_, but not 100%
identically:

  * There is **no magical file name** like _aop.xml_ for LTW, i.e. an XML configuration file for CTW needs to be
    specified on the command line explicitly.
  * In the `<weaver>` section, `<include within="..."/>` is ignored (see example above), because in CTW mode all
    classes the compiler can see are implicitly included in weaving, unless explicitly excluded.

Limitations which apply to both LTW and CTW modes include:

  * Scopes and excludes only affect regular pointcuts (e.g. method interception), not ITDs. The latter will always be
    applied and are unaffected by XML configuration.
  * When using logical operators, you cannot write `&&` in XML. Instead, use `AND` as a replacement. The operators `||`
    and `!` can be used normally. Complex expressions like `(A||B||C) AND !D` are also permitted.
  * If you want to apply a scope to an aspect extending an abstract base aspect, you need to list and scope both aspects
    in the XML file.
--

`-crossrefs`::
  Generate a build .ajsym file into the output directory. Used for
  viewing crosscutting references by tools like the AspectJ Browser.
`-emacssym`::
  Generate .ajesym symbol files for emacs support (deprecated).
`-Xlint`::
  Same as -Xlint:warning (enabled by default)
`-Xlint:\{level}`::
  Set default level for messages about potential programming mistakes in
  crosscutting code. `\{level}` may be `ignore`, `warning`, or `error`. This
  overrides entries in _org/aspectj/weaver/XlintDefault.properties_ from
  aspectjtools.jar, but does not override levels set using the
  `-Xlintfile` option.
`-Xlintfile <PropertyFile>`::
  Specify properties file to set levels for specific crosscutting
  messages. PropertyFile is a path to a Java .properties file that takes
  the same property names and values as
  _org/aspectj/weaver/XlintDefault.properties_ from aspectjtools.jar,
  which it also overrides.
`-help`::
  Emit information on compiler options and usage
`-version`::
  Emit the version of the AspectJ compiler
`-classpath <Path>`::
  Specify where to find user class files. Path is a single argument
  containing a list of paths to zip files or directories, delimited by
  the platform-specific path delimiter.
`-bootclasspath <Path>`::
  Override location of VM's bootclasspath for purposes of evaluating
  types when compiling. Path is a single argument containing a list of
  paths to zip files or directories, delimited by the platform-specific
  path delimiter.
`-extdirs <Path>`::
  Override location of VM's extension directories for purposes of
  evaluating types when compiling. Path is a single argument containing
  a list of paths to directories, delimited by the platform-specific
  path delimiter.
`-d <Directory>`::
  Specify where to place generated .class files. If not specified,
  <Directory> defaults to the current working dir.

// AspectJ_JDK_Update: increment max. version and, if necessary, min. version
`-source <[1.3 to 22]>`::
  Set source file Java language level
`-target <[1.3 to 22]>`::
  Set classfile Java bytecode level
`-<[1.3 to 22]>`::
  Set compiler compliance level. Implies identical `-source` and `-target` levels.
  E.g., `-11` implies `-source 11` and `-target 11`.

`-nowarn`::
  Emit no warnings (equivalent to `-warn:none`) This does not suppress
  messages generated by `declare warning` or `Xlint`.
`-warn: <items>`::
  Emit warnings for any instances of the comma-delimited list of
  questionable code (e.g. `-warn:unusedLocals,deprecation`):
+
[source, text]
....
constructorName        method with constructor name
packageDefaultMethod   attempt to override package-default method
deprecation            usage of deprecated type or member
maskedCatchBlocks      hidden catch block
unusedLocals           local variable never read
unusedArguments        method argument never read
unusedImports          import statement not used by code in file
none                   suppress all compiler warnings
....
+
`-warn:none` does not suppress messages generated by `declare warning`
  or `Xlint`.
`-deprecation`::
  Same as `-warn:deprecation`
`-noImportError`::
  Emit no errors for unresolved imports
`-proceedOnError`::
  Keep compiling after error, dumping class files with problem methods
`-g<:[lines,vars,source]>`::
  debug attributes level, that may take three forms:
+
[source, text]
....
-g         all debug info ('-g:lines,vars,source')
-g:none    no debug info
-g:{items} debug info for any/all of [lines, vars, source], e.g.,
           -g:lines,source
....
`-preserveAllLocals`::
  Preserve all local variables during code generation (to facilitate
  debugging).
`-referenceInfo`::
  Compute reference information.
`-encoding <format>`::
  Specify default source encoding format. Specify custom encoding on a
  per-file basis by suffixing each input source file/folder name with
  '[encoding]'.
`-verbose`::
  Emit messages about accessed/processed compilation units
`-showWeaveInfo`::
  Emit messages about weaving
`-log <file>`::
  Specify a log file for compiler messages.
`-progress`::
  Show progress (requires -log mode).
`-time`::
  Display speed information.
`-noExit`::
  Do not call `System.exit(n)` at end of compilation (n=0 if no error)
`-repeat <N>`::
  Repeat compilation process N times (typically to do performance
  analysis).
`-XterminateAfterCompilation`::
  Causes compiler to terminate before weaving
`-XaddSerialVersionUID`::
  Causes the compiler to calculate and add the SerialVersionUID field to
  any type implementing Serializable that is affected by an aspect. The
  field is calculated based on the class before weaving has taken place.
`-Xreweavable[:compress]`::
  (Experimental - deprecated as now default) Runs weaver in reweavable
  mode which causes it to create woven classes that can be rewoven,
  subject to the restriction that on attempting a reweave all the types
  that advised the woven type must be accessible.
`-XnoInline`::
  (Experimental) do not inline around advice
`-XincrementalFile <file>`::
  (Experimental) This works like incremental mode, but using a file
  rather than standard input to control the compiler. It will recompile
  each time file is changed and and halt when file is deleted.
`-XserializableAspects`::
  (Experimental) Normally it is an error to declare aspects
  Serializable. This option removes that restriction.
`-XnotReweavable`::
  (Experimental) Create class files that can't be subsequently rewoven
  by AspectJ.
`-Xajruntimelevel:1.2, ajruntimelevel:1.5`::
  (Experimental) Allows code to be generated that targets a 1.2 or a 1.5
  level AspectJ runtime (default 1.5)

=== File names

ajc accepts source files with either the `.java` extension or the `.aj`
extension. We normally use `.java` for all of our files in an AspectJ
system -- files that contain aspects as well as files that contain
classes. However, if you have a need to mechanically distinguish files
that use AspectJ's additional functionality from those that are pure
Java we recommend using the `.aj` extension for those files.

We'd like to discourage other means of mechanical distinction such as
naming conventions or sub-packages in favor of the `.aj` extension.

* Filename conventions are hard to enforce and lead to awkward names for
your aspects. Instead of `TracingAspect.java` we recommend using
`Tracing.aj` (or just `Tracing.java`) instead.
* Sub-packages move aspects out of their natural place in a system and
can create an artificial need for privileged aspects. Instead of adding
a sub-package like `aspects` we recommend using the `.aj` extension and
including these files in your existing packages instead.

=== Compatibility

AspectJ is a compatible extension to the Java programming language. The
AspectJ compiler adheres to the
https://java.sun.com/docs/books/jls/index.html[The Java Language
Specification, Second Edition] and to the
https://java.sun.com/docs/books/vmspec/index.html[The Java Virtual
Machine Specification, Second Edition] and runs on any Java 2 compatible
platform. The code it generates runs on any Java 1.1 or later compatible
platform. For more information on compatibility with Java and with
previous releases of AspectJ, see xref:compatibility.adoc#versionCompatibility[Version Compatibility].

=== Examples

Compile two files:

[source, text]
....
ajc HelloWorld.java Trace.java
....

To avoid specifying file names on the command line, list source files in
a line-delimited text argfile. Source file paths may be absolute or
relative to the argfile, and may include other argfiles by @-reference.
The following file `sources.lst` contains absolute and relative files
and @-references:

[source, text]
....
Gui.java
/home/user/src/Library.java
data/Repository.java
data/Access.java
@../../common/common.lst
@/home/user/src/lib.lst
view/body/ArrayView.java
....

Compile the files using either the -argfile or @ form:

[source, text]
....
ajc -argfile sources.lst
ajc @sources.lst
....

Argfiles are also supported by jikes and javac, so you can use the files
in hybrid builds. However, the support varies:

* Only ajc accepts command-line options
* Jikes and Javac do not accept internal @argfile references.
* Jikes and Javac only accept the @file form on the command line.

Bytecode weaving using -inpath: AspectJ 1.2 supports weaving .class
files in input zip/jar files and directories. Using input jars is like
compiling the corresponding source files, and all binaries are emitted
to output. Although Java-compliant compilers may differ in their output,
ajc should take as input any class files produced by javac, jikes,
eclipse, and, of course, ajc. Aspects included in -inpath will be woven
into like other .class files, and they will affect other types as usual.

Aspect libraries using -aspectpath: AspectJ 1.1 supports weaving from
read-only libraries containing aspects. Like input jars, they affect all
input; unlike input jars, they themselves are not affected or emitted as
output. Sources compiled with aspect libraries must be run with the same
aspect libraries on their classpath.

The following example builds the tracing example in a command-line
environment; it creates a read-only aspect library, compiles some
classes for use as input bytecode, and compiles the classes and other
sources with the aspect library.

The tracing example is in the AspectJ distribution
(\{aspectj}/doc/examples/tracing). This uses the following files:

[source, text]
....
aspectj1.1/
  bin/
    ajc
  lib/
    aspectjrt.jar
  examples/
    tracing/
      Circle.java
      ExampleMain.java
      lib/
        AbstractTrace.java
        TraceMyClasses.java
      notrace.lst
      Square.java
      tracelib.lst
      tracev3.lst
      TwoDShape.java
      version3/
        Trace.java
        TraceMyClasses.java
....

Below, the path separator is taken as ";", but file separators are "/".
All commands are on one line. Adjust paths and commands to your
environment as needed.

Setup the path, classpath, and current directory:

[source, text]
....
cd examples
export ajrt=../lib/aspectjrt.jar
export CLASSPATH="$ajrt"
export PATH="../bin:$PATH"
....

Build a read-only tracing library:

[source, text]
....
ajc -argfile tracing/tracelib.lst -outjar tracelib.jar
....

Build the application with tracing in one step:

[source, text]
....
ajc -aspectpath tracelib.jar -argfile tracing/notrace.lst -outjar tracedapp.jar
....

Run the application with tracing:

[source, text]
....
java -classpath "$ajrt;tracedapp.jar;tracelib.jar" tracing.ExampleMain
....

Build the application with tracing from binaries in two steps:

* (a) Build the application classes (using javac for
demonstration's sake):
+
[source, text]
....
mkdir classes
javac -d classes tracing/*.java
jar cfM app.jar -C classes .
....
* (b) Build the application with tracing:
+
[source, text]
....
ajc -inpath app.jar -aspectpath tracelib.jar -outjar tracedapp.jar
....

Run the application with tracing (same as above):

[source, text]
....
java -classpath "$ajrt;tracedapp.jar;tracelib.jar" tracing.ExampleMain
....

Run the application without tracing:

[source, text]
....
java -classpath "app.jar" tracing.ExampleMain
....

=== The AspectJ compiler API

The AspectJ compiler is implemented completely in Java and can be called
as a Java class. The only interface that should be considered public are
the public methods in `org.aspectj.tools.ajc.Main`. E.g.,
`main(String[] args)` takes the the standard `ajc` command line
arguments. This means that an alternative way to run the compiler is

[subs=+quotes]
 java org.aspectj.tools.ajc.Main [_option_...] [_file_...]

To access compiler messages programmatically, use the methods
`setHolder(IMessageHolder holder)` and/or
`run(String[] args, IMessageHolder holder)`. `ajc` reports each message
to the holder using `IMessageHolder.handleMessage(..)`. If you just want
to collect the messages, use `MessageHandler` as your `IMessageHolder`.
For example, compile and run the following with `aspectjtools.jar` on
the classpath:

[source, java]
....
import org.aspectj.bridge.*;
import org.aspectj.tools.ajc.Main;
import java.util.Arrays;

public class WrapAjc {
  public static void main(String[] args) {
    Main compiler = new Main();
    MessageHandler m = new MessageHandler();
    compiler.run(args, m);
    IMessage[] ms = m.getMessages(null, true);
    System.out.println("messages: " + Arrays.asList(ms));
  }
}
....

=== Stack Traces and the SourceFile attribute

Unlike traditional java compilers, the AspectJ compiler may in certain
cases generate classfiles from multiple source files. Unfortunately, the
original Java class file format does not support multiple SourceFile
attributes. In order to make sure all source file information is
available, the AspectJ compiler may in some cases encode multiple
filenames in the SourceFile attribute. When the Java VM generates stack
traces, it uses this attribute to specify the source file.

(The AspectJ 1.0 compiler also supports the .class file extensions of
JSR-45. These permit compliant debuggers (such as jdb in Java 1.4.1) to
identify the right file and line even given many source files for a
single class. JSR-45 support is planned for ajc in AspectJ 1.1, but is
not in the initial release. To get fully debuggable .class files, use
the -XnoInline option.)

Probably the only time you may see this format is when you view stack
traces, where you may encounter traces of the format

[source, text]
....
java.lang.NullPointerException
  at Main.new$constructor_call37(Main.java;SynchAspect.java[1k]:1030)
....

where instead of the usual

[source, text]
....
File:LineNumber
....

format, you see

[source, text]
....
File0;File1[Number1];File2[Number2] ... :LineNumber
....

In this case, LineNumber is the usual offset in lines plus the "start
line" of the actual source file. That means you use LineNumber both to
identify the source file and to find the line at issue. The number in
[brackets] after each file tells you the virtual "start line" for that
file (the first file has a start of 0).

In our example from the null pointer exception trace, the virtual start
line is 1030. Since the file SynchAspect.java "starts" at line 1000
[1k], the LineNumber points to line 30 of SynchAspect.java.

So, when faced with such stack traces, the way to find the actual source
location is to look through the list of "start line" numbers to find the
one just under the shown line number. That is the file where the source
location can actually be found. Then, subtract that "start line" from
the shown line number to find the actual line number within that file.

In a class file that comes from only a single source file, the AspectJ
compiler generates SourceFile attributes consistent with traditional
Java compilers.