A Swift molecular viewing app for iOS

Today I have uploaded and made public iMolecular Visualisation System (iMVS), a simple molecular visualisation system (app) for viewing proteins in 3D. It is a project I used to learn Apple’s new Swift programming language. It makes use of object oriented programming in modelling the molecule data structures and SceneKit for 3D rendering, and uses a simple Storyboard for creating the views. The project has a modest roadmap to make it more usable, include some networking, some further display modes and some data persistence.

iMolecular Visualisation System

CakePHP join models – or hasMany through

The following article has been coded, tested and submitted to the Cake 1.3 Book by Roxxor but has yet to be published.

It is sometimes desirable to store additional data with a many to many association. Consider the following

Student hasAndBelongsToMany Course
Course hasAndBelongsToMany Student

In other words, a Student can take many Courses and a Course can be taken my many Students. This is a simple many to many association demanding a table such as this

id | student_id | course_id

Now what if we want to store the number of days that were attended by the student on the course and their final grade? The table we’d want would be

id | student_id | course_id | days_attended | grade

The trouble is, hasAndBelongsToMany will not support this type of scenario because when hasAndBelongsToMany associations are saved, the association is deleted first. You would lose the extra data in the columns as it is not replaced in the new insert.

The way to implement our requirement is to use a join model, otherwise known (in Rails) as a hasMany through association. That is, the association is a model itself. So, we can create a new model CourseMembership. Take a look at the following models.

		student.php

		class Student extends AppModel
		{
			public $hasMany = array(
				'CourseMembership'
			);

			public $validate = array(
				'first_name' => array(
					'rule' => 'notEmpty',
					'message' => 'A first name is required'
				),
				'last_name' => array(
					'rule' => 'notEmpty',
					'message' => 'A last name is required'
				)
			);
		}

		course.php

		class Course extends AppModel
		{
			public $hasMany = array(
				'CourseMembership'
			);

			public $validate = array(
				'name' => array(
					'rule' => 'notEmpty',
					'message' => 'A course name is required'
				)
			);
		}

		course_membership.php

		class CourseMembership extends AppModel
		{
			public $belongsTo = array(
				'Student', 'Course'
			);

			public $validate = array(
				'days_attended' => array(
					'rule' => 'numeric',
					'message' => 'Enter the number of days the student attended'
				),
				'grade' => array(
					'rule' => 'notEmpty',
					'message' => 'Select the grade the student received'
				)
			);
		}

The CourseMembership join model uniquely identifies a given Student’s participation on a Course in addition to extra meta-information.

Working with join model data

Now that the models have been defined, let’s see how we can save all of this. Let’s say the Head of Cake School has asked us the developer to write an application that allows him to log a student’s attendance on a course with days attended and grade. Take a look at the following code.

	controllers/course_membership_controller.php

	class CourseMembershipsController extends AppController
	{
		public $uses = array('CourseMembership');

		public function index() {
			$this->set('course_memberships_list', $this->CourseMembership->find('all'));
		}

		public function add() {

			if (! empty($this->data)) {

				if ($this->CourseMembership->saveAll(
					$this->data, array('validate' => 'first'))) {

					$this->redirect(array('action' => 'index'));
				}
			}
		}
	}

	views/course_memberships/add.ctp

		echo $form->create('CourseMembership');
		echo $form->input('Student.first_name');
		echo $form->input('Student.last_name');
		echo $form->input('Course.name');
		echo $form->input('CourseMembership.days_attended');
		echo $form->input('CourseMembership.grade');
		echo '';
		echo $form->end();

You can see that the form uses the form helper’s dot notation to build up the data array for the controller’s save which looks a bit like this when submitted.

	Array
	(
	    [Student] => Array
	        (
	            [first_name] => Joe
	            [last_name] => Bloggs
	        )

	    [Course] => Array
	        (
	            [name] => Cake
	        )

	    [CourseMembership] => Array
	        (
	            [days_attended] => 5
	            [grade] => A
	        )

	)

