Home > Java, JavaOne > JavaOne day four

JavaOne day four

I have to admit that I went to the session at midday. All the late past nights, the constant attention of the sessions and the club we went last night took a toll on me and I wasn’t there on time. So I only managed to attend four sessions and unfortunatelyl I missed the session with the Swing extensions 😦 

Distributed client-server persistence with JPA  by Alexander Snaps

The session started with a few words and code examples of how to use JavaDB. Then the speaker went on explaining what an object relational mapping is and what are the benefits of using it.

An object relational mapping

  • eliminates the need for JDBC
  • provides object identity management
  • provides inheritance strategies (class hierarchies to single or multiple tables)
  • provides associations and compositions (lazy navigation, fetching strategies)
  • provides transparency

The JPA is vendor independent ORM solution, it is easily configurable (configuration can be done directly in code using Java 5 annotations or you can override annotations and XML). JPA implementations are also available outside a J2EE container and there is a dedicated JSR (JSR 317)  as of JPA2.0

It provides (almost) transparent POJO persistence

  • non-final class or methods
  • constructor with no argument
  • collections typed to interfaces
  • associations aren’t managed for you
  • database identifier field.

Entity sample code 

@Entity
public class Person
{
    @Id
    private Long id;
 
    @ManyToOne
    private Company company;

    @OneToMany(mappedBy=”resident”)
    private Set<Address> addresses;
}

The persistence can be managed by using an EntityManagerFactory which is created by the persistence based on a persistence unit name. The EntityManagerFactory in turn creates EntityManager instances and the EntityManager instances know how to handle the persistence of the entities. Use a Query object to query the entities back from the database. An EntityTranaction class is used for transaction demarcation.

The persistent unit can also be set up by using an XML file

<persistence-unit name=”persistenceUnitName”
        transaction-type=”RESOURCE_LOCAL”>
  <provider>
    oracle.toplink.essentials.PersistenceProvider
  </provider>
  <class>some.domain.Class</class>
  ...
</persistence-unit>

There are managed and detached entities. Managed entities have their state being synchronised back to the database transparently for you (no need to call a persist operation on managed instances and the status is flushed to the database automatically). Detached entities on the other hand are not managed any more after they have been persisted. If the state needs to be saved back to the database this requires a merge operation.

Of course there are a few pitfalls

  • transaction management (no need for long living transactions)
  • exception handling (as entities become detached)
  • transaction rollbacks

JPA can be used nicely with Swing. Model View Controller (MVC) is still a good way to design the user interface and layered MVC makes even better match. 

Each MVC layer can 

  • have its own persistent context
  • inherit the one from its parent controller

events can 

  • be MVC local
  • propagate down to child
  • or to the entire tree

At this point they presented a nice Swing and JPA demo.

The data can be distributed by

  • client/server with off-line mode
  • distributed data sets
  • sharing data(it means everyone can update the data)

But the difference of distributed data is that the server and the client might see different data. There might be

  • different database identifier
  • maybe the database itself
  • the JPA implementation used
  • the entities that can be altered on each side

You can use the Holchoko framework. In order to use it you have to define a client side

  • client keeps track of “pairs”
  • a pair is a local and remote ids for an entity
  • the id can be represented by any Serializable type
  • communicates to server through a “filter”

How do we synchronise the state to clients?

  • server simply sends entities to the client
  • sending entities over wires makes them (the entities) detached automatically
  • client changes id field to the local value matching the remote identity
  • client merges the detached entities with the current local persistence context

How do we synchronise the state back to the server?

  • client sends entities to server (after having replaced local id with remote ones)
  • entities with remote id are being references in value holder object (that also hold the local id value)
  • value holders are being send back to the client (holding the identity matches)
  • entity matches are persisted locally for future reference
  • All that currently happens over HTTP

In summary JPA and JavaDB really ease persistence, even on the desktop, all this abstraction pays out and enables distributed persistence, it enables you to DRY and KISS.

For more info

javadb website

 

Design patterns reconsidered  by Alex Miller

The session started by explaining what is a design pattern. In a few words a design pattern is a common solution to a recurring problem. The epitome of the design patterns is considered the “Design patterns, elements of re-usable object oriented software” by Gamma at all published in1994.

There are three types of design patterns

  • creational
  • structural
  • behavioural

The programming language you have solve a problem affects how you think about it.

But there is also the patterns backlash. Some people claim that patterns stop people from thinking. they encourage 

  • copy/paste
  • design by template
  • cookbook/recipe approach

People might not understand what they are doing. “The design pattern solution is to turn the programmer into a fancy macro processor” – M.J.Dominous

Other people also claim that the design patterns are not patterns; they are just workarounds for language missing features. “At code level, most design patterns are code smell” – Stuart Halloway

Overuse is another thing you see thrown around here and then. “Beginning developers never met a  pattern or an object they didn’t like. Encouraging them to experiment with patterns is like throwing gasoline on a fire” – Jeff Atwood, coding horror

