Andrew Cooke | Contents | Latest | RSS | Previous | Next

C[omp]ute

Welcome to my blog, which was once a mailing list of the same name and is still generated by mail. Please reply via the "comment" links.

Always interested in offers/projects/new ideas. Eclectic experience in fields like: numerical computing; Python web; Java enterprise; functional languages; GPGPU; SQL databases; etc. Based in Santiago, Chile; telecommute worldwide. CV; email.

Personal Projects

Choochoo Training Diary

Last 100 entries

Surprise Paradox; [Books] Good Author List; [Computing] Efficient queries with grouping in Postgres; [Computing] Automatic Wake (Linux); [Computing] AWS CDK Aspects in Go; [Bike] Adidas Gravel Shoes; [Computing, Horror] Biological Chips; [Books] Weird Lit Recs; [Covid] Extended SIR Models; [Art] York-based Printmaker; [Physics] Quantum Transitions are not Instantaneous; [Computing] AI and Drum Machines; [Computing] Probabilities, Stopping Times, Martingales; bpftrace Intro Article; [Computing] Starlab Systems - Linux Laptops; [Computing] Extended Berkeley Packet Filter; [Green] Mainspring Linear Generator; Better Approach; Rummikub Solver; Chilean Poetry; Felicitations - Empowerment Grant; [Bike] Fixing Spyre Brakes (That Need Constant Adjustment); [Computing, Music] Raspberry Pi Media (Audio) Streamer; [Computing] Amazing Hack To Embed DSL In Python; [Bike] Ruta Del Condor (El Alfalfal); [Bike] Estimating Power On Climbs; [Computing] Applying Azure B2C Authentication To Function Apps; [Bike] Gearing On The Back Of An Envelope; [Computing] Okular and Postscript in OpenSuse; There's a fix!; [Computing] Fail2Ban on OpenSuse Leap 15.3 (NFTables); [Cycling, Computing] Power Calculation and Brakes; [Hardware, Computing] Amazing Pockit Computer; Bullying; How I Am - 3 Years Post Accident, 8+ Years With MS; [USA Politics] In America's Uncivil War Republicans Are The Aggressors; [Programming] Selenium and Python; Better Walking Data; [Bike] How Fast Before Walking More Efficient Than Cycling?; [COVID] Coronavirus And Cycling; [Programming] Docker on OpenSuse; Cadence v Speed; [Bike] Gearing For Real Cyclists; [Programming] React plotting - visx; [Programming] React Leaflet; AliExpress Independent Sellers; Applebaum - Twilight of Democracy; [Politics] Back + US Elections; [Programming,Exercise] Simple Timer Script; [News] 2019: The year revolt went global; [Politics] The world's most-surveilled cities; [Bike] Hope Freehub; [Restaurant] Mama Chau's (Chinese, Providencia); [Politics] Brexit Podcast; [Diary] Pneumonia; [Politics] Britain's Reichstag Fire moment; install cairo; [Programming] GCC Sanitizer Flags; [GPU, Programming] Per-Thread Program Counters; My Bike Accident - Looking Back One Year; [Python] Geographic heights are incredibly easy!; [Cooking] Cookie Recipe; Efficient, Simple, Directed Maximisation of Noisy Function; And for argparse; Bash Completion in Python; [Computing] Configuring Github Jekyll Locally; [Maths, Link] The Napkin Project; You can Masquerade in Firewalld; [Bike] Servicing Budget (Spring) Forks; [Crypto] CIA Internet Comms Failure; [Python] Cute Rate Limiting API; [Causality] Judea Pearl Lecture; [Security, Computing] Chinese Hardware Hack Of Supermicro Boards; SQLAlchemy Joined Table Inheritance and Delete Cascade; [Translation] The Club; [Computing] Super Potato Bruh; [Computing] Extending Jupyter; Further HRM Details; [Computing, Bike] Activities in ch2; [Books, Link] Modern Japanese Lit; What ended up there; [Link, Book] Logic Book; Update - Garmin Express / Connect; Garmin Forerunner 35 v 230; [Link, Politics, Internet] Government Trolls; [Link, Politics] Why identity politics benefits the right more than the left; SSH Forwarding; A Specification For Repeating Events; A Fight for the Soul of Science; [Science, Book, Link] Lost In Math; OpenSuse Leap 15 Network Fixes; Update; [Book] Galileo's Middle Finger; [Bike] Chinese Carbon Rims; [Bike] Servicing Shimano XT Front Hub HB-M8010; [Bike] Aliexpress Cycling Tops; [Computing] Change to ssh handling of multiple identities?; [Bike] Endura Hummvee Lite II; [Computing] Marble Based Logic; [Link, Politics] Sanity Check For Nuclear Launch; [Link, Science] Entropy and Life

© 2006-2017 Andrew Cooke (site) / post authors (content).

Static Mixins at the Presentation Layer with AspectJ and JSP

From: "andrew cooke" <andrew@...>

Date: Fri, 2 Dec 2005 09:38:27 -0300 (CLST)

A quick note on an interesting pattern I stumbled across yesterday.
It's very obvious in retrospect, but I think it's also an interesting
illustration of AspectJ in use, showing both its good and bad
features.


