Eclipse: Optimising Handler Code in Menus

Eclipse has quite a bad reputation for requiring extremely verbose code for plugin development. As a developer, I constantly look for ways to make life easier for myself rather than having to produce lots and lots of code. Here is one way of reducing the code required to handle an eclipse ‘command’ extension.

The traditional setup for menu->command->handlers in eclipse

I was recently tasked with adding a “Global Menu” to eclipse to present the user with shortcuts for some plugin features that my colleagues have been working on. Traditionally, when adding an extension to eclipse, you would create a menu with entries linked to different commands and each command would require a unique handler object that implements the org.eclipse.core.commands.IHandler interface. This approach is shown in the adjacent diagram. Although commands themselves don’t have any code behind them (they are typically specified in 2-3 lines of XML inside the plugin file), all of the handlers have concrete implementations which means loading each individual class into memory (we’re not talking Gigs or even Megs here, but hell, every little helps right?).

Rather than implementing a new Handler class for every command, I chose to use a single handler class for a whole menu and use the Command ID (specified in the plugin XML) to decide what action to undertake. This cuts down the number of classes loaded into the virtual machine, the number of files that need to be updated in the event of a code change and therefore the efficiency of my plugin. Running a few comparisons on Java strings (which are just wrappers for char[] arrays) is much cheaper, memory and performance-wise, than loading up lots of small classes in the JVM.

Plugin XML Definition

In my plugin.xml file, I have several commands set up, each with the same argument for their defaultHandler.

 
<!-- Command definitions -->
<extension
          point="org.eclipse.ui.commands">
  <command
       commandId="uk.co.roarc.commands.commandA"
       id="uk.co.roarc.menus.commandA"
       mnemonic="A">
  </command>
  <command
       commandId="uk.co.roarc.commands.commandB"
       id="uk.co.roarc.menus.commandB"
       mnemonic="B">
  </command>
</extension>
 
<!-- Handler definitions -->
<extension
     point="org.eclipse.ui.handlers">
  <handler
        class="uk.co.roarc.internal.ui.handlers.MenuHandler"
        commandId="uk.co.roarc.commands.commandA">
  </handler>
  <handler
        class="uk.co.roarc.internal.ui.handlers.MenuHandler"
        commandId="uk.co.roarc.commands.commandB">
  </handler>
</extension>

Handler Code

The main method that we are concerned with within the handler is execute. Inside this method, we can find out which command was called by Eclipse through the getCommand().getId() method and therefore carry out the appropriate response.

public class MenuHandler implements IHandler {
 
  ...
  ...
  ...
 
    public Object execute(ExecutionEvent event) throws ExecutionException {
 
        String cmdID = event.getCommand().getId();
 
        if(cmdID.equals("uk.co.roarc.commands.commandA")){
            Activator.log(new Status(Status.INFO, Activator.getPluginId(),
                  "Caught action A..."));
        }elseif(cmdID.equals("uk.co.roarc.commands.commandB")){
            Activator.log(new Status(Status.INFO, Activator.getPluginId(),
                  "Caught action B..."));
        }
 
        return null;
    }
 
  ...
  ...
  ...
}

Finally…

This trade-off becomes less worthwhile as you add more and more commands to the same handler as more comparisons may have to be made before the right course of action is found. My rule of thumb is to stick to one handler per menu or toolbar. However, I still recommend using multiple handler classes within a plugin project unless you want things to get really ugly, really quickly.

Dev8D – The Things I Learned, The People I met and the fun stuff I did

Last week I had the great pleasure of attending the annual geektastic conference Dev8D in london. This is a conference put on around the same time every year and funded completely by 3rd party sponsors (for what we have already received, we are truly grateful. Thanks be to JISC. Amen).

