Java 7: Try-With-Resources (AutoCloseable)

Another great thing introduced with Java 7 is the “try-with-resources” construct – previously known as Automatic Resource Management (ARM). This feature is part of Project Coin, which is an umbrella project for a set of small changes to the Java language. You can see my other post on Java 7: Project Coin for more info.

When you work with files, networks streams or databases you follow a common pattern.

  1. Open resources
  2. Perform operation
  3. Close resources

You have to wrap the code in a try-finally block to make sure the resources are closed even if an exception occurs. Take a look at this example that copies the contents of one file to another file.

Java 7 introduces a new construct called try-with-resources. You can initialize the resources inside parenthesis between the try keyword and the opening bracket, and Java will automatically close them for you. This works for all resources that implement the AutoCloseable interface.

Java 7 also contains NIO.2 which improves file operations in Java, and adds several essential features that Java has been missing. For example, now you can copy a file in one line. As a bonus this method not only copies the file contents but also the file metadata!

Posted in Java | Tagged , , | Leave a comment

Java 7: Project Coin

Java 7 is just around the corner. Sadly it does not contain the highly anticipated closures/lambda expressions, but instead it includes a set of small language changes developed under the codename “Project Coin”.

In this post I will explore the basic language changes.

Strings in switch

Yes, finally you can switch on string constants in switch statements!

 

Binary Literals and Underscores in Numeric Literals

If you work with computer graphics, signal processing or integrate with old native C libraries, you often have to perform bit-manipulations and bit-masking etc. For some strange reason Java only supported decimal, octal and hexadecimal literals. Java Coin adds support for binary literals with the 0b prefix, and now it is legal to use underscores inside all numeric literals to make them easier to read.

 Type Inference for Constructing Instances of Generic Types

This feature is going to remove a lot the verbosity of generic types. Take for example this example of a Map of a List of Strings:

The first method demonstrates the old way of creating generified collections.

The second method demonstrates how you can save a lot of typing by using the diamond operator <> and let the compiler infer the types from the left hand side.

Multi-Catch Exceptions

If you want to perform the same exception handling for a set of Exception types you can now catch them in a single catch statement by separating the types with a pipe character

Automatic Resource Management

The final part of Project Coin is support for automatic resource management, which I will explore in a separate blog post.

Posted in Java | Tagged , , | 1 Comment

Simple HTML5 Todo List

Lately I have been experimenting with Ender. It is a JavaScript library with a twist. In fact the authors refer to it as “no-library library”. It is a tiny wrapper and a command line tool that you can use to construct a Javascript library from a range of microframeworks. This way you only get the features you actually need, and in theory you can pick and choose between alternative implementations of the individual featues, so you get a library that matches your preferred programming style.

I have created a small todo-list that uses local storage in the browser to persist your todo items. This way, the todolist will remember your items from last visit, without storing anything on the server!

Posted in Web | Tagged , , | Leave a comment

Canvasteroids

A couple of weeks ago I wrote a small game using Javascript and HTML5 canvas. It is a clone of the classic Asteroids game by Atari Inc.

A screenshot of the game in action

CanvAsteroids Screenshot

The game is not complete yet, but I have decided to put it up anyway. You can try it out here: CanvAsteroids

Posted in Web | Tagged , , , , | Leave a comment

Fra LED til Simon

Here is the slides, a video and the source code from a 15 minute speed-talk I did for the Tech Talk Tuesday at OSAA yesterday.
It shows the highlights of how to build a clone of the classic Simon game, using an Arduino and some buttons and LEDs. In Danish only!

Slides

View more presentations from giddy.

The Video Demonstration

Source Code

/*
 * Arduino Clone of the classic Simon Game
 *
 * Made at Hack Aarhus / OSAA
 * http://www.hackaarhus.dk
 * http://www.osaa.dk
 *
 * Released into the public domain by
 * Rene Hangstrup Moeller, July 2010
 *
 * http://www.giddyplanet.com
 */

//---------------------------------------------------------
//	GLOBALS weeeee!
//=========================================================

// the number of leds/switches
int SIZE = 4;

// milliseconds delay between each element in the sequence
int PLAY_DELAY = 250;
int INPUT_DELAY = 200;

// the sequence
int sequence[128];

// current sequence length
int seqlen = 0;

// Sound frequencies for each led-switch pair
int notes[] = {
    261/2, 392/2, 587/2, 880/2  
};

//---------------------------------------------------------
//	PIN MAPPINGS
//=========================================================

// the buzzer control pin
int buzzPin = 11;

// calculate pin for led
int ledPin(int num) {
  return (num + 1) * 2;
}

// calculate pin for button
int buttonPin(int num) {
  return ledPin(num) + 1;
}

//---------------------------------------------------------
//	HELPER FUNCTIONS
//=========================================================

// mute the buzzer and turn off all leds
void turnOff() {
    noTone(buzzPin);
    for (int n = 0; n < SIZE; n++) {
      digitalWrite(ledPin(n), LOW);
    }
}

// new game
void newGame() { 
  // generate random sequence with two entries
  sequence[0] = random(SIZE);
  sequence[1] = random(SIZE);
  seqlen = 2;
    
  // blink leds 10 times to indicate game start
  for (int i = 0; i < 10; i++) {
    for (int n = 0; n < SIZE; n++) {
      digitalWrite(ledPin(n), HIGH);
    }
    delay(200);

    turnOff();    
    delay(200);
  }  
}

// add an entry to the sequence
void expand() {
  sequence[seqlen++] = random(SIZE);
}

// play the sequence
void playSequence() {
  Serial.println("Playing sequence");
  
  for (int i = 0; i < seqlen; i++) {
    int v = sequence[i];
    tone(buzzPin, notes[v]);
        
    for (int n = 0; n < SIZE; n++) {
      digitalWrite(ledPin(n), n == v ? HIGH : LOW);
    }
    
    delay(PLAY_DELAY);
    noTone(buzzPin);
    
    for (int n = 0; n < SIZE; n++) {
      digitalWrite(ledPin(n), LOW);
    }
    
    delay(PLAY_DELAY);
  }
  turnOff();
}

// wait for button press
int nextButton() {
  
  while (true) {
    
    for (int n = 0; n < SIZE; n++) {
      if (digitalRead(buttonPin(n)) == HIGH) {
        digitalWrite(ledPin(n), HIGH);

        while (digitalRead(buttonPin(n)) == HIGH) {
          delay(INPUT_DELAY);
        }
        
        turnOff();
        return n;
      }
    }
    delay(INPUT_DELAY);
  }
  
  return 0; // never
}

// read sequence from player
int readSequence() {
  for (int i = 0; i < seqlen; i++) {
    int nb = nextButton();
    
    if (nb != sequence[i]) {
      Serial.println("Error");
      return false;
    }
  }
  
  Serial.println("Accepted");
  return true;
}

//---------------------------------------------------------
//	ARDUINO ENTRY POINTS
//=========================================================

// initialize the Arduino
void setup() {
  // initialize random number sequence
  randomSeed(micros() + analogRead(0));
  
  // configure pins for LEDs and buttons
  for (int i = 0; i < SIZE; i++) {
    pinMode(ledPin(i), OUTPUT);
    pinMode(buttonPin(i), INPUT);
  }

  // configure pin for sound
  pinMode(buzzPin, OUTPUT);
  
  // initialize serial communication for debugging
  Serial.begin(9600);
  Serial.println("Setup completed. Welcome to Simon");
}

// The game loop - each run corresponds to a game 
void loop() {  
  Serial.println("Starting new game");
  newGame();
  
  int running = true;
  
  while (running) {
    delay(1000);  
    playSequence();
    running = readSequence();
    if (running) {
      expand();
    }
  }   

  delay(250);
}
Posted in Electronics | Tagged , , , | 5 Comments

Simplicity

Stumbled upon this fantastic quote:

It seems strange to have to emphasize simplicity. You’d think simple would be the default. Ornate is more work. But something seems to come over people when they try to be creative. Beginning writers adopt a pompous tone that doesn’t sound anything like the way they speak. Designers trying to be artistic resort to swooshes and curlicues. Painters discover that they’re expressionists. It’s all evasion. Underneath the long words or the “expressive” brush strokes, there is not much going on, and that’s frightening.

When you’re forced to be simple, you’re forced to face the real problem. When you can’t deliver ornament, you have to deliver substance.

http://www.paulgraham.com/taste.html

Posted in Uncategorized | Leave a comment

Hello World

…please hold…

Posted in Uncategorized | Leave a comment