Wednesday, December 29, 2010

OxenIoC: an IoC container for Objective C

Last year I've been working on two applications for IPhone with several views and core data entities, a lot of classes that really are hard to maintain. These projects were started on september of 2009 by other company. In 2010 we received this legacy and we are still adding features and new versions on the store.
I know that iPhone applications are not really big applications but we think that an IoC Container can help to do applications like these a little more maintainable. This is the reason because we decided make a proof of concept with an IoC container. Now we going to explain what we did.

The main concern is how we are going to specify the objects for the container. We took two approaches, the first one consist in specifying the objects from code and the second one in reading the context from XML.

Specifying context from code

For this approach we have the class IoCObjectDefinition wich can specify, a name, a class name, if it's singleton, if it's lazy and the references.

Here's an example:

- (IoCContainer *) buildContainerFromCode {
  IoCContainer *container = [[IoCContainer alloc] init];

  IoCObjectDefinition *serviceDefinition = [[IoCObjectDefinition alloc] init];
  serviceDefinition.name = @"theService";
  serviceDefinition.className = @"ExampleServiceImpl1";
  serviceDefinition.lazy = NO;
  [container addDefinition:serviceDefinition];
  [serviceDefinition release];

  IoCObjectDefinition *serviceExecutorDef = [[IoCObjectDefinition alloc] init];
  serviceExecutorDef.name = @"theExecutor";
  serviceExecutorDef.className = @"ServiceExecutorImpl1";

  // inject theService to serviceExecutor
  [serviceExecutorDef addPropertyReference:@"service" toObjectName:@"theService"];

  [container addDefinition:serviceExecutorDef];
  [serviceExecutorDef release];

  return [container autorelease];
}



Specifying references from code

Also you can specify the injection of objects in the class code. The macro called IoCContainerInject(property,objectName)


provides such functionality. Here's an example,

@implementation ServiceExecutorImpl2
  @synthesize service;

  //Inject theService object to service property
  IoCContainerInject(service, theService)

  - (void) executeService {
    [service execute];
  }
@end



Specifying objects from an XML

Also you can specify the same context by XML. Here's the example,

<contanier>  

  <object id="theService" class="ExampleServiceImpl2" lazy="false"/>  

  <object id="theExecutor" class="ServiceExecutorImpl1">
    <property name="service" ref="theService"/>  
  </object>

</contanier>




Getting objects from container

We have the class IoCContainer. This class have the method - (id) getObject: (NSString*) name;

Here's an example:

id<ServiceExecutor> executorFromCode = [containerFromCode getObject:@"theExecutor"];

Application example

We uploaded an app example in order to show these concepts.

This application has 3 contexts, one built from code other built from an XML and the last one built from code but inject the reference by the macro.

This app has 2 protocols,

  1. ExampleService with a method named execute.
  2. ServiceExecutor with a method named executeService. ServiceExecutors have an ExampleService.

There are 2 implementations for each of these protocols.


  • ExampleServiceImpl1 the execute method write in log Service Implementation 1.
  • ExampleServiceImpl2 the execute method write in log Service Implementation 2.
  • ServiceExecutorImpl1 is a class with a property of kind id.
  • ServiceExecutorImpl2 is a class with a property of kind id that specifies the injection of the object called "theService".

OxenIoCAppDelegate builds the 3 contexts wiring those objects in different ways, then it gets the 3 serviceExecutors and executes them.


What's next

We will try to find out how to reduce the code to write for adding objects to container. We think that conventions and default values could help.

Monday, December 20, 2010

CodePro AnalytiX first impression

I'm evaluating CodePro AnalytiX in order to use it in a project. We're currently using Checkstyle.

At first sight, it seems that CodePro AnalytiX is more strict and validates more topics. However, I'm just trying the default configuration.


  • It suggest you always overriding toString() method.
  • Checkstyle ignores the lack of Javadoc comment if the method has an @Override annotation. CodePro doesn't. Also, CodePro doesn't take in account the {@inheritDoc} Javadoc annotation, so you must specify all the method documentation (even for toString(), for example).
  • There is a validation for package names: they should start with a reverse domain name.
  • It suggest not using String literals. You can add an //$NON-NLS-1$ comment for Strings that are not internationalized.
  • Constants ending with digits (for example, TEXT_1) produces a warning.
  • The use of System.out is discouraged.
  • Checkstyle asked variable parameters to be final. CodePro suggest local variables to be final too.


