Deep Freeze

I'll be moving to a new province to start a new job soon, so this blog and my projects likely won't get updated in the near future. Maybe some day I'll start things up again, so I'll keep the site up just in case :)

Cheers!

When to Use Design Patterns

Lately I've been doing a refresher course on design patterns. I've been wondering if it's worth memorizing them. It seems that once I read about a pattern, I'll want to apply it in a lot of situations while programming. Sometimes I'll work my way into an overly complex solution that has to be simplified later.

I think maybe the best way to approach design patterns is to use the quickest approach to get things working - without applying any patterns. Then, only after things are working, take a break from the code for a few days and sparingly refactor with design patterns if any make themselves apparent.

Of course, there are exceptions to this rule. Patterns like the inversion of control, abstract factory and data access object seem almost too intuitive not to use when initially designing a system.

Java Unit Testing: Mock A Spring Bean Using a Test Spring Context

Spring has a lot of ways to mock beans for testing. Here we'll be setting up a Spring context just for testing, which will have a mock bean.

First, make a new Maven project called 'mock':


mvn archetype:generate -DgroupId=org.vpxd.example -DartifactId=mock -DarchetypeArtifactId=maven-archetype-quickstart -DinteractiveMode=false


Add Spring to your project:

/pom.xml


<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
  xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd">
  <modelVersion>4.0.0</modelVersion>
  <groupId>org.vpxd.example</groupId>
  <artifactId>mock</artifactId>
  <packaging>jar</packaging>
  <version>1.0-SNAPSHOT</version>
  <name>mock</name>
  <url>http://maven.apache.org</url>
  <properties>
     <maven.compiler.source>1.7</maven.compiler.source>
     <maven.compiler.target>1.7</maven.compiler.target>
     <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
  </properties>
  <dependencies>
    <dependency>
      <groupId>junit</groupId>
      <artifactId>junit</artifactId>
      <version>4.12</version>
      <scope>test</scope>
    </dependency>
    <dependency>
      <groupId>org.springframework</groupId>
      <artifactId>spring-context</artifactId>
      <version>4.3.3.RELEASE</version>
    </dependency>
    <dependency>
      <groupId>org.springframework</groupId>
      <artifactId>spring-test</artifactId>
      <version>4.3.3.RELEASE</version>
      <scope>test</scope>
  </dependency>
  </dependencies>
</project>


Create a main method that loads up the Spring context:

/src/main/java/org/vpxd/example/App.java


package org.vpxd.example;

import org.springframework.context.annotation.AnnotationConfigApplicationContext;

public class App {
  public static void main(String... args) {
    AnnotationConfigApplicationContext context = new AnnotationConfigApplicationContext(Config.class);

    Example example = context.getBean(Example.class);

    System.out.println(example.run());
  }
}


Create a simple Spring context configuration:

/src/main/java/org/vpxd/example/Config.java


package org.vpxd.example;

import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;

@Configuration
@ComponentScan(basePackages="org.vpxd")
public class Config {

}


Create a Spring bean:

/src/main/java/org/vpxd/example/Example.java


package org.vpxd.example;

public interface Example {
  String run();
}


/src/main/java/org/vpxd/example/ExampleImpl.java


package org.vpxd.example;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.beans.factory.annotation.Qualifier;

@Service
public class ExampleImpl implements Example {

  private MockMe mockMe;

  @Autowired
  public ExampleImpl(MockMe mockMe) {
    this.mockMe = mockMe;
  }

  @Override
  public String run() {
    return mockMe.run();
  }
}


Create a Spring bean that will be mocked during testing

/src/main/java/org/vpxd/example/MockMe.java


package org.vpxd.example;

public interface MockMe {
  String run();
}


/src/main/java/org/vpxd/example/MockMeImpl.java


package org.vpxd.example;

import org.springframework.stereotype.Service;

@Service
public class MockMeImpl implements MockMe {

  @Override
  public String run() {
    return "real impl";
  }

}


Create a jar and then run the project, "real impl" should be output:


mvn assembly:assembly -DdescriptorId=jar-with-dependencies
java -cp target/mock-1.0-SNAPSHOT-jar-with-dependencies.jar org.vpxd.example.App


Now we're ready to add the unit test with a testing context configuration. It tests that "test impl" is returned:

/src/test/java/org/vpxd/example/ExampleTest.java


package org.vpxd.example;

import org.junit.Test;
import static org.junit.Assert.*;
import org.junit.runner.RunWith;
import org.springframework.test.context.junit4.SpringRunner;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.beans.factory.annotation.Autowired;

@RunWith(SpringRunner.class)
@ContextConfiguration(classes=ConfigWithMock.class)
public class ExampleTest {

  @Autowired
  private Example example;

  @Test
  public void testRun() {
    assertEquals("test impl", example.run());
  }
}


Now the test context configuration we used in the unit test above. Instead of component scanning everything, a filter is set up to exclude the actual implementation of the MockMe interface and the actual Config class. A mock implementation is manually defined.

/src/test/java/org/vpxd/example/ConfigWithMock.java


package org.vpxd.example;

import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Bean;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.context.annotation.FilterType;

@Configuration
@ComponentScan(basePackages="org.vpxd", 
  excludeFilters = {@ComponentScan.Filter(type=FilterType.ASSIGNABLE_TYPE, value=MockMe.class),
  @ComponentScan.Filter(Configuration.class)})
public class ConfigWithMock {

  @Bean
  public MockMe getMockMe() {
    return new MockMeMockImpl();
  }
}


Finally we add the mocked implementation of the MockMe interface:

/src/test/java/org/vpxd/example/MockMeMockImpl.java


package org.vpxd.example;

import org.springframework.stereotype.Service;

@Service
public class MockMeMockImpl implements MockMe {

  @Override
  public String run() {
    return "test impl";
  }

}


Now just run the test:


mvn test


First Impressions with Android Development

I'm fairly late to the Android development party, this weekend I decided to install the SDK and see what it's all about.

Installing the Android SDK and an emulator was simple enough. Almost everything is open source, which is awesome. Tedious licensing agreements for development tooling is insane.

I didn't have the newest JDK (OpenJDK 8 doesn't come with Ubuntu 14.04), so I extracted the open source Zulu Java 8 JDK in my user directory and set JAVA_HOME accordingly, rather than use what Oracle offers. To run the emulator, I had to enable virtualization in my BIOS, it's in the security settings for Lenovo Thinkpad T420 laptops. I also had to install some additional packages via apt-get to run the SDK on my 64 bit distro:

sudo apt-get install lib32z1 lib32ncurses5 lib32bz2-1.0 lib32stdc++6

Once the SDK was running, I signed up for the free Udacity Developing Android Apps course. I didn't go into it with very high hopes because a lot of the open source documentation I come across is terrible. Was pleasantly surprised though.

Even though the material wasn't 100% up to date with the newest SDK, there are explanations about what's changed and what is now deprecated. They have a github repository set up with branches for every section of the course. They'll show you a video, then offer a diff link (usually along with additional documentation), then explain what the code in the diff does. I'm about 75% done after two days, and it seems to be working for me. I don't think I'll be a master of Android development at the end, but it will be enough to get started with my own app.

More posts about Android development to follow I think. Seems fun :)

Ubuntu 16.04 LTS First Impressions

I've been an Ubuntu user for a while. Currently I use 14.04 LTS on my main laptop. Last month 16.04 LTS came out, I put it on a spare laptop that's currently sitting in my media center connected to my TV. The laptop is a stock Asus N56VJ. It has a TP-LINK WN722N USB wifi dongle, and a wireless keyboard attached.

Package Manager Issue

After installing, I couldn't install any applications that weren't in the default repositories. Chrome, etc just wouldn't install using the software manager. I ended up installing some packages and their dependencies using dpkg -i. I'm wondering how a bug like this was shipped, possibly a rush to get this release out the door?

Hardware Support

Hardware support is about the same as other releases of Ubuntu - good but not great. The Atheros wifi drivers aren't as fast as they should be, and I cannot get sound from the HDMI port. After messing around with configuration files for a few hours I gave up on both of these issues.

On a more positive note, I did manage to set up a wifi repeater using the network manager app. It worked right with no messing around. I connected a USB wifi dongle to an external network, and selected 'shared with other computers' along with 'hotspot mode' for the internal wifi chip. Previously in similar situations I would have had to set up hostapd for an AP, dnsmasq for DHCP/DNS, and iptables for NAT. One quirk I found while doing this was that the network manager app would disable the save button without any explanation if the wifi password wasn't long enough.