The practical patterns are not just code you throw around, they talk about real design issues and help us compare alternatives and found the best solution and understand of a particular problem.

The singleton pattern is simple: I want one instance of a particular class in a system. We create a static instance and provide an accessor method, then hide the ability to create more.

Things that can go wrong;. If you need to test the singleton, how do you mock the singleton? You might not even know that a piece of code uses a singleton. This kind of singleton creates a hidden coupling which means it’s hard to pick up a piece of code in your design and test it in isolation. It’s  hard to test/maintain/evolve.

Singleton has issues.

  • Hidden coupling
  • testing
  • possible memory leak
  • sub classing (it’s possible but its pretty ugly)
  • initialisation order and dependencies if you have a lot of singletons

We address these issues by having an interface and an implementation. Dependency injection comes to the rescue

public class InnocentBystander
{
    private final Singleton singleton;

    public InnocentBystander(Singleton singleton)
    {
        this.singleton = singleton;
    }
}

Testing

public class testInnocentBystander
{
    public void testSomething()
    {
        Singleton s = new MockSingleton();
        InnocentBystander bystander = new InnocentBystander(s);
    }

}

So if you only need one instance of an object you can control it by configuration, not by pattern. You can use Guice, Spring or injection by hand.

The template method pattern. This pattern deals with a template method which (the template method) is essentially a pluggable algorithm. When you subclass the algorithm you need to define details of what’s happening in an algorithm. Take for example the class Controller in Spring. You create a very complex API to get the functionality you need. You have an algorithm and a couple of sub-classes and then you find out that one of the subclasses needs more implementation and this can go on and on. You have to subclass you have no other choice. This makes things complicated. 

With template method you are fighting over inheritance. Think about a Map and subclasses, all of them have a different implementation. If you need functionality from more than one subclass you need to subclass even more.

Alternative to inheritance is composition. When you subclass you bring in all protected and public methods from parent class. It’s unclear often which ones you need to implement. With composition you split the algorithm in different steps and then you inject them to the class you need. It’s a naïve strategy (most likely it’s going to be more fine grained for what we need and therefore there might be a better model).

What about use of context class in template methods? You can create a context class in the algorithm and pass it into the different steps.

Can closures help us with this? If you have them you can use them to replace the strategy pattern.

What have we learned so far? We should prefer composition to inheritance. Composition 

  • allows better use of the pieces functionality
  • it communicates better
  • easier to understand
  • easier to maintain and more robust as it evolves. 
  • Inheritance is a very strong form of coupling, a dependency in your code.

The visitor pattern comes out when you use a composite hierarchy. For example when you have a   Node class and then a CompositeNode class as a leaf. The visitor addresses that and instead of having a bunch operations in every node, you have one generic method (which takes a visitor) and put it on in any one of them. Then you can define visitors at will without changing your data structure.

public interface Visitable
{
    void acceptVisitor(Visitor visitor);
}

public interface Visitor
{
    void Visit(ConcreteNode1 node1);
}

public class ConcreteNode1 implements Visitable
{
    public void acceptVisitor(Visitor visitor)
    {
        visitor.visitor(this);
    }
}

The visitor pattern allows you to add new operations easily, so we can add easily visitor types.

There are some common visitor types

  • collector visitor (collect and accumulate for return)
  • finder visitor (return immediately when match found)
  • event visitor (stateless, fire events for subset of nodes)
  • transform visitor
  • validation visitor

You can simplify visitors with many similar methods if you dynamically assemble them with closures.

Some design principles are

  • use interfaces and dependency injection to reduce coupling
  • favour composition over inheritance
  • separate logic that will evolve at different rates
  • rely on object identity as little as possible
  • leverage static typing and generics

In summary

  • design patterns are a valuable tool to describe real programming model
  • solutions to all design problems are contextual (dependent on language, the code base and the developers themselves)
  • use design patterns as a starting point to discuss alternative.

 

Taming the Leopard: Extending OS X the Java™ Technology Way with Tim Gleason and Jonathan Maron

The session started by presenting how you can extend the mac OS-X for Java.

There are two different types of plugins

  • quicklook
  • spotlight importers

And also two different types of events

  • spotlights
  • fsevents (monitoring a file system for changes)

The quicklook (you get a preview of the file without opening it) plugin

  • written in objective-c
  • implement a number of standard interface methods
  • render a representation of the file type (can be heavyweight GUI, typically developers seem to leverage native platform display capabilities)

The interface for the quicklook plugin is as follows

public interface QuickLookGenerator
{
    public String generateHTMLForPath(String path);
}

In order to build the plugin one needs to 

  • implement the QuickLookGenerator interface
  • create a jar file
  • place jar file and dependencies in a directory
  • update plugin properties file
  • run “ant generate plugin”
  • copy generated plugin directory to /Libary/… plugin folder

Then a demo of building a plugin followed.