However, the scope of CodePro goes beyond syntax checking. It also has metrics reports and code analisys (for example, detecting dead and duplicated code). So it could be compared with PMD and FindBugs too. But this, my friends, is is matter for another post :)

Sunday, December 5, 2010

Adding dependency injection to jMonkeyEngine with Google Guice

I'been playing for a while with jMonkeyEngine 3. I downloaded the SDK and tried the starter tutorial series. I recommend you reading these tutorials before reading this post.

The examples where created extending the SimpleApplication class, which provides many services as instance variables, such as instances of AssetManager, AppSettings, etc. All the examples were written in a single class. I wanted to split the functionality into smaller classes, so I needed to pass such references to other classes. A way to implement this in a generic way could be integrating Google Guice. I recommend you reading some basics about Guice too.

I built 3 annotations:
  • GuiNodeRef: for injecting a reference to guiNode instance.
  • AssetManagerRef: for injecting a reference to assetManager instance.
  • AppSettingsRef: for injecting a reference to appSettings instance.
A new base application class, GuiceApplication, will create and configure the injector:

public abstract class GuiceApplication extends SimpleApplication {

    private Injector injector;

    @Override
    public final void simpleInitApp() {
        /* building modules */
        Collection<module> modules = new LinkedList<module>();

        modules.add(new AbstractModule() {

            @Override
            protected void configure() {
                bind(AssetManager.class).annotatedWith(AssetManagerRef.class).toInstance(assetManager);
                bind(Node.class).annotatedWith(GuiNodeRef.class).toInstance(guiNode);
                bind(AppSettings.class).annotatedWith(AppSettingsRef.class).toInstance(settings);
            }
        });

        this.addApplicationModules(modules);

        this.injector = Guice.createInjector(modules);
        this.injector.injectMembers(this);

        this.guiceAppInit();
    }

    public abstract void guiceAppInit();

    protected void addApplicationModules(Collection<module> modules) {
    }
}

The simpleInitApp, which is inherited from SimpleApplication, creates the injector, configures it using a collection of modules, injects application members, and calls the abstract guiceAppInit method. A module that binds the three annotations mentioned before is provided by default, but you can add custom modules by overriding the addApplicationModules method. I took this idea from RoboGuice, which is  a framework that we are using at LeapFactor in order to integrate Guice into Android.

Now you can define injections in the application or in classes injected into the application. Injecting defined annotations would look like this:

@Inject
private @AssetManagerRef AssetManager assetManager;

@Inject
private @GuiNodeRef Node guiNode;

@Inject
private @AppSettingsRef AppSettings settings;
...


I tried it creating a simple Breakout-Arkanoid-like (without bricks :P) game. When I got my first computer in 1988, I started learning Sinclair Basic by writing a simple brick game. I called it Batty II, since I had a tape with (the excellent!) Batty game. This will be a remake, so I called Batty II too. You can download it here. I used the same guice-2.0-no_aop.jar that we used for Android at LeapFactor in order to avoid unnecessary dependencies.

Here you have some screenshots:


Mmmm, the physics engine makes the paddle rotate! This didn't happened with my CZ Spectrum+!


And finally, a friendly message indicating that the game is over:






Sunday, November 28, 2010

A pattern? for keyboard handling with Swing

Recently, working in a Swing-based project for System (OpenbravoPos), we needed to build a generic keyboard handling mechanism. The following requirements were mandatory:


  • It must be possible to fire key-mapped logic in two ways:
    • Regardless of current widget focus.
    • Capturing key event on an specific widget (because OpenbravoPos main sales panel uses a hidden text field in order to handle all the key events).
  • Logic can be specified using:
    • Custom Java code
    • BeanShell scripts, stored in an XML file.
  • Key mapping must be easily changed when active window changes.



We built a three classes schema, which is based on some functionalities provided by Swing, but it could be ported to other UI frameworks as well. I'll describe the approach (the names of classes and methods are not exactly the same, but I'm trying to give an overall idea).

First of all, a interface called KeyHandler acts as callback for keyboard events. This allows us:

  • Creating custom Java-based key handlers, using inner classes.
  • Create generic BeanShell key handlers, which are populated by a process that reads definitions from the before mentioned XML file.

The interface provides just a method:

public void onKey(int keyCode, int keyModifiers);

