Integer IP Addresses

I know that every couple of years I need the snippet of code that helps me convert the integer version of an IP address back and forth to a string. You would think that after all this time I’d be able to write it blind.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
public static String convertIntegerToIp(long ip) {
     StringBuffer buf = new StringBuffer();
      buf.append(((ip >> 24 ) & 0xFF)).append(".")
          .append(((ip >> 16 ) & 0xFF)).append(".")
          .append(((ip >>  8 ) & 0xFF)).append(".")
          .append(( ip        & 0xFF));		
      return buf.toString();
}
 
 public static long convertStringToIntegerIp(String ip) {
     String[] parts = ip.split("\\.");
     return (Long.valueOf(parts[0]) << 24) +
              (Long.valueOf(parts[1]) << 16) +
              (Long.valueOf(parts[2]) << 8) +
              (Long.valueOf(parts[3]));
 }

In C/C++ you can use an unsigned int instead of a long but in java there are no unsigned types and while I know that you can still do this calculation using a signed integer just as well in java, when you print out the address for visual inspection you will get a negative number and it won’t match the c++ printout so I’ve chosen to use a long to store the values.

Enjoy.



Asynchronous Executor

I hate that sometimes I have to make calls to systems outside of my own system, essentially outside of my own control. And not all of these calls allow me to detect and recover when an operation is taking longer than it should.

So I’ve written a class that allows you to execute a task asynchronously and give it a maximum time to run, and you get a callback upon completion or upon failure. Now I can detect and recover when things happen that are outside of my control.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
package com.peterfranza.synchro;
 
public class AsyncExecutor {
 
	private static java.util.concurrent.ExecutorService pool = 
		java.util.concurrent.Executors.newCachedThreadPool();
 
	public synchronized static void asyncExecuteTask(
			final Runnable task, 
			final long timeout, 
			final AsyncExecutorCallback callback) {
		pool.execute(new Runnable() {
 
			@Override
			public void run() {
				java.util.concurrent.Future<AsyncExecutorCallback> marker = 
					pool.submit(task, callback);
				try {
					marker.get(timeout, 
						java.util.concurrent.TimeUnit.MILLISECONDS)
						.taskCompleted();
				} catch (Exception e) {
                                        marker.cancel(true);
					callback.taskFailed();
				} 
			}
 
		});
	}
 
	public interface AsyncExecutorCallback {
		void taskCompleted();
		void taskFailed();
	}
 
}

Usage

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
package com.peterfranza.synchro;
 
import com.peterfranza.synchro.AsyncExecutor.AsyncExecutorCallback;
 
public class Usage {
 
	public static void main(String[] args) {
 
		AsyncExecutorCallback callback = new AsyncExecutorCallback() {
 
			@Override
			public void taskCompleted() {
				System.out.println("Task Completed");
			}
 
			@Override
			public void taskFailed() {
				System.out.println("Task Failed");
			}
 
		};
 
		AsyncExecutor.asyncExecuteTask(new QuickTask(), 1000, callback);
		AsyncExecutor.asyncExecuteTask(new LongTask(), 1000, callback);
	}
 
 
	private static class QuickTask implements Runnable {
		public void run() {
			try {Thread.sleep(10);}
			catch(Exception e){}
		}		
	}
 
	private static class LongTask implements Runnable {
		public void run() {
			try {Thread.sleep(100000);}
			catch(Exception e){}
		}		
	}
}


Copying Files Using NIO

Prior to the JDK 1.4 introduction of the NIO package a tipical file copy routine would look something like:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
public static void copyFile(File in, File out) throws Exception {
    FileInputStream fis  = new FileInputStream(in);
    FileOutputStream fos = new FileOutputStream(out);
    try {
        byte[] buf = new byte[1024];
        int i = 0;
        while ((i = fis.read(buf)) != -1) {
            fos.write(buf, 0, i);
        }
    } catch (Exception e) {
        throw e;
    } finally {
        if (fis != null) fis.close();
        if (fos != null) fos.close();
    }
  }

With the introduction of the NIO package’s conecpt of channels we can rewrite the fileCopy routine as:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
public static void copyFile(File in, File out) 
        throws IOException  {
        FileChannel inChannel = new
            FileInputStream(in).getChannel();
        FileChannel outChannel = new
            FileOutputStream(out).getChannel();
        try {
            inChannel.transferTo(0, inChannel.size(),
                    outChannel);
        } catch (IOException e) {
            throw e;
        } finally {
            if (inChannel != null) inChannel.close();
            if (outChannel != null) outChannel.close();
        }
    }

However on windows platforms, you may have to replace

1
2
3
4
try {
            inChannel.transferTo(0, inChannel.size(),
                    outChannel);
        }

with