Cake will happily be able to save the lot together and assigning the foreign keys of the Student and Course into CourseMembership with a saveAll call with this data structure. If we run the index action of our CourseMembershipsController the data structure received now from a find(‘all’) is:

	Array
	(
	    [0] => Array
	        (
	            [CourseMembership] => Array
	                (
	                    [id] => 1
	                    [student_id] => 1
	                    [course_id] => 1
	                    [days_attended] => 5
	                    [grade] => A
	                )

	            [Student] => Array
	                (
	                    [id] => 1
	                    [first_name] => Joe
	                    [last_name] => Bloggs
	                )

	            [Course] => Array
	                (
	                    [id] => 1
	                    [name] => Cake
	                )

	        )

	)

There are of course many ways to work with a join model. The version above assumes you want to save everything at-once. There will be cases where you want to create the Student and Course independently and at a later point associate the two together with a CourseMembership. So you might have a form that allows selection of existing students and courses from picklists or ID entry and then the two meta-fields for the CourseMembership, e.g.

	views/course_memberships/add.ctp

	echo $form->create('CourseMembership');
	echo $form->input('Student.id', array('type' => 'text', 'label' => 'Student ID', 'default' => 1));
	echo $form->input('Course.id', array('type' => 'text', 'label' => 'Course ID', 'default' => 1));
	echo $form->input('CourseMembership.days_attended');
	echo $form->input('CourseMembership.grade');
	echo '';
	echo $form->end();
	$this->data when POSTed

	Array
	(
	    [Student] => Array
	        (
	            [id] => 1
	        )

	    [Course] => Array
	        (
	            [id] => 1
	        )

	    [CourseMembership] => Array
	        (
	            [days_attended] => 10
	            [grade] => 5
	        )

	)

Again Cake is good to us and pulls the Student id and Course id into the CourseMembership with the saveAll.

Join models are pretty useful things to be able to use and Cake makes it easy to do so with its built-in hasMany and belongsTo associations and saveAll feature.

DIY how to rescue data from your Western Digital MyBook

Western Digital MyBook data recovery – the DIY method.

So today I was just listening to some music that I keep on my Western Digital My Book ES 500GB external drive and suddenly the music stops playing and worse the MyBook no longer appears in My Computer. Oh dear.

I notice that the drive is still listed in the Device Manager which is strange. All my data is on this drive and my heart sinks.

However, one week on and I have recovered all my data and consider the drive to be rescued. This article describes how.

Things that didn’t work work for me

  • Unplugging the power cable from the MyBook and back in. No show.
  • Restarting Windows. Nope, she’s still not here.
  • Using the USB system tray “Safely Remove Hardware” tool to disconnect the MyBook and reconnect. Still being stood up.
  • Trying Linux – I’m going home.

So what works?

Well, dismantling your MyBook and plugging it directly into a spare SATA slot in your motherboard is what. And that’s because common opinion has it that the USB connector board in the MyBook enclosure is crap and breaks for some reason.

Note! You will likely ruin the enclosure casing in this procedure, so be aware. You will also need to make sure you actually have a spare SATA slot on your motherboard and an additional SATA power cable as you will need both to hook up the back of your MyBook harddrive. If you don’t have those, then you can probably find another USB SATA harddrive connector to do the same thing since it’s the actual USB controller stuff that breaks easily I read on these MyBooks.

Step 1. Remove the rubber seal around the enclosure if you have one.

Step 2. I used a normal eating knife to pry around the casing edges to snap open the catches. You can lift the casing and look for where the catches are then just lever them up to release.

Step 3. Continue releasing the catches until the sleeve pulls off.

Step 4. Voila! You are now ready.

Step 5. Unscrew the circled screws with a Phillips screwdriver.

Step 6. Also unscrew this one.

Step 7. And finally unscrew these 2 and uou will free the harddrive. It probably has some additional casing on it. I didn’t bother to remove that but it’s just a couple more screws if you do want to get rid of it to mount it into a desktop slot.

Step 8. Get your standard SATA data cable

Step 9. And plug it into a free motherboard SATA socket.

Step 10. Hook the other end up to the back of the harddrive and plug in a spare SATA power cable too.

Step 11. Now, I had to activate the SATA slot I used on the motherboard. You may not have to. Best to check in your BIOS to see if there is an On/Off setting like mine had.