In second place, a class called KeyboardManager maps keys (and modifiers) to KeyHandlers:

public void registerKeyHandler(KeyHandler keyHandler, int keyCode, int keyModifiers);

The process that reads keys definitions from XML must also register the keys in the KeyboardManager. Also, this class can fire the logic associated with a specific key:

public void triggerKeyEvent(int keyCode, int keyModifiers);

Now, with a KeyboardManager properly created and configured, we can call its triggerKeyEvent on a widget key event listener in order to respond to key events.

And finally, in order to meet the requirement of being able of map keys without using a widget event listener, there is a 3rd class, KeyboardDispatcher. This class is responsible for activating/deactivating KeyboardManagers, with an stack-like approach:

public void pushKeyboardManager(KeyboardManager keyboardManager);
public void popKeyboardManager();

Typically, the push method is called when the panel is activated and the the pop method, on deactivate event. Internally, the class uses Swing's KeyboardFocusManager and KeyEventDispatcher classes.

This approach works well for panels and windows that are opened in a LIFO way (for example, modal windows called from a panel). The main problem is that it doesn't support mixing multiple KeyboardManagers into the same  KeyboardDispatcher.

By the way, the “pattern” word in the title is there just for marketing purposes :P

For updates, subscribe to http://groups.google.com/group/oxen-software-studio.

Friday, October 8, 2010

WindowBuilder Pro brief sample – Part 3 of 3

In my previous post, WindowBuilder Pro brief sample – Part 2 of 3, I explained how to create a simple Swing frame with WindowsBuilder Pro. This time, I'm going to make some examples using SWT and Eclipse RCP.

The SWT plugin has biding capabilities that are similar to the Swing one (which I tested in my previous post), so I'm not going to cover them in this post. I prefer to show you integration with Eclipse RCP, which is really cool (sometimes, when I test new frameworks and tools, I feel like Hommer criticizing dinner).

The plugin can create a new SWT / JFace project, but this just adds such libraries to the project. I't is nice if you want to play for a while with SWT shells and JFace components.



But if we want to build an Eclipse RCP project, we must use the standard Eclipse option, Plugin Project:


You'll need the Eclipse Plug-in Development Environment installed. I recommend you reading this excellent Eclipse RCP tutorial before trying this one. At least, read the installation section.

Put any name for the project on the first wizard page. On the second one:


be sure of checking "This plug-in makes contributions to the UI" and choosing "yes" on "Would you like to create a rich client application?" radiobutton.

On the next step, select "RCP application with a view" template (some Eclipse versions have other templates, in such cases, look for a template that creates a view and a perspective).



In the last step, be sure of selecting "Add branding" option:



The wizard will create a View and a Perspective.  You can edit them just by opening with the graphical editor provided by the plugin. Let's add a button to the generated view. Before dropping the button, I recommend you dropping an absolute layout.




In order to run the application, select Run As -> Eclipse Application in project contextual menu. Something like this should appear:


Now, we aere going to add a new View and a new  Perspective. Start adding the view by selecting New -> WindowBuilder -> SWT Designer -> View Part. Follow the same path in order to create a Perspective. I'm going to call MyView and MyPerspective.

If you open the MANIFEST.MF file, you will see that the plugin automatically edited it in order to add the perspective. Cool.


Now, let's play with the perspective editor. Drop on it both, the first generated view and the new one. They appear in the "other" section.


And as last step (I promise), add the following line:

configurer.setShowPerspectiveBar(true);

to the preWindowOpen method on ApplicationWorkbenchWindowAdvisor class. Now, running the project, you should see something like this:


Changing the perspective, you will see the one that you created:


And that's all folks. I hope you enjoyed this three-steps tutorial.

Related posts:



Monday, October 4, 2010

New Group for Notifications

Since Blogger doesn't automatically notifies followers (too bad!), I just created a Google Group. I configured the blog so each time a new post is published, it is notified to oxen-software-studio@googlegroups.com.

In order to subscribe to the group, please go to:

http://groups.google.com/group/oxen-software-studio

Regards

Lautaro

Friday, October 1, 2010

WindowBuilder Pro brief sample – Part 2 of 3

Last week we started testing WindowBuilder Pro and created a simple GWT example project. This time I'm going to show you how to create a Swing project.

There is no specific Swing project option, so we should just create a standard Java project:


