Moving to WordPress!

I want to have comments on my blog posts, but implementing them on Tumblr is just a pain in the butt. Apparently, Tumblr was never designed to handle this - serves me right for not thinking it through. Take a look below my posts here - you might spot a diminuitive ‘comments’ link which I have crow-barred in using Disqus, but it looks truely, truely awful.

So, you can find my future posts at http://jamesoncode.wordpress.com/ - see you there!

posted 2 years ago

Comments (View)

Developer’s Nirvana

Coding is easy. You have a specific, small problem (usually a large problem broken down into small units), you have a first try. Think, write a test, test fails, write some code, fix it when it goes wrong (it almost NEVER works first time!), see the test go green. Rinse, repeat.

Software development is hard, because it requires more than code - it requires organisation, discussion, debate, communication with customers, sharing ideas - in short, a lot of talk. That’s why it’s great to have an open-plan office where everyone can see and talk to everyone else without walking down a corridor and through some doors or on the phone - if you have those barriers you will communicate less, its just human nature.

There’s just one downside to open-plan: noise. And this (me included) can be a real bummer - especially when you are trying to get into ‘the zone’ on a problem. You could have 2 conversations going on either side of you, and this can be distracting.

The answer? Noise-cancelling headphones! I received a Sennheiser PXC-450 through the post today, and it has revolutionised (okay, that over the top) how I work.

Now I can hit the noise-cancelling function, and office noise fades into a blissful, muffled background. Sweet.

posted 2 years ago

Comments (View)

Creately for the win!

Gliffly Creately

A while ago I touted Gliffy as a great free easy-to-use online diagramming tool perfect for those little diagrams you may need from time to time but you havn’t got access to Visio (the daddy of diagramming).

Now there is Creately (currently in beta), which after trying I can say is a lot neater, cleaner and even easier to use! It has a pretty good set of features (I’m sure it will be improved upon), and there are loads of editor options for linking together objects, aligning etc etc. So for me, it’s Creately all the way (unless they go out of beta and start charging me!)

posted 2 years ago

Comments (View)

SqLite in-memory testing for Fluent NHibernate

I love Fluent NHibernate, it’s so readable and clean. But I found getting it configured (using the new Fluently.Configure() method) to play nicely in integration tests against SqLite in-memory database a bit of a challenge. The problem was working out how SqLite in-memory databases behave (they are destroyed when the connection is closed), and how to export the schema into the in-memory database. For the latter I’m grateful to Daniel Hölbling for his post describing how to do the latter using Fluent. Here’s the finished code:

public class NHibernateTestFixtureBase
{
    protected ISessionFactory SessionFactory { get; set; }
    protected Configuration SavedConfig { get; set; }

    public void SetUp()
    {
        FluentConfiguration configuration = Fluently.Configure()
            .Database(SQLiteConfiguration.Standard.InMemory())
            .Mappings(m =>
                m.FluentMappings
                .AddFromAssembly(
                    Assembly.Load("Assembly.With.Mappings")))
            .ExposeConfiguration(cfg =>
            {
                 cfg.AddProperties(new Dictionary
                 {{"proxyfactory.factory_class",
               "NHibernate.ByteCode.Castle.ProxyFactoryFactory, NHibernate.ByteCode.Castle"
                 }});
                 SavedConfig = cfg;
             });

        SessionFactory = configuration.BuildSessionFactory();
    }

    public ISession CreateSession()
    {
        ISession session = SessionFactory.OpenSession();
        var export = new SchemaExport(SavedConfig);
        export.Execute(true, true, false, session.Connection, null);
        return session;
    }
}

posted 2 years ago

Comments (View)

Printing in Java

Printing is often a desirable feature for an application, but not something you want to devote a lot of time implementing. You just want to print a component. Unfortunately, the standard Java SE library from Sun only offers only very low-level access to the printing API.

This does allow flexible and powerful control, but (as I found out) it also means that carrying out simple printing tasks can be a cumbersome, lengthy process. Hopefully, the generic printing package I have developed can help other Java developers out there to quickly get into printing, or at least to give suggestions of how to develop your own. So here it is.

Features:

  • Print an awt / swing component, such as a JPanel or JTextPane.
  • Scale the item to print to whatever size you need, e.g. scale to fill a page.
  • Print a single awt / swing component split over multiple pages
  • Print multiple pages, e.g. a book

Download

Class library (.jar)

Source code (.zip)

Netbeans project (.zip)

Documentation

Java doc

Quick-start

To use the printing library, download the jar file, and add it to your classpath.