The spotlight plugin

  • local box/network wide search/metadata feature
  • extensible
  • xcode spotlight plugin template
  • written in objective-C
public interface SpotlightImporter
{
    public Map<String, Object> importFile(String path);
}

In order to build the spotlight plugin one needs to implement the SpotlightImporter interface and follow the same steps as the QuickLookGenerator plugin.

A simialr demo followed of how to build a spotlight extension.

The spotlight can use a query language to do a search. The query language

  • has sql “where clause” like syntax (wildcards, scoped to certain directories)
  • can query over any file metadata attributes and can be scoped to directories

The Java FSEvent can receive notification of file system modifications. 

 

The future of Guice by Bob Lee

This was the coolest session of all I have attended. It wasn’t exactly like a session but more of a friendly chat with beers and laughs. Google bought several beers and everyone at the session had the chance to have a relaxed conversation with the Guice guys over a few bottles of beer. 

The chat started by Bob going through the philosophy behind Guice. This was similar to what he had said in JavaPolis last year. All in all the philosophy of Guice is

  • back to basics
  • @inject is the new “new” brevity of “new”, flexibility of a factory
  • fail early but no too early (try all possible ways)
  • make it easy to do the right thing
  • types are the natural currency of java
  • prefer annotations to convention
  • singleton’s aren’t bad – the typical implementation is
  • focus on readability over write-ability
  • maximise power-to-weight ration of API
  • balance – just because you can doesn’t necessarily mean you should

The goals for Guice 2.0 are

  • relieving pain point
  • compatibility with 1.0
  • extensibility
  • tool support (last summer they had an intern developer for an eclipse plugin)
  • shooting for Summer 2008 release

They also announced that Jesse Wilson (from the glazed lists project) is the latest member of the team.

The core features of Guice 2.0 will be:

  • mirror API (it’s the Software Service Provider, for people who want to have fairly deep integration with Guice, like writing Guice extensions, or you want to hook up Guice to a 3rd party tools)
  • tool stage (when you call Guice.createInjector() it does a lot of work, this is a mechanism to create injector that is indented for tools to use)
  • binder.getProvider() (you are writing a module and you want another module to provide some other binding. This is an API where in your module you can get a provider and when the application starts up all dependencies are available)
  • class/constructor listeners (the idea is that if you build arbitrarily complex framework like EJBs you can use Guice to be your hosting environment. Guice can give you the opportunity to have a hook and use all the cool ELP stuff with reflection. This is a way to write very powerful aspect code)
  • multi-bindings (it lets you bind the same type as many times as you want. It’s fairly often requested feature)
  • constant type converters
  • @nullable (you can inject null, so Guice knows that null is a valid value)
  • enhanced error reporting
  • specified exception handling (whenever you throw from a provider get method you catch a ProvisionException)
  • module overrides (someone else gave you a module and that module has a dependency you don’t really want, this lets you say “take this module but whenever a certain binding happens I want another binding to happen instead)

Provider methods have been improved 

Old code:

bind(new TypeLiteral<Set<String>>(){})
    .annotatedWith(new HostNameImpl(“servers”))
    .toProvider(new Provider<Set<String>>()
    {
        @Inject Provider<User> userProvider;
        public Set<String> get()
        {
            User user = userProvider.get();
            return user.isImpatient()
                ? ImmutableSet.of(“azul”)
                : ImmutableSet.of(“tandy”, “commodore”);
        }
    });

New code:

@Provides @HostName(“servers”)
public Set<String> provideServerNames(User user)
{
    return user.isImpatient()
                ? ImmutableSet.of(“azul”)
                : ImmutableSet.of(“tandy”, “commodore”);
}

(At this point the Guice team complained that there were still so many beers left and we all helped ourselves to some more)

The Eclipse rich tool is almost ready. It lets you search for bindings and when you give it a type it lets you go to this binging. IntelliJ and NetBeans tools will follow shortly after the Eclipse one is released.

Thoughts about improving Guice beyond the 2.0 version. 

  • compile-time Guice (if you don’t like reflection this project will let you take a Guice module and convert it to Java code that is equivalent but has no reflection)
  • 3rd party extensions like warp, GuiceBerry (they use Guice to inject unit, functional and integration tests), Peaberry OSGI (extends Guice to support dependency injection of dynamic services. It provides OSGi integration out of the box).

(as a side note it was nice to see Joshua Bloch in the Guice session)

Q&As

Can I support custom annotations? Yes, this is where the class/constructors listeners come into place. 

Are there any plans to support things like XML configuration? They are going to provide the hooks to build our own stuff with them.

Do you take advantage of any class loader hooks? They don’t need to because they don’t do anything magical. Its simply reflection.

Do they look it favourably if releases happen more often or if they happen less often? Frequent releases could be a bad or a good thing. The Guice team does not necessarily push out releases but they need to be careful when they release because they have to be convinced that something is good.

Advertisements
Categories: Java, JavaOne
  1. No comments yet.
  1. No trackbacks yet.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: