DaedTech

Stories about Software

By

Setting Up AJAX and JQuery

AjaxSo, in response to feedback from my previous post about my   home automation server site, I’ve decided to incorporate AJAX and JQuery into my solution. This is partially because it’s The Right Thing ™ and partially because I’m a sucker for the proposition of learning a new technology. So, here are the steps I took toward going from my previous solution to a working one using AJAX, including downloads and other meta-tasks.

The first thing that I did was poke around until I found this tutorial, which is close enough to what I to do to serve as a blueprint. I found it very clear and helpful, but I realized that I had some legwork to do. I setup my java code as per the tutorial, but on the client side in JSP, I realized things wouldn’t work since I couldn’t very well source a jquery library that didn’t exist in the workspace. I poked around on my computer a bit and saw that I did have various jquery.js libraries, but they were part of Visual Studio, Android, and other concerns, so I figured I’d download one specifically for this task rather than try to reappropriate.

So, I went to jquery.com. I poked around a bit until I found the most recent “minified” version, since that’s what the example was using, and discovered it here. I was a little surprised to find that the ‘download’ would consist of copying it and pasting it into a local text file that I named myself, but I guess, what did I expect – this is a scripted language executed by browsers, not a C++ compiler or the .NET framework or something.

In Eclipse, I made a directory under my WebContent folder called “js”, and I put my new jquery-1.7.1.min.js file in it. Now, I had something to link to in my JSP page. Here is the actual link that I put in:

Just to make sure my incremental progress was good, I built and ran on localhost, and

My project now error’d on build and at runtime. For some reason, Eclipse seems not to like the minified version, so I switched to using the non minified. I still got a runtime error in Eclipse browser (though not in Chrome) and the javascript file had warnings in it instead of errors. This was rectified by following the high scoring (though strangely not accepted) answer on this stack overflow post.

However, it was at this point that I started to question how much of this I actually needed. I don’t particularly understand AJAX and JQuery, but I’m under the impression that JQuery is essentially a library that simplifies AJAX and perhaps some other things. The tutorial that I was looking at was describing how to send POST variables and get a response, and how this was easier with JQuery. But I actually don’t need the variables, nor do I need a response at this time. So, given the JQuery runtime errors that were continuing to annoy me, I deleted JQuery from the proiejct and resolved to work this out at a later date. From here, after a bit of poking around, I realized that using AJAX from within Javascript was, evidently, pretty simple. I just needed to instantiate an XMLHttpRequest object and call some methods on it. Here is what I changed my kitchen.jsp page to be:

Pretty simple, though when you have no idea what you’re doing, it takes a while to figure out. :)

I instantiate a request, populate it and send it. Given my RESTful scheme, all the info the server needs is contained in the path of the request itself, so it isn’t necessary for me to parse the page or ask for a response. I added the javascript:void(0) calls so that the buttons would still behave like actual, live links. I think that later, when it is, I’ll probably bring JQuery back and revisit the tutorial that I found. Here is my updated controller class.

I’m fairly pleased with the asynchronous setup and the fact that I’m not playing weird games with redirect anymore. I have a unit test project setup, so I think I’m now going to get back to my preference of TDD, and factor the controller to handle more arbitrary requests, making use of an interfaced service for the lights and a data driven model for the different rooms and appliances. I’ve got my eye on MongoDB as a candidate for data storage (I’m not really doing anything relational), but if anyone has better ideas, please let me know.

By

The Outhouse Anti Pattern

Source Control Smells?

I was reading through some code the other day, and I came across a class that made me shutter a little. Interestingly, it wasn’t a code smell or a name smell. I wasn’t looking at the class itself, and it had an innocent enough name. It was a source control smell.

I was looking through source control for something unrelated, and for some reason this class caught my eye. I took a look at its version history and saw that it had been introduced and quickly changed dozens of times by several people. Even assuming that you like to check code in frequently, it’ll take you what, one or two checkins to write a class, and then maybe a few more to tweak its interface or optimize its internals, if need be? Why were there all these cooks in this kitchen, and what were they doing in there? The changes to the class continued like that over the course of time, with periods of few changes, and then bouts of frenzied, distributed activity. How strange.