Step 12. Boot into Windows and OH … MY … GOD. It’s back and it’s working perfectly. No data loss :) Am so happy.

Hope it works for you too!

PHP SoapClient Could Not Connect to Host

The Could Not Connect to Host error message when using PHP SoapClient can be a tricky sucker to trace the root of. There are varying responses across the internets to what may cause this problem such as firewalls and proxies.

But there is one other thing you can check. Look through the WSDL for the soap:address locations. You may find that a server name is given that the machine running your code does not have access to.

Take a look at the example below;


  
    
  

I experienced the issue when deploying my code from my dev machine to a live server. I couldn’t understand why my dev machine was fine calling the web services and the live server was not.

That’s because I had forgotten that I had provided access to my dev machine in the early days of coding to the appserver3 server name by virtue of a hosts file entry. Looking in my hosts file revealed

123.123.123.123  appserver3

And this is what was missing on the live server.

So if you get this error and you just can’t figure it out, take a wander through the WSDL for location URLs that may not be accessible to the server running your code. If you have a server name rather than an IP as in the example above, then add a hosts file mapping to the IP and you’re away.

Using XNA DrawableGameComponent

This post is for those thinking about using the DrawableGameComponent class in the XNA framework.

I am going to demonstrate how you might use the class by using the example of dice.

Project Files

Download Dice.zip for the Visual Studio Express 2005 XNA 2.0 project files. Extract the zip, then run Dice.csproj to open the project in VSE 2005. You can then just compile the project by pressing the play icon.

DrawableGameComponent

Dice are ideal for illustrating the DrawableGameComponent class because dice, even in the real-world, are reusable across many table games, and that’s really where DrawableGameComponent comes in handy.

The DrawableGameComponent provides the developer a nice structured way to create modular, self-contained and reusable game components. A component should by definition be able to be dropped into a game and with minimal wiring up, just work.

Understanding the Source

The way in which to use DrawableGameComponent is to extend it. By doing this, when we add our component to the game, the XNA framework will know how to call it properly.

The Dice class therefore is made to extend DrawableGameComponent. The constructor for DrawableGameComponent requires the Game instance to be passed, so we need to ensure our component class constructor receives the game instance in addition to any specific variables so that it may pass the game instance on to the superclass for instantiation.

In essence when creating a component, you will want to override 3 of the methods of the DrawableGameComponent superclass; LoadContent, Update and Draw. For beginners, LoadContent is a method in which we instantiate resources like graphics and sounds, Update is used to update game logic (and this is done per game loop cycle – which is fast), and Draw in which we paint stuff to the screen.

You will see in the Dice class that I have overridden these 3 methods using the override keyword in the method declarations.  Each of these methods as their last statement call the superclass’s version of the method to ensure the component is fully called.

A die has 6 faces, so I added 6 graphics files to represent each face of a die. These are added to the Content folder in the project. As such, within LoadContent, I am able to load them as Texture2D files.

A separate Die class represents a single die since the actual Dice class supports as many die instances as you want. In practice this will be 1 or 2, but hey, it’s all about extensibility!

The Die class contains a method for rolling the single die. It uses a static instance of Random to roll a random face between 1 and 6.

The Dice class also contains some logic methods. Roll iterates all the die instances and calls their Roll methods. And Total returns the sum of all die instance faces at the time of call.

Using the Dice Component

To use the Dice component, we need to add it to our main game instance. In Game1 we just have to add an instance of Dice to the Game.Components collection. Simple as that.

By doing this, each game update tick, the Dice component’s Update and Draw methods are called.

The Dice.Update method monitors the keyboard for presses of the Space Bar. This triggers a roll of the active die instances.

Dice.Draw draws the relevant Texture2D graphics for the active die instances.

In the project, I just draw out each die next to each other.

Keep pressing Space Bar and you will see the dice change as you roll them.#

Final Words

I hope this article was of use to some of you, particularly those starting out with XNA. The DrawableGameComponent method of encapsulating game logic is a really good pattern to follow.

Some of you may be wondering though – since the Dice class is constantly monitoring the Space Bar, when you add that to a real game, where you would want to block dice rolls until certain other events take place – how do you do that?

