Sunday, 15 February 2015

Bosch and FBP: Federal Bureau of Physics

Last night, or rather this morning, I was up watching a series whose pilot I'd watched a few months ago on Amazon, based on the crime novels by Michael Connelly. L.A.P.D. Detective Hieronymus “Harry” Bosch (Titus Welliver) is called in to investigate some bones found by a dog in the Hollywood Hills.


Ably supported by an excellent cast (including Jamie Hector as his partner and Lance Reddick as his ambitious and more political boss, both actors from The Wire), Welliver looks very suited to the role and the story is excellent, as you would expect from the author of The Lincoln Lawyer. The only complaint is that when there's a deviation from the main character, it does feel somewhat artificial and contrived. Overall, though, it's an enjoyable, if conventional, series. I even like theme tune.

I'm also reading a Trade Paperback from Vertigo about an agency that fixes breakdowns in the fabric of reality. Trying to determine what happened to his father in a "quantum tornado", Adam Hardy joins the Federal Bureau of Physics and, with his partner Jay Kelly, gets caught in a bubble universe trying to rescue a financial fraudster.


I'm always looking for comics that break out of the conventions of the genre and this is no exception. Written by Simon Oliver (Story), Robbi Rodriguez and Rico Renzi (Artwork), it's just one roller-coaster of weirdness, but intriguing and entertaining in equal measure. And not a super-hero or zombie in sight.

Saturday, 7 February 2015

Blue Skies – The Future of Regenerative Medicine, with Stephen Minger

Last Saturday, I attended a presentation hosted by the London Futurists in the basement at Birkeck College on the subject of stem cell-based regenerative medicine by Dr. Stephen Minger, Chief Scientist at GE Healthcare.


Stephen gave us an overview of what GE Healthcare did (they have a $1 billion budget for research) and a potted history of stem-cell research. He seemed somewhat hesitant to speculate on what the future might be for (stem) cell therapy, although he did highlight both the successes, in particular with leukaemia, and difficulties with the treatment.

The group has been posting the presentation on Youtube, and this one is no exception:


Overall I found the presentation both engaging and informative.

Sunday, 1 February 2015

A Man Who Wants Nothing Cannot be Bought - Hercules and Godzilla

A few more films from my Amazon subscription, both based on legends old and new.

The first is based on one of the oldest Greek legends. After completing his twelve labours, a war-weary and haunted Hercules (Dwayne Johnson) and his companions Amphiaraus (Ian McShane), Autolycus (Rufus Sewell), Tydeus (Aksel Hennie), Atalanta (Ingrid Bolsø Berdal) and his nephew Iolaus (Reece Ritchie), are hired by King Cotys of Thrace (John Hurt) to defend his kingdom from ruthless bandits.


Despite a slightly shaky start, this turns out to be quite a good film. It's a good story and deceptive enough to keep you second guessing almost until the end; the special effects aren't too bad; and the acting is more than adequate, the effect of all the class British thesps in supporting roles encouraging Dwayne to raise his game above previous attempts. Recommended as an above average pizza movie.

In contrast we have as my second film, Godzilla: a remake of a remake of a modern Japanese legend. Fifteen years after his wife dies in a mysterious accident at a Japanese nuclear power plant, engineer Joe Brody (Bryan Cranston) breaks into the quarantined area with his estranged son Ford (Aaron Taylor-Johnson) to get answers.


I suppose that if you like the original Japanese movies, this will be quite a good experience, even nostalgic. For me, however, it was a little tedious. Most of the "A" listers had gone by the time the movie got going and all that was left was three huge monsters slugging it out in San Fransisco. In the dark.

Saturday, 24 January 2015

3 Movies - Edge of Tomorrow, Guardians of the Galaxy and Three Days to Kill

The movies I get from Amazon are in threes and I managed to get them all replaced this time around and watched one after the other.

First, Three Days to Kill, a (perhaps unintentional) comedy thriller staring Kevin Costner as an ageing CIA agent trying to reconnect with his estranged family and offered treatment for his terminal illness in return for one last job.


An inferior competitor to the Taken series, even the occasional stabs at comedy don't really work and the whole thing, although workman-like, is a damp squib. Only the action scene's redeem it a little, but even those are run-of-the-mill. Ignore.

Next up, Guardians of the Galaxy, based on the Marvel comics, one of whose authors is one of my favourites, Dan Abnett of the Eisenhorn\Ravenor series. Having been kidnapped by extra-terrestrials as a child, adventurer and thief Peter Quill (Chris Pratt) manages to acquire a metal orb that attracts the attention of villain Ronan (Lee Pace).


Not bad. The plot's pretty good, if relentless; the action well paced and the special effects gob-smacking and original. The characters are a little too cardboard for my taste: Vin Diesel plays Groot who only says the same thing over and over again, "I am Groot", so everyone got their money's worth there. Dave Bautista as Drax the Destroyer is better value, but Bradley Cooper adds little as Rocket. The 70's sound track and Quill's use of it to connect with his past, especially his mother, does add a human touch and stops it all being too alien. A good all-round pizza movie.

