Java 8 on Raspberry Pi

 Development, general, Java  Comments Off on Java 8 on Raspberry Pi
May 192013

This is more of a reminder to myself. But others may find it useful.

Make sure ssh is enabled on your raspberry pi and set the memory split down to 16 for the gui.

ssh into the raspberry pi

cd /tmp
tar zxf jdk-8-ea-b36e-linux-arm-hflt-29_nov_2012.tar.gz
rm jdk-8-ea-b36e-linux-arm-hflt-29_nov_2012.tar.gz
sudo mv ./jdk1.8.0/ /opt/
sudo chown root:root -R /opt/jdk1.8.0/
sudo ln -s /opt/jdk1.8.0/ /opt/jdk8

Then just add it to your path.


and your done. I went on and install jetty 9

Spring MVC 3 testing RESTful api

 Java, Spring MVC  Comments Off on Spring MVC 3 testing RESTful api
Jul 102012

While there are lots of articles around testing spring mvc, it took me a while to find all the info I needed to get my tests up and running, so I wanted to put down here for others to gain from and also for me to lookup when I inevitably forget something in the future.

My project is using maven and these dependencies are used by my tests:

<!-- Test -->
<!-- Jackson convertors -->

Then the method under test: MissingPersonsController

@RequestMapping(method=RequestMethod.GET, value={"/missing"})
public ResponseEntity list(@RequestParam(value="limit",required=false) Integer limit ) {
        List missing = mpDao.listAll();
	return this.responseHandler(missing);
    catch(Exception e){
	return this.responseHandler(new ArrayList(), HttpStatus.INTERNAL_SERVER_ERROR);

And now finally the Test:

@ActiveProfiles(profiles = "development")
public class TestMissingPersonsController extends TestCase {
	MissingPersonsController cont;
	AnnotationMethodHandlerAdapter adapter;
	MockHttpServletRequest request;
	MockHttpServletResponse response;
	ObjectMapper mapper;
	TypeReference> type = new TypeReference>() {};

	public void setUp(){
		adapter = new AnnotationMethodHandlerAdapter();
		request = new MockHttpServletRequest();
		response = new MockHttpServletResponse();
		mapper	= new ObjectMapper();
	public void testShouldGetResponse() {
		request.addHeader("x-auth-api", "abcd1234");
		 adapter.handle(request, response, cont);
		 assertEquals(200, response.getStatus());
		 Map converted = mapper.readValue(response.getContentAsString(), type);
		 assertEquals("application/json", response.getContentType());
		}catch(Exception e){



Any questions about this give me a shout in the comments and I’ll explain anything I can.

Multiple processes in nodejs and sharing ports

 Development, node.js  Comments Off on Multiple processes in nodejs and sharing ports
Mar 172012

Recently I have been doing alot of work with node.js. As part of that work, we used multiple processes spawned by the node main node process. I wanted to just write down and share some of my experiences.

Starting new processes in node is easy
Nodejs docs

Using the child_process module you have several options for creating child processes. These include spawn,
fork and exec.

fork :
duplicates your shell in a sub shell. So if node is running you can run new node code in this new process.

exec :
Normally executes in the current shell replacing the process space. in nodejs it runs the command in a sub shell. To run the command in the current process space you should use execFile

spawn :
duplicates and then execs. So is like calling fork (create new duplicate process) and then execFile (the command you want to run in that environment).


   var child = require('child_process');

   var forked = child.fork("./mynewscript.js");

if you were to open up your terminal now and run a ps -ef | grep node, you should see two processes running (assuming the code doesn’t run and immediately exit).
Another useful feature, is that the child and parent process can send messages to one another. Taking the above example you can add.

  forked.on('message', function(msg){
     console.log("parent received message" + msg);
  // send message to child
  forked.send({ hello: 'world' });

  //in mynewscript.js
  process.on('message', function(m) {
    console.log('CHILD got message:', m);

  process.send({ foo: 'bar' });

Starting new processes that listens on a shared port is easy

Cluster info nodejs
Node.js has a cluster module which is made for sharing ports with multiple processes. “The cluster module allows you to easily create a network of processes that all share server ports.”

A quick example:

 var cluster = require('cluster');

 var server = require('http').createServer(function (req,res){
     res.end("hello world");
 var workers = [];
    for(var i=0; i < 2; i++){
       var worker = cluster.fork();
    //forked process space also have server

 //restart on death of any sub process
 cluster.on('death', function (worker){
      for(var i=0; i < workers.length){
            var aworker = workers[i];
            if( === workers.splice(i);
     var regen = cluster.fork();

Points to bear in mind

With the clustering if you kill the parent process the child processes will not die and so will continue to serve. If you want to stop all child processes when you stop the parent process do something like:

     for(var i=0; i < workers.length; i++){

Also something to note is that from my testing, if you put the http server on the main process and also on the worker processes, the main process will always answer the request and the child processes will receive none of the requests.


I’ve been writing a lot of javascript lately. Lots of nodejs and also sencha touch and jquerymobile.

I ran across a very frustrating error in jquerymobile the other day when injecting a list into the dom.

From jquerymobile docs it says you should call $(‘#mylist’).listview(‘refresh’);
However when I did this I got the error jquerymobile cannot call methods on listview prior to initialization. This is a very annoying error and it seems that jquerymobile has overlooked injecting content into the dom and restyling it, as from my google searches, it appears to be a common problem.

Here is my solution:

after injecting call:


Seems simple but I thought I would share this info as it caused quite a lot of pain before discovering the solution.

Project Plan for the year.

 Ideas, thoughts and musings, Uncategorized  Comments Off on Project Plan for the year.
Jan 282012

So it’s a new year and this post is largely a base of reference for myself to look over as the year progresses.

Coding Soundtracks

So I registered the domain and plan to and have been building a fairly simple website allowing coders to add their favourite coding soundtracks for other coders to find.
It is currently live at coding soundtracks


Eventzin was a previous project which while it never quite took off on its first iteration does offer potential for being a useful tool. Basically it is a simple way to set up events with your friends, even friends that aren’t on eventzin. This will be rebuilt with node and also js css html5 mobile apps, probably using either sencha touch or the new jqmobi.

Walking Companion

Walking companion is personal project which will be a native iOS app doing something which has already been done, but something which I want to have an experiment with. It will be an app to keep track of your walks, how far your walk each week, how many calories you burn etc.

Kids Game on the Ipad

Having a 3yr old has told me that parents with iPads buy quite a lot of apps. The iPad is a brilliant device for children. The interface is perfect for a child’s hands on interaction. All of this has made me want to do a kids game. More on this later.

This is an attempt to try harness the connected networks we have created and use them to help find missing people. Again this would likely be build in node js and then cross platform mobile app.


This is a business project. I bought this site at the end of last year and while it is paying for itself, it needs some investment of time and effort on my part to bring it to a better place and improve the revenue flow from it.


Finally, but not least, Nomad is a novel that I am writing. I hope to have a reasonable draft of this completed by the end of the year.

So that’s it. A busy year ahead as I have also just started a new job with start up company Feedhenry.

Running Multiple Apps on Same port Nodejs

 Development, general, node.js  Comments Off on Running Multiple Apps on Same port Nodejs
Jan 072012

This is actually surprisingly simple due to great work done by nodejitsu and also by the connect team. And I have largely copied the content from the links at the bottom of the page:

So with http proxy you can use it as follows:

npm install http-proxy

-- app.js ---

var http = require('http'),
httpProxy = require('http-proxy');
// Create your proxy server
var options = {
hostnameOnly: true,
router: {
'': '',
'': ''

in terminal run
nohup nodemon app.js & //will keep it running

-- foo.js --

var http = require('http');
http.createServer(function (req, res) {
res.writeHead(200, { 'Content-Type': 'text/plain' });
res.write('request successfully proxied 8001!' + '\n' + JSON.stringify(req.headers, true, 2));

in terminal run nodemon foo.js
-- bar.js --

var http = require('http');
http.createServer(function (req, res) {
res.writeHead(200, { 'Content-Type': 'text/plain' });
res.write('request successfully proxied 8001!' + '\n' + JSON.stringify(req.headers, true, 2));

in terminal run nodemon bar.js

finally edit your /private/etc/hosts file and add:

browse to and to see that both apps are running.

more info here
nodejitsu http proxy

The vhosts from connect is also really nice:
you can see a really good example of this in action here:

vhosts example

Run nodejs app on centos 5 vps

 node.js, Uncategorized  Comments Off on Run nodejs app on centos 5 vps
Dec 062011

So I have been doing quite a lot of experimenting with nodejs. Really enjoying it at the moment.
I started by creating a simple website using the express web framework and mongodb. I ran this app on the cloudfoundry service.
After doing this I decided to do something a little more challenging and interesting.
I’m going to be building a html5 and javascript multiplayer game and using nodejs on the server side for the tcp server.

I have already started on the code base locally, but wanted to run it on my vps so Today I got nodejs installed and connected to my nodejs tcp server.

For those interested in installing nodejs on centos 5 here is what I did:

First I installed the centos development tools package using yum:

yum groupinstall 'Development Tools' you may already have this.

Next I got nodejs from and used wget to pull it down; you could also clone using git.

wget where x is the vers you want.

next I ran

gunzip node-v0.x.x.tar.gz and also tar -xf node-v0.x.x.tar

then you need to cd into the new dir and run ./configure
then run make
and then finally make install

if like me you want node on a particular tcp in and out port you may need to configure the firewall. If you are using whm/cpanel this is quite easy by adding a port to the tcp_in and tcp_out fields of the firewall config.

I made a dir mkdir /var/node to keep my node app in and to test it I used the basic node tcp example on and connected using mudlet get mudlet

And thats it. So over the next few weeks I will add more posts about the development of the game etc.

Models in node.js and data validation

 Development, node.js  Comments Off on Models in node.js and data validation
Nov 292011

So I have been learning about node.js and I have to say that so far I am finding myself warming to it.

I wanted to write a little bit about how I’ve enjoyed using models in a node.js app using the Express web framework.

I am using mongodb for this app and so I am using the mongoose data layer. Mongoose is described as a object modeling tool.

You define a model as follows:

var mongoose = require('mongoose')
, Schema = mongoose.Schema;

/event model/

var Event = new Schema({
title : {type: String, index: true}
, content : {type: String}
, startdate : Date
, enddate : Date
, creator : Schema.ObjectId
, longlat : {lon:Number,lat:Number}
, county : {type:String, index:true}


Since writing this piece I have found out that there is a better way of achieving the same result. You can add validators to mongoosejs Schemas as follows:

if(\/\/[a-z0-9\-\.]+\.[a-z][a-z][a-z\.]*/gi) !== -1){
return true;
return false;
}, "link error");

The path is the path to the field in the schema and the second arg is the type of error which will be thrown.

What I have really liked is the “middleware” options. So you can define methods which will be called at a certain point in the execution; for example pre save.
Here is an example:


var errors = [];
console.log("I was called first before save");
if(this.title.length < 20) errors[errors.length] = {field:"title",message:"title invalid"}; if(errors.length > 0){
var error = new Error("Invalid Input");
error.errors = errors;


So in the above code next is the next function to be called in the chain which ends with the call back defined after save was called on the model

/some controller method

saveEvent : function(req,res){
var event = new Event();
event.title = req.body.title;,suc){
//control is returned here
if(err){ //do something with errors}

You can define more than one function in your model to be called pre some event in this case the next will refer to the next peice of middleware.

For more info on mongoose you can see here Middle ware in mongoose

Models and Decorators adjusting data the right way

 Development, general  Comments Off on Models and Decorators adjusting data the right way
Nov 102011

Carrying on from my previous article about heavy lifting models Heavy lifting models I thought I would write a little about decorators and models.

What is a decorator
Briefly a decorator is an class whose purpose it is to decorate another object adding functionality or adjusting the current functionality. This can sometimes be a good alternative to subclassing.

A quick example

abstract class PricingDecorator implements Pricing {

Pricing price;

public PricingDecorator(Pricing price) {
this.price = price;

public class DiscountPricingDecorator extends PricingDecorator {

Discount discount;

public DiscountPricingDecorator(Pricing price, Discount discount) {
super(price); = discount;

public Float getPrice() {
if (discount.getType() == Discount.DISCOUNT_TYPE_PERCENTAGE) {
return price.getPrice() - (discount.getValue() / 100) * price.getPrice();
} else if (discount.getType() == Discount.DISCOUNT_TYPE_PRICE) {
return discount.getValue();
return price.getPrice();

public class DiscountImp implements Discount {

public int type;
public Float value;

public DiscountImp(int type, Float value) throws InvalidDiscountType {
this.type = type;
this.value = value;

public int getType() {
return type;

private void checkType(int type) throws InvalidDiscountType {
if (type == Discount.DISCOUNT_TYPE_PERCENTAGE || type == Discount.DISCOUNT_TYPE_PRICE) {
} else {
throw new InvalidDiscountType("invalid discount type");

public void setType(int type) throws InvalidDiscountType {
this.type = type;

public Float getValue() {
return value;

public void setValue(Float value) {
this.value = value;


So some of the above code is contrived and compacted to save too much code. The above would be used to decorate a Pricing Object with a various Discounts. As shown below:

Discount discount = new DiscountImp(Discount.DISCOUNT_TYPE_PERCENTAGE, new Float(10));
Pricing price = new DiscountPricingDecorator(new ProductPricing(new Float(30)), discount);
System.out.print("discounted price" + price.getPrice());
}catch(InvalidDiscountType e){

It may be tempting to subclass your Pricing Object maybe into a DiscountedPricing:
and this is also an ok solution but in scenarios as seen above, I believe a Decorator is a better way of achieving this solution as I think it is clearer what is happening but because we have stuck to interface driven design we can reuse the decorator with other Pricing implementations and Discount implementations. It also maintains the simplicity of your Pricing Model class.


So recently I was asked for my thoughts on model view controller MVC and where business logic should be done. While I hope I answered the question well enough, I wanted to expand on my thoughts and maybe see what others thought.

What should a model know?
Often you see models represented as bare bean or container classes filled only with properties and setters and getters. Normally these properties relate to fields in some form of database. So the model only knows about the data it contains. This is a good thing. However it is also a very powerful piece of information. In my opinion the model should have many helper methods on top of the normal setters and getters to formulate the data as cleanly as possible for a nice skinny view and controller and also allowing improved decoupling of the code. The model should never contain any html, but an example of a helper method in a java bean model might be something like:

class Person{
private String firstName;
private String secondName;

/..Setter and Getters../

public String getFullName(){
return firstName+" "+secondName;

Another example of a helper method but with a bit more meat to it:

class Customer implements CustomerModel {
private List<ProductModel> customerProducts;

//normally would be a Hibernate hasMany mapping
public List<ProductModel> getCustomerProducts(){
if(customerProducts == null){
Mapper mapper = new ProductMapper();
customerProducts = mapper.findById(this.customerId);
return customerProducts;

public Integer productCount(){
return getCustomerProducts().size();

Public Integer getCustomersTotalSpend(){
List<Products> prods = getCustomerProducts();
Integer total = 0;
return total;
for(ProductModel prod : prods){
total+= prod.getValue();
return total;


These kind of methods are clearly tightly associated with the models data and so should never be done in the controller and even less so in the view. While the examples are a little simple and contrived, I think they highlight how you should think about your models. Having the model do as much as it can, but without stepping beyond the mark of what a model should know, provides you with the opportunity to have “Skinny controllers and Views with Fat Models”. In the above example, as long as you observe programming to an interface, you can easily swap in out models if needed without needing to change the controllers or the views and although I have written this example with Java in mind it transposes languages and is just as relevant in PHP or any other kind of language.

© 2012 Craig Brookes Suffusion theme by Sayontan Sinha