I opened the class itself to take a look, and the source control checkin pattern immediately made sense to me. The class was a giant static class that did nothing but instantiate ICommand implementations and expose them as public fields. I haven’t tagged this class with C# for a reason — this anti-pattern transcends languages — so, I’ll briefly explain for non C# savvy readers. ICommand is an interface that defines Execute and CanExecute methods – sort of like a command pattern command, but without forcing implementation of UnExecute() or some such thing.

So, what was going on here was that this class was an already-large and robustly growing dumping repository for user actions in the application. Each property in the class was an instance of an ICommand implementation that allowed specifying delegates for the Execute and CanExecute methods, so they looked something like this:

So, the ‘pattern’ here is that if you want to define some new user action, you open this class and find whatever shared global state will inform your command, and then add a new command instance field here.

A Suitable Metaphor

I try to stay away from the vulgar in my posting, so I beg forgiveness in advance if I offend, but this reminds me most of an outhouse at a campground. It’s a very public place that a lot of people are forced to stop by and… do their business. The only real reason to use it is that a some people would probably be upset and offended if they caught you not using it (e.g. whoever wrote it), as there is no immediately obvious benefit provided by the outhouse beyond generally approved decorum. Like the outhouse, over time it tends to smell worse and worse and degenerate noticeably. If you’re at all sensitive to smells, you probably just go in, hold your nose, and get out as quickly as possible. And, like the high demand outhouse, there are definitely “merge conflicts” as people are not only forced to hold their noses, but to wait in line for the ‘opportunity’ to do so.

There are some periodic attempts to keep the outhouse clean, but this is very unpleasant for whoever is tasked with doing so. And, in spite of the good intentions of this person, the smell doesn’t exactly go away. Basic etiquette emerges in the context of futile attempts to mitigate the unpleasantness, such as signs encouraging people to close the lid or comments in the code asking people to alphabetize, but people are generally in such a hurry to escape that these go largely unheeded.

At the end of the day, the only thing that’s going to stop the area from being a degenerative cesspool is the removal of the outhouse altogether.

Jeez, What’s So Bad About This

The actual equivalence of my metaphor is exaggerating my tone a bit, but I certainly think of this as an anti-pattern. Here’s why.

  1. What is this class’s single responsibility? The Single Responsibility Principle (SRP) wisely advises that a class should have exactly one reason to change. This class has as many reasons as it has commands. And, you don’t get to cop out by claiming that its single responsibility is to define and store information about everything a user might ever want to do (see God Class).
  2. This class is designed to be modified each and every time the GUI changes. That is, this thing will certainly be touched with every release, and it’ll probably be touched with every patch. The pattern here is “new functionality — remember to modify ApplicationCommands.cs”. Not only is that a gratuitous violation of (even complete reversal of) the Open/Closed Principle, but if you add a few more outhouses to the code base, people won’t even be able to keep track of all the changes that are needed to alter some small functionality of the software.
  3. Dependency inversion is clearly discouraged. While someone could always access the static property and inject it into another class, the entire purpose of making them public fields in a static class is to encourage inline use of them as global ‘constants’, from anywhere. Client code is not marshaling all of these at startup and passing them around, but rather simply using them in ad-hoc fashion wherever they are needed.
  4. Besides violating S, O, and D of SOLID, what if I want a different command depending on who is logged in? For example, let’s say that there is some Exit command that exits the application. Perhaps I want Exit command to exit if read-only user is logged in, but prompt with “are you sure” for read-write user. Because of the static nature of the property accessors here, I have to define two separate commands and switch over them depending on which user is logged in. Imagine how nasty this gets if there are many kinds of users with the need for many different commands. The rate of bloat of this class just skyrocketed from linear with functionality to proportional to (F*R*N) where F is functionality items, R is number of roles and N is nuance of behavior in roles.
  5. And, the rate of bloat of the client classes just went up a lot too, as they’ll need to figure out who is logged in and thus which of the commands to request.

  6. And, of course, there is the logistical problem that I noticed in the first place. This class is designed to force multiple developers to change it, often simultaneously. That’s a lot like designing a traffic light that’s sometimes green for everyone.