By the way, without looking at the credits, see if you can spot Karen Gillan from Doctor Who.

Last, but far from least, there's Edge of Tomorrow, the latest Tom Cruise vehicle. After an alien invasion of near-future Europe, U.S. Army spokesman William Cage (Cruise) gets accidentally caught up in the human counter-attack.


It's like an over-the-top mash-up of Independence Day, Groundhog Day and The Longest Day. The technology (me being geeky) is incredibly well realised with lots of vertical take-off aircraft (similar to the V-22 Osprey currently in service) and hovercraft, as well as the exo-skeletons. The plot's a bit convoluted but its origins as a Japanese short-story might be responsible for that. Cruise and Emily Blunt, as the soldier who's experienced the same time-looping before, do well enough, but there is a sort of forgettable quality about the story (in a similar way to a previous Cruise film, Oblivion). A good enough pizza movie if you ignore all the resurrection undertones.

Here's a thing. There's a school of thought that says that recent movies have a preoccupation with ageing, death, longevity or immortality. The reason for this is that the people who make the movies (star in them, produce or direct them) are the so-called post war baby-boomer generation and mortality is catching up with them. This is expressing itself in the films (Cruise is 52 and Costner 60) so the idea has some merit.

Friday, 23 January 2015

Update: R.I.P. Oliver, Lazarus and 12 Monkeys

Just thought I'd do an update as it's been a few weeks and I've been a little preoccupied with work and whatnot.

R.I.P. Oliver.

A sad departure was my budgie Oliver who had been in declining health all last year, but worse in the run up to Christmas. Budgies are social creatures by nature and the loss of the female, Snowflake, the year before had hit him hard, plus he was around ten years old, which is about their lifespan.


He was a great budgie and he's missed already. Chez Lemon is very quiet.

Lazarus

On a different tack, I've been reading a copy of Greg Rucka's latest story, Lazarus, from Image comics:


It takes place in a dystopian future where society has descended into technically advanced fiefdoms run by families, each of which has a super soldier, or Lazarus of the title. The stories focus on the Lazarus of the Carlyle family, Forever, but in the second book, a story of a "waste" (a disenfranchised social class) family runs parallel to hers.

So far, there's little in the story which is positive or uplifting, but this is in keeping with Rucka's style (Queen and Country was a little bit like that, with no real winners, just survivors). The art work is also good, so it's all promising, if a bit grim.

12 Monkeys

Continuing on with the dystopian theme, the TV version of the Terry Gilliam film has been made over in the 'States and it looks good.


Friday, 2 January 2015

True(ish) Stories: American Hustle and Dallas Buyers Club

On the upside of a disruptive and chaotic Christmas/New Year (welcome to 2015, everybody), I watched a few films from my Amazon subscription. First up, two con artists (Christian Bale and Amy Adams) are blackmailed into an FBI sting operation:


On paper, this looks like it could be a really great movie, with a top notch cast and a true(ish) story, but the direction is poor and the casting laughable. Bale couldn't sell a lifebelt to a drowning man and generates no sympathy or empathy as the lead. Jennifer Lawrence and Amy Adams, as his wife and girlfriend respectively, do better, but, like Bale, are too young for the roles. Jeremy Renner is also good, but Bradley Cooper is just embarrassing. It's just simply not their kind of film. However, you do get a glimpse of what might have been when Robert De Niro turns up for 5 minutes and steals not just the scene but the movie.

Next is the Dallas Buyers Club. Ron Woodruff (Matthew McConaughey), after contracting HIV and developing AIDS, decides to treat himself and others using non-FDA approved drugs after the approved treatment fails.


The acting in the film is top notch, as you'd expect, with McConaughey ably supported by Jennifer Garner as his doctor and Jared Leto as his business partner, and the story is handled well. However, as with the previous film, I've always felt that true stories don't fit particularly well into film because a life cannot be told in 90-120 minutes. I always have a feeling that the truth is more complex and you're just getting half the story. Still, it's not a bad film and worth the watch.

Sunday, 7 December 2014

Dragonmeet 2014

Yes, it's December, which must mean that it's Dragonmeet again. It's been moved to a new venue from Kensington Town Hall to the Ibis Hotel in Earls Court ("more room" according to one of the volunteers).


To me it seemed smaller, or more compact. There weren't many vendors there, but perhaps more producers, including a new card game called Stak Bots:


I bought an RPG that I've had my eye on for a while, which seems to be a bit different from the usual character based games:


Unfortunately, I didn't get a game so, on my way back, I stopped off at Covent Garden to do a little more shopping and saw the lights:


Wednesday, 3 December 2014

Turning Japanese - 47 Ronin and Kick-Ass 2

Two films from my Amazon subscription. The first is the sequel to the popular Kiss-Ass. Bored with premature "retirement", David Lizewski a.k.a. Kick-Ass (Aaron Taylor-Johnson) and Mindy Macready a.k.a. Hit-Girl (Chloë Grace Moretz) join with other super-heroes while struggling with growing up and leading a normal life.


