-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathsample-code.html
2139 lines (1926 loc) · 71.6 KB
/
sample-code.html
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
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
<html>
<title>AspectJ sample code</title>
<body>
<a name="top"></a>
<h2>AspectJ sample code</h2>This contains contributions from the AspectJ community of
<ul>
<li>sample code for AspectJ programs,</li>
<li>sample code for extensions to AspectJ tools using the public API's,</li>
<li>sample scripts for invoking AspectJ tools, and</li>
<li>documentation trails showing how to do given tasks using AspectJ, AJDT, or various IDE or deployment
environments.
</li>
</ul>
<p>
Find complete source files in the AspectJ CVS repository at
<code>org.aspectj/modules/docs/sandbox</code>.
For instructions on downloading code from the CVS repository,
see the <a href="doc/faq.html#q:buildingsource">FAQ entry "buildingsource"</a>.
</p>
<p><small>
Copyright 2003 Contributors. All Rights Reserved. This sample code is made available under the Eclipse Public License
version 1.0 available at <a href="https://www.eclipse.org/legal/epl-v10.html">https://www.eclipse.org/legal/epl-v10.html</a>. Contributors are
listed in this document as authors. Permission to republish portions of this sample code is hereby granted if the
publication acknowledges the author by name and the source by reference to the AspectJ project home page at
https://eclipse.org/aspectj.
</small></p>
<p><small>Generated on Apr 18, 2004 by SamplesGatherer</small>
<h2>Contents</h2>
<ul>
<li><a href="#api">api</a></li>
<ul>
<li><a href="#api-asm">api-asm</a></li>
<ul>
<li><a href="#api-asm-listAffectedFiles">Walk model to list affected files</a></li>
</ul>
</ul>
<li><a href="#caching">caching</a></li>
<ul>
<li><a href="#caching-dirty">caching-dirty</a></li>
<ul>
<li><a href="#caching-dirty-reflectiveSetters">Use getter/setter pattern to track dirtiness</a></li>
</ul>
</ul>
<li><a href="#declares">declares</a></li>
<ul>
<li><a href="#declares-exceptionSpelunking">Using declare warning to find Exception-related code</a></li>
<li><a href="#declares-inoculated">declares-inoculated</a></li>
<ul>
<li><a href="#declares-inoculated-nonSetterWrites">Warn when setting non-public field</a></li>
<li><a href="#declares-inoculated-prohibitNonprivateConstructors">Error to have accessible sub-Point
constructors</a></li>
<li><a href="#declares-inoculated-validExceptionHandlingMethod">Error when subclass method handles exception</a>
</li>
<li><a href="#declares-inoculated-validPointConstruction">Error when factory not used</a></li>
</ul>
<li><a href="#declares-softenRemoteException">declares-softenRemoteException</a></li>
<li><a href="#declares-threadFactoryRequired">Error when not using Thread factory</a></li>
<li><a href="#declares-typeConstraints">Using declare to enforce type constraints</a></li>
</ul>
<li><a href="#j2ee">j2ee</a></li>
<ul>
<li><a href="#j2ee-myeclipseide">j2ee-myeclipseide</a></li>
<ul>
<li><a href="#j2ee-myeclipseide-generally">Using MyEclipseIDE to develop AspectJ programs for J2EE</a></li>
</ul>
<li><a href="#j2ee-servlets">j2ee-servlets</a></li>
<ul>
<li><a href="#j2ee-servlets-generally">Using AspectJ in servlets</a></li>
</ul>
<li><a href="#j2ee-tomcat4">j2ee-tomcat4</a></li>
<ul>
<li><a href="#j2ee-tomcat4-jsp">Running AspectJ JSP's in Tomcat 4.x</a></li>
<li><a href="#j2ee-tomcat4-precompileJsp">Precompile JSP's for Tomcat 4.x using AspectJ</a></li>
<li><a href="#j2ee-tomcat4-servlets">Running AspectJ servlets in Tomcat 4.x</a></li>
</ul>
</ul>
<li><a href="#language">language</a></li>
<ul>
<li><a href="#language-cflowRecursionBasic">Pick out latest and original recursive call</a></li>
<li><a href="#language-doubleDispatch">Implementing double-dispatch</a></li>
<li><a href="#language-fieldSetContext">Check input and result for a field set.</a></li>
<li><a href="#language-handlerContext">Log exception being handled</a></li>
<li><a href="#language-initialization">Understanding object creation join points</a></li>
</ul>
<li><a href="#library">library</a></li>
<ul>
<li><a href="#library-classPointcutLibrary">Defining library pointcuts in a class</a></li>
<li><a href="#library-pointcutIdioms">Standard pointcut idioms</a></li>
</ul>
<li><a href="#pubs">pubs</a></li>
<ul>
<li><a href="#pubs-all">pubs-all</a></li>
<ul>
<li><a href="#pubs-all-links">List of AspectJ publications</a></li>
</ul>
<li><a href="#pubs-books">pubs-books</a></li>
<ul>
<li><a href="#pubs-books-aspectjinaction">AspectJ in Action</a></li>
</ul>
<li><a href="#pubs-papers">pubs-papers</a></li>
<ul>
<li><a href="#pubs-papers-aodesignpatterns">Aspect-Oriented Design Pattern Implementations</a></li>
</ul>
<li><a href="#pubs-projects">pubs-projects</a></li>
<ul>
<li><a href="#pubs-projects-atrack">ATrack bug tracker</a></li>
</ul>
</ul>
<li><a href="#scripts">scripts</a></li>
<ul>
<li><a href="#scripts-weaveLibraries">Shell script to use ajc to weave jars and then run</a></li>
</ul>
<li><a href="#testing">testing</a></li>
<ul>
<li><a href="#testing-inoculated">testing-inoculated</a></li>
<ul>
<li><a href="#testing-inoculated-adviseProxyCallsOnly">Advise calls to the proxy object only</a></li>
<li><a href="#testing-inoculated-failureCapture">Log failures</a></li>
<li><a href="#testing-inoculated-injectIOException">Inject IOException on test driver command</a></li>
<li><a href="#testing-inoculated-permitWritesDuringConstruction">Constructor execution</a></li>
<li><a href="#testing-inoculated-proceedVariants">Using around for integration testing</a></li>
<li><a href="#testing-inoculated-prohibitWritesByOthers">Prohibit field writes by other instances</a></li>
<li><a href="#testing-inoculated-prohibitWritesEvenByStaticOthers">Prohibit writes by other instances and static
methods</a></li>
<li><a href="#testing-inoculated-prohibitWritesEvenBySubclasses">Prohibit writes by subclasses</a></li>
<li><a href="#testing-inoculated-prohibitWritesExceptWhenConstructing">Prohibit field writes after
construction</a></li>
<li><a href="#testing-inoculated-replaceWithProxy">Replace object with proxy on constructiono</a></li>
<li><a href="#testing-inoculated-roundTrip">Round-trip integration testing</a></li>
<li><a href="#testing-inoculated-runtimeErrorWhenNullReturnedFromFactory">Throw Error when factory returns
null</a></li>
</ul>
</ul>
<li><a href="#tracing">tracing</a></li>
<ul>
<li><a href="#tracing-simpleTiming">Record time to execute public methods</a></li>
<li><a href="#tracing-traceJoinPoints">Trace join points executed to log</a></li>
</ul>
<li><a href="#trails">trails</a></li>
<ul>
<li><a href="#trails-debugging">trails-debugging</a></li>
<ul>
<li><a href="#trails-debugging-aspectj10">Debugging AspectJ 1.0 Programs</a></li>
<li><a href="#trails-debugging-aspectj11">Debugging AspectJ 1.1 Programs</a></li>
</ul>
</ul>
</ul>
<li><a href="#authorIndex">Author Index</a></li>
</ul> <h2>Listings</h2>
<a name="api"></a>
<h3>api</h3>
<a href="#top">back to top</a>
<a name="api-asm"></a>
<h3>api-asm</h3>
<a href="#top">back to top</a>
<a name="api-asm-listAffectedFiles"></a>
<h3>Walk model to list affected files</h3>
<a href="#top">back to top</a>
<p>| Wes Isberg
| api-clients org/aspectj/samples/AffectedFilesReporter.java:3 |
<p>
<pre>
package org.aspectj.samples;
import org.aspectj.tools.ajc.Main;
import org.aspectj.asm.*;
import org.aspectj.bridge.*;
import java.io.*;
import java.util.*;
/**
* Run ajc and list files affected by advice or inter-type declarations.
*
* WARNING: Does not emit info messages for uses-pointcut dependencies.
* @author Wes Isberg
*/
public class AffectedFilesReporter implements Runnable {
/*
* Walk down asm hierarchy, looking for source files,
* and check if any of their children has a relation of
* kind ADVICE or INTER_TYPE_DECLARATION
*/
/**
* Wrapper for ajc that emits list of affected files.
* @param args the String[] of args for ajc,
* optionally prefixed with -to {file}
* @throws IOException if unable to write to {file}
*/
public static void main(String[] args) throws IOException {
Main main = new Main();
PrintStream toConfig = System.out;
FileOutputStream fin = null;
if ((args.length > 1) && ("-to".equals(args[0]))) {
File config = new File(args[1]);
fin = new FileOutputStream(config);
toConfig = new PrintStream(fin, true);
String[] temp = new String[args.length-2];
System.arraycopy(args, 2, temp, 0, temp.length);
args = temp;
}
Runnable runner = new AffectedFilesReporter(toConfig);
main.setCompletionRunner(runner);
// should add -emacssym to args if not already there
main.runMain(args, false);
if (null != fin) {
fin.close();
}
}
final PrintStream sink;
public AffectedFilesReporter(PrintStream sink) {
this.sink = (null == sink ? System.out : sink);
}
public void run() {
IHierarchy hierarchy = AsmManager.getDefault().getHierarchy();
if (null == hierarchy) {
sink.println("# no structure model - use -emacssym option");
return;
}
List /*IProgramElement*/ nodes = new LinkedList();
List /*IProgramElement*/ newNodes = new LinkedList();
// root could be config file or blank root - either way, use kids
nodes.addAll(hierarchy.getRoot().getChildren());
while (0 < nodes.size()) {
for (ListIterator it = nodes.listIterator(); it.hasNext();) {
IProgramElement node = (IProgramElement) it.next();
if (node.getKind().isSourceFileKind()) {
if (isAffected(node)) {
ISourceLocation loc = node.getSourceLocation();
sink.println(loc.getSourceFile().getPath());
}
} else {
// XXX uncertain of structure - traverse all??
newNodes.addAll(node.getChildren());
}
it.remove();
}
nodes.addAll(newNodes);
newNodes.clear();
}
}
/**
* Return true if this file node is affected by any aspects.
* Recursively search children for any effect,
* and halt on first affect found.
* @param node the IProgramElementNode for a source file
* @return true if affected.
*/
private boolean isAffected(final IProgramElement fileNode) {
final IRelationshipMap map =
AsmManager.getDefault().getRelationshipMap();
List /*IProgramElement*/ nodes = new LinkedList();
List /*IProgramElement*/ newNodes = new LinkedList();
nodes.add(fileNode);
while (0 < nodes.size()) {
for (ListIterator iter = nodes.listIterator();
iter.hasNext();) {
IProgramElement node = (IProgramElement) iter.next();
List relations = map.get(node);
if (null != relations) {
for (Iterator riter = relations.iterator();
riter.hasNext();) {
IRelationship.Kind kind =
((IRelationship) riter.next()).getKind();
if ((kind == IRelationship.Kind.ADVICE)
|| (kind == IRelationship.Kind.DECLARE_INTER_TYPE)) {
return true;
}
}
}
iter.remove();
newNodes.addAll(node.getChildren());
}
nodes.addAll(newNodes);
newNodes.clear();
}
return false;
}
}
</pre>
<a name="caching"></a>
<h3>caching</h3>
<a href="#top">back to top</a>
<a name="caching-dirty"></a>
<h3>caching-dirty</h3>
<a href="#top">back to top</a>
<a name="caching-dirty-reflectiveSetters"></a>
<h3>Use getter/setter pattern to track dirtiness</h3>
<a href="#top">back to top</a>
<p>| Ricardo Giacomin, Wes Isberg
| common caching/WatchSetters.java:5 |
<p>
<pre>
package caching;
import java.lang.reflect.Method;
/**
* Watch setters to skip if new value is same as old
* or to set a dirty flag otherwise.
* Clients classes opt-in by implementing IWatched,
* and anyone can read the dirty and dirty-valid flags.
* <pre>
* class Foo implements WatchSetters.IWatched {
* ...
* }
* Foo foo = new Foo();
* ...
* if (!foo.isDirtyValid() || foo.isDirty()) {
* foo.write();
* }
* </pre>
*
* (Initial draft was sent to [email protected] by
* Ricardo on 5/13/2003
* (https://dev.eclipse.org/mhonarc/lists/aspectj-users/msg00482.html)
* but his email fails now, so we
* did not get explicit authorization to post.)
*
* @author Ricardo Giacomin, Wes Isberg
*/
public aspect WatchSetters {
// just to invoke test code below
public static void main(String[] args) {
Client.handleTimer(new Timer());
}
private static final Class[] GETTER_ARG_TYPES = new Class[]{};
private static final Object[] GETTER_ARGS = new Object[]{};
private static final Object NONE = new Object();
/** maintain dirty flag for any IWatched */
public interface IWatched {}
/** true if new value sent to any setter */
private boolean IWatched.dirty;
/** false if unable to maintain dirty b/c no privileges, no getter... */
private boolean IWatched.dirtyValid = true;
/** clients can use dirty flag */
public boolean IWatched.isDirty() {
return dirty;
}
/** clients handle case when dirty flag is invalid */
public boolean IWatched.isDirtyValid() {
return dirtyValid;
}
/** Setters are instance methods returning void,
* prefixed "set..." and taking exactly 1 argument.
* Does not use args(id), since that requires the
* argument be non-null.
*/
public pointcut setters(IWatched watched) : target(watched)
&& execution(void IWatched+.set*(*)); // advice uses args[0]
/**
* Skip setter if arg is same as current value;
* otherwise, set dirty flag after proceeding with setter.
* Skip this advice if we tried it but failed because
* there wasn't a corresponding setter, we didn't
* have the right security permissions, etc.
*/
void around(IWatched watched) : setters(watched)
&& if(watched.dirtyValid) {
// get value by invoking getter method
Object value = NONE;
try {
String getterName = "g" +
thisJoinPoint.getSignature().getName().substring(1);
Method method = watched.getClass()
.getMethod(getterName, GETTER_ARG_TYPES);
value = method.invoke(watched, GETTER_ARGS);
} catch (Throwable t) {
// NoSuchMethodException, SecurityException,
// InvocationTargetException...
}
if (NONE == value) {
watched.dirtyValid = false;
proceed(watched);
return;
}
// compare value with arg being set - pointcut has exactly 1 parm
Object arg = thisJoinPoint.getArgs()[0];
if (!(null == arg ? value == null : arg.equals(value))) {
proceed(watched);
watched.dirty = true;
}
}
}
// ----------- sample clients of WatchSetter
// classes may opt in - can also use aspects to declare.
class Timer implements WatchSetters.IWatched {
private static int ID;
public final int id = ++ID;
private int counter;
public int getCounter() {
return counter;
}
public void setCounter(int i) {
counter = i;
}
public void write() {
System.out.println("writing " + this);
}
public String toString() {
return "Timer " + id + "==" + counter;
}
}
// clients can use dirty flag directly
class Client {
static void handleTimer(Timer timer) {
timer.setCounter(0); // should result in no write
if (!timer.isDirtyValid() || timer.isDirty()) {
timer.write();
}
timer.setCounter(2);
if (!timer.isDirtyValid() || timer.isDirty()) {
timer.write();
}
}
}
// ---- aspects use dirty to implement cache, etc.
// Volatile things are flushed when dirty
abstract aspect Volatile {
// subaspects declare targets using Volatile.ITag
protected interface ITag {}
declare precedence : Volatile+, WatchSetters;
after(WatchSetters.IWatched watched) returning :
WatchSetters.setters(watched) {
if (!watched.isDirtyValid() || watched.isDirty()) {
flushCache(watched);
}
}
abstract void flushCache(Object o);
}
// treat Timer as volatile, write when flushing
aspect VolatileTimer extends Volatile {
declare parents: Timer implements ITag;
void flushCache(Object o) {
Timer timer = (Timer) o;
timer.write();
}
}
</pre>
<a name="declares"></a>
<h3>declares</h3>
<a href="#top">back to top</a>
<a name="declares-exceptionSpelunking"></a>
<h3>Using declare warning to find Exception-related code</h3>
<a href="#top">back to top</a>
<p>| Wes Isberg
| common declares/Declares.java:44 |
<p>
<pre>
/**
* List AppException catch blocks and callers as a way
* of investigating a possibly-large code base.
*/
aspect SeekAppExceptions {
pointcut withinScope() : within(com.company..*);
/**
* Find calls to stuff that throws AppException.
*/
declare warning : withinScope() &&
(call(* *(..) throws AppException+)
|| call(new(..) throws AppException+)) :
"fyi, another call to something that can throw IOException";
/**
* Find catch clauses handling AppException
*/
declare warning : withinScope() && handler(AppException+):
"fyi, code that handles AppException";
}
</pre>
<a name="declares-inoculated"></a>
<h3>declares-inoculated</h3>
<a href="#top">back to top</a>
<a name="declares-inoculated-nonSetterWrites"></a>
<h3>Warn when setting non-public field</h3>
<a href="#top">back to top</a>
<p>| Wes Isberg
| inoculated/src com/xerox/printing/CompileTime.java:46 |
<p>
<pre>
/** warn if setting non-public field outside a setter */
declare warning :
within(com.xerox.printing..*)
&& set(!public * *) && !withincode(* set*(..))
: "writing field outside setter" ;
</pre>
<a name="declares-inoculated-prohibitNonprivateConstructors"></a>
<h3>Error to have accessible sub-Point constructors</h3>
<a href="#top">back to top</a>
<p>| Wes Isberg
| inoculated/src RunTime.java:29 |
<p>
<pre>
/** We make it an error for any Point subclasses to have non-private constructors */
declare error : execution(!private Point+.new(..))
&& !within(java*..*) :
"non-private Point subclass constructor";
</pre>
<a name="declares-inoculated-validExceptionHandlingMethod"></a>
<h3>Error when subclass method handles exception</h3>
<a href="#top">back to top</a>
<p>| Wes Isberg
| inoculated/src com/xerox/printing/CompileTime.java:55 |
<p>
<pre>
declare error : handler(IOException+)
&& withincode(* PrinterStream+.delegate(..))
: "do not handle IOException in this method";
</pre>
<a name="declares-inoculated-validPointConstruction"></a>
<h3>Error when factory not used</h3>
<a href="#top">back to top</a>
<p>| Wes Isberg
| inoculated/src com/xerox/printing/CompileTime.java:61 |
<p>
<pre>
declare error : !withincode(Point+ SubPoint+.create(..))
&& within(com.xerox..*)
&& call(Point+.new(..))
: "use SubPoint.create() to create Point";
</pre>
<a name="declares-softenRemoteException"></a>
<h3>declares-softenRemoteException</h3>
<a href="#top">back to top</a>
<p>| Jim Hugunin, Wes Isberg
| common declares/Declares.java:78 |
<p>
<pre>
/**
* Convert RemoteExceptions to RuntimeRemoteException
* and log them. Enable clients that don't handle
* RemoteException.
*/
aspect HandleRemoteException {
/**
* Declare RemoteException soft to enable use by clients
* that are not declared to handle RemoteException.
*/
declare soft: RemoteException: throwsRemoteException();
/**
* Pick out join points to convert RemoteException to
* RuntimeRemoteException.
* This implementation picks out
* execution of any method declared to throw RemoteException
* in our library.
*/
pointcut throwsRemoteException(): within(com.company.lib..*)
&& execution(* *(..) throws RemoteException+);
/**
* This around advice converts RemoteException to
* RuntimeRemoteException at all join points picked out
* by <code>throwsRemoteException()</code>.
* That means *no* RemoteException will be thrown from
* this join point, and thus that none will be converted
* by the AspectJ runtime to <code>SoftException</code>.
*/
Object around(): throwsRemoteException() {
try {
return proceed();
} catch (RemoteException re) {
re.printStackTrace(System.err);
throw new RuntimeRemoteException(re);
}
}
}
</pre>
<a name="declares-threadFactoryRequired"></a>
<h3>Error when not using Thread factory</h3>
<a href="#top">back to top</a>
<p>| Wes Isberg
| common declares/Declares.java:13 |
<p>
<pre>
/** signal error if Thread constructor called outside our Thread factory */
declare error : call(Thread+.new(..)) && within(com.company..*)
&& !withincode(Thread com.company.lib.Factory.makeThread(..)) :
"constructing threads prohibited - use Factory.makeThread(..)";
</pre>
<a name="declares-typeConstraints"></a>
<h3>Using declare to enforce type constraints</h3>
<a href="#top">back to top</a>
<p>| Wes Isberg
| common declares/Declares.java:28 |
<p>
<pre>
protected interface SoughtException {}
// XXX ajc broken here?
/**
* Require that any SoughtException implementation be
* a subclass of Throwable. This picks out the mistake
* of declaring SoughtException a parent of something
* that is not an exception at all.
*/
declare error : staticinitialization(SoughtException+)
&& ! staticinitialization(SoughtException)
&& ! staticinitialization(Throwable+) :
"all SoughtException must be subclasses of Throwable";
</pre>
<a name="j2ee"></a>
<h3>j2ee</h3>
<a href="#top">back to top</a>
<a name="j2ee-myeclipseide"></a>
<h3>j2ee-myeclipseide</h3>
<a href="#top">back to top</a>
<a name="j2ee-myeclipseide-generally"></a>
<h3>Using MyEclipseIDE to develop AspectJ programs for J2EE</h3>
<a href="#top">back to top</a>
<p>| Wes Isberg
| trails myeclipseide.html:5 |
<p>
MyEclipseIde
(<a href="https://www.myeclipseide.com/">https://www.myeclipseide.com</a>)
aims to make it easy to develop J2EE applications using Eclipse.
AJDT
(<a href="https://eclipse.org/ajdt">https://eclipse.org/ajdt</a>)
is an Eclipse plug-in that supports AspectJ.
<ul>
<li>To install AJDT with MyEclipseIDE, direct the Eclipse update manager to
<a href="https://download.eclipse.org/technology/ajdt/dev/update">
https://download.eclipse.org/technology/ajdt/dev/update</a>,
install the plug-in, and follow any post-install instructions.
</li>
<li>To enable a project to use aspects, first
select <code>Convert to AspectJ project</code>
from the project's context menu (select project, right click).
(XXX Bug: AJDT reverts perspective to Java; go back to MyEclipseIDE)
Note that you must convert each project;
converting the master J2EE project will not affect
the child components (XXX RFE: option to convert child if parent).
</li>
<li>To build, select the menu item <code>Project > Rebuild Project</code>.
AJDT creates <code>default.lst</code> which lists all source files and
compiles them.
You can also recompile by clicking the AJDT build button.
(XXX Bug: only available in the Java perspective)
</li>
<li>To deploy, first add <code>aspectjrt.jar</code> to the project's
library directory.
For servlets and JSP's, that is in <code>{Web Root}/WEB-INF/lib</code>.
For EJB's, it's XXX todo.
Then deploy as usual for your application server.
</li>
<li>If you are using AspectJ in more than one project,
you might instead deploy <code>aspectjrt.jar</code>
whereever shared libraries belong for your server.
</li>
</ul>
<a name="j2ee-servlets"></a>
<h3>j2ee-servlets</h3>
<a href="#top">back to top</a>
<a name="j2ee-servlets-generally"></a>
<h3>Using AspectJ in servlets</h3>
<a href="#top">back to top</a>
<p>| Wes Isberg
| trails j2ee.html:11 |
<p>
AspectJ programs work if run in the same namespace and with aspectjrt.jar.
Servlet runners and J2EE web containers should run AspectJ programs fine
if the classes and required libraries are deployed as usual.
As with any shared library, if more than one application is using AspectJ,
then the aspectjrt.jar should be deployed where it will be loaded by a
common classloader. The same is true of any shared aspects.
<a name="j2ee-tomcat4"></a>
<h3>j2ee-tomcat4</h3>
<a href="#top">back to top</a>
<a name="j2ee-tomcat4-jsp"></a>
<h3>Running AspectJ JSP's in Tomcat 4.x</h3>
<a href="#top">back to top</a>
<p>| Wes Isberg
| trails j2ee.html:44 |
<p>
Tomcat 4.x uses the Jasper engine based on Ant to compile JSP's.
To set up ajc as the compiler, do the following before starting Tomcat:
<ol>
<li>Put <code>aspectjtools.jar</code> in
<code>${CATALINA_HOME}/common/lib</code> so that it can be loaded
by Jasper.
</li>
<li>Update Jasper servlet parameters in
<code>${CATALINA_HOME}/conf/web.xml</code> to tell Ant to use
<code>ajc</code> by setting the compiler property to the
AspectJ compiler adapter:
<pre>
<servlet>
<servlet-name>jsp</servlet-name>
<servlet-class>org.apache.jasper.servlet.JspServlet</servlet-class>
...
<init-param>
<param-name>compiler</param-name>
<param-value>org.aspectj.tools.ant.taskdefs.Ajc11CompilerAdapter</param-value>
</init-param>
</pre>
</li>
<li>The classpath is dynamically generated from the webapp deployment,
so <code>aspectjrt.jar</code> should be in
<code>{webapp}/WEB-INF/lib</code> or some shared or common
directory supported by the server.
</li>
<li>Alternatively, you can precompile JSP's using
<a href="#j2ee-tomcat4-precompileJsp">this Ant script</a>.
That involves manually updating the <code>web.xml</code> file
with the <code>Jasper</code>-generated servlet mappings.
</li>
</ol>
<a name="j2ee-tomcat4-precompileJsp"></a>
<h3>Precompile JSP's for Tomcat 4.x using AspectJ</h3>
<a href="#top">back to top</a>
<p>| Wes Isberg
| scripts precompile-jsp.build.xml:2 |
<p>
<pre>
<project name="Precompile Tomcat JSPs" default="all" basedir=".">
<target name="all" depends="jspc,compile"/>
<target name="info">
<echo>
This Ant script precompiles deployed .jsp files in Tomcat
using AspectJ 1.1.
Usage:
{ant} -f {this-script} \
-Dtomcat.home=/home/tomcat \
-Dwebapp.name=launchWeb \
-DASPECTJ_HOME=/dev/tools/aspectj-1.1.0
This defines the web application deployment $${webapp.dir} as
$${tomcat.home}/webapps/$${webapp.name}
, generates the Java source files to
$${webapp.dir}/WEB-INF/src
, uses iajc (AspectJ) to compile them to
$${webapp.dir}/WEB-INF/classes,
, and creates the mappings
$${webapp.dir}/WEB-INF/generated_web.xml,
which must be manually inserted into
$${webapp.dir}/WEB-INF/generated_web.xml,
at which point the web application can be reloaded.
This assumes that aspectjrt.jar is already deployed in
any of places on the Tomcat application classpath
(the application, shared, or common classpath).
If ASPECTJ_HOME is not defined, it assumes that
aspectjtools.jar is in
${CATALINA_HOME}/common/lib
</echo>
</target>
<target name="init">
<!-- declare these two on command-line -->
<property name="webapp.name"
value="launchWeb"/>
<property name="tomcat.home"
location="i:/home/tomcat"/>
<property name="webapp.path"
location="${tomcat.home}/webapps/${webapp.name}"/>
<property name="webapp.src.dir"
location="${webapp.path}/WEB-INF/src"/>
<property name="ASPECTJ_HOME"
location="${tomcat.home}/common"/>
</target>
<target name="jspc" depends="init">
<taskdef classname="org.apache.jasper.JspC" name="jasper2" >
<classpath id="jspc.classpath">
<pathelement location="${java.home}/../lib/tools.jar"/>
<fileset dir="${tomcat.home}/server/lib">
<include name="*.jar"/>
</fileset>
<fileset dir="${tomcat.home}/common/lib">
<include name="*.jar"/>
</fileset>
</classpath>
</taskdef>
<mkdir dir="${webapp.src.dir}"/>
<jasper2
validateXml="true"
uriroot="${webapp.path}"
webXmlFragment="${webapp.path}/WEB-INF/generated_web.xml"
outputDir="${webapp.src.dir}" />
</target>
<target name="compile" depends="init">
<mkdir dir="${webapp.path}/WEB-INF/classes"/>
<mkdir dir="${webapp.path}/WEB-INF/lib"/>
<path id="iajc.classpath">
<fileset dir="${ASPECTJ_HOME}/lib">
<include name="aspectjtools.jar"/>
</fileset>
</path>
<taskdef
resource="org/aspectj/tools/ant/taskdefs/aspectjTaskdefs.properties">
<classpath refid="iajc.classpath"/>
</taskdef>
<!-- forking compile so it runs in Eclipse -->
<iajc destdir="${webapp.path}/WEB-INF/classes"
sourceroots="${webapp.src.dir}"
debug="on"
verbose="true"
fork="true"
forkclasspathRef="iajc.classpath"
failonerror="true"
>
<classpath>
<pathelement location="${webapp.path}/WEB-INF/classes"/>
<fileset dir="${webapp.path}/WEB-INF/lib">
<include name="*.jar"/>
</fileset>
<pathelement location="${tomcat.home}/common/classes"/>
<fileset dir="${tomcat.home}/common/lib">
<include name="*.jar"/>
</fileset>
<pathelement location="${tomcat.home}/shared/classes"/>
<fileset dir="${tomcat.home}/shared/lib">
<include name="*.jar"/>
</fileset>
</classpath>
</iajc>
</target>
</project>
</pre>
<a name="j2ee-tomcat4-servlets"></a>
<h3>Running AspectJ servlets in Tomcat 4.x</h3>
<a href="#top">back to top</a>
<p>| Wes Isberg
| trails j2ee.html:24 |
<p>
In Tomcat, you can deploy application servlets in WAR's
or in exploded web directories and share code across
applications.
<ol>
<li>Use <code>ajc</code> to compile the servlets,
and deploy the classes as usual into
<code>{WebRoot}/WEB-INF/classes</code>.
</li>
<li>If your web applications or aspects do not interact, deploy
<code>aspectjrt.jar</code> into
<code>{WebRoot}/WEB-INF/lib</code>.
</li>
<li>If your web applications or aspects might interact, deploy
them to <code>${CATALINA_BASE}/shared/lib</code>.
</li>
</ol>
<a name="language"></a>
<h3>language</h3>
<a href="#top">back to top</a>
<a name="language-cflowRecursionBasic"></a>
<h3>Pick out latest and original recursive call</h3>
<a href="#top">back to top</a>
<p>| Erik Hilsdale
| common language/ControlFlow.java:27 |
<p>
<pre>
/** call to factorial, with argument */
pointcut f(int i) : call(int Fact.factorial(int)) && args(i);
/** print most-recent recursive call */
before(int i, final int j) : f(i) && cflowbelow(f(j)) {
System.err.println(i + "-" + j);
}
/** print initial/topmost recursive call */
before(int i, final int j) : f(i)
&& cflowbelow(cflow(f(j)) && !cflowbelow(f(int))) {
System.err.println(i + "@" + j);
}
</pre>
<a name="language-doubleDispatch"></a>
<h3>Implementing double-dispatch</h3>
<a href="#top">back to top</a>
<p>| Wes Isberg
| common language/DoubleDispatch.java:30 |
<p>
<pre>
/**
* By hypothesis, there is a working class with
* methods taking a supertype and subtypes.
* The goal of double-dispatch is to execute the
* subtype method rather than the supertype
* method selected when the compile-time
* reference is of the super's type.
*/
class Worker {
void run(SuperType t) {}
void run(SubTypeOne t) {}
void run(SubTypeTwo t) {}
}
class SuperType {}
class SubTypeOne extends SuperType {}
class SubTypeTwo extends SuperType {}
/** Implement double-dispatch for Worker.run(..) */
aspect DoubleDispatchWorker {
/**
* Replace a call to the Worker.run(SuperType)
* by delegating to a target method.
* Each target subtype in this method dispatches back
* to the subtype-specific Worker.run(SubType..) method,
* to implement double-dispatch.
*/
void around (Worker worker, SuperType targ):
!withincode(void SuperType.doWorkerRun(Worker)) &&
target (worker) && call (void run(SuperType)) &&
args (targ) {
targ.doWorkerRun(worker);
}
void SuperType.doWorkerRun(Worker worker) {
worker.run(this);
}
// these could be in separate aspects
void SubTypeOne.doWorkerRun(Worker worker) {
worker.run(this);
}
void SubTypeTwo.doWorkerRun(Worker worker) {
worker.run(this);
}
}
</pre>
<a name="language-fieldSetContext"></a>
<h3>Check input and result for a field set.</h3>
<a href="#top">back to top</a>
<p>| Erik Hilsdale, Wes Isberg
| common language/Context.java:42 |
<p>
<pre>
/**
* Check input and result for a field set.
*/
void around(int input, C targ) : set(int C.i)