32leaves.net

Advanced Java generics for method arguments

Currently we’re having the semester break. During this time I work for a automotive software/hardware tool vendor. And while working there I stumbled upon a piece of code (wich was part of the API) which basically looked like this:

1
2
3
public void doSomething(ArrayList<String> list) {
    ...
}

The intention of the author was not that he wanted to have an ArrayList here, but he needed a List of String which was Serializable as well. For obvious reasons it’s not really a good idea to expect something as concrete as an ArrayList here, so there should be a better way – and there is:

1
2
3
4
public <SerializableStringList extends List<String> & Serializable>
void doSomething(SerializableStringList list) {
    ...
}

This piece of code is far better in expressing the authors intention, but still there are some drawbacks.
First of all it does not work for Java 1.4 (which might be a requirement).
The worst disadvantage is the lacking support in Eclipse. If you want to call this method, the only thing you’ll see in that little light-yellow description box is that a SerializableStringList is expected, but it won’t tell you that this is a generic type and not a real type like a class or an interface.

Still I’d prefer the later solution over the first one any time as the first one forces people to use classes they might not want to and the second solution is by far more expressive.

FastSilver is the new QuickSilver for Eclipse

Being inspiered by QuickSilver (totaly awesome software, basically a Mac without it is pretty much useless), I wrote a small plugin for Eclipse providing similiar functionality. For those who don’t know QuickSilver, it allows you to start applications or trigger commands using nothing but your keyboard. So why would I want this within my Eclipse, you may ask. Simply to save the time it would take you to grab your mouse and use the menu. FastSilver basically takes all the commands available within Eclipse and makes them available using one single keystroke which is Cmd-6 per default. This binding can be changed in the settings.

Again the code is available thru SVN, or if you’re solely interested in the binaries, here is the update site. For both (Update Site and SVN) the username and password are guest. Screenshots and eye-candy will follow as soon as my WordPress installation works fine again.
Update: my upload works again, so here are the screenshots. The first one shows FastSilver in action:

snapshot2

The second one below shows the preferences dialog where you can change the keybindings to trigger FastSilver:
snapshot3

X11 automation during a presentation

The other day I was giving a presentation at UnFUG (during the Pimp my x86_64 lighting talk session). What I presented was exclusively console based. And as a programmer I love things I can automate, like typing during a presentation. So I wrote a little Ruby script to do the job for me and bound it to some key-strokes using my window manager on the eeePC. That thing is even able to fake typos, and has some random timing to not let the typing become to regular and fluent. In order to run this script below you’ll need the xdotool.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
def play(text, type_speed)
    escape = false
    text.split("\n").each{|l| l.scan(/./).each {|c|
        if c == '!'
            escape = true
        elsif escape
            if c == '<'
                `xdotool keyup BackSpace`
                sleep (rand / 10)
            elsif c[0] - '0'[0] > 0
                sleep (c[0] - '0'[0]) / 10.0
            end
            escape = false
        else
            `xdotool type "#{c}"`
        end
        sleep type_speed + ((rand / 100) * (rand > 0.5 ? -1 : 1))
    }
   `xdotool keyup Return`
    }

end

play STDIN.readlines.join, 0.09

The script has some sort of escape/ex mode to be able to place some commands. The following snipped uses them (watch out for the ! chars):

1
2
3
4
5
ruby session.rb

!5
nr :base, 42,-1,0.2,5,16,EUU!<CLID
!1play

Possible use-cases:

  • stunningly fast typing with one hand
  • telekinesis like typing

All in all it’s just a cool effect :)

The a2 automaton and Clojure

Clojure

During the preparation time for my exams I wanted to do something else than just learning. So I decided to give functional programming a try. The language of choice was Clojure. It’s a LISP written specifically for the JVM. This language got some pretty neat features (taken from wikipedia):

  • Dynamic development with a read-eval-print loop
  • Functions as first-class objects with an emphasis on recursion instead of side-effect-based looping
  • Provides a rich set of immutable, persistent data structures
  • Concurrent programming through software transactional memory, an agent system, and a dynamic var system
  • Compatibility with Java: Clojure can natively call methods and create objects from any Java library, and Java programs can call Clojure functions
  • Clojure is a compiled language producing JVM bytecode

To try this thing out I decided to implement the a2 automaton described a few posts before (those neat picture and the videos, etc.). So below is the code for the automaton. If you’re able to read/understand LISP this should be (hopefully) understandable :-). Especially the

moore-aliveness

function is really neat.

All in all it took me about 8 hours to write this code. Functional programming is a completely new world. Especially that we’re mostly working with immutable data here. That’s also the cause for this code being propably pretty slow. My use of recursion here is most likely not the way that is supposed to be done in Clojure. Anyway it was a fun experience and broadened my (programmers) horizon.

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
42
43
44
45
46
47
48
49
(def WORLD_WIDTH  800)
(def WORLD_HEIGHT 600)

(def setup
    (map (fn [x] (vec (range WORLD_HEIGHT)))
        (vec (range WORLD_WIDTH))))

(defn init ([field]
    (concat
        (vector (map (fn [x] (rem x 2)) (first field)))
        (map (fn [x] (map (fn [y] 0) x)) (rest field))
    )
))

(defn moore-aliveness ([field x y]
    (let [n (vector [-1 -1] [ 0 -1] [ 1 -1]
                            [-1  0]         [ 1  0]
                            [-1  1] [ 0  1] [ 1  1])]
                ((fn [a i] (do
                    (let [rem (rest  i)
                                cev (first i)
                                row (nth field (+ y (nth cev 0)) [])
                                col (nth row   (+ x (nth cev 1)) 0)
                                b   (+ a col)]
                    (if (nil? rem) b (recur b rem))))) 0 n))
))