Dev8D was my first developer conference. As you all know I’m an undergrad at Aberystwyth Uni and I’m on placement at IBM. As such, I felt like a naughty schoolchild sneaking into a conference for full time IT professionals and I was reminded of that every time people quizzed me about my job at IBM (printed on my name badge). However, I had a great time, I learned loads of cool stuff, met some truly awesome people and did loads of fun things too! Below is a short summary of each of these three things

Here is a short video of what we got up to over the 3 day conference. The Best of Dev8D

Things I learned

One of the biggest features of Dev8D is the selection of free education for developers, put on daily in 1 and 2 hour slots throughout the day. I went to several of these talks and picked up a hell of a lot.

Most Mind Blowing Session

The most impressive and ‘brain-hurty’ session I attended was the OpenIMAJ workshop. OpenIMAJ is a wonderfully convenient, easy* and ‘cross-platformy’ image processing library for Java. The library was put together by Jonathon Hare, Sina Samangooei and David Dupplaw, Doctors Jonathon and Sina were on hand  to run the workshop and teach us how to use their library.

*Disclaimer: well as easy as image processing gets at least

With OpenIMAJ, a copy of eclipse and some Java knowledge from all those Eclipse Plugins I have to build at work, I was able to put together several small applications to do things like detect different regions of colour in an image, draw onto a video and even analyse sound. Both Jonathon and Sina had to leave on the first day, but they made quite a first impression. Thanks very much guys!

Most Practical and Useful Session

The most useful session I attended had to be David Chalice’s talk on Git and Git Flow. During which, he demonstrated how to use Git for branching and introduced Vincent Driessen’s branching model for GIT – a system I have already fallen in love with and am using to maintain a couple of projects with. This truly was a hugely useful tip, thanks to Dave for a great discovery.

Most Entertaining Session

The most entertaining session I attended was Ben O’Steen’s interactive fiction talk. During which he introduced Inform 7,  a platform for building and distributing text-based adventure games, using plain English. Ben’s talk was really interesting and as well as demonstrating the power of Inform 7, he was able to show off a set of retro adventure games written in the 80s and a a Dev8D game he’d put together on the day, with various people from the committee implemented as characters in the game. I really enjoyed playing one retro game called 9:05 – a short but very satisfying text game with a twist. Thanks to Ben for introducing me to a whole new world of fiction-based happiness.

Cool People I Met

Most Influential Person

The person I spoke to who had the biggest impact on the way I perceive the computer science industry was certainly Patrick McSweeney.  His lightning talk on Sexism in video games was not only true, but very well delivered. This was one of the talks I remember the most and I predict is going to be one of the most talked about parts of Dev8D 2012.

Most helpful person in times of distress

As you may know, I am a bit of a country bumpkin and I get easily disoriented and lost in city landscapes. It was a good job then, that Mark Johnson was on hand when Pete and I got lost in London on our third day at Dev8D. Mark steered us towards the venue with astounding speed and skill. Three cheers for not getting lost!

Most fascinating hobbyist

As you may have spotted in the above video, there was a RepRap – 3D printing device – at the conference for the duration of the event. I find these 3D fabrication facilities are absolutely amazing. The dedication and patience to get one working however, should not be overlooked. Graham Klyne is the man who put together the glorious machine you see in the above video. He is also working on a 2nd one. He was a fascinating person to talk to and it was a real pleasure meeting him.

Fun Things I Did

As with all things in life, its important to strike a balance between work and pleasure. As well as learning lots while I was at Dev8D I also had lots of fun.

Observed the first major robot air disaster in history

The video above shows David Tarrant from Dev8D playing with a Quadrocoptor controlled by an XBox Kinect. This is a marvelous remote control helicopter with 4 blades and lots of clever onboard AI to allow the aircraft to stay level automatically and hover on the spot. Unfortunately, both of the two Quadrocoptors that were brought along to the event suffered tragic crashes. On Wednesday, one of the coptor’s was slammed against the roof after the person controlling it with a brain sensor thought too hard. The second device was smashed against a wall after a rogue hacker took control of it with their iPhone, flying it away from a startled David.