Printing a component, using it’s preferred size, on a single page

  1. Create a PrintManager object.
         PrintManager manager = new PrintManager();
  2. (Optional) Show the print setup dialog to allow the user to choose print settings.
         manager.showPageSetupDialog();
  3. Create a page, passing the component you wish to print to the constructor.
         Page page = new Page(yourComponent);
  4. Pass the page to the PrintManager’s printSingleSwingComponent method.
         manager.printSingleSwingComponent(page);

Printing a component to fill the whole page

  1. Create a PrintManager object.
         PrintManager manager = new PrintManager();
  2. (Optional) Show the print setup dialog to allow the user to choose print settings.
         manager.showPageSetupDialog();
  3. Create a page, passing a PrintScale object to the constructor, along with the component you want to print.
         Page page = new Page(yourComponent, new PrintScale(1, PrintScale.SCALE_TO_PAGE));

    Use the double argument of the PrintScale object to specify what proportion of the page to print. For example, 0.5 will print to fill half the page:

         Page page = new Page(yourComponent, new PrintScale(0.5, PrintScale.SCALE_TO_PAGE));
  4. Pass the page to the PrintManager’s printSingleSwingComponent method.
         manager.printSingleSwingComponent(page);

Printing a component at half it’s actual size

The example above scales the component according to the page size (e.g. the whole page, or half a page). If you want to apply the scaling to the component itself (e.g. half the component’s actual size, or double the component’s actual size), use the PrintScale.SCALE_TO_COMPONENT argument in the PrintScale constructor.

  1. Create a PrintManager object.
         PrintManager manager = new PrintManager();
  2. (Optional) Show the print setup dialog to allow the user to choose print settings.
         manager.showPageSetupDialog();
  3. Create a page, passing a PrintScale object to the constructor, along with the component you want to print.
         Page page = new Page(yourComponent, new PrintScale(0.5, PrintScale.SCALE_TO_COMPONENT));

    Use the double argument of the PrintScale object to specify how much to scale the component. For example, 0.75 will print the component at three-quarters of it’s size.

         Page page = new Page(yourComponent, new PrintScale(0.75, PrintScale.SCALE_TO_COMPONENT));
  4. Pass the page to the PrintManager’s printSingleSwingComponent method.
         manager.printSingleSwingComponent(page);

posted 2 years ago

Comments (View)

Unit tests, mocking and DI in Java

I have recently been investigating dependency injection (DI) and unit testing using mock objects in Java. After browsing advice on Stack Overflow and trying out various frameworks, I have settled on my favourite stack:

  • Dependency Injection: Guice. It was either Guice or Spring, but don’t want / need all the other stuff bundled with Spring. Nice and lightweight, and simple.
  • Unit tests: JUnit. I chose this because Netbeans (my IDE of choice) has extensive integration with JUnit
  • Mocking framework: EasyMock. As the name implies, it’s easy to use nad seems to be popular, and the documentation is clear
  • AtUnit. This is a nice auto-mocker which integrates Guice with EasyMock, meaning much less code needs writing to set up tests with dependency injected mocks

I knew I had a good stack here because my first tests was easy and quick to write, readable and concise, requiring no base classes to write at all. For me, K.I.S.S. always wins - Keep It Simple Stupid! 

After downloading the libraries and adding them to my project, I just needed to write one class:

import static org.easymock.EasyMock.*;
import atunit.AtUnit;
import atunit.Container;
import atunit.Mock;
import atunit.MockFramework;
import atunit.Unit;
import com.google.inject.Inject;
import components.utilities.ISecurityTask;
import org.junit.Test;
import org.junit.runner.RunWith;

@RunWith(AtUnit.class)
@Container(Container.Option.GUICE)
@MockFramework(MockFramework.Option.EASYMOCK)
public class StartupTest
{
    @Inject @Unit Startup startup;
    @Mock ISecurityTask mockSecurityTask;

    @Test
    public void testStart() throws Exception
    {
        expect(mockSecurityTask.userIsAuthorised()).andReturn(true);
        replay(mockSecurityTask);
        startup.start();
        verify(mockSecurityTask);
    }
}

In this test I am testing my Startup class, which has a constructor dependency on ISecurityTask, testing to make sure that it calls userIsAuthorised() on ISecurityTask when startup() is called. To achive this I have:

  • Told JUnit to use AtUnit as the test runner with @RunWith
  • Told AtUnit that I am using Guice as theDI container with @container
  • Told AtUnti I am using EasyMock with @MockFramework
  • Mocked my ISecurityTask interface (you just need to annotate it with @mock and AtUnit will create a mock for it when you run your test) to decouple the concree implementation of ScurityTask from my test
  • Declared my Startup class as the unit under test with @Unit
  • Told Guice to inject starup with dependencies with @Inject. This is where the AtUnit magic happens: because I have declared a mock ISecurityTask, the mock will automatically by injected into Startup
  • Set up an expectation on the mock security task for a call to its userIsAuthorised() method
  • Called startup() on the Statrup class