(defn nextgen-for-row ([field row x y result]
    ;(println (str x "x" y ": " row))
    (let [nx (inc x) rr (rest row) cr (first row)]
        ;(println (str "[" x " " y "] " cr))
        (let [
            nr (if (== (moore-aliveness field x y) 2) 1 0)
            nresult (conj result nr)]
            (if (nil? rr) nresult (recur field rr nx y nresult))
        )
    )
))

(defn nextgen (
    [field] (
        (fn [f y r] (let [ny (inc y) nf (rest f) cf (first f)]
            (let [nr (concat r (vector (nextgen-for-row field cf 0 y ())))]
                (if (nil? nf) nr (recur nf ny nr)))
        )) field 0 ()
    )
))

(def ng (nextgen (init setup)))

Quick and dirty HTTP server in Ruby

Today I quickly wrote a HTTP server in Ruby for a fellow student. It’s nothing special, does not care a single bit about security. But it’s easy to use, enhance and understand and below 100 lines of code. I’m sure there are better, more efficient and propably easier ways to implement this in Ruby, but I wanted it to be done quickly.

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
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
#
# DeineMudder
# written by blacki
#
# This is an extremely minimalistic implementation of a HTTP server in ruby
# It does not care about security and stuff, so don't use this in a production
# environment. The code was written to be easily understandable (and I was tired
# when writting this), so there sure are ways to improve this.
#
# If you want to add URLs have a look at the KnownURLs class
#
# THERE IS ABSOLUTELY NOW WARRANTY FOR FITNESS OR WHATSOEVER OF
# THIS SOFTWARE. SO USE AT YOUR OWN RISK
#
# Published as Public Domain
#
#

require 'socket'

HOST = 'localhost'
PORT = 8080

#
# To introduce new URLs simply add methods to this class which will
# become available using "/METHOD_NAME" (GET requests only)
#
class KnownURLs
 
  def read(params)
    return File.new(params["name"]).readlines
  end
 
  def connect(params)
    Thread.start do
      system("ping", "-c 2", params["ip"])
    end

    return <<EOF
<html><head><title>connect</title></head><body><center><h1>Connection to #{params["ip"]} established</h1></center></body></html>
EOF

  end

end



#
# If you do any modification after this point be sure you know what you do
#

KNOWN_URLS = KnownURLs.new
def dispatch(method, url)
  result = nil

  params_str = url.split("?")
  url_handler_name = params_str[0][1..-1]
  if method == "GET"
    params = {}
    if params_str.length == 2
      params_key_value_pairs = params_str[1].split("&")
      params = Hash[*params_key_value_pairs.collect {|v| p = v.split("="); [p[0], p[p.size == 2 ? 1 : 0]]}.flatten]
    end

    result = KNOWN_URLS.send(url_handler_name, params) rescue "Caught error<br /><pre>#{$!}</pre>"
  end

  return result
end

serverSocket = TCPServer.new(HOST, PORT)
while clientSocket = serverSocket.accept
  req = clientSocket.gets.strip
  method, url = req.split(" ")
  puts "[REQ] #{method} #{url}"

  result = dispatch(method, url)
  response = { :status => 300, :body => "" }
  if result.nil?
    response = { :body   => "<html><head><title>404 NOT FOUND</title></head><body><center><h1>Unknown URL</h1></center></body></html>",
                 :status => 404 }
  else
    response[:body] = result
  end

  clientSocket.puts <<EOF
HTTP/1.0 #{response[:status]} OK
Server: Deine Mudder
Content-Lenhth: #{response[:body].length}
Content-Type: text/html
Connection: close

#{response[:body]}
EOF

  clientSocket.close
end

Use Mylyn to build your commit log

Every heard of Mylyn? The absolutely awesome task focusing feature for Eclipse. With Eclipse Ganymede it became a part of the release train. To me, the two most interessting features are:

  1. the bug tracking system connectors (e.g. to Bugzilla). It’s just so awesome having the bugs/feature-requests you’re currently working on right in your Eclipse.
  2. the ability to create local tasks

These days I started using both to remember what I changed in my code since the last commit. But as I’m not (or at least not most of the time) using the Mylyn context, I don’t get to use the commit log integration. Just to have a workaround for this I wrote a small plugin. This plugin just runs thru all the tasks available and shows them in a text box (

Task Summary View

).
And just to have that mentioned, there something I don’t like about the plugins implementation. I had to use internal API of Mylyn to access the tasks. If someone knows a better way to implement this just write a comment.
There are a few more things I’d love to implement some time:

  • Use the JFace templates to have some neat summary template
  • The template should be editable in the preferences (include field assist)
  • Be able to filter the summary for more than just one category
  • Oh, and don’t rely on internal API

To get your hands on this stuff download the binary/source here (unfortunately WordPress messes up the filename), or the project’s source files here.

Open Smultron from your console

In case you don’t want to spend a lot of money (even though well worth) on TextMate, have a look at Smultron. And if you want to open a file using your handy command line, just alias it. Put the following line in your

.bash_profile

and your ready to go

1
alias edit='open -a Smultron'

Once you got that (and have ensured that you’ve loaded the latest version of your profile), type

1
edit somefile.txt

to edit a file in Smultron.

Fork me on GitHub