Nomming Dev8D food

The food provided at the event was spectacular. There was free lunch provided every day and a snack/drink buffet all day throughout the event – providing us with free chocolate and fizzy drinks if we got the munchies during a talk or lecture.

Cyberdog and Camden Market

After the talks finished on Wednesday night, my fellow adventurers Pete and Luke, and I, took a trip to Camden Town to visit the famous market. While we were there, we stumbled upon Cyberdog, possibly the coolest shop I’ve ever visited. As you can see from the picture, there are a pair of 20ft robots outside and that’s just the beginning. Inside they play trance music, have UV lights and Cyberpunk accessories to make any hacker squee with delight! This is a must see for any geeks in London.

And finally…

Of course we did lots of other stuff while we were there. If I met you, but didn’t mention you, your talk, or your tragic air disaster, then fear not. I probably still really enjoyed your company and apologise profusely for not writing about how awesome you are.

Huge thanks to Mahendra MaheyChris Gutteridge, and the rest of the Dev8D team for a fantastic time!

JAXP and XInclude woes

I’ve been working on a product at work that uses XML and the XInclude system to allow me to assemble large XML documents together dynamically. Unfortunately, for the last few days I’ve been getting a java error saying:

org.xml.sax.SAXParseException: Error attempting to parse XML file (href='YourDocument.xml').

It’s taken me a very very long time to find out what the problem is, but it turns out it was very simple. When JAXP does an include, it validates the XML and makes sure that it conforms to the any connected XSD schemas and that the elements are in the right namespace etc. If there are any problems with the structure of the document, it throws this, rather unhelpful, error message.

The problem I was having was that although I’d declared the XSD schema and XML namespace in the master document, the namespace had not been declared in the child document. As soon as I sorted that out, there were no more problems.

Has anyone else had any strange problems with JAXP? How did you resolve them? Feel free to comment below!

Don’t get milked: Debunking the Android Antivirus Cash Cow

“…Virus companies are playing on your fears to try to sell you bs protection software for Android…”

Chris DiBona, an open source programmer at Google, who produce Android OS

TL;DR?

Android OS, the operating system behind many popular smartphones including the HTC Desire and the Samsung Galaxy handsets, has been snowballing in popularity since its commercial release in September 2009.As with many emerging technologies, there was an onslaught of technically minded early adopters and in the very beginning, Average Joe didn’t bother. In the Android 1.x days, The technology was a little rudimentary, there was next to no publicity and Apple had released their shiny IPhone two years previously. Now, non technical people are adopting android and being tricked into buying needless, useless antivirus systems for their smartphones. Chris DiBona, one of Google’s lead open-source programmers wrote in a statement that ” virus companies are playing on your fears to try to sell you bs protection software for Android, RIM and IOS.” Here’s why you don’t need to buy protection for your phone and how to deal with some real threats without spending money on something that you don’t need.

“…To do anything important (good or bad) on Android, Linux, Mac or any other UNIX system, explicit permission must be given to the program… Programs cannot sneak around your Android device without your say so…”

Firstly, Android is a type of UNIX System. UNIX is the great grandfather of the modern operating system. Its where Apple Mac came from, its where Linux came from and its where Android came from. Conversely, it is not where Microsoft Windows and DOS came from. UNIX enforces something commonly known as file permissions – that is that only certain users can access files in certain ways. There are three primary permissions: Read, Write and Execute. If a file is not marked as “can be executed” then it cannot be run as a program. Windows and DOS (prior to Windows Vista which started implementing UAC, a less powerful but comparable system for Windows) do not have file permissions. This is one of the aspects of DOS-based operating systems that makes it significantly more vulnerable to viruses and malware. Once a program gets executed on Windows, it can do whatever it wants to your system, registering itself as a service on your system, modifying core operating system files, logging your keystrokes, or anything else you can imagine that is bad. To do anything important (good or bad) on Android, Linux, Mac or any other UNIX system, explicit permission must be given to the program that wants to make the changes. This makes the matter of virus protection a whole lot easier: Don’t want a program to delete your family photos or corrupt your system files Don’t give it permission!

