Ryan Harrison My blog, portfolio and technology related ramblings

Java - Converting Between Timezones

In Java it’s not too easy to convert Date objects between timezones as they always like to store the time in UTC (even though they will happily print BST when converted to a String form). Normal timezone conversion in Java is done through the Calendar class which is, as all Java developers know, really heavy and a nightmare to use. Even using a Calendar though, getting a Date object out if it in a different timezone doesn’t seem to happen at all. But it can be useful to have a Date object represent a time in a different timezone, so here is a little helper method that gets around it. Included is also another handy helper method that creates a Date object at a certain time (something that you often want to do but don’t want to see or use a Calendar directly):

import java.util.Calendar;  
import java.util.Date;  
import java.util.TimeZone;

public class TimeZoneConversions {  
	public static void main(String[] args) {  
		Date date = dateOf(14, 30, 0, 20, 8, 2014);  
		TimeZone local = TimeZone.getTimeZone("Europe/London");  
		TimeZone dest = TimeZone.getTimeZone("America/New_York");

		System.out.println(translateTime(date, local, dest));

	public static Date dateOf(int hour, int minute, int second,  
		int dayOfMonth, int month, int year) {  
		Date date = new Date();  
		Calendar c = Calendar.getInstance();  

		c.set(Calendar.YEAR, year);  
		c.set(Calendar.MONTH, month - 1);  
		c.set(Calendar.DAY_OF_MONTH, dayOfMonth);  
		c.set(Calendar.HOUR_OF_DAY, hour);  
		c.set(Calendar.MINUTE, minute);  
		c.set(Calendar.SECOND, second);  
		c.set(Calendar.MILLISECOND, 0);  
		return c.getTime();  

	public static Date translateTime(Date date, TimeZone src, TimeZone dest) {  
		long time = date.getTime();  
		int offset = (dest.getOffset(time) - src.getOffset(time));  
		return new Date(time - offset);  
Read More

How to Create a .gitignore File in Windows Explorer

When working with Git repositories in Windows, it’s not rare to have to create .gitignore or even a .gitattributes file for your repo. Unfortunately, in Windows Explorer, creating files with a dot prefix isn’t so easy. If you try to rename a file to .gitignore for example in Windows Explorer, you will be met with this error message:

gitignore error

To get around this problem, you normally have to open up a command prompt window in your repo and manually rename an existing file using:

ren gitignore.txt .gitignore

There is however a much easier way. Instead of naming your newly created file .gitignore, add an extra period onto the end making .gitignore. and your file will be created without the errors:

gitignore create

As an aside those on Unix machines (or with Git Bash installed on Windows) can simply use this command and forget about the above:

touch .gitignore

Read More

JdbcTemplate queryForInt() is deprecated

There is a lot of Spring documentation online which makes use of the queryForInt() and queryForLong methods of the very handy JdbcTemplate class. However, using newer versions of the Spring framework, these methods have now become deprecated (apparently this has happened from version 3.2.2).

These are the two methods affected:

public long queryForLong(String sql, Object... args) throws DataAccessException
public int queryForInt(String sql, Object... args) throws DataAccessException

I’m not sure why the designers have to decided to deprecate these two methods, but the solution (or perhaps the workaround is simple):


int result = getJdbcTemplate().queryForInt(sql, new Object[] { param });


int result = getJdbcTemplate().queryForObject(sql,  
new Object[] { param }, Integer.class);

The workaround makes use of the queryForObject method and we pass in the Integer class in order to coerce the general object into the type we desire. Similarly, for queryForLong, you can replace Integer.class with Long.class.

Read More

Java - Common Pitfall when using Scanner

It’s very common for beginners in Java to use the many helpful methods of Scanner to obtain input from the user. They normally have some sort of task which involves asking the user for some String input, some numerical input and finally more String input - be this to do some processing with or just output back to the user in the simplest case. Most people will be happy using the nextLine() and nextInt() methods of Scanner to do so, however will then get confused when they don’t get the behaviour they expect. This is a great example of why you should know the specific behaviour of the library methods you call and not just assume that they will conform exactly to your needs by default.

As an example, say we get the task to ask the user for their name, storing it in a String variable, their age, storing it in an int variable, and finally their address, again storing it in a String variable. We may come up with this code to start off with:

import java.util.Scanner;

public class Sample {  
    public static void main(String[] args) {  
        Scanner scanner = new Scanner(System.in);  
        System.out.println("Enter name:");  
        String name = scanner.nextLine();

        System.out.println("Enter age:");  
        int age = scanner.nextInt();

        System.out.println("Enter address:");  
        String address = scanner.nextLine();

        System.out.println("Your name = " + name);  
        System.out.println("Your age = " + age);  
        System.out.println("Your address = " + address);  

Seems OK at a first glance, we prompt the user for input, use Scanner to retrieve it from the console and finally output what they entered. When we run this code however, it doesn’t function as expected:

C:\Users\Ryan\Java>java Sample  
Enter name  
Enter age  
Enter address  
Your name = Ryan  
Your age = 20  
Your address =  

We get the name and age input successfully, but what happened to the address? We get prompted for the address yet have no opportunity to enter anything - resulting in a blank String for this field.

Although it may not seem like it, Scanner is actually behaving here exactly how it was designed to do so. The Scanner class is a multi-purpose tool, capable of not only parsing character input from the console, but also from other files and streams. In order to do so, it provides two methods: next() and nextLine(). The next() method takes a token from the current input stream up to the next delimiter (which by default is whitespace although this can be changed). It then returns this parsed token, but importantly leaves the delimiter in the stream. The nextLine() method on the other hand accepts a whole line up to and including the newline character. This time however, the delimiter gets consumed as well. Most of the other parsing methods in Scanner base themselves around these two base models.

Examples of those other parsing methods include convenient methods to accept input and convert it into another type (a call to nextInt() for example). Scanner does this by calling the next() method and then attempting to parse the output into the resulting type. This seems quite reasonable, but recall that we have called the next() method here and not nextLine(). This is where the problems occurs in our example above. The next() method leaves the delimiter in the stream, which means that when the user types a number, say “20” for their age and hits return, the Scanner gets a stream consisting of “20\n”. When the nextInt() call happens, the “20” is removed, and becomes a 20, and now the stream is “\n”. Now we call nextLine() again to retrieve the address. The Scanner does what it’s meant to and takes the the “\n”, discards the newline character (“\n”) and returns the remaining String - which in this case is “”. Thus we get the undesired behaviour.

The solution? Simply call nextLine() after we call nextInt() to consume the remaining newline character so that we get the chance to enter the address. Ideally however, you shouldn’t litter your input code with a load of new nextLine() calls to get the desired behaviour. Therefore, its probably best to implement your own utility class to take input in the manner you expect - leaving the Scanner in the correct state for further use afterwards.

This leaves the question as to why they decided to implement it in this way. As I said before Scanner is a very multi-purpose tool that should be able to accept a wide variety of input formats - not just one token on each line. A major use case of Scanner is to for example parse all the ints on one line, separated by whitespace, in order to populate some kind of Collection. If the nextLine() methods was used in nextInt() rather than next() we wouldn’t be able to do this and Scanner would be restrained in its use. This of course wouldn’t be a useful design decision and so we have to do this small bit of extra work to make it conform to our requirements.

Read More

Python - Iterate over a list with indexes


for (index, value) in enumerate(values):  
	print "The value at index {0} = {1}".format(index, value)

In Python the typical way to iterate over a loop is to use the conventional foreach loop, as lists expose iterators:

values = ["Foo", "Bar", "Baz", "Qux"]

for value in values:  
	print value


In a lot of cases this is all that’s needed, however in other circumstances we may need access to the index that each element is at inside the list - most of the time in order to perform some kind of check on the next or previous values in the list. The conventional for loop above of course simply gives us the values inside the list, not the indexes. We could set up a counter variable which increments each time around the loop, yet this seems clumsy. We are increasing the scope of a variable that should ideally be kept local to the loop.

Another popular solution is to use the range function, which returns an iterator of values from zero to the number we specify as a parameter. By creating a list of numbers from zero to the size of the list, we can then use each element as an index in order to extract each value:

for i in range(len(values)):  
	print "The value at index {0} = {1}".format(i, values[i])

The value at index 0 = Foo  
The value at index 1 = Bar  
The value at index 2 = Baz  
The value at index 3 = Qux  

Although this gets us our desired output (in this simple example anyway), it again seems quite a clunky way to perform such as simple task in Python. We have to refer to each value as values[i], or otherwise set up a new local variable. Luckily however, as ever, this is a much neater way of doing this in Python.

One of the built-in functions that Python provides is the enumerate function. This handy function gives us an iterator that returns a tuple containing a count (which by default starts from zero) and the values obtained from iterating over the sequence. By simply running through the tuples returned from the iterator provided by this function, we get access to both the indexes and the corresponding values:

for (index, value) in enumerate(values):  
	print "The value at index {0} = {1}".format(index, value)

The value at index 0 = Foo  
The value at index 1 = Bar  
The value at index 2 = Baz  
The value at index 3 = Qux  

As you can see this is much neater and more efficient than the other solutions. There is no need for extra variables - everything is provided to us in the loop declaration.

Read More