Overall

This release is about the same as other recent Ubuntu releases, nothing special. It's not any faster and the user interface isn't any better. That being said, it is better than Windows and most other distributions I've tried, so I'll keep using it.

Speeding Up Line Drawing on HTML5 Canvas

A while ago (maybe a year) I made a crappy little game called Space Cave. It's nothing special, mainly just programmed it to learn about the HTML5 canvas and how to interact with it using Javascript + jQuery.

The game basically draws a bunch of lines and the player cannot let a spaceship come into contact with the ends of the lines.  The initial version was super slow and choppy, so I recently decided to speed it up a bit.

Double Buffering

Double buffer by drawing changes to a canvas created in Javascript, then draw that canvas on the main one.  This improved smoothness quite a bit.

Clearing the Canvas

There is a lot of conflicting information about this, likely just from differences in browsers. From what I've read, there are two ways to clear a canvas: clearRect(...) and resetting the canvas width. Some sites say never reset the width, some say it's alright but not ideal, some say it's the best way.

In the end I just went with clearRect(), it works fairly quickly on all the browsers I've tried. Resetting the width honestly seems like a dirty hack.

Window.requestAnimationFrame(...)

Instead of setting a timeout of 1000/fps to call a draw method, some websites say simply calling this method is faster. I honestly didn't do much of a scientific test, but when I first made the game it seemed that setTimeout was smoother. Now when I go back and use this method it does seem a bit smoother. Possibly a difference in the browser versions? It's a mystery :)

Using Duplicity for Manual Backups In Linux

I use duplicity and an external USB drive to do simple and secure manual backups.

How to Backup

  1. If you're on Ubuntu, skip this step. Duplicity is installed with the default desktop environment. Otherwise, install duplicity.  It's included in most package managers.
  2. Put all of your stuff that you'd like to backup into one directory. In the example below, I used /home/profit/my_data/
  3. Create a temporary directory. In the example below, I used /home/profit/tmp/.  This is required to prevent out of space errors while backing up.
  4. As a normal user, run this command. Replace /home/profit/my_data/ and file:///home/profit/to_hdd/ with your directories.  The file:/// part is the destination.
    duplicity full --tempdir /home/profit/tmp/ /home/profit/my_data/ file:///home/profit/to_hdd/
  5. Type a pass-phrase when it asks.
  6. If it finished with no errors reported, congratulations you've backed up your stuff.  You'll have a directory full of encrypted archives.

How to Restore

Always test that your backup works :) Here's the command to run. Make sure that you're either logged in as root, or as the same user that performed the backup.

Replace file:///home/profit/to_hdd/ with your backup directory and /home/profit/tmp_restore/ with your destination.

duplicity restore --tempdir /home/profit/tmp/ file:///home/profit/to_hdd/ /home/profit/tmp_restore/ 





Choosing Blog Software: Blogger vs Wordpress vs Custom Built

I considered a few platforms for this blog.  My requirements are:
  • Reasonably secure
  • Easy to update
  • Easy to port data if I decide to leave
  • Low cost
  • Visitors should be able to comment

Wordpress

Self Hosted

I have access to a PHP/MySQL host, and installing Wordpress is easy.  The deal breaking issue is that I simply don't trust it to be secure.  Even when kept up to date, I've had off-the-shelf content management systems hacked on websites I've maintained.  Won't be going down that road again.

Hosted

Wordpress.com offers free hosting. They charge way too much to have a custom domain pointed at your blog though.

Custom Built

I seriously considered this option. I'm confident that anything I programmed would be simple and bare bones.  This would limit many security related problems. I'm very aware that nothing is bug free though :)

There is also a lot of time involved in the creation and maintenance of a custom blog.  A few years ago I had a personal blog programmed in Java using Spring MVC, it took a lot more work to program and maintain than I was willing to put in.  I'm the kind of programmer who loves to refactor and redesign code, it took time away from the actual purpose of the blog.  After about a year, I was tired of it.

Blogger

For now, I'm using Blogger. It meets all of my requirements fairly well. Nothing is set in stone though. If I decide to leave, it shouldn't be to hard to export my data either using the Atom feed or the export blog feature.

First Post

Hello! This blog will be a kind of a hub for projects I'm working on.