On top of the native security that a UNIX operating system offers you, Android also offers further security in the form of Android permissions. Google developers put these in to restrict apps from doing various activities without the user’s consent. These are very fundamental and the user must grant these permissions when the app is installed (or not install it). For example, if I, as an android developer, want to write a program that can read and write files on the SD storage card, I must request permission from the operating system. If my application requires Internet access, I must request permission, if I want to use the GPS service, I must request permission and if I want to send and receive SMS or MMS messages, I must request permission. Android’s security architecture makes it almost impossible for a developer to write an app that does anything at all without being granted some permissions first.

Programs cannot sneak around your Android phone without your say so. As an Android user, there is no reason for you to install any apps to detect viruses. If anything bad happens, you’ll know about it, you’ll know which program you installed before the problems started and, unless you’ve really goofed and gave an app called “Delete all my files LOL” permission to access your storage card.

Another way to make sure your phone is secure is by being very careful about which apps you install and where they are from. For example, it is ok to trust an application written by Google that is available from the android market place. However, if you see an app from “Dodgy Inc.” that isn’t available from the marketplace but in fact a personal home page hosted in Russia, alarm bells should be ringing.

If you do decide to download an app from a third party site, you can easily make sure that the program is written by the publisher you are expecting via the Application Signing mechanism. You can think of this like the digital fingerprint of the developer being imprinted on every app that they produce. If the fingerprint doesn’t match the application developer, then the app is clearly not from the person it claims to be from. For example if an Email application claims to be from Google, but doesn’t have their fingerprint, then you can give that app a wide berth.

So, in conclusion, the best way to avoid an Android mess is to be vigilant about what you install on your device. Check that the application came from the Android Market, that the fingerprint matches the publisher you were expecting and that it doesn’t require permissions that you are not comfortable granting. If you follow these guidelines, you should have no problems with your device and there will be no need to purchase any extra protection.

 

__init__ Keywords must be strings – python setup.py

Snakey!

Sometimes Python can get itself into a pickle for no obvious reason. One of these less than obvious scenarios is the peculiar error code above caused when installing python packages using distutils When you see this error and there is a library name in the output – e.g. libmtp, it usually means that that library (or its development files) is not available on your system. In my case, the simple solution was to install libmtp-dev. After that, everything worked as expected :)

Programming Language Bigotry

A bigot is a person obstinately or intolerantly devoted to his or her own opinions and prejudices, especially one exhibiting intolerance, and animosity toward those of differing beliefs. (from wikipedia entry for “Bigotry”)

I’ve been a programmer for coming up to 10 years now, and in that time, I’ve done my fair share of what I call “Programming Language Bigotry”. That is, telling people not to use a specific programming language because its “rubbish” or “horrible” or “made by company X, who harm dolphins.” Until recently, I’ve been one of the biggest bigots out there in this sense. I’ve spent yonks telling people to avoid language X and use language Y instead, but I never usually had and real reasons for my propaganda other than “because language X is rubbish, and I don’t like it,” bearing in mind that I’ve probably never even tried programming in language X and I’m just making snap judgments. I have realised that this has at least two negative connotations: I’m restricting the experience and depth of knowledge of the bigotry victim, and I’m restricting my own depth of knowledge.