Now I just need to right-click the test (or a test suite which includes the test) in NetBeans, and hit ‘Run’. I’ll look into running them using Ant later!

posted 2 years ago

Comments (View)

Online workspaces for project management

I’m really excited about the future of software as a service, and looking forward to the big fight between Google (e.g. Google Docs) and Microsoft (e.g. Office Live) for dominance of the online software market. Project management seemed a great candidate for an online service, so I’ve signed up for an Assembla account to try the concept out. So far I love it, here are the main things I like:

  • No setup - I don’t have to install and maintain Subversion for source control, Trac for ticketing, a wiki - Assembla provides them all. I can concentrate on developing software.
  • No backups or disaster recovery plans needed - I trust Assembla to provide this. My office could burn down, and everything important (code, tickets) would be safe. Assembla even has plans to allow you to download backups for you to keep, so even if Assembla exploded, you have all your data.
  • I or anyone else I allow can access it and contribute from anywhere.

Here are some limitations:

  • Customisation: you don’t have control.
  • Continuous integration: you can’t (at the moment) easily run continuous integration on your source repositories. (There are plans to introduce this feature.)
  • Speed of checkin / checkout: slower than a local repository on your intranet

For small teams / companies I can see Assembla being a really attractive solution.

posted 2 years ago

Comments (View)
Went climbing at the Berghaus Wall in Eldon Square (Newcastle upon Tyne) at lunchtime today - it’s actually too hot to be outside. Nobody else there - the whole wall to myself :)

What I didn’t expect was the pensioner’s ball taking place in the sports hall below! Surreal

Went climbing at the Berghaus Wall in Eldon Square (Newcastle upon Tyne) at lunchtime today - it’s actually too hot to be outside. Nobody else there - the whole wall to myself :)

What I didn’t expect was the pensioner’s ball taking place in the sports hall below! Surreal

posted 2 years ago

Comments (View)

Optimisation benchmark results

In an earlier post I outlined some options for optimising a bottleneck in a system I am working on. Some basic benchmark results:

  • Original box query times:

    • 8141 milliseconds - queried all boxes in March
    • 8093 milliseconds - queried all boxes in February
    • 8110 milliseconds - queried all boxes in January
    • 8063 milliseconds - added a new box and queried all boxes in January (again)
    • 7953 milliseconds - queried all boxes in January (again)
  • Query times with 20 MB cache set in MySql:

    • 10666 milliseconds - queried all boxes in March
    • 8555 milliseconds - queried all boxes in February
    • 7927 milliseconds - queried all boxes in January
    • 7919 milliseconds - added a new box and queried all boxes in January (again)
    • 55 milliseconds - queried all boxes in January (again)
  • Query times after adding a File Count column to the box table and using this instead of joins to count files. Modified app code to set the file count correctly when adding or editing a box:

    • 974 milliseconds - queried all boxes in March
    • 843 milliseconds - queried all boxes in February
    • 858 milliseconds - queried all boxes in January
    • 861 milliseconds - added a new box and queried all boxes in January (again)
    • 834 milliseconds - queried all boxes in January (again)
  • Query times after adding a File Count column to the box table and using this instead of joins to count files. Modified app code to set the file count correctly when adding or editing a box:

    • 3548 milliseconds - queried all boxes in March
    • 854 milliseconds - queried all boxes in February
    • 840 milliseconds - queried all boxes in January
    • 840 milliseconds - added a new box and queried all boxes in January (again)
    • 38 milliseconds - queried all boxes in January (again)

Conclusion

Cache

Using the cache seems to add overhead (increased query time) for the very first query. After that, subsequent queries which are different (e.g. queries for January, February and March), or are done after the table has changed (e.g. after adding a new box, which will flush the cache) are about the same as without the cache. But when two subsequent queries are the same and have the same result set, the performance increase is jaw dropping - going from 8 seconds to about 50 milliseconds!

File count column

A nice, easy, predictable and decent decrease in query time. Not as good as 50 milliseconds, but it is consistently good on all queries, regardless if anything has changed in the tables.

Both

An interesting mix. Probably what I will go for. Still a big overhead on that first query, but after that I get the benefit of good performance on all queries, and extra-good performance when the cache kicks in (e.g. the last query for January).

posted 2 years ago

Comments (View)

‘Copy Local’ in Visual Studio

Trying MySql with NHibernate for the first time. On the first run, I got:

Could not create the driver from NHibernate.Driver.MySqlDataDriver

For some reason, when I referenced the MySql Connector-Net in my project, it’s ‘Copy Local’ attribute was set to false (usually false is only set on System DLLs that will definately be in the GAC). Setting it to true fixed my problem.

posted 2 years ago

Comments (View)