After creating the project we are going to create a JFrame class:


On the next screen, enter names for class and package (I'm going to put ar.com.oxen.test.swing - the main purpose of this blog is to make publicity for Oxen :P). When finished, you should have a class like this one:

package ar.com.oxen.test.swing;

import java.awt.BorderLayout;

public class MyFrame extends JFrame {

 private JPanel contentPane;

 /**
  * Launch the application.
  */
 public static void main(String[] args) {
  EventQueue.invokeLater(new Runnable() {
   public void run() {
    try {
     MyFrame frame = new MyFrame();
     frame.setVisible(true);
    } catch (Exception e) {
     e.printStackTrace();
    }
   }
  });
 }

 /**
  * Create the frame.
  */
 public MyFrame() {
  setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
  setBounds(100, 100, 450, 300);
  contentPane = new JPanel();
  contentPane.setBorder(new EmptyBorder(5, 5, 5, 5));
  contentPane.setLayout(new BorderLayout(0, 0));
  setContentPane(contentPane);
 }

}

It's worth noting that the wizard created a main method, so we can just run the frame as a ordinary Java application.

In order to edit the frame, we must open the file and select the design tab:


By default, the frame has a BorderLayout. You can use any layout of your preference, depending the needs of your application UI (just drag the layout over the panel). I'm going to use an absolute layout just for this example. After adding A couple of JLabels and JTextFields, we have a nice registration screen:


In order to make the code more readable, be sure of putting a meaningful name in each JTextField variable name (properties view on design editor):


Now, I'm going to show you a pretty cool feature: bindings. With bindings, you can link values between object properties without writing specific code, which eases the implementation of MVC and MVP patterns. With this Swing plugin, a 3rd party library (org.jdesktop.beansbinding) is used. The editor allows a graphical and intuitive definition of such bindings. The SWT plugin has binding support also, but I'm going to test ti on the next post.

Let's begin by adding a JCheckBox for  enabling e-mail notifications (in our imaginary example).


Now, on the bindings tab, we are going to add a new binding, selecting the enabled property of the e-mail text field on Target (left) and selected property of checkbox on Model (right).


There is an option for selecting beans or widgets. For this binding, both sides must be widgets:


Add the binding by clicking on any of the + buttons:


Select READ on UpdateStrategy. This means that when the model is changed, the value is copied into the target. A READ_ONCE strategy makes a copy only one time (when the panel is shown) and a READ_WRITE strategy makes a bidirectional binding.

When you add the binding, you can specify a data converter and a data validator, but I'm not going to cover them on this post.

Now, when you run the example, the e-mail text field is enabled/disabled according to checkbox selection. If you don't believe me, just try it :)

Now, we are going to add a model bean. Let's suppose we have a Person bean which holds the name and the e-mail:

package ar.com.oxen.test.swing;

public class Person {
 private String name;
 private String email = "johann.sebastian@mastropiero.org.ar";

 public String getName() {
  return name;
 }

 public void setName(String name) {
  this.name = name;
 }

 public String getEmail() {
  return email;
 }

 public void setEmail(String email) {
  this.email = email;
 }
}

I intentionally put a default value on the e-mail just to show the bidirectionally of the binding. Now, we must add a Person property on the JFrame:



After that, we must add two READ_WRITE bindings from name and email to their respective field text properties (remember selecting "Bean" on Model panel):


This should wire all the properties. Just to test it, we are going to add a button that shows person data on a dialog. In order to achieve this, an action event handler must be added:



the code for the event handler could be as follows:

btnShowPerson.addActionListener(new ActionListener() {
    public void actionPerformed(ActionEvent e) {
        JOptionPane.showMessageDialog(null, "Name: " + person.getName()
                + " and e-mail:" + person.getEmail(), "Person data",
                JOptionPane.PLAIN_MESSAGE, null);
    }
});

This should be enough for running the example.

This is all for this post. I hope you enjoyed this mini-tutorial. On the next post (and last one of this serie) I'll play for a while with SWT/JFace editor.

Related posts:

Thursday, September 23, 2010

WindowBuilder Pro brief sample – Part 1 of 3

Last week, Eclipse users received good news: Google relaunched Instantiations tools for free. Not just for GWT, but for all the technologies supported by the suite.

When I read the notice, my mind went back to 2005, when I tried to use Eclipse Visual Editor in a project. It was a little frustrating since the plugin didn't worked very well. Back in that moment, I didn't find any good free SWT/Swing editor for Eclipse.

Currently at Oxen, we have a customer that uses NetBeans. Since I´m an Eclipse fan, we always make fun kidding about which one is the best. But when the discussion turned about visual editor, it was clear that NetBeans surpassed Eclipse. Now, it's time for revenge :)

So, let's make a brief review of WindowBuilder Pro. The first step is to install the tool through an update site, as explained here.

There is another update site just for GWT Designer, but it seems that WindowBuilder Pro site includes all the tools (for GWT, Swing, SWT and so on).

The first thing that causes a good impression is the number of things that can be created using the plugin.




(wow, Mac OSX screenshots... today you can't make a post showing Linux/Windows images... it wouldn't be cool enough!!!)

Talking seriously... Too many options! We are going to try just some of them. Let's begin with a GWT project:



The second screen will ask us for GWT installation directory. If you don't have it installed, download it from here.


On the following screen, select “Create GWT module” and enter names for module and package:


The support for Ext GWT, GWT-Ext and Smart GWT is pretty cool. I would found it useful two years ago, when I developed an application using GWT-Ext (currently superseded by Smart GWT). Now I'm working in a project that uses Vaadin. But Vaadin support would be too much happiness for a single tool.

On the next screen, select a name for your project... and that's it! Your'e ready to edit the module with the two-way editor:



As a negative point, the first access to the editor is really slow. It seems that it uses something from GWT hosted mode. After the editor is started, it's use is relatively fast (well, I didn't tried creating very complex layout).