Background, Database Layer
--------------------------

I have some information in my database that I want to display in the
user's browser (don't we all?).  These are three integers - labelled
red, yellow and green - that "score" someone's performance (green is
good, red bad and yellow intermediate).

So I have a transport object - a bean - that is a transparent carrier
of this information (and other related values).  The database layer
supports reading and writing instances of this object.

This transport bean is very simple - a collection of private fields
with public setters/getters (largely auto-generated by Eclipse) that
provide dynamic access to the fields via introspection (what a bean
is, really).

Presentation Layer
------------------

At the presentation layer (inside a JSP tag) I decided to display the
information as an LED bar display (like you see on cheesy hi-fi).
However, the numeric values of these scores can be large, so I decided
to make the number of bars proportional to the log of the value (more
exactly; 1 + log2(n)).

Within the tag I would like to access these logarithmic values using
JSP's expression language.  So my tag code looks something like:

<c:if test="${value.red > 0}">
  <c:forEach begin="1" end="${value.logRed}">
    <img src="<c:url value="/themes/red.png"/>" alt="-" title="bad" />
  </c:forEach>
</c:if>

To do this, I need a getLogRed() getter on my object.  But my
transport bean only has a getRed() method.

Mixin
-----

Enter AspectJ.  In the part of my source tree related to presentation
I define an AspectJ mixin that adds the lgoarithm calculations.  This
is done in three steps.

First, I define an interface that provides the new functionality (I'll
only include red here, but in practice all three colours are present):

public interface LogColour {
  public int getLogRed();
}

Second, I add that interface to the transport bean, along with a dummy
implementation:

public aspect LogColourMixin {

  declare parents : TransportBean
  implements LogColour;

  public int LogColour.getLogRed() {return -999;}

}

Third, I define a "pointcut" that identifies when this method is
called, and an "advice" that does the appropriate calculation (this
goes inside LogColourMixing defined above; Tk is a static toolkit):

  pointcut beanRed(TransportBean bean):
    call(public int LogColour.getLogRed()) && target(bean);

  int around(TransportBean bean): beanRed(bean) {
    return Tk.log2(bean.getRed());

Note here that the pointcut and advice are both parameterised with a
TransportBean instance.  This gives us access to the bean inside the
advice so that we can call the getRed() method.

Coding Style
------------

The use of mixins here is completely gratuitous.  I could equally well
have added the getLogRed() method directly to the transport bean.  Or
I could have used some kind of facade.

However, this approach helps separate the different concerns.  The
presentation mixin lives with my presentation source and is not
referred to by the transport, database or business logic layers.  As
it happens, the database layer also uses a mixin to add a table key to
the object; that doesn't appear in the transport, business or
presentation code.

It Doesn't Work
---------------

While the code above does work in my test case, the tag failed!
Inside the tag, the getLogRed() method is returning -999.  The advice
is not being applied.

This is due to an implementation detail of AspectJ.  The addition of
the interface is achieved by modifying the class file - it is a static
change.  The pointcut and advice, however, are dynamic; they are
implemented by inserting tests in *calling* code.

The dynamic interception works fine in my tests because I am using
AspectJ-aware Eclipse.  But the tag files are compiled in the server
(Tomcat), which knows nothing about AspectJ and so doesn't add the
appropriate indirection.

(One solution to this is to pre-compile the tags using AspectJ).

Ugly -999
---------

And that dummy method implementation is ugly!  Here it is again:

  public int LogColour.getLogRed() {return -999;}

Why can't that be:

  public int LogColour.getLogRed() {
    return Tk.log2(getRed());
  }

Because getRed is part of the parent!  I cannot find a way to acccess
the parent class statically from within the method.  The above, and
this.getRed() both give compilation errors.

Overlapping Interface Pattern
-----------------------------

A better solution struck me on the way home from work today.  This
makes the mixing completely static and removes the ugly dummy method:

public interface LogColour {
  public int getRed();
  public int getLogRed();
}

public aspect LogColourMixin {
  declare parents : TransportBean
  implements LogColour;

  public int LogColour.getLogRed() {
    return Tk.log2(getRed());
  }
}

(I did say it was obvious in retrospect...)  All I have done is
include the getRed() method in the mixin interface.  This already
exists in TransportBean, so I don't need to re-implement it, but by
adding it to the mixin I can now call it from within the getLogRed()
implementation.

This works fine when called from code compiled in the server because
the changes are all confied to static modifications in the called
code; the calling code does not need any dynamic interceptions.

So by following this pattern I have a simple mixin: easier to
understand; more efficient; and works when called from Aspectj-unaware
code.

Andrew


-- 
`__ _ __ ___  ___| |_____   personal web site: http://www.acooke.org
/ _` / _/ _ \/ _ \ / / -_)  list: http://www.acooke.org/andrew/compute.html
\__,_\__\___/\___/_\_\___|  aim: acookeorg; skype: andrew-cooke

_______________________________________________
compute mailing list
compute@...
https://acooke.dyndns.org/mailman/listinfo/compute

Comment on this post