Alternative Design

So, how to work toward a more SOLID, flexible design? For a first step, I would make this an instance class, and hide the delegate methods. This would force clients to be decoupled from the definition, except in one main place. The second step would be to factor the commands with the more complex delegates into their own implementations of ICommand and thus their own classes. For simpler classes, these could simply be instantiated inline with the delegate methods collapsed to lambda expressions. Once everything had been factored into a dedicated class or flagged as declarable inline, the logic for generating these things could be moved into some sort of instance factory class that would create the various kinds of command. Now, we’re getting somewhere. The command classes have one reason to change (the command changes) and the factory has one reason to change (the logic for mapping requests to command instances changes). So, we’re looking better on SRP. The Open/Closed principle is looking more attainable too since the only class that won’t be closed for modification is the factory class itself as new functionality is added. Dependency inversion is looking up too, since we’re now invoking a factory that provides ICommand instances, so clients are not going out and searching for specific concrete instances on their own.

The one wrinkle is the shared global state from the previous commands static class. This would have to be passed into the factory and injected into the commands, as needed. If that starts to look daunting, don’t be discouraged. Sure, passing 20 or 30 classes into your factory looks really ugly, but the ugliness was there all along — you were just hiding it in the outhouse. Now that the outhouse is gone, you’ve got a bit of work to do shoveling the… you get the idea. Point is, at least you’re aware of these dependencies now and can create a strategy for managing them and getting them into your commands.

If necessary, this can be taken even further. To satisfy complaint (4), if that is really an issue, the abstract factory can be used. Alternatively, one could use reflection to create a store of all instances of ICommand in the application, keyed by their names. This is a convention over configuration solution that would allow clients to access commands by knowing only their names at runtime, and not anything about them beyond their interface definition. In this scheme, Open/Closed is followed religiously as no factory exists to modify with each new command. One can add functionality by changing a line of markup in the GUI and adding a new class. (I would advise against this strategy for the role/nuance based command scheme). Another alternative would be to read the commands in from meta-data, depending on the simplicity or complexity of the command semantics and how easily stored as data they could be. This is, perhaps the most flexible solution of all, though it may be too flexible and problematic if the commands are somewhat involved.

These are just ideas for directions of solution. There is no magic bullet. I’d say the important thing to do, in general, is recognize when you find yourself building an outhouse, and be aware of what problems it’s going to cause you. From there, my suggestions are all well and good in the abstract, but it will be up to you to determine how to proceed in transitioning to a better design.

By

Adding a Google Map to Android Application

I’m documenting here my first successful crack at adding a google map to an android application. Below are the steps I followed, with prerequisite steps of having the Android SDK and Eclipse installed, and being all set up for Android development (documented here).

  1. Created a new Android project
  2. Navigated to Help->Install New Software in Eclispe.
  3. Added a new source with URL http://dl.google.com/eclipse/plugin/3.7
  4. Selected all possible options (why not, right?) to have access to the google API in general.
  5. This install took about 5 minutes, all told, and I had to restart Eclipse
  6. In my new project, I navigated to project properties and went to Android, where I selected (the newly available) “Google APIs”
  7. From here, I got excited and ran my project, and was treated to a heaping helping of fail in the form of an error message saying that I needed API version 9 and my device was running API version 8 (Android 2.2.1). I fixed this by opening the manifest and changing the uses-sdk tag’s android:minSdkVersion to 8. Then when I ran, I had hello world on my phone. (Later, when all was working, I just deleted this line altogether, which eliminated an annoying build warning)
  8. With that in place, I added the node

    to my application node in the same manifest XML file.

  9. Then, as I discovered in an earlier post, I had to add
  10. From there, I followed the steps in this tutorial, starting at number 4.
  11. One thing to watch for in the tutorial is that you should add the lines about the map view after all boilerplate code already in onCreate or mapView will be set null and you’ll dereference it.