Well, you’d need additional wiring in that case. One idea might be to maintain a flag CanDiceRoll for example in the main game. The Dice.Update method would need to use a conditional block based on that flag to determine if it should roll. Suggestions from readers are welcome.

Wrapping text in FPDF table cells

This article aims to help those who like myself wondered how to make text wrap within a table cell using FPDF to generate a the PDF. A few posts around the web seem to have missed the point that wrapping comes out of the box in FPDF using the MultiCell function. However, it’s just a tiny bit tricky but not prohibitively so. So, this is what we are aiming for – an invoice.

FPDF Invoice

There are 2 examples of wrapping here. Firstly the client address is wrapped, and secondly the first row of the line item data has a wrapped description.

In both cases the MultiCell in-built function is used. Before I had this solution working I was using the Cell function. In that case, long text simply continued through to the next cell ‘Quantity’. In the case of Cell, you can simply output a series of calls to the function with a cell width and so fourth and the cells will line up against each other on the same line.

When I switched to MultiCell for the first cell of each row only, I found that it would cause all subsequent cells in the same row to wrap to the next line. Therefore my solution was to use the SetXY function to reposition the ‘cursor’ back to where the 2nd cell of the current row would normally be, and then proceed to use Cell calls.

In order to do that it’s a case of marking the current X and Y coordinates of the cursor prior to entering the line item loop and calling SetXY just after the 1st cell MultiCell function call. That solved the line wrapping issue and my text wrapped inside the first cell – great.

The second issue however is that the MultiCell is arbitrarily high depending on the amount of text wrapping going on. I had been provided a static height to my Cell calls as as such they were now out of line with the first column, that is, the text and border lines were all out of sync with the 1st column.

To solve that problem it was a case of grabbing the Y coordinate of the cursor before and immediately after the MultiCell call, finding the difference to ascertain the height of the cell, and then using this to size the height of the remaining Cell calls on the row.

See it in action

Source Code

Please feel free to download the source code for this article which builds the invoice PDFs as described.

The source code is provided as a ZIP file with index.php for the mixed example and index-all-mc.php for all Multi-cell with the 2 classes that build the PDFs. You will need to obtain the FPDF library yourself and modify the FPDF_FONTPATH and fpdf.php require. By default the code looks for fpdf17 in the same folder as the index files.

Best of luck!

XAMPP on Vista

I found that getting XAMPP to work on Vista required 2 things. A fresh 1.6.2 install today did not work out of the box.

First, don’t forget to run setup_xampp.bat in the XAMPP installation folder.

Second, you need a file called msvcp71.dll to reside in the root XAMPP folder. I copied this from an old XP Windows/system32 folder, but you might need to get it elsewhere.

With these 2 things taken care of, XAMPP 1.6.2 was happy to run in Vista.

Dynamic PDF generation with JasperReports, Struts and a database

Generating a dynamic PDF from a database with JasperReports and Struts

A requirement appeared recently as part of a Purchase Ordering application to allow a user to dynamically generate a PDF copy of the final Purchase Order to send to the supplier. Taking a look around I stumbled rather fortunately upon an API called JasperReports (JR). JasperReports is a powerful open source Java reporting tool that has the ability to deliver rich content onto the screen, to the printer or into PDF, HTML, XLS, CSV and XML files. This tutorial is aimed at the beginner JR user who is happy with J2EE web application development. It will show you how JR was used to deliver the requirement described and should convince you that it is a truly fantastic piece of kit.

What we will be doing in 1 sentence

You will define a report template using JR’s XML syntax and then bind data from a database into it and get a PDF sent back to a web browser.

What will I need

OK, you need a few bits of kit. Firstly, I hate to break it to you but I kind of cheated with defining the report template. See, thing is, you can write this manually, but I didn’t have time to learn the ins and outs of JR’s XML syntax, so I got hold of JasperAssistant, a brilliant Eclipse IDE plugin that allows a developer to visually draw their report for JR. If like me you use Eclipse, or indeed you just want to use this method for creating your report template, grab Eclipse and JasperAssistant. There is also another tool called iReport that does a similar thing without Eclipse but you’ll need to look at that yourself. So, you will need

  • JasperReports – head to the Download section
  • Either JasperAssistant, iReports OR a willingness to learn the JR XML syntax for which there are many examples with the JR distribution. Whichever method you chose, I leave it to you to configure the environment – full instructions are available on each site.
  • A knowledge of J2EE web application development. In this tutorial I shall be using Struts but only in the slightest way to illustrate how to send the PDF back to the web user. You can do the same stuff with a plain old Servlet.