I must admit that I haven't read much of Mark Millar's work, in particular the Kick-Ass books, so I can't compare them to the original. The one book I have read, Wanted, was awful, and the film much better. The original Kick-Ass had a kind of naive violence, like Tom and Jerry, and the corresponding charm. This has the difficulty that the novelty has worn off, and the violence seems a little more serious and intense, as does the whole film. Jim Carrey (Colonel Stars and Stripes) plays the father figure that Nicolas Cage (Big Daddy) played in the first film, and the supporting cast is good enough, but it is an inferior sequel to a mediocre film.

The second film is 47 Ronin, based on a classic Japanese story. Kai (Keanu Reeves), a mixed-race woodsman in feudal Japan, is treated with suspicion and ill-disguised contempt by his master Lord Asano's (Tadanobu Asano) samurai retainers.


A visually stunning film, and worth watching for that alone, the cast, aside from Reeves (who isn't that bad, really), is excellent, headed by Hiroyuki Sanada as the lead samurai and the beautiful Ko Shibasaki as Kai's true love. Tadanobu Asano and Rinko Kikuchi are also suitably evil as Asano's nemesis and his sorceress.

It's problem, however, is that it adheres too closely to the original story for the Western audience (and is too conservative a film for the modern Japanese audience: Battle Royale is more typical) and yet is too Western for the Japanese audience, so it's no surprise (but a bit unfair) that it's the second most unsuccessful movie of all time, losing $20 million at the box office. You can imagine the effect on us if Hollywood decided to make a film about The Battle of Britain with Harrison Ford as Hugh Dowding, or The Dambusters with Nick Cage as Guy Gibson. Nah.. they wouldn't... would they?

Saturday, 29 November 2014

Once Upon a Time in the East End - Wild Bill

Every so often, there's a new film on Film 4. Mostly I've seen them through other media, but Wild Bill was a new one and a little gem. Having served eight years for crimes he did commit, "Wild" Bill Hayward (Charlie Creed-Miles) returns to his East London home to try to reconcile with his estranged sons and lead a quiet life.


A kind of anti-revenge film, Creed-Miles is great as Bill, trying to avoid any trouble with his former associates, while dealing with the resentment of his eldest son Dean (Will Poulter) and keeping his youngest Jimmy (Sammy Williams) away from the villains. The supporting cast is top notch, with Olivia Williams as Bill's probation officer, Sean Pertwee as the cop who arrested him the first time and Andy Serkis as his even wilder former boss. However, it's Bill and his family who hold the attention until the final, inevitable, confrontation looms like a thundercloud. Very recommended.

...oh all right then. YES, there's a trailer out for the new Star Wars movie coming out next year. And, YES, it looks good. And, YES, it's got the Millenium Falcon in it. Go on then...


J.J. Abrams is at the helm and if Lucas is smart, he'll let him do what he wants: it didn't do Star Trek any harm.

Sunday, 23 November 2014

It's The (Dead) Rozzers Part 2! R.I.P.D. and Non-Stop

Two from my Amazon film subscription. First the latest Liam Neeson film. Struggling alcoholic U.S. Air Marshal Bill Marks (Neeson) sets off on a trans-Atlantic flight, but is being sent mysterious messages threatening the safety of the passengers and crew:


With a ridiculous plot, bad pacing (there's are some very tedious moments) and small details that let the whole thing down (why would RAF Typhoons be anywhere near Iceland?), the only saving grace is the action scenes, special effects and the cast, although wasted. Better than nothing, but not much.

Marks might have been better off dead, which brings us to my next film, R.I.P.D. Having being shot and killed by his partner (Kevin Bacon), Boston Detective Nick Walker (Ryan Reynolds) is teamed with a former western lawman (Jeff Bridges) and tasked with returning "deadoes" back to the afterlife:


From a comic book of the same name, this is an enjoyable hybrid of Ghostbusters and Men in Black, let down only by Bridges trying to lampoon his own version of Rooster Cogburn. The effects are good and the supporting cast, especially Bacon, Mary-Louise Parker as their boss and Robert Knepper as their first suspect (much underused). Good fun and a decent pizza movie.

Wednesday, 19 November 2014

Spring Boot and Spring Data

Continuing on from the previous article, I finally managed to get to Spring Data. In a way, this is just Spring JPA and looks like this:

@Configuration
@EnableAutoConfiguration
public class Application {

  public static void main(String[] args) {

    ConfigurableApplicationContext context = SpringApplication.run(Application.class);
    PersonRepository repository = context.getBean(PersonRepository.class);

    for (Person person : repository.findAll()) {
      System.out.println(person);
    }
    context.close();
  }
}
Although this looks similar to the Hibernate JPA previously, there are some significant changes. The first is the use of a Repository interface, PersonRepository. This has to descend from the Spring Data Repository interface, usually via another interface:

public interface PersonRepository extends CrudRepository<Person, Long> {
}
I’ve used CrudRepository, the most basic, and given it the class name of the POJO and the type of the unique identifier, which is a Long. Notice that you have to use the class equivalent of the primitive type. You don’t need to define anything else if you don’t want to; CrudRepository defines the basic functions as standard:

public interface CrudRepository<T extends Object, ID extends Serializable> extends Repository<T, ID> {
  public <S extends T> S save(S s);
  public <S extends T> Iterable<S> save(Iterable<S> itrbl);
  public T findOne(ID id);
  public boolean exists(ID id);
  public Iterable<T> findAll();
  public Iterable<T> findAll(Iterable<ID> itrbl);
  public long count();
  public void delete(ID id);
  public void delete(T t);
  public void delete(Iterable<? extends T> itrbl);
  public void deleteAll();
}
As before, the field mappings have to be put directly in the POJO using annotations. Something to remember is that with Spring JPA you have to make sure the column names are lower case.

Next you have to configure the connection properties. This goes in a file called “application.properties”, the default:

spring.datasource.url=jdbc:jtds:sqlserver://localhost:1433/A_DB
spring.datasource.username=aaron
spring.datasource.password=********
spring.datasource.driverClassName=net.sourceforge.jtds.jdbc.Driver
You may have noticed in the application definition is the use of the EnableAutoConfiguration annotation. This is from Spring Boot, which is our next subject.

Spring Boot

So far, behind the scenes, so to speak, we’ve been adding dependencies into the Maven POM file with some abandon, but, to get Spring Boot working, we have to remove them. Why use Spring Boot? I can’t really give you a straight answer, other than to say there are a lot fewer problems when using Spring Data. Take my word for it.

As described in the starting guide instruction on the Spring Boot web site, you have to add the following:

<parent>
  <groupId>org.springframework.boot</groupId>
  <artifactId>spring-boot-starter-parent</artifactId>
  <version>1.1.8.RELEASE</version>
</parent>
… which goes in the project root. Next you want something to tell Spring Boot to pull in the Data JPA layer:
<dependency>
  <groupId>org.springframework.boot</groupId>
  <artifactId>spring-boot-starter-data-jpa</artifactId>
</dependency>
… which goes in the dependencies. Clear everything else out of the dependencies: this will cause all kinds of errors in the code, but resist the temptation to fix this by pulling in the dependencies. You will regret it if you don’t. Do a build (or clean and build), you’ll find that new dependencies have been pulled in via the parent and you don’t have to define anything. This also sorts out any import errors.

The dependencies that do have to be put in are specific to this particular project and that is the JTDS driver for MS SQL Server:
<dependency>
  <groupId>net.sourceforge.jtds</groupId>
  <artifactId>jtds</artifactId>
  <version>1.2</version>
</dependency>
You will be surprised to find that all this works straight away with no other configuration.

Spring Boot Web Services

So far, we’ve just been playing with the data, outputting the results to the console. To get it to do something useful, we need to introduce web services, in the form of a REST interface. This is what Spring Boot is really used for and this introduces the idea of Micro Services.

Micro Services are an architectural concept that takes componentisation to a system level. A system is divided up into sub-systems, each of which is considered a system in its own right, with its own security, metrics etc., and even its own built-in web server. These components are connected together using REST web services, so the definitions of these interfaces become very important. The implementation of one sub-system, or Micro Service, is independent of others, providing the interfaces are adhered to, so you can have one service built using .Net and another in Java, yet another in Node.js and JavaScript. There are lots of technologies being introduced and maturing that support, take advantage of or are being taken advantage of by this concept, in particular Docker, for deployment, Spring Boot and Drop Wizard for Java development.

Now we’ll add a REST service to the previous data project. First, we remove the data code from the Application class:
  public static void main(String[] args) {
    SpringApplication.run(Application.class);
  }

Exactly as before, just without the data code. This has been moved to the web service class, MyController:

@RestController
public class PersonController {

  @Autowired
  private PersonRepository repository;

  @RequestMapping("/")
  public String index() {
    StringBuilder sb = new StringBuilder();
    sb.append("<!DOCTYPE html>").append("<html lang='en'>");
    sb.append("<head>").append("<meta charset='UTF-8'>");
    sb.append("<title>Something, something</title>").append("</head>");
    sb.append("<body>");
    sb.append("<table>");
    for (Person person : repository.findAll()) {
      sb.append("<tr>");
      sb.append("<td>").append(person.getId()).append("</td>");
      sb.append("<td>").append(person.getFirstName()).append("</td>");
      sb.append("<td>").append(person.getLastName()).append("</td>");
      sb.append("</tr>");
    }
    sb.append("</table>");

    sb.append("</body>");
    sb.append("</html>");
    return sb.toString();
  }
}

The class is designated a RestController, which tells Spring that it’s the class that handles http requests as REST requests. The RequestMapping annotation tells it which path to respond to, in this case the root. I’m responding with a string at this point and creating a simple web page as the payload.

Notice that the repository is automatically created by annotating the declaration with @Autowired.

The POM has also been added to with Spring Boot dependencies, spring-boot-starter-web and spring-boot-starter-jetty:
<dependency>
  <groupId>org.springframework.boot</groupId>
  <artifactId>spring-boot-starter-web</artifactId>
  <exclusions>
    <exclusion>
      <groupId>org.springframework.boot</groupId>
      <artifactId>spring-boot-starter-tomcat</artifactId>
    </exclusion>
  </exclusions>
</dependency>

<dependency>
  <groupId>org.springframework.boot</groupId>
  <artifactId>spring-boot-starter-jetty</artifactId>
</dependency>

The former seems to be mostly used to enable the web services, but also to prevent Tomcat being used. Instead it used Jetty, which is simpler. The only other thing needed is to tell Maven that this is a Boot application, rather than a Java one:

<build>
  <plugins>
    <plugin>
      <groupId>org.springframework.boot</groupId>
      <artifactId>spring-boot-maven-plugin</artifactId>
    </plugin>
  </plugins>
</build>

That’s pretty much it. If you now run up the application, it will start Jetty on port 8080 and the response will be a web page with the Persons loaded from the database.

JSON

Instead of delivering an HTML page as the payload, we can deliver a JSON string. This is all built into Spring Boot and is just a case of altering the definition of the index function:

  @RequestMapping("/")
  public Person[] index() {
    List personList = new ArrayList();
    personList.addAll((Collection) repository.findAll());
    return personList.toArray(new Person[0]);
  }

findAll returns an Iterable, so this needs to be converted to an array via ArrayList. The array of JobType objects is coded to JSON and sent as the response automatically.

Friday, 14 November 2014

Scaling Business Application Development with Play and Scala

Yesterday evening, I went to see a presentation by Peter Hilton at Skills Matter on using Scala and Play for small-scale development.


In an affable and down-to-earth manner, Peter went through two case studies that his company had handled, both small scale web developments in Holland, where he is based. This is somewhat unusual for Scala in particular and any JVM-based language in general: normally much "lighter" technologies, such as ASP.Net or PHP, are used.

He highlighted the use of a stack of technologies: Play, Scala, Slick (for database connectivity and access), PostgreSQL and MySQL for the database and Bootstrap for the website layout. In particular, he went through the use of Slick, which he recommended, as it has an unusual, more SQL, feel compared to other ORM's.

He also emphasised the speed of development and that the amount of code needed was much smaller than previous applications he'd developed: the first application was ~4000 lines and the second ~2000, which are both a lot smaller than the applications I've worked on. It was interesting to see how his team short-cutted: using social media for security (why not?) and Excel spreadsheet integration for record maintenance.

Overall, it was a good presentation about using Scala in a different way.

Sunday, 9 November 2014

It's The Rozzers! Welcome to the Punch, Robocop and Gotham

I've managed to watch some DVD's recently from my Amazon subscription (what used to be LoveFilm). First up is cops-and-robbers drama, Welcome to the Punch.

After being shot by career robber Jacob Sternwood (Mark Strong), detective Max Lewinsky (James McAvoy) seizes the opportunity for revenge when the formers son is found severely wounded.


Although it has it's moments, it's a little too domestic and small scale to impress as a good crime thriller. Strong is good enough to carry the role, but McAvoy has never impressed me that much and he's not much better in this. The supporting cast is pretty good, with Johnny Harris as the main villain and Peter Mullan as Sternwood's old partner, but the plot is a little tedious and uninspired. As I've said before with The Sweeney, the Americans do it better: they've got more money.

They're not always inspired or inspiring, though, and that brings us to Robocop (the remake). After being assassinated and left for dead, detective Alex Murphy (Joel Kinneman) is transformed by a large multinational into a new kind of policeman:


I don't really have the heart to slag it off as much as others have done. True, it does lack the novelty of the original, but then that's inevitable, given our world of drone strikes and cybercrime. The production is good and the supporting cast is excellent (Gary Oldman and Samuel L. Jackson), but Michael Keaton doesn't really impress as a villain. Perhaps that's the problem: Omnicorp isn't evil enough. Plus the original had a kind of grizzly humour, which is lacking in the remake. Clarence Bodikker (Kurtwood Smith), where are you when the film industry needs you?

Maybe it's in television? A new series has started in the 'States based on the DC Batman characters.

Jim Gordon (Ben McKenzie) joins the Gotham Police as a detective and is immediately struggling not only with his conscience, but survival itself:


It looks promising, with nods to the original characters such as The Penguin and The Riddler, but whether it gets too weird and/or camp remains to be seen. A good mark in it's favour is Donal Logue as Gordon's partner. His series, Terriers, was one of the best U.S. series ever made.


Apparently, it's available on Netflix.

Monday, 3 November 2014

Database Integration with Java

The other week I saw a presentation on InfoQ regarding Spring Data, so I thought I’d have a look at how Java connects to databases.

JDBC

The most basic way of connecting to a database in Java is to use JDBC (Java Database Connectivity). This involves creating suitable objects, establishing a connection to the database, executing a SQL statement and parsing the results:

try {
      Connection connection = null;
      ResultSet resultset = null;
      try {
        Class.forName("net.sourceforge.jtds.jdbc.Driver").newInstance();
        connection = DriverManager.getConnection("jdbc:jtds:sqlserver://localhost:1433/A_DB",
                                                 "aaron",
                                                 "********");
        Statement statement = connection.createStatement();
        resultset = statement.executeQuery("SELECT "
                                           + "firstName, "
                                           + "lastName, "
                                           + "gender "
                                           + "FROM person");
        Person person;
        while (resultset.next()) {
          person = new Person();
          person.setFirstName(resultset.getString("firstName"));
          person.setLastName(resultset.getString("lastName"));
          person.setGender(resultset.getString("gender"));
          System.out.println(person);
        }

      } finally {
        if (resultset != null) {
          resultset.close();
        }
        if (connection != null) {
          connection.close();
        }
      }
    } catch (ClassNotFoundException ex) {
      Logger.getLogger(ConnectingUsingJDBC.class.getName()).log(Level.SEVERE, null, ex);
    } catch (InstantiationException ex) {
      Logger.getLogger(ConnectingUsingJDBC.class.getName()).log(Level.SEVERE, null, ex);
    } catch (IllegalAccessException ex) {
      Logger.getLogger(ConnectingUsingJDBC.class.getName()).log(Level.SEVERE, null, ex);
    } catch (SQLException ex) {
      Logger.getLogger(ConnectingUsingJDBC.class.getName()).log(Level.SEVERE, null, ex);
    }

Legacy systems contain a lot of code just like this, or variations of. As you can see, there’s a lot of “boilerplate” code: connecting to the database; closing the connections and cleaning up afterwards; mapping the fields in the recordset to the attributes of the class, etc. However, it is standard with the JDK, which means you don’t need any third part library. You can also remove some of the boilerplate using the latest features such as multiple catches and try-with-resources:

try {
      Connection connection = null;
      ResultSet resultset = null
      Class.forName("net.sourceforge.jtds.jdbc.Driver").newInstance();
      try(connection = DriverManager.getConnection("jdbc:jtds:sqlserver://localhost:1433/A_DB",
                                                 "aaron",
                                                 "********");
        Statement statement = connection.createStatement();
        resultset = statement.executeQuery("SELECT "
                                           + "firstName, "
                                           + "lastName, "
                                           + "gender "
                                           + "FROM person")){
        Person person;
        while (resultset.next()) {
          person = new Person();
          person.setFirstName(resultset.getString("firstName"));
          person.setLastName(resultset.getString("lastName"));
          person.setGender(resultset.getString("gender"));
          System.out.println(person);
        }

      } finally {
        if (resultset != null) {
          resultset.close();
        }
        if (connection != null) {
          connection.close();
        }
      }
    } catch (InstantiationException | IllegalAccessException | SQLException | ClassNotFoundException ex) {
      Logger.getLogger(ConnectingUsingJDBC.class.getName()).log(Level.SEVERE, null, ex);
    }

Try-with-resources saves having to tidy up as it closes the resources for you. The multiple catch gain saves you some lines, but only if you do the same thing for every exception. This is now 34 lines as opposed to 53, but you still get the feeling that there’s an easier way to do this. And there is…

Hibernate

Look up the word “Object Relational Mapping” on Wikipedia and you get this:

“Object-relational mapping (ORM) is a programming technique for converting data between incompatible type systems in object-oriented programming languages. This creates, in effect, a "virtual object database" that can be used from within the programming language.”

In the list of ORM software for Java you’ll find a reference to Hibernate.

Essentially, what Hibernate does is map objects onto the result set fields, reducing the code even further, or, really, moving it somewhere else:

    Configuration config = new Configuration();
    config.configure();
    Session session = config.buildSessionFactory().openSession();

    Transaction tx = session.beginTransaction();
    try {
      List result = session.createQuery("from person").list();

      for (Person person : (List<Person>) result) {
        System.out.println(person);
      }
    } finally {
      tx.commit();
      session.close();
    }

The connection details are moved to an XML configuration file that, by default, is named hibernate.cfg.xml and contained in the root resources folder:

<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE hibernate-configuration PUBLIC "-//Hibernate/Hibernate Configuration DTD 3.0//EN" "http://hibernate.sourceforge.net/hibernate-configuration-3.0.dtd">
<hibernate-configuration>
  <session-factory>
    <property name="hibernate.connection.driver_class">net.sourceforge.jtds.jdbc.Driver</property>
    <property name="hibernate.connection.url">jdbc:jtds:sqlserver://localhost:1433/A_DB</property>
    <property name="hibernate.connection.username">aaron</property>
    <property name="hibernate.connection.password">********</property>
    <mapping resource="jobtype.hbm.xml"/>
  </session-factory>
</hibernate-configuration>

Notice that it refers to a “mapping resource”, in this case another XML file called “jobtype.hbm.xml”. This is where the details of the mapping are kept and it’s in the root folder again:

<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE hibernate-mapping PUBLIC "-//Hibernate/Hibernate Mapping DTD 3.0//EN" "http://www.hibernate.org/dtd/hibernate-mapping-3.0.dtd">
<hibernate-mapping>
  <class name="org.laughing.lemon.Person" table="person">
    <id column="ID" name="ID" type="int">
      <generator class="assigned"/>
    </id>
    <property column="firstName" name="firstName" type="string"/>
    <property column="lastName" name="lastName" type="string"/>
    <property column="gender" name="gender" type="string"/>
  </class>
</hibernate-mapping>

Notice that it’s mapped the class name to the table and the column names to the attribute names of the Person class. This, in turn, has to extend the Java Serializable interface:

import java.io.Serializable;

public class Person implements Serializable {

  private int ID;
  private String firstName;
  private String lastName;
  private String gender;

You still have to do the work (you can, in theory, leave the mapping if the column names and attribute names are the same and it will work out the mappings automatically, but better safe…), but it is now done in configuration files rather the Java. You also have to introduce some transaction handling for the first time, which was done automatically for you in the JDBC.

The problem with this is that it’s not a standard. There’s still a fair bit of messing around if I wanted to switch to different ORM software. To impose some kind of standardisation, Java now has JPA, the Java Persistence API.

JPA

This is not a library or framework of any kind, but a standard or specification that ORM’s now adhere to, usually by implementing a plug-in or extension, which is what Hibernate does. Thus Hibernate JPA:

    EntityManagerFactory entityManagerFactory =
          Persistence.createEntityManagerFactory("org.laughing.lemon");
    EntityManager entityManager = entityManagerFactory.createEntityManager();
    
    List<person> result = 
         entityManager.createQuery("from org.laughing.lemon.Person", Person.class).getResultList();
    for (Person person : result) {
      System.out.println(person);
    }

    entityManager.close();

Very similar to the Hibernate implementation and, like Hibernate, it takes the connection information from an XML file, in this case “persistence.xml”:

<?xml version="1.0" encoding="UTF-8"?>
<persistence version="2.1" xmlns="http://xmlns.jcp.org/xml/ns/persistence" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/persistence http://xmlns.jcp.org/xml/ns/persistence/persistence_2_1.xsd">
  <persistence-unit name="org.laughing.lemon" transaction-type="RESOURCE_LOCAL">
    <provider>org.hibernate.jpa.HibernatePersistenceProvider</provider>
    <class>org.laughing.lemon.Person</class>
    <properties>
      <property name="javax.persistence.jdbc.url" value="jdbc:jtds:sqlserver://localhost:1433/A_DB"/>
      <property name="javax.persistence.jdbc.password" value="********"/>
      <property name="javax.persistence.jdbc.driver" value="net.sourceforge.jtds.jdbc.Driver"/>
      <property name="javax.persistence.jdbc.user" value="aaron"/>
    </properties>
  </persistence-unit>
</persistence>

Notice that the persistence unit has a name that then gets used in the Java application. The mapping is done in the POJO class:

import java.io.Serializable;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.Id;
import javax.persistence.Table;

@Entity
@Table(name="person")
public class Person implements Serializable {

  @Id
  @Column(name="id")
  private int ID;
  @Column(name="firstname")
  private String firstName;
  @Column(name="lastname")
  private String lastName;
  @Column(name="gender")
  private String gender;

Conclusion

So far, I've shown three seperate ways that a Java application can connect to a database. JDBC is the most direct and basic, with Hibernate and JPA abstracting the database table to Java objects.

Saturday, 4 October 2014

Comic Reading

I've been reading a few of the latest trade paperbacks recently. First up is Mind Mgmt (no, not a misspelling) from Matt Kindt. A reporter and author, Meru, tries to complete her book on an airline flight where everyone lost their memory.


Although the art work is a little too sketchy for me, the story line is quite good, something along the lines of the TV series Fringe or "Life During Wartime" by Lucius Shepard, with secret organisations and mind control.

Following on from this was The Nowhere Men by Eric Stephenson (writer) and Nate Bellegarde (artist). Science multinational World Corp tries to recover some of it's employees lost during the explosion aboard a space station, while avoiding public exposure and fighting off the attentions of one of it's original founders.


Although the art work is pretty good, this first instalment was a little confused and fractured. Was it a story about the scientists who set up World Corp, or a story about the team aboard the station and what happened to them? It seems like an opportunity squandered at the moment, but, hopefully, it will improve.

The third is Sex Criminals, by Matt Fraction (writer) and Chip Zdarsky (artist). On finding they both have a unique ability, two people decide to use it rob banks, but find they don't have it all their own way...


Quite funny and an original story, the artwork is pleasing to the eye. I don't think it'll get onto TV, though.

Saturday, 13 September 2014

The Proactionary Imperative with Steve Fuller and Veronika Lipinska

Today I went to see a presentation hosted by the London Futurists at Birbeck regarding a new book about transhumanism.


The book is written by Steve and Veronika, two academics, one on science and philosophy, the other in law.


Their idea is that there is a trend in society of being over precautionary (the example was given of the Bush government's restrictions on stem cell development, severely inhibiting biotechnology in the 'States). Their counter to this is to examine the current state of transhumanism and to make some recommendations based on an idea proposed by Max More called the Proactionary Principal. This is to say that instead of trying to avoid the consequences of change by not changing, the risks should be managed on a national or even global scale, underwritten by governments and the benefits distributed by the same to all. They also propose an idea of "hegenetics", which is a portmanteau of genetics and hedge-fund, that when a person, or group, have their DNA exploited they can benefit from it. It's a bit like you or I copyrighting our own DNA.

The presentation was very engaging and the discussion afterwards lively, Steve noting that the Futurists aught to be more politically engaged than currently, and that it seemed to be more of a hobby than a movement.

Saturday, 6 September 2014

Brighton Mini-Maker Faire 2014

Today I went for a day out to Brighton to the Mini-Maker Faire. There was the usual collection of stands there, with rather a lot of 3D printers in evidence. There's a move to put 3D printers in every school!


There was also robots and sculpture and sculpture of robots:


There were also some very stange tricks with LED's. This is a set of spinning LEDs making a globe:


I went for a walk on the seafront afterwards and saw some rather good grafitti:


Monday, 25 August 2014

Using PowerMock to Test Singletons

Back to the Job again.

I've been trying to test a small suite of classes based around exception handling. One of the classes is a class factory implemented as a singleton, which has proved impossible to test with the usual techniques, i.e. sub-class and override and Mockito.

A class factory is a class used to create and initialise other classes. A singleton class is designed only to be instantiated once and then every use afterwards uses the same instance over and over again, rather than creating multiple copies of the same class.

Sub-class and override is a technique used to isolate various methods of a class during testing. Take a simple class like this:

public class DemoSuperClass {

    protected List createNameList() {
        List returnList = new ArrayList();

        returnList.add("Steve Stranger");
        returnList.add("James Jones");
        returnList.add("Harry Harnot");
        returnList.add("Bill Blogger");

        return returnList;
    } 

    public void printNameList() {
        List nameList = createNameList();
        for(String name: nameList)
            System.out.printLn(name.split(" ")[0]); //prints the first name
    }

}

Say you want to test printNameList but with an empty list of names, or different names. The best way to do this is in the test harness declare a sub-class of DemoSuperClass and override createNameList:

private class DemoSubClass { //class in the test harness

    @Override
    protected List createNameList() {
        List returnList = new ArrayList();
        return returnList;
    } 
}

Now the sub-class can be tested.

Even if the method being overridden is called by the constructor, it will still work:

public class DemoConstructorClass {

    protected DemoConstructorClass() {
        procedure1();
    }

    protected void procedure1() {
        System.out.println("procedure1");
    }
}

    //in the test harness
    private class TestDemoConstructor extends DemoConstructorClass {

        @Override
        protected void procedure1() {
            System.out.println("Overriden procedure1");
        }
        
    }


Where this won't work is in testing singletons. The singleton I'm trying to test looks something like this:

public class SingletonClass {
    private static SingletonClass instance = new SingletonClass();

    public static SingletonClass getInstance() {
        return instance;
    }
    
    protected SingletonClass() {
        procedure1();
    }

    protected void procedure1() {
        System.out.println("procedure1 called");
    }
}

    //in use, say, in the test harness
    SingletonClass instance = SingletonClass.getInstance();

Notice that the constructor is protected and cannot be accessed from outside the class. The only way to create the class is through getInstance and that returns the private static instance field created when the class is first referenced. Sub-classing and overriding has no effect, because the call to constructor happens as soon as the class gets referenced and the private static instance gets created. Mockito spies don't work either for the same reason. Enter PowerMock.

PowerMock is a set of libraries used to extend existing mock libraries, such as EasyMock and Mockito to cover situations where it's difficult to use them, such as static or final methods and constructors. In particular, the MemberModifier.replace method allows us to override methods (but only static ones) without instantiating the class.

    public static void replacement() {
        System.out.println("replacement");
    }
    
    public void testGetInstance() {
        //procedure1 has to be static to be replaced
        MemberModifier.replace(MemberModifier.method(SingletonClass.class,
                                                     "procedure1"))
                .with(MemberModifier.method(this.getClass(),
                                            "replacement"));
        SingletonClass result = SingletonClass.getInstance();
    }

It's a bit brute-force, and with better design of the singleton class maybe unnecessary, but at least it can now be tested.

Saturday, 16 August 2014

The Future of Futurism with Amy Zalman

Today I went to see a speech, hosted by the London Futurists, by Amy Zalman, who is CEO of the World Future Society.


Amy introduced herself. She's worked in various strategy think tanks and the like, including the U.S. War College. She wants to promote futurism and the futurist profession, intoducing the idea of the "Now" futurist.

There was a lively Q&A afterwards, which was, to some extent, more interesting that the main speech.

Monday, 4 August 2014

Rhythms of the World 2014

This Saturday I went to the Rhythms of the World festival in Hitchin with my mate John:


He and his wife, Alison, are moving to France shortly, so this may be the last time we do the gig together. Jill, the organiser, was somewhat disappointed to hear that he wouldn't be able to do it in future, misguidedly attempting to dissuade him by pointing out that France was full of French people.

We did our usual four hour shift and caught an excellent sitar player, Mehboob Nadeem, half way through his set:


Truly excellent!

I also spotted the mural, done every year:


Exhausted, we had our free lunch and retired gracefully. I tell you now, if you had to pick up dog ends for four hours, you wouldn't smoke!