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).

Java Annotations to Construct POJOs from HTTP Requests

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

Date: Wed, 20 Aug 2008 16:25:55 -0400 (CLT)

At work I'm writing code to provide a REST interface to a database (really
it's simpler than that - it's read only).  In the controller I want to
automate the construction of the model as much as possible.  This is
driven by the parameters in the request, so as a first step I want to be
able to set object attributes from the HTTP request.

I also want to be able to generate URLs from these same objects, when they
are modified (so that it is easy to generate URLs in the view to related
information).

So I need to (1) associate attributes with HTTP requests and (2) store
default parameters (so that the generated URI is no longer than
necessary).  After wondering exactly how to go about this I remembered the
rather excellent approach taken by args4j - https://args4j.dev.java.net/ -
which uses annotations on attributions.

It turns out that this is incredibly easy to do.  I now have some simple
annotations that let me define a tree of objects that will be
automatically generated with attributes populated from the request (which
tree is generated will depend on some other logic using the URI).

Here's the test (this is work's code, so it's (c) ISTI http://www.isti.com
and available under an attribution-based licence; contact ISTI for full
details).

public class BuilderTest
{

  @Test
  public void testAll()
  throws IllegalArgumentException, SecurityException, InstantiationException,
  IllegalAccessException, InvocationTargetException, NoSuchMethodException {
    MockHttpServletRequest request = new MockHttpServletRequest();
    request.setParameter("value-1", "one");
    request.setParameter("value-3", "3");
    request.setParameter("value-a", "a");
    request.setParameter("value-b", "5");
    Builder builder = new Builder(request);
    Outer outer = builder.build(Outer.class);
    assertEquals("Bad value for value1", "one", outer.value1);
    assertEquals("Bad value for value2", "default", outer.value2);
    assertEquals("Bad value for value3", 3, outer.value3);
    assertEquals("Bad value for valuea", "a", outer.inner.valuea);
    assertEquals("Bad value for valueb", 5, outer.inner.valueb, 0.001);
  }

  public static class Outer {
    @Parameter(deflt = "", name = "value-1")
    public String value1;
    @Parameter(deflt = "default", name = "value-2")
    public String value2;
    @Parameter(deflt = "", name = "value-3")
    public int value3;
    @Parameterised
    public Inner inner;
  }

  public static class BaseInner {
    @Parameter(deflt = "", name = "value-a")
    public String valuea;
  }

  public static class Inner extends BaseInner {
    @Parameter(deflt = "", name = "value-b")
    public double valueb;
  }

}

And you can see that:
1 - attributes are set from the HTTP request
2 - defaults are supplied as necessary
3 - a tree of objects can be created

The implementation is simple (the annotations themselves are trivial
interfaces).  All the work is done in the Builder, mainly in these
methods:

public <Type> Type build(final Class<Type> clazz)
{
  Type instance = clazz.getConstructor().newInstance();
  // if we use getDeclaredFields here we don't superclass fields.
  // unfortunately, this then restricts us to public fields (declared
  // seems to also include protected fields)
  for (Field field: clazz.getFields()) {
    setParameter(instance, field);
    extendParameterised(instance, field);
  }
  return instance;
}

private <Type> void setParameter(final Type instance, final Field field)
{
  logger.debug("Field {}", field.getName());
  Parameter parameter = field.getAnnotation(Parameter.class);
  if (parameter != null) {
    String value = getValue(parameter);
    if (field.getType() == String.class) {
      field.set(instance, value);
    } else if (field.getType() == Integer.TYPE) {
      field.setInt(instance, Integer.parseInt(value));
    } else if (field.getType() == Double.TYPE) {
      field.setDouble(instance, Double.parseDouble(value));
    } else {
      throw new BadParameterException(
        String.format("Bad type %s for %s = %s.",
                      field.getType().getSimpleName(),
                      parameter.name(), value));
    }
  }
}

private <Type> void extendParameterised(
    final Type instance, final Field field)
{
  if (field.isAnnotationPresent(Parameterised.class)) {
    field.set(instance, build(field.getType()));
  }
}

Andrew

Spring's Command Controller

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

Date: Wed, 20 Aug 2008 17:11:55 -0400 (CLT)

...is kind-of similar.  The differences (from the point of view of the
Spring class are):

- Proper Java bean support (setters rather than attributes)
- Wider range of values via Java bean property editors
- Dotted paths (rather than single flat namespace)
- No defaults (which makes constructing compact URIs hard)
- No annotations (as far as I can see) to restrict what is set
  (instead uses standard "public" interface)
- Validators (not needed in my read-only case, thankfully)

Validators and property conversion are the biggies, but in my case
constructing URIs and a flat namespace are what I need.

Andrew

Comment on this post