With all of this, if you ignore the bit about the API key, what you’ll wind up with is a map with no overlay on your phone. That is, it looks like everything is normal, including zoom icons, but the map hasn’t loaded yet. This was the state I found myself in when I decided that I’d take the last step and get the API key. This was not at all trivial.

I understand that if you’re familiar with the concept of signing software for distribution in app market, this probably makes sense. But, if this isn’t something you’ve been doing, it comes straight out of left field and, what’s more, there was no real place where how to do this was described in any detail. So, I’ll offer that here.

  1. Navigate to your JAVA_HOME bin folder (wherever your java and javac executables are)
  2. Run the command
    keytool -v -list {keystore}

    . The -v is important because this gives yo all the fingerprints (the default is SHA1, which won’t help you in the next step — you want MD5). The keystore is going to be debug.keystore, which is what your device uses for signing when you’re developing and not releasing. For me, this was located in C:\documents and settings\erik\.android on this win XP machine (YMMV with the directory)

  3. What you’ve done here is generated a fingerprint for the developer debug keystore that Eclipse automatically uses. This is fine until you want to deploy the app to an app store, at which time you’ll have to jump through a few more hoops.
  4. Take the key that this spits out and copy it (right click and select “mark” in cmd window), and paste it into the “my certificate’s MD5 fingerprint” text box here: http://code.google.com/android/maps-api-signup.html
  5. This will give you both your fingerprint, and an example layout XML to use in your Android map project
  6. Copy this into your project’s layout, following the guide for naming the attribute that contains the key. (That is, find your layout’s com.google.android.maps.MapView node and set its android:apiKey attribute to the same as the one on the page you’re looking at.
  7. Once you’ve got this, you can paste it into your map layout, run your app (phone or emulator) and get ready to start navigating to your heart’s content

After I went through all this, I found this clearly superior tutorial: http://mobiforge.com/developing/story/using-google-maps-android. This is really great for getting started, complete with code samples and starting as simple as possible.

By

Redirect Back with Spring 3.0 MVC

As I’m getting back into Java and particularly Spring MVC, it’s a bit of an adjustment period, as it always is when you’re dusting off old skills or trying something new. Things that should be easy are maddeningly beyond your reach. In light of that, I’m going to document a series of small milestones as I happen on them, in the hopes that someone else in my position or a complete newbie might find it useful.

So, today, I’m going to talk about processing a GET request without leaving the page. The reason I wanted to do this is that I have a page representing my house’s kitchen. The page has two buttons (really links styled as buttons through CSS) representing lights on and off. I’m providing a restful URL scheme to allow them to be turned on and off: kitchen/on and kitchen/off will turn the lights on and off, respectively. However, when this happens, I don’t have some kitchen/off.jsp page that I want handling this. I want them redirected right back to the kitchen page for further manipulation, if need be.

Here is how this was accomplished. Pay special attention to the kitchen() method taking the variable name and request as paramters:

So, the idea here is that I’m returning a redirect to the referrer. So, basic logic flow is that client sends an HTTP get request by clicking on the link. We process the request, take appropriate action, and then redirect back to where he started.

This certainly may not be the best way to accomplish what I’m doing, but it’s a way. And, my general operating philosophy is to get things working immediately, and then refactor and/or optimize from there. So, if you know of a better way to do it, by all means, comment. Otherwise, I’ll probably figure one out on my own sooner or later.

By

Adding a Switch to Your Home Automation

Last time in this series, I covered turning a lamp on and off with a keychain. Today, I’m going to up the ante and describe how to control an overhead light with your same keychain. This will be accomplished by replacing the switch for the light that you want to control with a new switch that you’re going order.

The benefits include not only the ability to remotely control the light itself, but also adding dimming capabilities to previously non-dimmable lights. In addition, their “soft” on and off behavior dramatically increases the lifespan of incandescent bulbs.

Prerequisites

A few things to check off your list before getting started:

  1. The light to be controlled must be an incandescent light with wattage of at least 40. Do not use on fluorescents, halogens, etc!.
  2. You must have the transceiver from the last post or this will not work.
  3. Needle nose pliers, screw driver(s), wire nuts, wire strippers/cutters, voltage tester.

Also, and perhaps most importantly, you’ll need some degree of comfort changing out a wall socket. I assume absolutely no responsibility for what you do here. Working with home electricity can be very dangerous, and if you are the least bit uncomfortable doing this, I recommend hiring an electrician to wire up the outlet.

Making the purchase

The first thing that you’re going to need to do is order your part. You’re going to want to order the X10 Wall Switch Module (WS467). The price on this varies, but you can probably get it for anywhere from $12 to $20. It is pictured here:

I recommend this one because it will fit into the same space as most existing standard toggle switches. If you are looking to replace a rocker switch, you can order WS12A, which tends to be a bit more pricey, but such is the cost of elegance.

Installation

The unit itself will come with instructions, but here is my description from experience:

  1. First, remove the wall plate from the box just to peer in and make sure there isn’t some kind of crazy wiring scenario going on that may make you want to abort mission and/or call in an electrician. This might include lots of different wires using this switch as a stop along the way to other boxes or outlets in the house, for instance. Careful while you do this as your electricity is still live.
  2. Once you’re satisfied that the mission looks feasible, head to your circuit breaker and kill the power. Make sure power is off by using your voltage tester with one lead on the hot wire and the other on ground somewhere (if you didn’t figure out which was hot and which was ground, try both leads on the switch).
  3. Once you’re doubly sure power is no longer flowing, pop the screws on the switch itself that are holding it to the junction box and remove the switch.
  4. Your old switch should have two connected leads, and each of these should have one or more wires connected to each lead. At this point, you can basically just swap the old wireup for the new module’s wireup — the colors don’t matter (though I’ve adopted a convention with these guys of wiring black to hot). You’re going to need your needle nose pliers and wire nuts because unlike most existing outlets, the X10 have wires instead of terminal receptacles.
  5. Once you’ve twisted up the wires and made sure no bare wires are showing anywhere, settle the switch into the junction box and screw it back in. You’re now going to restore power at the breaker box.
  6. When power is back on, verify that pushing the button on the switch turns lights on and pushing it again turns them off. This switch will always be manually operable. Also, don’t be surprised that the lights come on more gradually than you’re used to (it may seem weird at first, but I love this, personally).
  7. Once everything is working properly, you can replace the wall plate. However, in continuation from our first post, what you’re going to want to do now is match the dials on the switch to one of the remote settings, in terms of house code and unit code, before you replace the wall plate. You can always change this later, but you might as well do it now while it’s already off

Operation

Now, you’ve got it installed, and it should work manually or from your keychain remote. Generally speaking, wall switches are always operational both manually and remotely. These are not rocker/toggle switches but pushbutton switches, so they have no concept of state. Each time you press the button either on the switch or from the remote, the command boils down to “do the opposite of what you’re currently doing.” That is, there’s no concept of manual or remote push overriding the other — it’s just flipping the light from whatever state it was last in.

In addition to this functionality, you also get dimming functionality. If you hold the button in instead of simply pushing it, the light’s brightness will change. Holding it in when the light is off causes it to ramp up from dim to bright, and the opposite is true when the light is on – it will ramp down. On top of this, the light will ‘remember’ its last brightness setting. So, if I turn the light on by gradually bringing it up from dark and then turn it off, the next time I turn it on, it will ‘remember’ its previous brightness.

One final note is that there is a manual slide below the main switch. This is, in effect, a kill switch. If you push that, you will completely break the circuit and no amount of remote presses or X10 signals can activate it in this state. This is the equivalent of unplugging your transceiver module from the last post. If power is cut, the signals you send don’t matter.

Recap

So, now you’ve got a remote control capable of controlling two lights in the house. One is a lamp and the other an overhead light that can now be dimmed and brightened manually, as well as turned on and off remotely. (Next time I install a switch, I will take some pictures of what I’m doing and add them to the instructions above).