1
2
3
4
5
6
7
8
9
try {
           // magic number for Windows, 64Mb - 32Kb)
           int maxCount = (64 * 1024 * 1024) - (32 * 1024);
           long size = inChannel.size();
           long position = 0;
           while (position < size) {
              position += 
                inChannel.transferTo(position, maxCount, outChannel);
        }

when attempting to copy a file in excess of 64Mb.



Simplify Unit Testing With Dependency Injection

After you read a bit about dependency injection you might say “So what? There isn’t much of a practical gain” and an the surface I actually agree with you, I mean how many instances are there where we really need to be able to create infinate class permutation without using subclassing? I believe the place where you are going to see dependency injection score major points is with your unit testing. The main reason is that you can provide mock implementations of all the dependencies and eliminate any vairance in their behaviour from the class you are testing.

For example, continuing from my previous post: with traditional composition we could test the Car class like this:

1
2
3
4
5
6
7
8
public class CarTest extends TestCase {
 
 public void testCar() throws Exception {
 Car c = new Car();
 assertEquals(.....);
 }
 
}

but the behaviour of the instance of car is really coupled to the behaviour of the AutomaticTransmission and GasEngine classes. If something breaks in the AutomaticTransmission class, more than likely our AutomaticTransmissionTest and CarTest cases will fail. This is slightly misleading because there isn’t really a problem with the Car class, and yet its test is failing because of the coupled behaviour to the AutomaticTransmission class. Using the dependency injection version of the class allows us to do something very different.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
public class CarTest extends TestCase {
 
 private static class MockTransmission implements Transmission {
   ...
 }
 
 private static class MockEngine implements Engine {
   ...
 }
 
 public void testCar() throws Exception {
 Car c = new Car(new MockTransmission(), new MockEngine());
 assertEquals(.....);
 }
 
}

Now the Car we are testing has no dependencies outside of our testcase, this allows us to tightly control what we are putting under test and allow us to focus our effort on testing the single class rather than any extra behaviour that comes from the subcomponenets. In this scenerio if something breaks in the AutomaticTransmission class only the AutomaticTransmissionTest will fail because CarTest no longer has a dependency on AutomaticTransmission allowing them to operate (and fail) independently of one another.



Dependency Injection Basics

Dependency Injection is a process of supplying external dependencies to componenets, changing the flow of control of the system to be inverted in comparison to the traditional architecture of software libraries. Dependency Injection builds of the concept that you should favor composition over inheritance [Effective Java Programming Language Guide, chapter 4, item 14], but extending it to say that the specific implementations of the subcomponenets that you are using to compose your class should be fully decoupled from the class itself.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
public interface BrakeSystem {
 
}
 
public interface Engine {
 
}
 
public class Car {
 
 private Transmission transmission = new AutomaticTransmission();
 private Engine brakes = new GasEngine();
 
}

We can see that in class Car we’ve coupled the implementation of AutomaticTransmission and DiscBrakeSystem to the implementation of Car. What do we do when we want to create an instance of Car that has a manual Transmission? The answer is dependency injection. In this example we find it trivial to remove the coupling of subcomponent implementations by passing in the subcomponents at time of construction rather than at the time of compiliation.

1
2
3
4
5
6
7
8
9
10
11
public class Car {
 
 private Transmission transmission;
 private Engine engine;
 
 public Car(Transmission transmission, Engine engine) {
    this.transmission = transmission;
    this.engine = engine;
 }
 
}

Now we can use the constructor to create variations of the cars behaviour.

1
2
3
4
5
6
7
8
9
10
11
12
13
public class CarFactory {
 
 public static final Car createAutomaticCar() {
 return new Car(new AutomaticTransmission(),
 new GasEngine());
 }
 
 public static final Car createManualCar() {
 return new Car(new ManualTransmission(),
 new GasEngine());
 }
 
}

Using this method we can vary the components of car without subclassing it, allowing the freedom to provide numerious unique representations of cars without changing anything in the car class itself. Its all left to wiring the classes together in an appropriate way.

Can’t I just use the Service Locator Pattern?

Well it is true that dependency injection does aim to solve the same problem as the Service Locator Pattern, usage of the pattern requires you to build in logic that preforms the dependency resolution and construction. This introduces cross cutting behaviour that disrupts the cohesion and singular responsibility of the class. By removing the service location logic and relegating it into a factory or some other framework level function, a high level of cohesion can be maintained. This will be true for both the object and its factory, as the single responsibility of the factory is to construct instances of the class, and the class just has to be itself.

Usage of Dependency Injection Frameworks

I sit firmly on the fence about the usage of frameworks for dependency injection, becuase it seems that they all have a dark side to them that in one way or another reduces readability/traceability of the classes. Some like Google Guice use method annotations to define where the injection points are, and while this seems to be be a relativly consice way to inform the framework it adds a lot of extranious information to your code that doesn’t really make sense within the context of the class.

This is where I actually like the use of factories that construct the objects and do the injection for you. Its generally clean, and it localizes the couplings to a factory which is natually where they should be. The downside is sometimes dependency injection can get several layers deep (you have a class that requires classes which requre classes etc) and the notion that you would have a factory method for each one of the permutations is quite excessive. However if you only add a method that builds the specific combination that you are looking for this might strike a nice middle ground.