Creating the report template

First of all, you need to think about what data your report needs to show. In my scenario, we are talking about a Purchase Ordering application. In this application is the master object called PurchaseOrder. A PurchaseOrder has at least one or more LineItem stored in a list collection. Each of these 2 objects have other attributes that reveal information, e.g the PuchaseOrder has a createdDate and orderId whereas a LineItem has a description and unitCost. These objects are persisted to a database. It is not really important how, it may be via a series of SQL statements or it may be via some Object Relational Mapping API such as Hibernate (which for the record, is how I have done it), but what matters is that you have code in place to save and fetch your particular application objects/data. Now, my report layout requires that the header contain master detail such as the created date and order id and then to list all the line items in a table below. Finally, some more master detail such as delivery address is required at the foot. JR divides up a report into a series of stacked bands from top to bottom, e.g title, header, detail and footer are names of some bands. In my case, I chose to use the header, detail and footer bands for the areas I have just mentioned.

Parameters, fields and static text

Using JasperAssistant, I was able to draw my report layout using guides and properties boxes. You may do the same or do it manually, but the main elements that I had to use were parameters, fields and static text. JR has a mechanism for binding a Map of data to a report. This is referred to as a parameter map. The idea being that the map element’s key is used for binding the map element’s value to the parameter defined in the report. For example, if I have an empty report with a parameter declaration orderId as follows:

http://jasperreports.sourceforge.net/dtds/jasperreport.dtd">

then I would need a corresponding Map

Map map = new HashMap();
map.put(orderId, "12345");

I will show how you can bind this to the report later. In addition to the parameter map mechanism, you can also use something called a DataSource. You musn’t think a DataSource is a database necessarily like it is with an application server. A DataSource is an object that provides methods that can be called by the report in obtaining rows of data. For my purposes if you remember, I have a collection of LineItem elements inside my PurchaseOrder and I need to loop through them outputting to a table in my report. The way I achieved this was by implementing JR’s DataSource interface JRDataSource. This interface requires an implementation provide methods;

public boolean next() throws JRException;
public Object getFieldValue(JRField field) throws JRException;

In your report, you must define fields in the detail band. When the report is run together with the custom implementation, JR will automatically keep calling next and then attempt to bind each field in the detail band to a call to getFieldValue(JRField field).

Since my implementation of JRDataSource will return operation on a collection of LineItem I have named my DataSource LineItemDataSource. It has 2 class variables; private List data; private int index; Which is an internal data List to use (which I will populate with LineItem objects later), and the index allows us to know at which position we are in iteration of the List. That’s why you need to use List, because it is indexed and has methods for getting elements at certain indexes.

I also have an add(LineItem lineItem) for adding LineItem objects. Now, the implementation of next is quite simple:

public boolean next() throws JRException {
  index++;
  return (index < data.size());
}

I increase the index by 1, and then return a boolean as to whether the index is still within the List's bounds. JR will use this to determine if any more binding to fields in the detail band is required. Finally, the implementation of getFieldValue. First, let's show you how to define iterating fields in your report template. You need to define fields in your detail band like this:

< ![CDATA[$F{getItemName}]]> < ![CDATA[$F{getItemCost}]]>

The detail band is iterated over using the custom DataSource implementation which I will show you in a moment. What is important is that you declare your textField elements along with their child textFieldExpression elements. The textFieldExpression tells the JR binding process what fields (by name) to look for in the DataSource. You can call these whatever you like, but as you can see in my case, I have decided to call them getXXX like a traditional bean accessor. Why have I done this? Well, because my LineItem object has matching accessor methods. So now let's return to the custom DataSource implementation of getFieldValue. Here is the full listing:

public Object getFieldValue(JRField field) throws JRException {
  LineItem lineItem = (LineItem) data.get(index);
  Object value = null;
  try {
    Object[] args = {};
    Class[] paramTypes = {};
    Class lineItemClass = lineItem.getClass();
    Method getMethod = lineItemClass.getDeclaredMethod(field.getName(), paramTypes);
    value = "" + getMethod.invoke(lineItem, args);
  } catch (Exception e) {
    throw new JRException(e.getMessage());
  }
  return value;
}

Clever huh? You don't have to do it like this, but I have decided to use Java Reflection in order to dynamically call the appropriate LineItem method for the JRField parameter. That is why I named my textFieldExpression elements with getXXX. So, now if I were ever to add a new attribute to LineItem that I wanted in my report, I only need add it to LineItem with the accessors, and then into the report. I can leave my custom DataSource alone. One last note, I have defined all my fields as String even through my LineItem has attributes of float, int, Calendar. I am not really bothered that the report uses correct data types, but you can do that if you want, just set it up with your fields.

Putting it all together

So, you have hopefully got an idea about how JR works, particularly for my Purchase Order scenario. You should understand that a report template is defined by you either manually or using an editor like JasperAssistant. You will also appreciate 2 ways in which you can bind data to this report through parameters and fields. Furthermore, you have seen a clever way to use both methods in binding a master object with internal collection of elements to a report template. So now you probably want to see how to get the PDF back to the user. Well, remember that I am using a web application here but you don't necessarily need to. First of all, I need to load my PurchaseOrder with it's collection. You can do this however you like. In my case, I use Hibernate to load the object out of the database. PurchaseOrder po = poDAO.load(id); Now, I need to setup a parameter map for the master details

Map parameterMap = new HashMap();
parameterMap.put("orderId", po.getOrderId());
parameterMap.put("createdDate", convertToDateString(po.getCreated()));
parameterMap.put("deliveryAddress", po.getDeliveryAddress());

There are a lot more! But this will do. Finally, I need to add my LineItem collection to my custom DataSource LineItemDataSource

LineItemDataSource lineItemDataSource = new LineItemDataSource(po.getLineItems());

And last of all, let's setup the response to the browser, and bind the parameter map and custom DataSource.

response.setContentType("application/pdf");
response.addHeader(
  "Content-Disposition",
  "attachment; filename=PO - " + po.getReference() + ".pdf");

try {
  JasperRunManager.runReportToPdfStream( getClass().getClassLoader().getResourceAsStream( "com/mycomp/po/pof.jasper"), response.getOutputStream(), parameters, lineItemDataSource );
} catch (Exception e) {
  e.printStackTrace(System.out);
  logger.error(e);
}

Right, so I have used just one of the many ways in which you can bind to the report. You will of course need to find out how to compile your report template. When you author your template it is in .jrxml format and this needs to be compiled into a .jasper file which you can do either automatically with JasperAssistant, or manually with bundled tools with JR. In my example here, the compiled report is located in the class struture and I dynamically load it as an InputStream as required by the runReportToPdfStream method.

You should examine the JR API for all the other alternatives including running PDFs to file and even doing HTML output rather than PDF. In an application you would need to use slightly different calls that can be found in the JR API also. Some of you have asked how to send the result direct to the browser. Well, that's easy - the code above forces a Save to Disk for the PDF by using the content-disposition header, so just comment out the response.addHeader call

/* comment the save to disk feature out so that the pdf goes straight to the browser response.addHeader("Content-Disposition", "attachment; filename=PO - " + po.getReference() + ".pdf"); */

Conclusion

This tutorial has covered some specific aspects of the fantastic JasperReports API that may or may not be suitable for your own projects. I hope if nothing else, it provides an insight into one way of using the API or grounds you in the basics. There is so much more to JR that I have not used myself so take time once you get the idea to look at the bundled examples and API to make sure you are making the right choices.

JasperAssistant was an invaluable piece of kit for this job. It is quite tough getting to grips with the report template XML syntax, especially when your report needs pixel perfect alignment and so fourth. I did not go into a great deal of depth with layout elements like boxes and lines, but I have used them to draw the table boundaries around my detail LineItem band. Good luck, and if this article was helpful or not, leave a comment.