Lets take an example: Perl will do. So I’ve always been a bit anti-perl. Until 2009, I’d never even tried it. I disliked it because my software developer father and several other techies I know, told me it’s rubbish. I refused to learn it on principle, sticking to “oh Python will be better for this, its a better scripting language” Unfortunately, this lead me down an irreversible track of Perl bigotry. Anyone who told me they were learning Perl or writing an app in Perl would receive a cold stare followed by an encouragement to switch to a ‘better’ language. Until one day, I was forced to learn Perl by my University. This was a wonderful eye-opener for me as I was forced to see that Perl does have a lot of cool features, the inherently simple regular expressions system for example. File handling is also a breeze, and its so easy to do basic (and even more advanced) processing with plain text in Perl. Just as importantly though, learning Perl helped me to understand its disadvantages properly and to be able to advise friends when to use the language and when to avoid it from a more educated point of view. I.e. avoid Perl when there is a processing bottleneck in your application (as opposed to an I/O bottleneck) or avoid Perl when memory efficiency is key: use a language where you allocate memory yourself (i.e. C/C++).

Learning a language and understanding how it works, doesn’t mean you have to like that language any more (although in my case, learning Perl made me love Perl). It just means that you understand how it works, you understand its limitations and its strengths and you therefore can be more justified and educated in your opinions. For example, I’ve been a Java programmer since 2006, and I currently teach Java to an audience of interns at IBM. I’m not claiming to be an ‘expert’, so don’t challenge me on this. However, I think its safe to say that I know it pretty well and am aware of most of its capabilities and many of its pitfalls. I also know that I don’t like Java; not in the slightest. I find it bloaty, memory hungry, and slow. It’s too memory hungry and slow to do the work of C and C++, and its what I would assess as overkill for any job that a scripting language (like Perl or PHP) could carry out. It is a great tool for learning to program, but then so is Python.

What I’m trying to say is that, I’m no longer a programming language bigot. I’ve gotten over my ridiculous rule of not trying any new languages because someone tells me they are rubbish. If I’m told to avoid a language, or I find myself inexplicably repulsed by one. I vow to throw myself in at the deep end, learn it thoroughly and come out with either a new found love or lots of very good, valid reasons why I don’t like it. I think that to be a good programmer, you should try this philosophy too.

Customising PHP + Apache on Ubuntu 11.04

Unfortunately, when installing Apache and PHP on Ubuntu, several useful features are disabled for “security purposes” (although I’m convinced they do it just to mess with us). This post will briefly discuss how to set up and install the LAMP stack on Ubuntu.

Installing

To install the stack, simply run the following command. All of the packages should be part of the standard public repository.

sudo apt-get install apache2 phpmyadmin  mysql-server php5-mysql libapache2-mod-php5

That should be enough to get you rolling and have apt find all the packages that you’ll need. You’ll need to complete a few steps as part of this command such as setting the default MySQL database password etc. However, this is fairly straight forward.

Configuration

Enabling UserDir and PHP

The first problem I found with this setup was that User Directories (the apache plugin that lets you use public_html in your home directory and navigate to localhost/~username/ to get to your stuff) are turned off for Apache by default, and even when set up, PHP is also disabled in user directories. To enable this plugin with PHP support, follow these steps:

  • First, you’ll want to enable the user directories module in the configuration. Run the following command to set this up:
sudo a2enmod userdir
  •  Luckily, PHP is enabled by default because we installed PHPMyAdmin. However, we still need to enable PHP support inside the user directories. To do this we need to edit the configuration file hidden away at /etc/apache/mods-enabled/php5.conf. Open this up in your favourite text editor (as root)
  • Next you need to comment out the if module mod_userdir,c statement completely. Once this is complete, save and close the file
  • Now restart the Apache server with the following command:
sudo /etc/init.d/ restart

Enabling PHP Error display

If you are a PHP developer, the last thing you want to be doing is debugging code with a ‘white screen’ for output. This is what happens when PHP’s error output is turned off and the interpreter encounters a problem when running through apache by default in Ubuntu. To re-enable PHP error output, follow these steps:

  • Open up /etc/php5/apache2/php.ini as root in your favourite text editor
  • Now scroll down to display_errors=Off and replace with display_errors=On
  • Restart the server with the command:
sudo /etc/init.d/ restart

