You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

examples.adoc 60KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918
  1. [[examples]]
  2. = Examples
  3. [[examples-intro]]
  4. == Introduction
  5. This chapter consists entirely of examples of AspectJ use.
  6. The examples can be grouped into four categories:
  7. technique::
  8. Examples which illustrate how to use one or more features of the language
  9. development::
  10. Examples of using AspectJ during the development phase of a project
  11. production::
  12. Examples of using AspectJ to provide functionality in an application
  13. reusable::
  14. Examples of reuse of aspects and pointcuts
  15. [[examples-howto]]
  16. == Obtaining, Compiling and Running the Examples
  17. The examples source code is part of the AspectJ distribution which may
  18. be downloaded from the https://eclipse.org/aspectj[AspectJ project page].
  19. Compiling most examples is straightforward. Go the `InstallDir/examples`
  20. directory, and look for a `.lst` file in one of the example
  21. subdirectories. Use the `-arglist` option to `ajc` to compile the
  22. example. For instance, to compile the telecom example with billing, type
  23. [source, text]
  24. ....
  25. ajc -argfile telecom/billing.lst
  26. ....
  27. To run the examples, your classpath must include the AspectJ run-time
  28. Java archive (`aspectjrt.jar`). You may either set the `CLASSPATH`
  29. environment variable or use the `-classpath` command line option to the
  30. Java interpreter:
  31. [source, text]
  32. ....
  33. (In Unix use a : in the CLASSPATH)
  34. java -classpath ".:InstallDir/lib/aspectjrt.jar" telecom.billingSimulation
  35. ....
  36. [source, text]
  37. ....
  38. (In Windows use a ; in the CLASSPATH)
  39. java -classpath ".;InstallDir/lib/aspectjrt.jar" telecom.billingSimulation
  40. ....
  41. [[examples-basic]]
  42. == Basic Techniques
  43. This section presents two basic techniques of using AspectJ, one each
  44. from the two fundamental ways of capturing crosscutting concerns: with
  45. dynamic join points and advice, and with static introduction. Advice
  46. changes an application's behavior. Introduction changes both an
  47. application's behavior and its structure.
  48. The first example, xref:#examples-joinPoints[Join Points and `thisJoinPoint`], is about
  49. gathering and using information about the join point that has triggered
  50. some advice. The second example, xref:#examples-roles[Roles and Views],
  51. concerns a crosscutting view of an existing class hierarchy.
  52. [[examples-joinPoints]]
  53. === Join Points and `thisJoinPoint`
  54. (The code for this example is in `InstallDir/examples/tjp`.)
  55. A join point is some point in the execution of a program together with a
  56. view into the execution context when that point occurs. Join points are
  57. picked out by pointcuts. When a program reaches a join point, advice on
  58. that join point may run in addition to (or instead of) the join point
  59. itself.
  60. When using a pointcut that picks out join points of a single kind by
  61. name, typicaly the the advice will know exactly what kind of join point
  62. it is associated with. The pointcut may even publish context about the
  63. join point. Here, for example, since the only join points picked out by
  64. the pointcut are calls of a certain method, we can get the target value
  65. and one of the argument values of the method calls directly.
  66. [source, java]
  67. ....
  68. before(Point p, int x):
  69. target(p) &&
  70. args(x) &&
  71. call(void setX(int))
  72. {
  73. if (!p.assertX(x))
  74. System.out.println("Illegal value for x"); return;
  75. }
  76. ....
  77. But sometimes the shape of the join point is not so clear. For instance,
  78. suppose a complex application is being debugged, and we want to trace
  79. when any method of some class is executed. The pointcut
  80. [source, java]
  81. ....
  82. pointcut execsInProblemClass():
  83. within(ProblemClass) &&
  84. execution(* *(..));
  85. ....
  86. will pick out each execution join point of every method defined within
  87. `ProblemClass`. Since advice executes at each join point picked out by
  88. the pointcut, we can reasonably ask which join point was reached.
  89. Information about the join point that was matched is available to advice
  90. through the special variable `thisJoinPoint`, of type
  91. xref:../api/org/aspectj/lang/JoinPoint.html[`org.aspectj.lang.JoinPoint`].
  92. Through this object we can access information such as
  93. * the kind of join point that was matched
  94. * the source location of the code associated with the join point
  95. * normal, short and long string representations of the current join
  96. point
  97. * the actual argument values of the join point
  98. * the signature of the member associated with the join point
  99. * the currently executing object
  100. * the target object
  101. * an object encapsulating the static information about the join point.
  102. This is also available through the special variable `thisJoinPointStaticPart`.
  103. ==== The `Demo` class
  104. The class `tjp.Demo` in `tjp/Demo.java` defines two methods `foo` and
  105. `bar` with different parameter lists and return types. Both are called,
  106. with suitable arguments, by ``Demo``'s `go` method which was invoked from
  107. within its `main` method.
  108. [source, java]
  109. ....
  110. public class Demo {
  111. static Demo d;
  112. public static void main(String[] args) {
  113. new Demo().go();
  114. }
  115. void go() {
  116. d = new Demo();
  117. d.foo(1,d);
  118. System.out.println(d.bar(new Integer(3)));
  119. }
  120. void foo(int i, Object o) {
  121. System.out.println("Demo.foo(" + i + ", " + o + ")\n");
  122. }
  123. String bar (Integer j) {
  124. System.out.println("Demo.bar(" + j + ")\n");
  125. return "Demo.bar(" + j + ")";
  126. }
  127. }
  128. ....
  129. ==== The `GetInfo` aspect
  130. This aspect uses around advice to intercept the execution of methods
  131. `foo` and `bar` in `Demo`, and prints out information garnered from
  132. `thisJoinPoint` to the console.
  133. [source, java]
  134. ....
  135. aspect GetInfo {
  136. static final void println(String s){ System.out.println(s); }
  137. pointcut goCut(): cflow(this(Demo) && execution(void go()));
  138. pointcut demoExecs(): within(Demo) && execution(* *(..));
  139. Object around(): demoExecs() && !execution(* go()) && goCut() {
  140. println("Intercepted message: " +
  141. thisJoinPointStaticPart.getSignature().getName());
  142. println("in class: " +
  143. thisJoinPointStaticPart.getSignature().getDeclaringType().getName());
  144. printParameters(thisJoinPoint);
  145. println("Running original method: \n" );
  146. Object result = proceed();
  147. println(" result: " + result );
  148. return result;
  149. }
  150. static private void printParameters(JoinPoint jp) {
  151. println("Arguments: " );
  152. Object[] args = jp.getArgs();
  153. String[] names = ((CodeSignature)jp.getSignature()).getParameterNames();
  154. Class[] types = ((CodeSignature)jp.getSignature()).getParameterTypes();
  155. for (int i = 0; i < args.length; i++) {
  156. println(
  157. " " + i + ". " + names[i] +
  158. " : " + types[i].getName() +
  159. " = " + args[i]);
  160. }
  161. }
  162. }
  163. ....
  164. ===== Defining the scope of a pointcut
  165. The pointcut `goCut` is defined as
  166. [source, java]
  167. ....
  168. cflow(this(Demo)) && execution(void go())
  169. ....
  170. so that only executions made in the control flow of `Demo.go` are
  171. intercepted. The control flow from the method `go` includes the
  172. execution of `go` itself, so the definition of the around advice
  173. includes `!execution(* go())` to exclude it from the set of executions
  174. advised.
  175. ===== Printing the class and method name
  176. The name of the method and that method's defining class are available as
  177. parts of the
  178. xref:../api/org/aspectj/lang/Signature.html[`org.aspectj.lang.Signature`]
  179. object returned by calling `getSignature()` on either `thisJoinPoint` or
  180. `thisJoinPointStaticPart`.
  181. ===== Printing the parameters
  182. The static portions of the parameter details, the name and types of the
  183. parameters, can be accessed through the
  184. xref:../api/org/aspectj/lang/reflect/CodeSignature.html[`org.aspectj.lang.reflect.CodeSignature`]
  185. associated with the join point. All execution join points have code
  186. signatures, so the cast to `CodeSignature` cannot fail.
  187. The dynamic portions of the parameter details, the actual values of the
  188. parameters, are accessed directly from the execution join point object.
  189. [[examples-roles]]
  190. === Roles and Views
  191. (The code for this example is in `InstallDir/examples/introduction`.)
  192. Like advice, inter-type declarations are members of an aspect. They
  193. declare members that act as if they were defined on another class.
  194. Unlike advice, inter-type declarations affect not only the behavior of
  195. the application, but also the structural relationship between an
  196. application's classes.
  197. This is crucial: Publically affecting the class structure of an
  198. application makes these modifications available to other components of
  199. the application.
  200. Aspects can declare inter-type
  201. * fields
  202. * methods
  203. * constructors
  204. and can also declare that target types
  205. * implement new interfaces
  206. * extend new classes
  207. This example provides three illustrations of the use of inter-type
  208. declarations to encapsulate roles or views of a class. The class our
  209. aspect will be dealing with, `Point`, is a simple class with rectangular
  210. and polar coordinates. Our inter-type declarations will make the class
  211. `Point`, in turn, cloneable, hashable, and comparable. These facilities
  212. are provided by AspectJ without having to modify the code for the class
  213. `Point`.
  214. ==== The `Point` class
  215. The `Point` class defines geometric points whose interface includes
  216. polar and rectangular coordinates, plus some simple operations to
  217. relocate points. ``Point``'s implementation has attributes for both its
  218. polar and rectangular coordinates, plus flags to indicate which
  219. currently reflect the position of the point. Some operations cause the
  220. polar coordinates to be updated from the rectangular, and some have the
  221. opposite effect. This implementation, which is in intended to give the
  222. minimum number of conversions between coordinate systems, has the
  223. property that not all the attributes stored in a `Point` object are
  224. necessary to give a canonical representation such as might be used for
  225. storing, comparing, cloning or making hash codes from points. Thus the
  226. aspects, though simple, are not totally trivial.
  227. The diagram below gives an overview of the aspects and their interaction
  228. with the class `Point`.
  229. image:images/aspects.png[image]
  230. ==== The `CloneablePoint` aspect
  231. This first aspect is responsible for ``Point``'s implementation of the
  232. `Cloneable` interface. It declares that `Point implements Cloneable`
  233. with a `declare parents` form, and also publically declares a
  234. specialized ``Point``'s `clone()` method. In Java, all objects inherit the
  235. method `clone` from the class `Object`, but an object is not cloneable
  236. unless its class also implements the interface `Cloneable`. In addition,
  237. classes frequently have requirements over and above the simple
  238. bit-for-bit copying that `Object.clone` does. In our case, we want to
  239. update a ``Point``'s coordinate systems before we actually clone the
  240. `Point`. So our aspect makes sure that `Point` overrides `Object.clone`
  241. with a new method that does what we want.
  242. We also define a test `main` method in the aspect for convenience.
  243. [source, java]
  244. ....
  245. public aspect CloneablePoint {
  246. declare parents: Point implements Cloneable;
  247. public Object Point.clone() throws CloneNotSupportedException {
  248. // we choose to bring all fields up to date before cloning.
  249. makeRectangular();
  250. makePolar();
  251. return super.clone();
  252. }
  253. public static void main(String[] args) {
  254. Point p1 = new Point();
  255. Point p2 = null;
  256. p1.setPolar(Math.PI, 1.0);
  257. try {
  258. p2 = (Point)p1.clone();
  259. } catch (CloneNotSupportedException e) {}
  260. System.out.println("p1 =" + p1);
  261. System.out.println("p2 =" + p2);
  262. p1.rotate(Math.PI / -2);
  263. System.out.println("p1 =" + p1);
  264. System.out.println("p2 =" + p2);
  265. }
  266. }
  267. ....
  268. ==== The `ComparablePoint` aspect
  269. `ComparablePoint` is responsible for ``Point``'s implementation of the
  270. `Comparable` interface.
  271. The interface `Comparable` defines the single method `compareTo` which
  272. can be use to define a natural ordering relation among the objects of a
  273. class that implement it.
  274. `ComparablePoint` uses `declare parents` to declare that `Point implements Comparable`,
  275. and also publically declares the appropriate `compareTo(Object)` method:
  276. A `Point` `p1` is said to be less than another `Point p2` if `p1` is closer to the origin.
  277. We also define a test `main` method in the aspect for convenience.
  278. [source, java]
  279. ....
  280. public aspect ComparablePoint {
  281. declare parents: Point implements Comparable;
  282. public int Point.compareTo(Object o) {
  283. return (int) (this.getRho() - ((Point)o).getRho());
  284. }
  285. public static void main(String[] args) {
  286. Point p1 = new Point();
  287. Point p2 = new Point();
  288. System.out.println("p1 =?= p2 :" + p1.compareTo(p2));
  289. p1.setRectangular(2,5);
  290. p2.setRectangular(2,5);
  291. System.out.println("p1 =?= p2 :" + p1.compareTo(p2));
  292. p2.setRectangular(3,6);
  293. System.out.println("p1 =?= p2 :" + p1.compareTo(p2));
  294. p1.setPolar(Math.PI, 4);
  295. p2.setPolar(Math.PI, 4);
  296. System.out.println("p1 =?= p2 :" + p1.compareTo(p2));
  297. p1.rotate(Math.PI / 4.0);
  298. System.out.println("p1 =?= p2 :" + p1.compareTo(p2));
  299. p1.offset(1,1);
  300. System.out.println("p1 =?= p2 :" + p1.compareTo(p2));
  301. }
  302. }
  303. ....
  304. ==== The `HashablePoint` aspect
  305. Our third aspect is responsible for ``Point``'s overriding of ``Object``'s
  306. `equals` and `hashCode` methods in order to make ``Point``s hashable.
  307. The method `Object.hashCode` returns an integer, suitable for use as a
  308. hash table key. It is not required that two objects which are not equal
  309. (according to the `equals` method) return different integer results from
  310. `hashCode` but it can improve performance when the integer is used as a
  311. key into a data structure. However, any two objects which are equal must
  312. return the same integer value from a call to `hashCode`. Since the
  313. default implementation of `Object.equals` returns `true` only when two
  314. objects are identical, we need to redefine both `equals` and `hashCode`
  315. to work correctly with objects of type `Point`. For example, we want two
  316. `Point` objects to test equal when they have the same `x` and `y`
  317. values, or the same `rho` and `theta` values, not just when they refer
  318. to the same object. We do this by overriding the methods `equals` and
  319. `hashCode` in the class `Point`.
  320. So `HashablePoint` declares ``Point``'s `hashCode` and `equals` methods,
  321. using ``Point``'s rectangular coordinates to generate a hash code and to
  322. test for equality. The `x` and `y` coordinates are obtained using the
  323. appropriate get methods, which ensure the rectangular coordinates are
  324. up-to-date before returning their values.
  325. And again, we supply a `main` method in the aspect for testing.
  326. [source, java]
  327. ....
  328. public aspect HashablePoint {
  329. public int Point.hashCode() {
  330. return (int) (getX() + getY() % Integer.MAX_VALUE);
  331. }
  332. public boolean Point.equals(Object o) {
  333. if (o == this) return true;
  334. if (!(o instanceof Point)) return false;
  335. Point other = (Point)o;
  336. return (getX() == other.getX()) && (getY() == other.getY());
  337. }
  338. public static void main(String[] args) {
  339. Hashtable h = new Hashtable();
  340. Point p1 = new Point();
  341. p1.setRectangular(10, 10);
  342. Point p2 = new Point();
  343. p2.setRectangular(10, 10);
  344. System.out.println("p1 = " + p1);
  345. System.out.println("p2 = " + p2);
  346. System.out.println("p1.hashCode() = " + p1.hashCode());
  347. System.out.println("p2.hashCode() = " + p2.hashCode());
  348. h.put(p1, "P1");
  349. System.out.println("Got: " + h.get(p2));
  350. }
  351. }
  352. ....
  353. [[examples-development]]
  354. == Development Aspects
  355. === Tracing using aspects
  356. (The code for this example is in `InstallDir/examples/tracing`.)
  357. Writing a class that provides tracing functionality is easy: a couple of
  358. functions, a boolean flag for turning tracing on and off, a choice for
  359. an output stream, maybe some code for formatting the output -- these are
  360. all elements that `Trace` classes have been known to have. `Trace`
  361. classes may be highly sophisticated, too, if the task of tracing the
  362. execution of a program demands it.
  363. But developing the support for tracing is just one part of the effort of
  364. inserting tracing into a program, and, most likely, not the biggest
  365. part. The other part of the effort is calling the tracing functions at
  366. appropriate times. In large systems, this interaction with the tracing
  367. support can be overwhelming. Plus, tracing is one of those things that
  368. slows the system down, so these calls should often be pulled out of the
  369. system before the product is shipped. For these reasons, it is not
  370. unusual for developers to write ad-hoc scripting programs that rewrite
  371. the source code by inserting/deleting trace calls before and after the
  372. method bodies.
  373. AspectJ can be used for some of these tracing concerns in a less ad-hoc
  374. way. Tracing can be seen as a concern that crosscuts the entire system
  375. and as such is amenable to encapsulation in an aspect. In addition, it
  376. is fairly independent of what the system is doing. Therefore tracing is
  377. one of those kind of system aspects that can potentially be plugged in
  378. and unplugged without any side-effects in the basic functionality of the
  379. system.
  380. ==== An Example Application
  381. Throughout this example we will use a simple application that contains
  382. only four classes. The application is about shapes. The `TwoDShape`
  383. class is the root of the shape hierarchy:
  384. [source, java]
  385. ....
  386. public abstract class TwoDShape {
  387. protected double x, y;
  388. protected TwoDShape(double x, double y) {
  389. this.x = x; this.y = y;
  390. }
  391. public double getX() { return x; }
  392. public double getY() { return y; }
  393. public double distance(TwoDShape s) {
  394. double dx = Math.abs(s.getX() - x);
  395. double dy = Math.abs(s.getY() - y);
  396. return Math.sqrt(dx*dx + dy*dy);
  397. }
  398. public abstract double perimeter();
  399. public abstract double area();
  400. public String toString() {
  401. return (" @ (" + String.valueOf(x) + ", " + String.valueOf(y) + ") ");
  402. }
  403. }
  404. ....
  405. `TwoDShape` has two subclasses, `Circle` and `Square`:
  406. [source, java]
  407. ....
  408. public class Circle extends TwoDShape {
  409. protected double r;
  410. public Circle(double x, double y, double r) {
  411. super(x, y); this.r = r;
  412. }
  413. public Circle(double x, double y) { this( x, y, 1.0); }
  414. public Circle(double r) { this(0.0, 0.0, r); }
  415. public Circle() { this(0.0, 0.0, 1.0); }
  416. public double perimeter() {
  417. return 2 * Math.PI * r;
  418. }
  419. public double area() {
  420. return Math.PI * r*r;
  421. }
  422. public String toString() {
  423. return ("Circle radius = " + String.valueOf(r) + super.toString());
  424. }
  425. }
  426. ....
  427. [source, java]
  428. ....
  429. public class Square extends TwoDShape {
  430. protected double s; // side
  431. public Square(double x, double y, double s) {
  432. super(x, y); this.s = s;
  433. }
  434. public Square(double x, double y) { this( x, y, 1.0); }
  435. public Square(double s) { this(0.0, 0.0, s); }
  436. public Square() { this(0.0, 0.0, 1.0); }
  437. public double perimeter() {
  438. return 4 * s;
  439. }
  440. public double area() {
  441. return s*s;
  442. }
  443. public String toString() {
  444. return ("Square side = " + String.valueOf(s) + super.toString());
  445. }
  446. }
  447. ....
  448. To run this application, compile the classes. You can do it with or
  449. without ajc, the AspectJ compiler. If you've installed AspectJ, go to
  450. the directory `InstallDir/examples` and type:
  451. [source, text]
  452. ....
  453. ajc -argfile tracing/notrace.lst
  454. ....
  455. To run the program, type
  456. [source, text]
  457. ....
  458. java tracing.ExampleMain
  459. ....
  460. (we don't need anything special on the classpath since this is pure Java
  461. code). You should see the following output:
  462. [source, text]
  463. ....
  464. c1.perimeter() = 12.566370614359172
  465. c1.area() = 12.566370614359172
  466. s1.perimeter() = 4.0
  467. s1.area() = 1.0
  468. c2.distance(c1) = 4.242640687119285
  469. s1.distance(c1) = 2.23606797749979
  470. s1.toString(): Square side = 1.0 @ (1.0, 2.0)
  471. ....
  472. ==== Tracing - Version 1
  473. In a first attempt to insert tracing in this application, we will start
  474. by writing a `Trace` class that is exactly what we would write if we
  475. didn't have aspects. The implementation is in `version1/Trace.java`. Its
  476. public interface is:
  477. [source, java]
  478. ....
  479. public class Trace {
  480. public static int TRACELEVEL = 0;
  481. public static void initStream(PrintStream s) {...}
  482. public static void traceEntry(String str) {...}
  483. public static void traceExit(String str) {...}
  484. }
  485. ....
  486. If we didn't have AspectJ, we would have to insert calls to `traceEntry`
  487. and `traceExit` in all methods and constructors we wanted to trace, and
  488. to initialize `TRACELEVEL` and the stream. If we wanted to trace all the
  489. methods and constructors in our example, that would amount to around 40
  490. calls, and we would hope we had not forgotten any method. But we can do
  491. that more consistently and reliably with the following aspect (found in
  492. `version1/TraceMyClasses.java`):
  493. [source, java]
  494. ....
  495. public aspect TraceMyClasses {
  496. pointcut myClass(): within(TwoDShape) || within(Circle) || within(Square);
  497. pointcut myConstructor(): myClass() && execution(new(..));
  498. pointcut myMethod(): myClass() && execution(* *(..));
  499. before (): myConstructor() {
  500. Trace.traceEntry("" + thisJoinPointStaticPart.getSignature());
  501. }
  502. after(): myConstructor() {
  503. Trace.traceExit("" + thisJoinPointStaticPart.getSignature());
  504. }
  505. before (): myMethod() {
  506. Trace.traceEntry("" + thisJoinPointStaticPart.getSignature());
  507. }
  508. after(): myMethod() {
  509. Trace.traceExit("" + thisJoinPointStaticPart.getSignature());
  510. }
  511. }
  512. ....
  513. This aspect performs the tracing calls at appropriate times. According
  514. to this aspect, tracing is performed at the entrance and exit of every
  515. method and constructor defined within the shape hierarchy.
  516. What is printed at before and after each of the traced join points is
  517. the signature of the method executing. Since the signature is static
  518. information, we can get it through `thisJoinPointStaticPart`.
  519. To run this version of tracing, go to the directory
  520. `InstallDir/examples` and type:
  521. [source, text]
  522. ....
  523. ajc -argfile tracing/tracev1.lst
  524. ....
  525. Running the main method of `tracing.version1.TraceMyClasses` should
  526. produce the output:
  527. [source, text]
  528. ....
  529. --> tracing.TwoDShape(double, double)
  530. <-- tracing.TwoDShape(double, double)
  531. --> tracing.Circle(double, double, double)
  532. <-- tracing.Circle(double, double, double)
  533. --> tracing.TwoDShape(double, double)
  534. <-- tracing.TwoDShape(double, double)
  535. --> tracing.Circle(double, double, double)
  536. <-- tracing.Circle(double, double, double)
  537. --> tracing.Circle(double)
  538. <-- tracing.Circle(double)
  539. --> tracing.TwoDShape(double, double)
  540. <-- tracing.TwoDShape(double, double)
  541. --> tracing.Square(double, double, double)
  542. <-- tracing.Square(double, double, double)
  543. --> tracing.Square(double, double)
  544. <-- tracing.Square(double, double)
  545. --> double tracing.Circle.perimeter()
  546. <-- double tracing.Circle.perimeter()
  547. c1.perimeter() = 12.566370614359172
  548. --> double tracing.Circle.area()
  549. <-- double tracing.Circle.area()
  550. c1.area() = 12.566370614359172
  551. --> double tracing.Square.perimeter()
  552. <-- double tracing.Square.perimeter()
  553. s1.perimeter() = 4.0
  554. --> double tracing.Square.area()
  555. <-- double tracing.Square.area()
  556. s1.area() = 1.0
  557. --> double tracing.TwoDShape.distance(TwoDShape)
  558. --> double tracing.TwoDShape.getX()
  559. <-- double tracing.TwoDShape.getX()
  560. --> double tracing.TwoDShape.getY()
  561. <-- double tracing.TwoDShape.getY()
  562. <-- double tracing.TwoDShape.distance(TwoDShape)
  563. c2.distance(c1) = 4.242640687119285
  564. --> double tracing.TwoDShape.distance(TwoDShape)
  565. --> double tracing.TwoDShape.getX()
  566. <-- double tracing.TwoDShape.getX()
  567. --> double tracing.TwoDShape.getY()
  568. <-- double tracing.TwoDShape.getY()
  569. <-- double tracing.TwoDShape.distance(TwoDShape)
  570. s1.distance(c1) = 2.23606797749979
  571. --> String tracing.Square.toString()
  572. --> String tracing.TwoDShape.toString()
  573. <-- String tracing.TwoDShape.toString()
  574. <-- String tracing.Square.toString()
  575. s1.toString(): Square side = 1.0 @ (1.0, 2.0)
  576. ....
  577. When `TraceMyClasses.java` is not provided to `ajc`, the aspect does not
  578. have any affect on the system and the tracing is unplugged.
  579. ==== Tracing - Version 2
  580. Another way to accomplish the same thing would be to write a reusable
  581. tracing aspect that can be used not only for these application classes,
  582. but for any class. One way to do this is to merge the tracing
  583. functionality of `Trace - version1` with the crosscutting support of
  584. `TraceMyClasses - version1`. We end up with a `Trace` aspect (found in
  585. `version2/Trace.java`) with the following public interface
  586. [source, java]
  587. ....
  588. abstract aspect Trace {
  589. public static int TRACELEVEL = 2;
  590. public static void initStream(PrintStream s) {...}
  591. protected static void traceEntry(String str) {...}
  592. protected static void traceExit(String str) {...}
  593. abstract pointcut myClass();
  594. }
  595. ....
  596. In order to use it, we need to define our own subclass that knows about
  597. our application classes, in `version2/TraceMyClasses.java`:
  598. [source, java]
  599. ....
  600. public aspect TraceMyClasses extends Trace {
  601. pointcut myClass(): within(TwoDShape) || within(Circle) || within(Square);
  602. public static void main(String[] args) {
  603. Trace.TRACELEVEL = 2;
  604. Trace.initStream(System.err);
  605. ExampleMain.main(args);
  606. }
  607. }
  608. ....
  609. Notice that we've simply made the pointcut `classes`, that was an
  610. abstract pointcut in the super-aspect, concrete. To run this version of
  611. tracing, go to the directory `examples` and type:
  612. [source, text]
  613. ....
  614. ajc -argfile tracing/tracev2.lst
  615. ....
  616. The file `tracev2.lst` lists the application classes as well as this
  617. version of the files Trace.java and TraceMyClasses.java. Running the
  618. main method of `tracing.version2.TraceMyClasses` should output exactly
  619. the same trace information as that from version 1.
  620. The entire implementation of the new `Trace` class is:
  621. [source, java]
  622. ....
  623. abstract aspect Trace {
  624. // implementation part
  625. public static int TRACELEVEL = 2;
  626. protected static PrintStream stream = System.err;
  627. protected static int callDepth = 0;
  628. public static void initStream(PrintStream s) {
  629. stream = s;
  630. }
  631. protected static void traceEntry(String str) {
  632. if (TRACELEVEL == 0) return;
  633. if (TRACELEVEL == 2) callDepth++;
  634. printEntering(str);
  635. }
  636. protected static void traceExit(String str) {
  637. if (TRACELEVEL == 0) return;
  638. printExiting(str);
  639. if (TRACELEVEL == 2) callDepth--;
  640. }
  641. private static void printEntering(String str) {
  642. printIndent();
  643. stream.println("--> " + str);
  644. }
  645. private static void printExiting(String str) {
  646. printIndent();
  647. stream.println("<-- " + str);
  648. }
  649. private static void printIndent() {
  650. for (int i = 0; i < callDepth; i++)
  651. stream.print(" ");
  652. }
  653. // protocol part
  654. abstract pointcut myClass();
  655. pointcut myConstructor(): myClass() && execution(new(..));
  656. pointcut myMethod(): myClass() && execution(* *(..));
  657. before(): myConstructor() {
  658. traceEntry("" + thisJoinPointStaticPart.getSignature());
  659. }
  660. after(): myConstructor() {
  661. traceExit("" + thisJoinPointStaticPart.getSignature());
  662. }
  663. before(): myMethod() {
  664. traceEntry("" + thisJoinPointStaticPart.getSignature());
  665. }
  666. after(): myMethod() {
  667. traceExit("" + thisJoinPointStaticPart.getSignature());
  668. }
  669. }
  670. ....
  671. This version differs from version 1 in several subtle ways. The first
  672. thing to notice is that this `Trace` class merges the functional part of
  673. tracing with the crosscutting of the tracing calls. That is, in version
  674. 1, there was a sharp separation between the tracing support (the class
  675. `Trace`) and the crosscutting usage of it (by the class
  676. `TraceMyClasses`). In this version those two things are merged. That's
  677. why the description of this class explicitly says that "Trace messages
  678. are printed before and after constructors and methods are," which is
  679. what we wanted in the first place. That is, the placement of the calls,
  680. in this version, is established by the aspect class itself, leaving less
  681. opportunity for misplacing calls.
  682. A consequence of this is that there is no need for providing
  683. `traceEntry` and `traceExit` as public operations of this class. You can
  684. see that they were classified as protected. They are supposed to be
  685. internal implementation details of the advice.
  686. The key piece of this aspect is the abstract pointcut classes that
  687. serves as the base for the definition of the pointcuts constructors and
  688. methods. Even though `classes` is abstract, and therefore no concrete
  689. classes are mentioned, we can put advice on it, as well as on the
  690. pointcuts that are based on it. The idea is "we don't know exactly what
  691. the pointcut will be, but when we do, here's what we want to do with
  692. it." In some ways, abstract pointcuts are similar to abstract methods.
  693. Abstract methods don't provide the implementation, but you know that the
  694. concrete subclasses will, so you can invoke those methods.
  695. [[examples-production]]
  696. == Production Aspects
  697. === A Bean Aspect
  698. (The code for this example is in `InstallDir/examples/bean`.)
  699. This example examines an aspect that makes Point objects into Java beans
  700. with bound properties.
  701. Java beans are reusable software components that can be visually
  702. manipulated in a builder tool. The requirements for an object to be a
  703. bean are few. Beans must define a no-argument constructor and must be
  704. either `Serializable` or `Externalizable`. Any properties of the object
  705. that are to be treated as bean properties should be indicated by the
  706. presence of appropriate `get` and `set` methods whose names are
  707. `get__property__` and `set__property__` where `__property__` is the name of
  708. a field in the bean class. Some bean properties, known as bound
  709. properties, fire events whenever their values change so that any
  710. registered listeners (such as, other beans) will be informed of those
  711. changes. Making a bound property involves keeping a list of registered
  712. listeners, and creating and dispatching event objects in methods that
  713. change the property values, such as `set__property__` methods.
  714. `Point` is a simple class representing points with rectangular
  715. coordinates. `Point` does not know anything about being a bean: there
  716. are set methods for `x` and `y` but they do not fire events, and the
  717. class is not serializable. Bound is an aspect that makes `Point` a
  718. serializable class and makes its `get` and `set` methods support the
  719. bound property protocol.
  720. ==== The `Point` class
  721. The `Point` class is a very simple class with trivial getters and
  722. setters, and a simple vector offset method.
  723. [source, java]
  724. ....
  725. class Point {
  726. protected int x = 0;
  727. protected int y = 0;
  728. public int getX() {
  729. return x;
  730. }
  731. public int getY() {
  732. return y;
  733. }
  734. public void setRectangular(int newX, int newY) {
  735. setX(newX);
  736. setY(newY);
  737. }
  738. public void setX(int newX) {
  739. x = newX;
  740. }
  741. public void setY(int newY) {
  742. y = newY;
  743. }
  744. public void offset(int deltaX, int deltaY) {
  745. setRectangular(x + deltaX, y + deltaY);
  746. }
  747. public String toString() {
  748. return "(" + getX() + ", " + getY() + ")" ;
  749. }
  750. }
  751. ....
  752. ==== The `BoundPoint` aspect
  753. The `BoundPoint` aspect is responsible for ``Point``'s "beanness". The
  754. first thing it does is privately declare that each `Point` has a
  755. `support` field that holds reference to an instance of
  756. `PropertyChangeSupport`.
  757. [source, java]
  758. ....
  759. private PropertyChangeSupport Point.support = new PropertyChangeSupport(this);
  760. ....
  761. The property change support object must be constructed with a reference
  762. to the bean for which it is providing support, so it is initialized by
  763. passing it `this`, an instance of `Point`. Since the `support` field is
  764. private declared in the aspect, only the code in the aspect can refer to
  765. it.
  766. The aspect also declares ``Point``'s methods for registering and managing
  767. listeners for property change events, which delegate the work to the
  768. property change support object:
  769. [source, java]
  770. ....
  771. public void Point.addPropertyChangeListener(PropertyChangeListener listener){
  772. support.addPropertyChangeListener(listener);
  773. }
  774. public void Point.addPropertyChangeListener(String propertyName, PropertyChangeListener listener) {
  775. support.addPropertyChangeListener(propertyName, listener);
  776. }
  777. public void Point.removePropertyChangeListener(String propertyName, PropertyChangeListener listener) {
  778. support.removePropertyChangeListener(propertyName, listener);
  779. }
  780. public void Point.removePropertyChangeListener(PropertyChangeListener listener) {
  781. support.removePropertyChangeListener(listener);
  782. }
  783. public void Point.hasListeners(String propertyName) {
  784. support.hasListeners(propertyName);
  785. }
  786. ....
  787. The aspect is also responsible for making sure `Point` implements the
  788. `Serializable` interface:
  789. [source, java]
  790. ....
  791. declare parents: Point implements Serializable;
  792. ....
  793. Implementing this interface in Java does not require any methods to be
  794. implemented. Serialization for `Point` objects is provided by the
  795. default serialization method.
  796. The `setters` pointcut picks out calls to the ``Point``'s `set` methods:
  797. any method whose name begins with "`set`" and takes one parameter. The
  798. around advice on `setters()` stores the values of the `X` and `Y`
  799. properties, calls the original `set` method and then fires the
  800. appropriate property change event according to which set method was
  801. called.
  802. [source, java]
  803. ....
  804. aspect BoundPoint {
  805. private PropertyChangeSupport Point.support = new PropertyChangeSupport(this);
  806. public void Point.addPropertyChangeListener(PropertyChangeListener listener) {
  807. support.addPropertyChangeListener(listener);
  808. }
  809. public void Point.addPropertyChangeListener(String propertyName, PropertyChangeListener listener) {
  810. support.addPropertyChangeListener(propertyName, listener);
  811. }
  812. public void Point.removePropertyChangeListener(String propertyName, PropertyChangeListener listener) {
  813. support.removePropertyChangeListener(propertyName, listener);
  814. }
  815. public void Point.removePropertyChangeListener(PropertyChangeListener listener) {
  816. support.removePropertyChangeListener(listener);
  817. }
  818. public void Point.hasListeners(String propertyName) {
  819. support.hasListeners(propertyName);
  820. }
  821. declare parents: Point implements Serializable;
  822. pointcut setter(Point p): call(void Point.set*(*)) && target(p);
  823. void around(Point p): setter(p) {
  824. String propertyName =
  825. thisJoinPointStaticPart.getSignature().getName().substring("set".length());
  826. int oldX = p.getX();
  827. int oldY = p.getY();
  828. proceed(p);
  829. if (propertyName.equals("X")){
  830. firePropertyChange(p, propertyName, oldX, p.getX());
  831. } else {
  832. firePropertyChange(p, propertyName, oldY, p.getY());
  833. }
  834. }
  835. void firePropertyChange(Point p, String property, double oldval, double newval) {
  836. p.support.firePropertyChange(property, new Double(oldval), new Double(newval));
  837. }
  838. }
  839. ....
  840. ==== The Test Program
  841. The test program registers itself as a property change listener to a
  842. `Point` object that it creates and then performs simple manipulation of
  843. that point: calling its set methods and the offset method. Then it
  844. serializes the point and writes it to a file and then reads it back. The
  845. result of saving and restoring the point is that a new point is created.
  846. [source, java]
  847. ....
  848. class Demo implements PropertyChangeListener {
  849. static final String fileName = "test.tmp";
  850. public void propertyChange(PropertyChangeEvent e){
  851. System.out.println(
  852. "Property " + e.getPropertyName() + " changed from " +
  853. e.getOldValue() + " to " + e.getNewValue()
  854. );
  855. }
  856. public static void main(String[] args) {
  857. Point p1 = new Point();
  858. p1.addPropertyChangeListener(new Demo());
  859. System.out.println("p1 =" + p1);
  860. p1.setRectangular(5,2);
  861. System.out.println("p1 =" + p1);
  862. p1.setX( 6 );
  863. p1.setY( 3 );
  864. System.out.println("p1 =" + p1);
  865. p1.offset(6,4);
  866. System.out.println("p1 =" + p1);
  867. save(p1, fileName);
  868. Point p2 = (Point) restore(fileName);
  869. System.out.println("Had: " + p1);
  870. System.out.println("Got: " + p2);
  871. }
  872. // ...
  873. }
  874. ....
  875. ==== Compiling and Running the Example
  876. To compile and run this example, go to the examples directory and type:
  877. [source, text]
  878. ....
  879. ajc -argfile bean/files.lst
  880. java bean.Demo
  881. ....
  882. [[the-subject-observer-protocol]]
  883. === The Subject/Observer Protocol
  884. (The code for this example is in `InstallDir/examples/observer`.)
  885. This demo illustrates how the Subject/Observer design pattern can be
  886. coded with aspects.
  887. The demo consists of the following: A colored label is a renderable
  888. object that has a color that cycles through a set of colors, and a
  889. number that records the number of cycles it has been through. A button
  890. is an action item that records when it is clicked.
  891. With these two kinds of objects, we can build up a Subject/Observer
  892. relationship in which colored labels observe the clicks of buttons; that
  893. is, where colored labels are the observers and buttons are the subjects.
  894. The demo is designed and implemented using the Subject/Observer design
  895. pattern. The remainder of this example explains the classes and aspects
  896. of this demo, and tells you how to run it.
  897. ==== Generic Components
  898. The generic parts of the protocol are the interfaces `Subject` and
  899. `Observer`, and the abstract aspect `SubjectObserverProtocol`. The
  900. `Subject` interface is simple, containing methods to add, remove, and
  901. view `Observer` objects, and a method for getting data about state
  902. changes:
  903. [source, java]
  904. ....
  905. interface Subject {
  906. void addObserver(Observer obs);
  907. void removeObserver(Observer obs);
  908. Vector getObservers();
  909. Object getData();
  910. }
  911. ....
  912. The `Observer` interface is just as simple, with methods to set and get
  913. `Subject` objects, and a method to call when the subject gets updated.
  914. [source, java]
  915. ....
  916. interface Observer {
  917. void setSubject(Subject s);
  918. Subject getSubject();
  919. void update();
  920. }
  921. ....
  922. The `SubjectObserverProtocol` aspect contains within it all of the
  923. generic parts of the protocol, namely, how to fire the `Observer`
  924. objects' update methods when some state changes in a subject.
  925. [source, java]
  926. ....
  927. abstract aspect SubjectObserverProtocol {
  928. abstract pointcut stateChanges(Subject s);
  929. after(Subject s): stateChanges(s) {
  930. for (int i = 0; i < s.getObservers().size(); i++) {
  931. ((Observer)s.getObservers().elementAt(i)).update();
  932. }
  933. }
  934. private Vector Subject.observers = new Vector();
  935. public void Subject.addObserver(Observer obs) {
  936. observers.addElement(obs);
  937. obs.setSubject(this);
  938. }
  939. public void Subject.removeObserver(Observer obs) {
  940. observers.removeElement(obs);
  941. obs.setSubject(null);
  942. }
  943. public Vector Subject.getObservers() { return observers; }
  944. private Subject Observer.subject = null;
  945. public void Observer.setSubject(Subject s) { subject = s; }
  946. public Subject Observer.getSubject() { return subject; }
  947. }
  948. ....
  949. Note that this aspect does three things. It define an abstract pointcut
  950. that extending aspects can override. It defines advice that should run
  951. after the join points of the pointcut. And it declares an inter-type
  952. field and two inter-type methods so that each `Observer` can hold onto
  953. its `Subject`.
  954. ==== Application Classes
  955. `Button` objects extend `java.awt.Button`, and all they do is make sure
  956. the `void click()` method is called whenever a button is clicked.
  957. [source, java]
  958. ....
  959. class Button extends java.awt.Button {
  960. static final Color defaultBackgroundColor = Color.gray;
  961. static final Color defaultForegroundColor = Color.black;
  962. static final String defaultText = "cycle color";
  963. Button(Display display) {
  964. super();
  965. setLabel(defaultText);
  966. setBackground(defaultBackgroundColor);
  967. setForeground(defaultForegroundColor);
  968. addActionListener(new ActionListener() {
  969. public void actionPerformed(ActionEvent e) {
  970. Button.this.click();
  971. }
  972. });
  973. display.addToFrame(this);
  974. }
  975. public void click() {}
  976. }
  977. ....
  978. Note that this class knows nothing about being a Subject.
  979. ColorLabel objects are labels that support the void colorCycle() method.
  980. Again, they know nothing about being an observer.
  981. [source, java]
  982. ....
  983. class ColorLabel extends Label {
  984. ColorLabel(Display display) {
  985. super();
  986. display.addToFrame(this);
  987. }
  988. final static Color[] colors =
  989. { Color.red, Color.blue, Color.green, Color.magenta };
  990. private int colorIndex = 0;
  991. private int cycleCount = 0;
  992. void colorCycle() {
  993. cycleCount++;
  994. colorIndex = (colorIndex + 1) % colors.length;
  995. setBackground(colors[colorIndex]);
  996. setText("" + cycleCount);
  997. }
  998. }
  999. ....
  1000. Finally, the `SubjectObserverProtocolImpl` implements the
  1001. subject/observer protocol, with `Button` objects as subjects and
  1002. `ColorLabel` objects as observers:
  1003. [source, java]
  1004. ....
  1005. package observer;
  1006. import java.util.Vector;
  1007. aspect SubjectObserverProtocolImpl extends SubjectObserverProtocol {
  1008. declare parents: Button implements Subject;
  1009. public Object Button.getData() { return this; }
  1010. declare parents: ColorLabel implements Observer;
  1011. public void ColorLabel.update() {
  1012. colorCycle();
  1013. }
  1014. pointcut stateChanges(Subject s):
  1015. target(s) &&
  1016. call(void Button.click());
  1017. }
  1018. ....
  1019. It does this by assuring that `Button` and `ColorLabel` implement the
  1020. appropriate interfaces, declaring that they implement the methods
  1021. required by those interfaces, and providing a definition for the
  1022. abstract `stateChanges` pointcut. Now, every time a `Button` is clicked,
  1023. all `ColorLabel` objects observing that button will `colorCycle`.
  1024. ==== Compiling and Running
  1025. `Demo` is the top class that starts this demo. It instantiates a two
  1026. buttons and three observers and links them together as subjects and
  1027. observers. So to run the demo, go to the `examples` directory and type:
  1028. [source, text]
  1029. ....
  1030. ajc -argfile observer/files.lst
  1031. java observer.Demo
  1032. ....
  1033. === A Simple Telecom Simulation
  1034. (The code for this example is in `InstallDir/examples/telecom`.)
  1035. This example illustrates some ways that dependent concerns can be
  1036. encoded with aspects. It uses an example system comprising a simple
  1037. model of telephone connections to which timing and billing features are
  1038. added using aspects, where the billing feature depends upon the timing
  1039. feature.
  1040. ==== The Application
  1041. The example application is a simple simulation of a telephony system in
  1042. which customers make, accept, merge and hang-up both local and long
  1043. distance calls. The application architecture is in three layers.
  1044. * The basic objects provide basic functionality to simulate customers,
  1045. calls and connections (regular calls have one connection, conference
  1046. calls have more than one).
  1047. * The timing feature is concerned with timing the connections and
  1048. keeping the total connection time per customer. Aspects are used to add
  1049. a timer to each connection and to manage the total time per customer.
  1050. * The billing feature is concerned with charging customers for the calls
  1051. they make. Aspects are used to calculate a charge per connection and,
  1052. upon termination of a connection, to add the charge to the appropriate
  1053. customer's bill. The billing aspect builds upon the timing aspect: it
  1054. uses a pointcut defined in Timing and it uses the timers that are
  1055. associated with connections.
  1056. The simulation of system has three configurations: basic, timing and
  1057. billing. Programs for the three configurations are in classes
  1058. `BasicSimulation`, `TimingSimulation` and `BillingSimulation`. These
  1059. share a common superclass `AbstractSimulation`, which defines the method
  1060. run with the simulation itself and the method wait used to simulate
  1061. elapsed time.
  1062. ==== The Basic Objects
  1063. The telecom simulation comprises the classes `Customer`, `Call` and the
  1064. abstract class `Connection` with its two concrete subclasses `Local` and
  1065. `LongDistance`. Customers have a name and a numeric area code. They also
  1066. have methods for managing calls. Simple calls are made between one
  1067. customer (the caller) and another (the receiver), a `Connection` object
  1068. is used to connect them. Conference calls between more than two
  1069. customers will involve more than one connection. A customer may be
  1070. involved in many calls at one time.
  1071. image:images/telecom.png[image]
  1072. ==== The `Customer` class
  1073. `Customer` has methods `call`, `pickup`, `hangup` and `merge` for
  1074. managing calls.
  1075. [source, java]
  1076. ....
  1077. public class Customer {
  1078. private String name;
  1079. private int areacode;
  1080. private Vector calls = new Vector();
  1081. protected void removeCall(Call c){
  1082. calls.removeElement(c);
  1083. }
  1084. protected void addCall(Call c){
  1085. calls.addElement(c);
  1086. }
  1087. public Customer(String name, int areacode) {
  1088. this.name = name;
  1089. this.areacode = areacode;
  1090. }
  1091. public String toString() {
  1092. return name + "(" + areacode + ")";
  1093. }
  1094. public int getAreacode(){
  1095. return areacode;
  1096. }
  1097. public boolean localTo(Customer other){
  1098. return areacode == other.areacode;
  1099. }
  1100. public Call call(Customer receiver) {
  1101. Call call = new Call(this, receiver);
  1102. addCall(call);
  1103. return call;
  1104. }
  1105. public void pickup(Call call) {
  1106. call.pickup();
  1107. addCall(call);
  1108. }
  1109. public void hangup(Call call) {
  1110. call.hangup(this);
  1111. removeCall(call);
  1112. }
  1113. public void merge(Call call1, Call call2){
  1114. call1.merge(call2);
  1115. removeCall(call2);
  1116. }
  1117. }
  1118. ....
  1119. ==== The `Call` class
  1120. Calls are created with a caller and receiver who are customers. If the
  1121. caller and receiver have the same area code then the call can be
  1122. established with a `Local` connection (see below), otherwise a
  1123. `LongDistance` connection is required. A call comprises a number of
  1124. connections between customers. Initially there is only the connection
  1125. between the caller and receiver but additional connections can be added
  1126. if calls are merged to form conference calls.
  1127. ==== The `Connection` class
  1128. The class `Connection` models the physical details of establishing a
  1129. connection between customers. It does this with a simple state machine
  1130. (connections are initially `PENDING`, then `COMPLETED` and finally
  1131. `DROPPED`). Messages are printed to the console so that the state of
  1132. connections can be observed. Connection is an abstract class with two
  1133. concrete subclasses: `Local` and `LongDistance`.
  1134. [source, java]
  1135. ....
  1136. abstract class Connection {
  1137. public static final int PENDING = 0;
  1138. public static final int COMPLETE = 1;
  1139. public static final int DROPPED = 2;
  1140. Customer caller, receiver;
  1141. private int state = PENDING;
  1142. Connection(Customer a, Customer b) {
  1143. this.caller = a;
  1144. this.receiver = b;
  1145. }
  1146. public int getState(){
  1147. return state;
  1148. }
  1149. public Customer getCaller() { return caller; }
  1150. public Customer getReceiver() { return receiver; }
  1151. void complete() {
  1152. state = COMPLETE;
  1153. System.out.println("connection completed");
  1154. }
  1155. void drop() {
  1156. state = DROPPED;
  1157. System.out.println("connection dropped");
  1158. }
  1159. public boolean connects(Customer c){
  1160. return (caller == c || receiver == c);
  1161. }
  1162. }
  1163. ....
  1164. ==== The `Local` and `LongDistance` classes
  1165. The two kinds of connections supported by our simulation are `Local` and
  1166. `LongDistance` connections.
  1167. [source, java]
  1168. ....
  1169. class Local extends Connection {
  1170. Local(Customer a, Customer b) {
  1171. super(a, b);
  1172. System.out.println(
  1173. "[new local connection from " + a + " to " + b + "]"
  1174. );
  1175. }
  1176. }
  1177. ....
  1178. [source, java]
  1179. ....
  1180. class LongDistance extends Connection {
  1181. LongDistance(Customer a, Customer b) {
  1182. super(a, b);
  1183. System.out.println(
  1184. "[new long distance connection from " + a + " to " + b + "]"
  1185. );
  1186. }
  1187. }
  1188. ....
  1189. ==== Compiling and Running the Basic Simulation
  1190. The source files for the basic system are listed in the file
  1191. `basic.lst`. To build and run the basic system, in a shell window, type
  1192. these commands:
  1193. [source, text]
  1194. ....
  1195. ajc -argfile telecom/basic.lst
  1196. java telecom.BasicSimulation
  1197. ....
  1198. ==== The Timing aspect
  1199. The `Timing` aspect keeps track of total connection time for each
  1200. `Customer` by starting and stopping a timer associated with each
  1201. connection. It uses some helper classes:
  1202. ===== The `Timer` class
  1203. A `Timer` object simply records the current time when it is started and
  1204. stopped, and returns their difference when asked for the elapsed time.
  1205. The aspect `TimerLog` (below) can be used to cause the start and stop
  1206. times to be printed to standard output.
  1207. [source, java]
  1208. ....
  1209. class Timer {
  1210. long startTime, stopTime;
  1211. public void start() {
  1212. startTime = System.currentTimeMillis();
  1213. stopTime = startTime;
  1214. }
  1215. public void stop() {
  1216. stopTime = System.currentTimeMillis();
  1217. }
  1218. public long getTime() {
  1219. return stopTime - startTime;
  1220. }
  1221. }
  1222. ....
  1223. ==== The `TimerLog` aspect
  1224. The `TimerLog` aspect can be included in a build to get the timer to
  1225. announce when it is started and stopped.
  1226. [source, java]
  1227. ....
  1228. public aspect TimerLog {
  1229. after(Timer t): target(t) && call(* Timer.start()) {
  1230. System.err.println("Timer started: " + t.startTime);
  1231. }
  1232. after(Timer t): target(t) && call(* Timer.stop()) {
  1233. System.err.println("Timer stopped: " + t.stopTime);
  1234. }
  1235. }
  1236. ....
  1237. ==== The `Timing` aspect
  1238. The `Timing` aspect is declares an inter-type field `totalConnectTime`
  1239. for `Customer` to store the accumulated connection time per `Customer`.
  1240. It also declares that each `Connection` object has a timer.
  1241. [source, java]
  1242. ....
  1243. public long Customer.totalConnectTime = 0;
  1244. private Timer Connection.timer = new Timer();
  1245. ....
  1246. Two pieces of after advice ensure that the timer is started when a
  1247. connection is completed and and stopped when it is dropped. The pointcut
  1248. `endTiming` is defined so that it can be used by the `Billing` aspect.
  1249. [source, java]
  1250. ....
  1251. public aspect Timing {
  1252. public long Customer.totalConnectTime = 0;
  1253. public long getTotalConnectTime(Customer cust) {
  1254. return cust.totalConnectTime;
  1255. }
  1256. private Timer Connection.timer = new Timer();
  1257. public Timer getTimer(Connection conn) { return conn.timer; }
  1258. after (Connection c): target(c) && call(void Connection.complete()) {
  1259. getTimer(c).start();
  1260. }
  1261. pointcut endTiming(Connection c): target(c) &&
  1262. call(void Connection.drop());
  1263. after(Connection c): endTiming(c) {
  1264. getTimer(c).stop();
  1265. c.getCaller().totalConnectTime += getTimer(c).getTime();
  1266. c.getReceiver().totalConnectTime += getTimer(c).getTime();
  1267. }
  1268. }
  1269. ....
  1270. ==== The `Billing` aspect
  1271. The Billing system adds billing functionality to the telecom application
  1272. on top of timing.
  1273. The `Billing` aspect declares that each `Connection` has a `payer`
  1274. inter-type field to indicate who initiated the call and therefore who is
  1275. responsible to pay for it. It also declares the inter-type method
  1276. `callRate` of `Connection` so that local and long distance calls can be
  1277. charged differently. The call charge must be calculated after the timer
  1278. is stopped; the after advice on pointcut `Timing.endTiming` does this,
  1279. and `Billing` is declared to be more precedent than `Timing` to make
  1280. sure that this advice runs after ``Timing``'s advice on the same join
  1281. point. Finally, it declares inter-type methods and fields for `Customer`
  1282. to handle the `totalCharge`.
  1283. [source, java]
  1284. ....
  1285. public aspect Billing {
  1286. // precedence required to get advice on endtiming in the right order
  1287. declare precedence: Billing, Timing;
  1288. public static final long LOCAL_RATE = 3;
  1289. public static final long LONG_DISTANCE_RATE = 10;
  1290. public Customer Connection.payer;
  1291. public Customer getPayer(Connection conn) { return conn.payer; }
  1292. after(Customer cust) returning (Connection conn):
  1293. args(cust, ..) && call(Connection+.new(..)) {
  1294. conn.payer = cust;
  1295. }
  1296. public abstract long Connection.callRate();
  1297. public long LongDistance.callRate() { return LONG_DISTANCE_RATE; }
  1298. public long Local.callRate() { return LOCAL_RATE; }
  1299. after(Connection conn): Timing.endTiming(conn) {
  1300. long time = Timing.aspectOf().getTimer(conn).getTime();
  1301. long rate = conn.callRate();
  1302. long cost = rate * time;
  1303. getPayer(conn).addCharge(cost);
  1304. }
  1305. public long Customer.totalCharge = 0;
  1306. public long getTotalCharge(Customer cust) { return cust.totalCharge; }
  1307. public void Customer.addCharge(long charge) {
  1308. totalCharge += charge;
  1309. }
  1310. }
  1311. ....
  1312. ==== Accessing the inter-type state
  1313. Both the aspects `Timing` and `Billing` contain the definition of
  1314. operations that the rest of the system may want to access. For example,
  1315. when running the simulation with one or both aspects, we want to find
  1316. out how much time each customer spent on the telephone and how big their
  1317. bill is. That information is also stored in the classes, but they are
  1318. accessed through static methods of the aspects, since the state they
  1319. refer to is private to the aspect.
  1320. Take a look at the file `TimingSimulation.java`. The most important
  1321. method of this class is the method `report(Customer)`, which is used in
  1322. the method run of the superclass `AbstractSimulation`. This method is
  1323. intended to print out the status of the customer, with respect to the
  1324. `Timing` feature.
  1325. [source, java]
  1326. ....
  1327. protected void report(Customer c){
  1328. Timing t = Timing.aspectOf();
  1329. System.out.println(c + " spent " + t.getTotalConnectTime(c));
  1330. }
  1331. ....
  1332. ==== Compiling and Running
  1333. The files timing.lst and billing.lst contain file lists for the timing
  1334. and billing configurations. To build and run the application with only
  1335. the timing feature, go to the directory examples and type:
  1336. [source, text]
  1337. ....
  1338. ajc -argfile telecom/timing.lst
  1339. java telecom.TimingSimulation
  1340. ....
  1341. To build and run the application with the timing and billing features,
  1342. go to the directory examples and type:
  1343. [source, text]
  1344. ....
  1345. ajc -argfile telecom/billing.lst
  1346. java telecom.BillingSimulation
  1347. ....
  1348. ==== Discussion
  1349. There are some explicit dependencies between the aspects `Billing` and
  1350. `Timing`:
  1351. * `Billing` is declared more precedent than `Timing` so that ``Billing``'s after
  1352. advice runs after that of `Timing` when they are on the same join point.
  1353. * `Billing` uses the pointcut `Timing.endTiming`.
  1354. * `Billing` needs access to the timer associated with a connection.
  1355. [[examples-reusable]]
  1356. == Reusable Aspects
  1357. === Tracing using Aspects, Revisited
  1358. (The code for this example is in `InstallDir/examples/tracing`.)
  1359. ==== Tracing - Version 3
  1360. One advantage of not exposing the methods `traceEntry` and `traceExit` as
  1361. public operations is that we can easily change their interface without
  1362. any dramatic consequences in the rest of the code.
  1363. Consider, again, the program without AspectJ. Suppose, for example, that
  1364. at some point later the requirements for tracing change, stating that
  1365. the trace messages should always include the string representation of
  1366. the object whose methods are being traced. This can be achieved in at
  1367. least two ways. One way is keep the interface of the methods
  1368. `traceEntry` and `traceExit` as it was before,
  1369. [source, java]
  1370. ....
  1371. public static void traceEntry(String str);
  1372. public static void traceExit(String str);
  1373. ....
  1374. In this case, the caller is responsible for ensuring that the string
  1375. representation of the object is part of the string given as argument.
  1376. So, calls must look like:
  1377. [source, java]
  1378. ....
  1379. Trace.traceEntry("Square.distance in " + toString());
  1380. ....
  1381. Another way is to enforce the requirement with a second argument in the
  1382. trace operations, e.g.
  1383. [source, java]
  1384. ....
  1385. public static void traceEntry(String str, Object obj);
  1386. public static void traceExit(String str, Object obj);
  1387. ....
  1388. In this case, the caller is still responsible for sending the right
  1389. object, but at least there is some guarantees that some object will be
  1390. passed. The calls will look like:
  1391. [source, java]
  1392. ....
  1393. Trace.traceEntry("Square.distance", this);
  1394. ....
  1395. In either case, this change to the requirements of tracing will have
  1396. dramatic consequences in the rest of the code -- every call to the trace
  1397. operations `traceEntry` and `traceExit` must be changed!
  1398. Here's another advantage of doing tracing with an aspect. We've already
  1399. seen that in version 2 `traceEntry` and `traceExit` are not publicly
  1400. exposed. So changing their interfaces, or the way they are used, has
  1401. only a small effect inside the `Trace` class. Here's a partial view at
  1402. the implementation of `Trace`, version 3. The differences with respect
  1403. to version 2 are stressed in the comments:
  1404. [source, java]
  1405. ....
  1406. abstract aspect Trace {
  1407. public static int TRACELEVEL = 0;
  1408. protected static PrintStream stream = null;
  1409. protected static int callDepth = 0;
  1410. public static void initStream(PrintStream s) {
  1411. stream = s;
  1412. }
  1413. protected static void traceEntry(String str, Object o) {
  1414. if (TRACELEVEL == 0) return;
  1415. if (TRACELEVEL == 2) callDepth++;
  1416. printEntering(str + ": " + o.toString());
  1417. }
  1418. protected static void traceExit(String str, Object o) {
  1419. if (TRACELEVEL == 0) return;
  1420. printExiting(str + ": " + o.toString());
  1421. if (TRACELEVEL == 2) callDepth--;
  1422. }
  1423. private static void printEntering(String str) {
  1424. printIndent();
  1425. stream.println("Entering " + str);
  1426. }
  1427. private static void printExiting(String str) {
  1428. printIndent();
  1429. stream.println("Exiting " + str);
  1430. }
  1431. private static void printIndent() {
  1432. for (int i = 0; i < callDepth; i++)
  1433. stream.print(" ");
  1434. }
  1435. abstract pointcut myClass(Object obj);
  1436. pointcut myConstructor(Object obj): myClass(obj) && execution(new(..));
  1437. pointcut myMethod(Object obj):
  1438. myClass(obj) && execution(* *(..)) && !execution(String toString());
  1439. before(Object obj): myConstructor(obj) {
  1440. traceEntry("" + thisJoinPointStaticPart.getSignature(), obj);
  1441. }
  1442. after(Object obj): myConstructor(obj) {
  1443. traceExit("" + thisJoinPointStaticPart.getSignature(), obj);
  1444. }
  1445. before(Object obj): myMethod(obj) {
  1446. traceEntry("" + thisJoinPointStaticPart.getSignature(), obj);
  1447. }
  1448. after(Object obj): myMethod(obj) {
  1449. traceExit("" + thisJoinPointStaticPart.getSignature(), obj);
  1450. }
  1451. }
  1452. ....
  1453. As you can see, we decided to apply the first design by preserving the
  1454. interface of the methods `traceEntry` and `traceExit`. But it doesn't
  1455. matter - we could as easily have applied the second design (the code in
  1456. the directory `examples/tracing/version3` has the second design). The
  1457. point is that the effects of this change in the tracing requirements are
  1458. limited to the `Trace` aspect class.
  1459. One implementation change worth noticing is the specification of the
  1460. pointcuts. They now expose the object. To maintain full consistency with
  1461. the behavior of version 2, we should have included tracing for static
  1462. methods, by defining another pointcut for static methods and advising
  1463. it. We leave that as an exercise.
  1464. Moreover, we had to exclude the execution join point of the method
  1465. `toString` from the `methods` pointcut. The problem here is that
  1466. `toString` is being called from inside the advice. Therefore if we trace
  1467. it, we will end up in an infinite recursion of calls. This is a subtle
  1468. point, and one that you must be aware when writing advice. If the advice
  1469. calls back to the objects, there is always the possibility of recursion.
  1470. Keep that in mind!
  1471. In fact, esimply excluding the execution join point may not be enough,
  1472. if there are calls to other traced methods within it - in which case,
  1473. the restriction should be
  1474. [source, java]
  1475. ....
  1476. && !cflow(execution(String toString()))
  1477. ....
  1478. excluding both the execution of `toString` methods and all join points
  1479. under that execution.
  1480. In summary, to implement the change in the tracing requirements we had
  1481. to make a couple of changes in the implementation of the `Trace` aspect
  1482. class, including changing the specification of the pointcuts. That's
  1483. only natural. But the implementation changes were limited to this
  1484. aspect. Without aspects, we would have to change the implementation of
  1485. every application class.
  1486. Finally, to run this version of tracing, go to the directory `examples`
  1487. and type:
  1488. [source, text]
  1489. ....
  1490. ajc -argfile tracing/tracev3.lst
  1491. ....
  1492. The file `tracev3.lst` lists the application classes as well as this
  1493. version of the files `Trace.java` and `TraceMyClasses.java`. To run the
  1494. program, type
  1495. [source, text]
  1496. ....
  1497. java tracing.version3.TraceMyClasses
  1498. ....
  1499. The output should be:
  1500. [source, text]
  1501. ....
  1502. --> tracing.TwoDShape(double, double)
  1503. <-- tracing.TwoDShape(double, double)
  1504. --> tracing.Circle(double, double, double)
  1505. <-- tracing.Circle(double, double, double)
  1506. --> tracing.TwoDShape(double, double)
  1507. <-- tracing.TwoDShape(double, double)
  1508. --> tracing.Circle(double, double, double)
  1509. <-- tracing.Circle(double, double, double)
  1510. --> tracing.Circle(double)
  1511. <-- tracing.Circle(double)
  1512. --> tracing.TwoDShape(double, double)
  1513. <-- tracing.TwoDShape(double, double)
  1514. --> tracing.Square(double, double, double)
  1515. <-- tracing.Square(double, double, double)
  1516. --> tracing.Square(double, double)
  1517. <-- tracing.Square(double, double)
  1518. --> double tracing.Circle.perimeter()
  1519. <-- double tracing.Circle.perimeter()
  1520. c1.perimeter() = 12.566370614359172
  1521. --> double tracing.Circle.area()
  1522. <-- double tracing.Circle.area()
  1523. c1.area() = 12.566370614359172
  1524. --> double tracing.Square.perimeter()
  1525. <-- double tracing.Square.perimeter()
  1526. s1.perimeter() = 4.0
  1527. --> double tracing.Square.area()
  1528. <-- double tracing.Square.area()
  1529. s1.area() = 1.0
  1530. --> double tracing.TwoDShape.distance(TwoDShape)
  1531. --> double tracing.TwoDShape.getX()
  1532. <-- double tracing.TwoDShape.getX()
  1533. --> double tracing.TwoDShape.getY()
  1534. <-- double tracing.TwoDShape.getY()
  1535. <-- double tracing.TwoDShape.distance(TwoDShape)
  1536. c2.distance(c1) = 4.242640687119285
  1537. --> double tracing.TwoDShape.distance(TwoDShape)
  1538. --> double tracing.TwoDShape.getX()
  1539. <-- double tracing.TwoDShape.getX()
  1540. --> double tracing.TwoDShape.getY()
  1541. <-- double tracing.TwoDShape.getY()
  1542. <-- double tracing.TwoDShape.distance(TwoDShape)
  1543. s1.distance(c1) = 2.23606797749979
  1544. --> String tracing.Square.toString()
  1545. --> String tracing.TwoDShape.toString()
  1546. <-- String tracing.TwoDShape.toString()
  1547. <-- String tracing.Square.toString()
  1548. s1.toString(): Square side = 1.0 @ (1.0, 2.0)
  1549. ....