Friday, December 31, 2010

GWT Designer

I am not a fan of WYSIWYG software.  Almost every experience I had with WYSIWYG tools had the same pattern:
  1. I implement some application using the tool because I am pressed for time.
  2. I get the initial project done very quickly.
  3. Someone requests a change.
  4. Because of the WYSIWYG generated code, I essentially have to rewrite the app.
Maybe I just didn't use the WYSIWYG right.  Obviously, a lot of people love them.  But they were always counter-productive for me.  In the end, they cost me more time than they saved.  So, you can imagine my feelings when I read about GWT Designer.  Here was a Drag and drop visual editor for GWT, complete with integration for SmartGWT and Ext GWT.  I was hesitant, to say the least.

But I also firmly believe that as a Software Engineer, you have to keep your mind open and constantly re-evaluate new tools.  So, I installed the GWT Designer plugin for Eclipse.  I used it for my capstone project, a CRUD application for running a sign installation company.  I was pleasantly surprised.  

Here are a few observations about the Editor:
  1. I was able to jump between code and the visual editor easily
  2. Changing my code by hand didn't break the visual editor 
  3. The code generated by the editor was easily readable and clean
Even though I started with the WYSIWYG, as I got a simple layout produced, I found myself easily translating into the code. It was a good experience.  The visual components I created were originally going to be mock ups, but they were so clean, I've transitioned them into the working code.  The application is not done yet, but its looking good - I've already been able to easily incorporate changes requested by my client.  

Now, here are the drawbacks I encountered:
  1. My 5 year old PC and laptop run the visual components a little slow. 
  2. The visual rendering isn't yet perfect.  While it was mostly reflective of the actual output, there were a few differences.
All in all, though, the drawbacks were more annoyances than restrictions.

If you use GWT, I recommend you try GWT Designer.

Friday, December 24, 2010

GWT Simple Security Configuration

For my capstone project in my MSE program at Carroll University, I am writing a GWT application. One of the requirements for this application is security. There are several posts on securing a GWT application on the Web already, but most of them are more heavy weight solutions that show you how to use Spring-AOP and Spring-security to secure your app.

For this project, I don't need anything that heavy-weight. Here is a little review of how I secured this application.

First, I wanted each service to have it's own access controls. More specifically, I want to be able to secure each method in each service. Second, I want to be able to support Role-based access. This way I can add users to roles to grant them the permissions they need. Finally, I don't have a real need to redefine role access in real-time. Given these constraints, I was able to put together a quick and easy solution to secure my application.

First, I decided that I wanted to be able to easily see in my code what the access control was. It seemed to me that Annotations would be an easy way to do this. Something like:

@Secure("ROLE_ADMINISTRATOR")

But I want to be able to specify multiple roles that can be configured to this action, so, multiple roles would look more like this:

@Secure({"ROLE_ADMINISTRATOR, ROLE_CONFIGURATION_MANAGER"})

So, the first thing I did was define the Annotation.


package com.archie.sma.server.util.security;

import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;

@Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.METHOD)
public @interface Secure {
  public String[] value();
}
  
AS you can see, annotations are annotated. This one says that this annotation applies to Methods, and it is kept at runtime.

Next I needed to apply the annotation to my services. This was quite easy. In my Service interface on the client, I used the annotation:

@Secure({"ROLE_ADMINISTRATOR", "ROLE_CONFIGURATION_MANAGER"})
public Object get(String id) throws Exception {
//Method implementation here...
}

Of course, I now need to tie these two together. Since I'm Using GWT, I decided to Extend the GWTServerServlet. By extending the servlet and over-riding the processCall and onAfterRequestDeserialized method, I am able to easily use a little bit of Reflection to get the annotation and determine if the user in Session has access to the method. This approach also requires me to extend my new security Servlet for all my secured classes. So its on the developer to ensure he is extending the class correctly. Here is the class:





public class SecureRemoteServiceServlet extends RemoteServiceServlet {

  private transient IDaoFactory daoFactory;

  @Override