In order to test the application, select Run As → GWT Application over the project. This will start GWT in hosted mode.



The hosted mode requires installing a plugin on the browser. Too bad that such plugin is not available for Google Chrome on Mac OSX. I needed to use Safari.



So, that's all folks! (for today). It's late and I'm pretty tired. On next posts I'll make some examples with Swing and SWT. See you, good night!

Related posts:


Monday, September 20, 2010

Generic MVP with Properties and binding

A few months ago at Oxen we started an Android project. It was our first Android project (which made us very happy since we're working for iPhone until that moment :P - goodbye Objective C, at least for a while).

The application required a lot of forms (login, signup, etc.) and we built an ad-hoc FormBuilder class that dynamically binded UI fields to model beans. But this was an application-specific solution. We realized that Android didn't provided a form-to-bean binding facility.

For future projects, we stared a proof-of-concept: to build a generic binder for Android. After reading some sites explaining the Model View Presenter pattern, we thought that it would be possible to create a generic MVP implementation, not just for android, but in a technology-agnostic way.

Our first try was to abstract property and event acces. We built two interfaces:

public interface ActionAccessor {
   Observable getActionNotifier();
}


and

public interface PropertyAccessor extends ActionAccessor {
    Object getValue();
    void setValue(Object newValue);
}


Plus, we created a Binder class that connects properties, propagating changes from one to another. This allowed us to build a generic view presenter, with a generic presentation model, binded to both, UI components and to a bean model. We tested it creating both, Vaadin and Swing PropertyAccessors.

This model could be used to implement validations and data conversion.

The problem was that using such accessors was very verbose. We solved it by creating a name-convention-bean-like dynamic proxy. All this seemed to fit well.

When we where about to upload this proof-of-concept to Oxen Java Commons, I read the following links (from a post on The Server Side):

The idea of using a class for accessing properties instead of using name convention based beans seemed to fit very well. With that, the proxy will not be necessary. In fact, the author was promoting exactly the oposite idea: deprecating beans!!!

So, we made a refactor of the code to follow this approach. We used an interface instead of a Property class and added an Observable interface in order to handle events. The results are explained here:


We put a simple example where the same presenter is binded to Vaadin and Swing. Also, we created an Android implementation:


which was the first motivation for all of this.

This is just a proof-of-concept. Maybe it makes no sense to create too much verbose code just to make a presenter independent. Or maybe yes (we'll know after implementing this in a project).

The main doubt is if this model can be applied more generically, not just for simple forms (for example, for UIs with data lists).









Hello World!!

Hello, this is the first post.

The idea behind this blog is to post information the technical stuff used in Oxen Software Studio. It can be ideas, dicussions, research, etc. Anything that could be of interest, regarding software development (technology, methodolody, etc.).

Enjoy!

Lautaro