That’s all for now, but if I come up with any other useful tidbits, I’ll post them here :)

Building things with CMake

As a C/C++ developer, it can often be quite a struggle to find a nice way to be able to deploy your code across multiple platforms and build it. Being fairly comfortable at writing Makefiles is quite a handy skill. However, when you’re a primarily Linux user, digging through the instruction manual for Visual Studio Express is not really much fun (we don’t even talk about MingW here). Not only that, CMake makes it very easy to add new compilable targets to your projects without much hassle. Anyone who’s played with AutoMake knows what a nightmare it can be. However, with CMake autoreconf is a thing of the past too!

I’ve been using CMake for compiling a couple of recent projects and I’d say its the least trouble I’ve ever had with compiling things. Check it out here!

Safe management of your nuclear powerplant with singletons

As an evil genius, you will no doubt be running several Nuclear Plants all over the world to keep your world domination plan on track and to power your armies of robots. However, as of late you’ve been having problems controlling them all. Your minions have devised a software solution, but every time you use it, you accidentally put your plants into meltdown (oops…) Its like there are two or three version of the program running at once and they are all telling the reactor to heat up and destroying things. We don’t want another Chernobyl scene like the one photographed by Carl Montgomery to the left.

 

Fear not, you have too many instances of your nuclear plant running at the same time, what you need is a Singleton class.

Singletons are possibly the simplest Design Patterns to understand. They restrict a class to only one instance at a time and provide universal access to that one instance through some sort of accessor method. In this case, the nuclear power controller could be set up as a singleton class to make sure that only one control is running at any given point, therefore preventing catastrophic nuclear annihilation (well unless that was your intention *evil cackle*). The actual UML model for this can be seen below.

UML diagram for control systemThis is very simple. The uniqueInstance is used to hold a single instance of the NuclearPowerControl. This is usually empty when the program starts running. Rather than instantiating the object as usual, the programmer calls getInstance on the class. This will either return the uniqueInstance or, if that hasn’t been instantiated yet, create a new instance and return it. The key here is that there is only ever one instance of NuclearPowerControl, that is ‘uniqueInstance’. Since there is no public constructor provided, there is no way for any other part of the program to create a new control system.

The next article will be “Manufacturing your armies of doom with ‘Builders’”

Controlling your army with the Abstract Factory

Abstract Factory

The ‘Abstract Factory’ design pattern is one of the most useful and frequently used design patterns available to the common computer scientist. The factory allows a single controller system to create and manipulate sets of related, yet distinct objects without having to refer to their concrete implementations.

Robot Chicken

This sounds like a fairly complicated concept on the surface of things, but let me explain it another way. You have a software system for controlling your army of automated combatant poultry (ACP). However, every time you add a new variety of Robot Laser Chickens (like the one from nicole_writes to the left) or Exploding Kamikaze Ducks to your ranks,  you have to employ one of your evil minions to update the control system, bringing it down for several days, and leaving your army of crazed robotic birds to fend for themselves for a while.

An abstract factory could be used to separate these varying controls away from the main program so that an abstract class called “BirdControl” could be used to control and move any type of robot poultry and the system could be built in a modular way so that new combatants could be added on the fly. Check out the following UML diagram to see how this would work.

Control System Diagram

So, just to recap, the control system i.e. the program that you, as an evil genius use to control the army of birds, relies upon the ControlFactory to enable it to get access to bird controllers. Each instance is used to control a specific, real robot bird, out there on the battle field. The Control system is not fussy about how the bird control is implemented, as long as it provides move, attack and sleep functions.

The Control factory is a similar story. Again, the control system doesn’t care how this works, as long as when it calls “GetControl”, the factory is able to return a bird controller that provides the above functions.

The program can therefore load the ChickenControlFactory and DuckControlFactory dynamically and integrate the new control capabilities without stalling your World Domination Plans.

Continue to “Safe management of your nuclear powerplant with singletons”.