  public void init(ServletConfig configthrows ServletException {

    super.init(config);

    daoFactory = new DaoFactory();

  }

  /**

   

   */

  private static final long serialVersionUID = 1000L;

  private static final String USER = "USER";

  private User user;

  @Override

  protected final void onAfterRequestDeserialized(RPCRequest rpcRequest) {

    Method method = rpcRequest.getMethod();

    Secure secure = method.getAnnotation(Secure.class);

    Boolean hasAccess = Boolean.FALSE;

    if (secure != null) {

      

      String[] roles = secure.value();

      HttpServletRequest request = getThreadLocalRequest();

      user = (Userrequest.getSession().getAttribute(USER);

      if (user != null) {

        List<Role> userRoles = user.getRoles();

        for (Role role : userRoles) {

          for (int i = 0; i < roles.length; i++) {

            if (role.toString().equals(roles[i])) {

              if(hasAccess != null) {

                hasAccess = Boolean.TRUE;

              }

            }

          }

        }

      }

    }

    if (!hasAccess){

      throw new RuntimeException("Not Authorized");

    }

  }

  /*

   * @Override public final String processCall(String payload) throws

   * SerializationException { if (!hasAccess) { throw new

   * UnexpectedException("Security Exception", new Exception(

   * "Not Authorized")); } return super.processCall(payload); }

   */



  public User getUser() {

    return user;

  }



  public void setUser(User user) {

    this.user = user;

  }



  public IDaoFactory getDaoFactory() {

    return daoFactory;

  }



  public void setDaoFactory(IDaoFactory daoFactory) {

    this.daoFactory = daoFactory;

  }

}


So that is my quick and dirty security implementation for my GWT app. This is not what you would call an enterprise solution, but it is a quick way to implement security for a little, self-contained application.

Saturday, June 26, 2010

Software engineering vs. Computer Science

There is a difference between Software engineering and Computer Science.  Just like there is a difference between Mechanical Engineering and Physics.  I believe that the big difference is that in the physical world, people have been building structures for thousands of years.  The difference between the theory of the physical world and the building of things in it is well defined.  Modern computing has been around for what, 60 years?  We have not yet defined the difference between the theory of Computing and the practical application of it.

In computer science, the task is often to find the best, or most efficient way to perform a task.  Often, Computer Scientists are looking for theoretical limits, or trying to resolve a new computing issue in a novel way.  


In software engineering, you are trying to build a system to meet a need using the tools at hand, given the constraints of your system.  Often this means NOT using the best solution.  It means using the best solution given the constraints placed on your use case.  
As a Software Engineer, this means we do not necessarily build things on our own.  Rather, we evaluate alternatives and select the best one.  One example of this might be Web Frameworks.  Another might be ORM selection (or whether to use either of these technologies at all and actually build our own).   This is analogous to a mechanical engineer designing a car - he doesn't also design the tires, alternator, battery, etc.  Rather he looks at the alternative possibilities and selects the best one for the vehicle he is trying to create.  Of course, there are going to be many areas that the mechanical engineer does build.  


It seems like in software engineering, using other peoples tools is frowned upon.  There is some sort of badge of honor to say, 'I built this myself'.  While it is impressive to have that broad range of skill, does that necessarily make you the best Software Engineer?  


It is my belief that as a profession, we Software Engineers need to start thinking of our task as more of an engineering endeavor and less of computer science endeavor.  We need to see ourselves not as Scientists, but as Engineers.  



Saturday, June 12, 2010

Bug fix for Unit Test Generation Plugin

I fixed a few bugs in the Unit Test Generation Plugin.  I think the next release is going to be a re-factor only, as the code is pretty rough and I want to be able to keep this project clean.  I believe after a few more edits I will be comfortable declaring the project a 'Beta' project.

Get the latest download

Tuesday, June 8, 2010

Inversion of Control - Results

In a previous post I talked about how to identify and re-factor a section of code that had a switch statement in it.  I was finally able to get to that statement at work and re-factor it.  I thought the results would be interesting to post.

First and foremost, I was able to remove 120 unnecessary lines of code and replace it with 2 lines.  That's right, where once there were 120 lines there are now  2.

But there is more to the story than that.  As I mention before, I've been unit testing the application(and that led to a new Eclipse tool), so as I re-factored the system, I re-ran my tests.  At one point my tests FAILED.  That's right, I BROKE the intended functionality with a re-factor that shouldn't have.

When I looked into it further, I found that one little switch statement buried in that twenty-two case wonder didn't follow the pattern.  Instead of getting an implementation from the factory and calling a getMap method, it was calling an entirely different method in the main class.  After a little research and a few short lines of code, the issue was fixed and the tests once again showed a green bar.

The actual work here is not relevant, what is relevant is this:  This is a pre-release version of this system.  It is not even in Beta testing yet, and there is already a place in the code that was 'hacked' to work differently than you would expect.  The implementation of a pattern will help prevent this kind of degrading of the code in the future, but it was there.  In the code. Before the software was even released.

The second thing to take away from this:  If I hadn't written all those unit tests, I wouldn't have found the error.  I would have re-factored the code and introduced a bug into the system without realizing it.  Unit tests saved me.  And because of that, my company will now have a system that is more resistant to errors and less prone to new bugs.

Sunday, June 6, 2010

A two week diversion. Eclipse Plugin to Generate Unit Tests

I took a new job about a month ago at an insurance company. The company is in the middle of rewriting the Point of Sale application for its line of business. Since the project had already kicked off and development had begun, I had been assigned the glorious task of filling in Unit test coverage.

You see, the management at this company is pretty new to Agile development methodologies, and until about a year ago, Unit tests were largely unknown to them. They are driving a tight timeline for delivering the rewritten project. Often, the developers are going over their burndown hours, so the first thing to suffer was, you guessed it, the unit tests. On top of that, management is insistent on getting 80% coverage. As you can probably guess from the title of this post, I was assigned the duty of creating unit tests for this iteration of the code, with the purpose of increasing code coverage to as close to 80% as possible.

When I was handed the code, the coverage, depending on sub-project, was between 0% and 20% covered.

I decided to create an Eclipse plugin to help me with the task (On my own time, of course.  During the day, I wrote tests.) I call it Unit Test Generation Plugin.  This version is very basic.  It really only works to create tests for POJOs at this point, but I think I'll extend it a bit to make it more useful soon.

I was really quite surprised at how easy and fun it was to create a plugin for Eclipse.   I thought I'd post some of the code and the process I used to create the plugin on the site.

Here are some highlights.  Let me know if you'd like me to write more detail about a particular topic.

Binding An Event To The Eclipse Package Menu
Eclipse uses a powerful plugin framework to allow you to extend and enhance the platform.  The way to add extensions is to use the PDE, which is a part of the core project.  Eclipse makes creating a new project VERY easy.  To start, go to File->New->Project...->Plugin Project.

In the New Plugin Window, Enter a name, like com.a.plugin.  The rest of the defaults can be left alone.  Click, Next.  Another popup appears to allow you to select more options for your project config.  Modify the name and provider all you like, but the defaults should suffice.  Click Next.

The final panel allows you to select several templates that demonstrate different extensions.  You can select a template if you like, or none at all.  For this project, I will select none.

When you finish, a new Eclipse plugin project is created and you are ready to continue.

Extension Points
An extension point is how you add new functionality to Eclipse.  They are configured using an XML file.  Eclipse supplies an editor to allow you to easily edit this file.  I had some trouble configuring my Handler through this screen, but was able to write the code by hand.  Once I edited it, it appeared correctly in the editor.  I've done a little reading and that might be because I didn't have some RCP plugins installed, but I haven't verified it yet.

Java Code Support
It also turns out that Eclipse has robust support for Java project Elements.  There are interfaces like ICompilationUnit, IPackageFragment and so forth.  It was pretty easy to generate new tests.

The Result
I have decided that I am going to make the project open-source and created a SourceForge project for it.  It is still in Alpha stage, and there is a bit of work to make it a 'real' plugin, but its now out there in the world.

Unit Test Generation Plugin

Now, I'm sure that Robert Martin would hunt me down if he knew what I created, and would destroy the laptop it was written on (OK, I don't really know him, but I've read one of his books, Agile Software Development, Principles, Patterns, and Practices.  From the perspectives presented there, I can infer that he would not be happy with my tool

Tuesday, May 25, 2010

Identifying and refactoring - Inversion Of Control

In my new position, I am now working on a large team of developers (15 in all). This team is working to complete a single product that has been designed using a Service Oriented Architecture. I have some insights into that design as well, however, in this post I thought I would show an example of how to identify and refactor to a design pattern, and why I feel this is a good thing for the project in the long term.

One of the hardest things about design patterns is recognizing when to use them and when not to. I have seen so many architects apply patterns for patterns sake, making code more complex, and making it HARDER to apply patterns where they are truly needed. I've also seen lots of code that isn't refactored to design patterns, and it COULD be made much easier to maintain and understand if it were changed. The code I will be talking about today is of the latter type. I've been writing Unit tests against the codebase at my new position. This has given me an opportunity to review the code. In order to protect the IP of the company I work for, the samples below have been changed. They represent the structure of some of the code, but are entirely unrelated to what my company does.

First, let me describe the general design of the code as it stands. In this instance, we have a method that takes an Enumeration argument. The method then calls the getInstance method of a Factory, and gets the proper implementation of an Interface. The getInstance method also takes an Enumeration. Finally, the code uses a case statement that tests the Enumeration value and uses the interface to set the values of different member variables in the class.  Here is the sample code that would implement this design:

The Container.  This is the class where our execution starts.  We call setMapValue and pass it a Type enum.

  1 package com.arciszewski.staterefactor; 
  2 import com.arciszewski.staterefactor.Type; 
  3 import java.util.Map; 
  4  
  5 public class Container {
  6     private Map<String,String> map1; 
  7     private Map<String,String> map2; 
  8     private Map<String,String> map3; 
  9      
 10     public void setMapValue(Type type) {
 11          
 12         ITypeInterface intf = TypeFactory.getInstance(type); 
 13          
 14         switch(type) { 
 15             case ONE : 
 16                 map1 = intf.getMap(); 
 17                 return; 
 18             case TWO :
 19                 map2 = intf.getMap(); 
 20                 return; 
 21             case THREE : 
 22                 map3 = intf.getMap(); 
 23                 return; 
 24             default : 
 25                 return; 
 26                  
 27                  
 28         } 
 29          
 30          
 31     } 
 32  
 33     public Map<String, String> getMap1() { 
 34         return map1; 
 35     } 
 36  
 37     public void setMap1(Map<String, String> map1) {
 38         this.map1 = map1; 
 39     } 
 40  
 41     public Map<String, String> getMap2() { 
 42         return map2; 
 43     } 
 44  
 45     public void setMap2(Map<String, String> map2) {
 46         this.map2 = map2; 
 47     } 
 48  
 49     public Map<String, String> getMap3() { 
 50         return map3; 
 51     } 
 52  
 53     public void setMap3(Map<String, String> map3) {
 54         this.map3 = map3; 
 55     } 
 56      
 57 } 
 58  
 59 

This is the Factory that creates ITypeIntf concrete classes.  For now there is only one implementation for type.ONE.

  1 package com.arciszewski.staterefactor; 
  2  
  3 public class TypeFactory {
  4  
  5     public static ITypeInterface getInstance(Type type) {
  6          
  7         ITypeInterface typeIntf = null; 
  8         if(type.ONE == type) { 
  9           return new  TypeImplOne();  
 10         } if(type.TWO == type) { 
 11              
 12         } if(type.THREE == type) { 
 13              
 14         } 
 15         return null; 
 16     } 
 17      
 18 }

The Enum.  Not much to say here.

  1 package com.arciszewski.staterefactor; 
  2  
  3 public enum Type { 
  4     ONE, TWO, THREE; 
  5 }

The Interface that defines getMap.

  1 package com.arciszewski.staterefactor; 
  2  
  3 import java.util.Map; 
  4  
  5 public interface ITypeInterface {
  6  
  7     public Map<String, String> getMap(); 
  8 }

An implementation class. Kept simple for discussion.

  1 package com.arciszewski.staterefactor; 
  2  
  3 import java.util.HashMap; 
  4 import java.util.Map; 
  5  
  6 public class TypeImplOne implements ITypeInterface {
  7  
  8     @Override 
  9     public Map<String, String> getMap() { 
 10         //Do something like get data from a DB. 
 11         return new HashMap<String, String>();
 12     } 
 13  
 14 }

Looking at this code, you'd probably say that the developers did some things right.  They designed to interfaces, they are using a creational pattern, and the code is pretty clean and easy to read.  I tend to agree, except when it comes to that ugly switch statement.  Here are my issues with the switch statement:

  1. Developers have to remember the return statement, or we will have NULL implementations when we shouldn't
  2. Developers will be tempted to add more logic to the case statements that are Type specific.  As these add up, the clarity of the code falls
  3. We're already verifying the type in the Factory, so this code is checking the Type value twice when it doesn't have to.
  4. Container needs to be aware of the different implementations of ITypeIntf.  Why should it need to?  Now we've added a dependency we don't need.

There is a change we can make that will improve this code.  Let's change the ITypeInterface to take a Container object in its argument list.  Then we can set the value in the method and the case statement is no longer needed.  This is a classic IOC technique.  Here is what the code looks like after the refactoring.

The new Container. Notice, there is no switch statement. None is needed. the IMPLEMENTATION of the ITypeIntf knows which attribute it needs to set. Also note that Container doesn't need to know anything about the implementation that the Factory returns.

  1 package com.arciszewski.staterefactor; 
  2 import com.arciszewski.staterefactor.Type; 
  3 import java.util.Map; 
  4  
  5 public class Container {
  6     private Map<String,String> map1; 
  7     private Map<String,String> map2; 
  8     private Map<String,String> map3; 
  9      
 10     public void setMapValue(Type type) {
 11         ITypeInterface intf = TypeFactory.getInstance(type); 
 12         intf.setMapValue(this); 
 13     } 
 14  
 15     public Map<String, String> getMap1() { 
 16         return map1; 
 17     } 
 18  
 19     public void setMap1(Map<String, String> map1) {
 20         this.map1 = map1; 
 21     } 
 22  
 23     public Map<String, String> getMap2() { 
 24         return map2; 
 25     } 
 26  
 27     public void setMap2(Map<String, String> map2) {
 28         this.map2 = map2; 
 29     } 
 30  
 31     public Map<String, String> getMap3() { 
 32         return map3; 
 33     } 
 34  
 35     public void setMap3(Map<String, String> map3) {
 36         this.map3 = map3; 
 37     } 
 38      
 39      
 40 }

The new interface. The interface definition was changed to return void and to make the name descriptive of what it does now.

  1 package com.arciszewski.staterefactor; 
  2  
  3 public interface ITypeInterface {
  4  
  5     public void setMapValue(Container container);
  6 }

The new implementation. Notice that the new implementation now has a dependency on Container. That's OK in my mind, since the interface is intended to work on Container. Here's what we gained, though. Now ALL the logic for this condition is in ONE place. Container will never need to be changed, even if a new implementation is defined (For instance, an implementation that will set ALL the map attribute values.)

  1 package com.arciszewski.staterefactor; 
  2  
  3 import java.util.HashMap; 
  4  
  5 public class TypeImplOne implements ITypeInterface {
  6     // Changed the name, too. getMap no longer describes this function, but
  7     // setMapValue does. 
  8     @Override 
  9     public void setMapValue(Container container) {
 10         // Do something like get data from a DB. 
 11         container.setMap1(new HashMap<String, String>());
 12     } 
 13  
 14 }

So what pattern does this conform to? It looks a bit like a State or Strategy pattern. It also looks a bit like a Command pattern. Which would you say it is?

Sunday, May 23, 2010

Android Application Part 6 - SQLLite Database

This post is part 6 of a series.  Click here to go to part 5.


In my previous post, I walked through the scaffolding for the ListService, which will query a REST Web service and sync data locally.  Of course, the code was just the implementation to allow the service to run in a new Thread.  Today I am going to start implementing the storage part of the application.  Android has a a SQLLite. Database.  The OS makes it available through a service.  It even comes packaged with a SQLLiteOpenHelper class.  The implementation for this one is rather easy.  Here I've modified the sample presented on the Android Developer Site.  First I'll show you the code, then I'll talk through what its doing.   

package com.arciszewski.family.shopping.db;

import android.content.Context;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;
import android.database.sqlite.SQLiteDatabase.CursorFactory;

public class FamilyListOpenHelper extends SQLiteOpenHelper {

private static final int DATABASE_VERSION = 1;
private static final String FAMILY_LIST_TABLE_NAME = "familyList.db";
private static final String LIST_TABLE_CREATE = "CREATE TABLE LIST (ID INTEGER PRIMARY KEY AUTOINCREMENT, SERVER_ID INTEGER, NAME TEXT, DESCRIPTION TEXT);";
private static final String ITEM_TABLE_CREATE = "CREATE TABLE ITEM (ID INTEGER PRIMARY KEY AUTOINCREMENT, SERVER_ID INTEGER, NAME TEXT, LIST_ID INTEGER NOT NULL, NEEDED BOOLEAN, UPDATED_DATE TEXT, UPDATED_BY TEXT);";

public FamilyListOpenHelper(Context context) {
this(context, null);
}

public FamilyListOpenHelper(Context context, CursorFactory factory) {
super(context, FAMILY_LIST_TABLE_NAME, factory, DATABASE_VERSION);;
}

@Override
public void onCreate(SQLiteDatabase db) {
db.execSQL(LIST_TABLE_CREATE);
db.execSQL(ITEM_TABLE_CREATE);
}

@Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
// TODO Auto-generated method stub

}
}


So what is this code doing? First, I've defined which version of the DB this is:


DATABASE_VERSION = 1;


I like this feature of Android. They have built-in support for upgrading. You'll notice, I have not implemented the onUpgrade method, that is because I have no need for it yet. But when I come out with version 2.0, I will have the opportunity to perform upgrade operations.


Next, I define the table names and create SQL for the List and Item tables.


private static final String LIST_TABLE_CREATE = "CREATE TABLE LIST (ID INTEGER PRIMARY KEY AUTOINCREMENT, SERVER_ID INTEGER, NAME TEXT, DESCRIPTION TEXT);"; private static final String ITEM_TABLE_CREATE = "CREATE TABLE ITEM (ID INTEGER PRIMARY KEY AUTOINCREMENT, SERVER_ID INTEGER, NAME TEXT, LIST_ID INTEGER NOT NULL, NEEDED BOOLEAN, UPDATED_DATE TEXT, UPDATED_BY TEXT);";


Finally, I've implemented a constructor that will always open the Family List Database and return it to the caller. That's it. And that is pretty easy my friends. Of course, I'm not making this available as a service to other applications, which is slightly more complex.


Next, I'll implement some querying and saving.

Sunday, May 16, 2010

Android Application Part 5 - Creating the Service

This post is part 5 of a series.  Click here to go to part 4.


In my previous posts, I outlined my general design for this application.  In this post, I will review the creation of the Service class for the Android device. This class will have one purpose: Communicate with the server to sync lists.

One of the things I hadn't decided on was how to construct the Web service.  Do I want to use a SOAP style service or a REST style service? The server side for either of these is pretty well defined for me - I've written both SOAP and REST services.  The unknown is how to build these on the client side.  I did a little Web research, and here are a few of the places I've found that have some good information on these topics:

  • It appears that Google isn't interested in including SOAP in the standard Android packages at this time, but there is a 3rd party library that provides this support: kSOAP
  • Google DOES support JSON with Android packaged,  org.json.*.  I also found a handy RestClient.
Given that JSON is less verbose, and the processing will take fewer resources, I think its a better choice for a constrained device like Android.  I also like that I have a RestClient class that I can use, but I can also see what's going on easily inside it.  So, the transport protocol for my application will be JSON.

Let's talk about the code.  Below is my first attempt at creating the ListService.  It's not fully fleshed out.  This first version is written to put in the Multithreading and get a basic framework for the application.  I will next work on pulling out the data from the JSON objects and store them locally (Using the local HSQL db Android provides).  It's also clear I need to understand Intents and bindings much better before I will be able to complete the app.  Let's start with a discussion on the ListService.  This extends the Android Service class and over rides the onCreate, onStartCommand, and stopService methods.  I also added extra logging to see what's going on.



01 package com.arciszewski.family.shopping.service;
02 
03 import android.app.Service;
04 import android.content.Intent;
05 import android.os.IBinder;
06 import android.util.Log;
07 
08 public class ListService extends Service {
09   private RunnableListService runnableListService;
10   @Override
11   public IBinder onBind(Intent arg0) {
12     
13     return null;
14   }
15 
16   @Override
17   public void onCreate() {
18     super.onCreate();
19     Log.i("BAA""created");
20   }
21 
22   @Override
23   public int onStartCommand(Intent intent, int flags, int startId) {
24     Log.i("BAA""starting");
25     if(runnableListService == null) {
26       runnableListService = new RunnableListService();
27       new Thread(runnableListService).start();
28     }
29     return START_STICKY;
30   }
31 
32   @Override
33   public boolean stopService(Intent name) {
34     Log.i("BAA", name.toString());
35     boolean superResult =  super.stopService(name);
36     if(runnableListService != null) {
37       runnableListService.setContinueRunning(false);
38       runnableListService = null;
39     }
40     return superResult;
41   }
42 }


Java2html

The ListService does nothing but create a RunnableListService and start it in a new Thread.  It also kills the flag that keep the polling loop open when stopService is called.  Here is the RunnableService:




01 /**
02  * Class that will poll the server for changes and sleep.  
03  @author barciszewski
04  *
05  */
06 public class RunnableListService implements Runnable {
07   private static final String SERVER_URI = "http://192.168.1.103/familyList";
08   private static final String APP_ID = "FL1"
09   private static boolean running = false;
10   private boolean continueRunning = true;
11   @Override
12   public void run() {
13     getListFromServer();
14   }
15   
16   private void getListFromServer() {
17     //don't want to try and connect twice
18     if(!getRunning()) {
19       setRunning(true);
20       RestClient.connect(SERVER_URI);
21       //save list data to local data store...
22       
23       setRunning(false);
24     }
25     while(continueRunning) {
26       try {
27         Thread.sleep(1000*60*5);
28       catch(InterruptedException e) {
29         //do nothing
30       }
31       getListFromServer();
32     }
33   }
34   
35   
36   public static synchronized void setRunning(boolean runnnig) {
37     RunnableListService.running = running; 
38   };
39   
40   public static synchronized boolean getRunning() {
41     return RunnableListService.running;
42   }
43   
44   public void setContinueRunning(boolean continueRunning) {
45     this.continueRunning = continueRunning;
46   }
47   
48 }
Java2html


Most of the heavy lifting is not implemented yet, but this provides the structure to poll the server.  I also modified the RestClient slightly to return the JSONObject.

Next - More implementation...

Sunday, May 9, 2010

Android Application Part 4 - The Activity and Service

This post is part 4 of a series.  Click Here to go to part 3.

After all of that, I am going to set aside any of the server programming and go straight to writing the Android portion of the system.  I know, I know, after all that work writing the UML for the core components, I'm just going ahead and writing an Android app anyway.  I have two good reasons for this.

Reason 1: I have never produced an Android app before, but I've written dozens of Web apps and Web services.  Therefore, the Android portion of the system is the least-known and most risky.  As a developer, I like to tackle these portions of a system first to reduce risk and get unknowns out of the way.  I believe this is a good practice, and leads to more successes in projects.

Reason 2: I WANT to program an Android app.  Especially now that I have my Droid  and my wife has her Incredible.

OK, so lets start on the Android app design.  My application will need to display a UI and run a background process to do synchronizations.  According to the Android Developers Web site, I will need two basic constructs, an Activity and a Service.  Let's explore the Activity first.  The Android developer site describes an Activity as:
An activity presents a visual user interface for one focused endeavor the user can undertake. For example, an activity might present a list of menu items users can choose from or it might display photographs along with their captions. A text messaging application might have one activity that shows a list of contacts to send messages to, a second activity to write the message to the chosen contact, and other activities to review old messages or change settings. Though they work together to form a cohesive user interface, each activity is independent of the others. Each one is implemented as a subclass of the Activity base class.
That seems pretty straight forward - An Activity is simply a UI component for a single task.  It sounds like my application will only need a couple of Activities.  One activity to show the grocery list, an activity to add a new item, and one to show the status of the sync.  A Service is defined as:


A service doesn't have a visual user interface, but rather runs in the background for an indefinite period of time. For example, a service might play background music as the user attends to other matters, or it might fetch data over the network or calculate something and provide the result to activities that need it. Each service extends the Service base class.
A prime example is a media player playing songs from a play list. The player application would probably have one or more activities that allow the user to choose songs and start playing them. However, the music playback itself would not be handled by an activity because users will expect the music to keep playing even after they leave the player and begin something different. To keep the music going, the media player activity could start a service to run in the background. The system would then keep the music playback service running even after the activity that started it leaves the screen.
It's possible to connect to (bind to) an ongoing service (and start the service if it's not already running). While connected, you can communicate with the service through an interface that the service exposes. For the music service, this interface might allow users to pause, rewind, stop, and restart the playback.

Like activities and the other components, services run in the main thread of the application process. So that they won't block other components or the user interface, they often spawn another thread for time-consuming tasks (like music playback). See Processes and Threads, later. 
From the description of a Service, it appears that my application will only have one service - the list sync.  This service should spawn a thread so it doesn't block other components or the UI.  It also appears that the service can be exposed to an Activity, so I should be able to force a sync through a UI action.

This all seems pretty simple.  Let's just do a quick UI sketch, though.  I've mocked up a header and one record to make sure I've got the screen space I'd like. 

This is a really rough mock up, but it demonstrates all I need for the list.  One form element, a check box, and three labels. 

It seems like the Android application design is going to be dictated by the platform.  An Activity and a Service are going to be my two main classes.  I think I'm going to tackle the Service first, as that is more complicated.

Next: Coding the Android Service




Thursday, May 6, 2010

Android Application Part 3 - UML

This post is part 3 of a series.  Click here to go to part 2.

Before I go into the actual UML for this application, I first have to talk about my opinion regarding things like UML Diagrams, Sequence Diagrams, State Diagrams, Activity Diagrams and Object Diagrams.  As Software Engineers, we differ from other Engineers in a major way.  The only thing we produce that is a COMPLETE representation of the systems we build is the code.  In no other engineering endeavor is the completed product also the description of that product.

Based on this knowledge, it is my belief that all the diagrams and drawings and 'design' aides we use to build software are there not to completely document a system.  On the contrary, attempts to completely document a system using these tools is rather counter-productive.  So what are they supposed to be used for?  I like to think of all these diagrams and pictures as tools to be used for the following purposes:

  • To allow the Software Engineer to organize his thoughts about the system, and aide in his decisions regarding the design.
  • To provide a way to describe a PART of a system that may be important or complicated at a high leve
  • To allow the view of a system at a higher, abstract level, without the details, to allow for a broad analysis of a system
That's it.  That's all.  That's what all these things are good for.  I know the very next question people will ask - What if we really need to understand the details?  What if we need to KNOW what the system is doing?  Well, there is only one reliable way for someone to know what a software system is doing - GO READ THE CODE!

So, when I produce UML, State or Sequence diagrams, I typically omit a lot of detail.  I intend for these things to convey limited messages and present limited data because they are simply tools of transition, there to help in the final build of the system.  Now I will get off my soapbox and present to you the simple designs for my app.

The UML

As you can see from the UML, this is a pretty simple object model.  We'll see if I need something more complex later, but this appears to be the basic outline for what I need. 

Notice that I added some auditable information to the Items.  I figured you would want to know who and when an item was added, removed, updated, etc.   




To the right, you will see my DAO UML diagram.  As you can see, I have declared a Dao interface that uses generics.  Each subclass will implement the generic type for its Type of object. I also chose to use a DaoFactory to create my objects.  You'll notice that I have not represented all the relationships, return types, arguments, etc, that would make this UML complete.  Isn't this version much less cluttered, though?  And isn't my intent straight forward?



I intend to use GWT for my Web site, so I have a set of RPC services that will extend RemoteServiceServlet.  As you can see, there is nothing magical here.  It is implied that each of these services will use the corresponding DAO associated with them.  I could add those relations to this UML, but I think it just adds complexity.


I am going to refrain from building the UML for the visual components of this system.  Why?  For one, the diagrams get pretty complicated pretty fast.  And two, because I already have plenty of diagrams showing the 'guts' of my system. 

The Sequence Diagram

I will demonstrate one sequence diagram that is representative of this design.  Most actions in this system will follow this pattern:



The first thing I want to point out about the sequence diagram, is that it is rather hard to model the AsyncCallback used by GWT RPC.  I supposed I can add a call to the AsyncCallback constructor from UserServiceAsyc, and fit the model that way, but this is another scenario where that tends to obscure the intent rather than enlighten it.  Instead, I just put a comment that the GWT magic is omitted.  I hope that other developers looking at this would be familiar with GWT.

By the way, my favorite modelling tool is called, Violet.  It is completely free.  It's simple, but makes for a rather quick and easy way to build your models so that you can get your thoughts together and start coding.

Next: We'll get into some coding. FINALLY!