Archive for January, 2009

Autologin on websites

Some sites provide for their login one form that just contain the login form. Firefox fills it out with username+password, but you still have to aim at the submit button.
This greasemonkey-script provides auto-login for TUWEL, TUWIS and any other site you want that only provides one form. autologin.user (js, 1 KB)

No Comments

Patterns for Unit testing multithreaded applications

What I do here is more module/component testing of threaded parts of an application. Testing a module without threads is way easier than one with threads. I use JUnit and standard concurrency mechanisms for testing. Logging (log4j) can be a big help during test development.

Pattern Alpha:

Basic asynchronous event checking using semaphores explicitly.
The general idea is the following: first add a Mocked Listener inline:

	final Semaphore s = new Semaphore(0);
fw.addListener(new IModificationListener() {
public void fileModified(File f, ModifyActions action) {
log.debug("got event: " + f.getAbsolutePath() + ":" + action);
Assert.assertEquals("just_edited", f.getName());
Assert.assertEquals(ModifyActions.MODIFIED, action);
s.release();
}
});

It is important to note that the AssertionFailedError from JUnit will not cause the test to fail, because it happens in a different thread! It is wise to do some logging.
After that:

	Assert.assertTrue("Real content change",
s.tryAcquire(interval * 3,TimeUnit.MILLISECONDS));

We test if we got the right call in time. You have to choose a useful timing. Note that this should still be fast, so my advice would be: Determine what timing is the lower limit that still works for you – choose 10x of that. Also document for other development what the expected run time is.

A similar example:

	@Test
public void testReceiveSend_XML() throws Exception {
final String testmsgcontent = "<msg>hello</msg>";
final Semaphore s = new Semaphore(0);
msgService.registerReceiveMessageListener(
new IMessageReceiveListener() {
@Override
public void receivedMessage(UserId from_userid,
String content) {
// do some more checks here
s.release();
}
});
msgService.sendMessage(testUser2, testmsgcontent);
Assert.assertTrue(s.tryAcquire(2, 5, TimeUnit.SECONDS));
}

Pattern Beta:

more advanced checking of one or more handlers with a state chain.

I use this Counter (java, 1 KB) class with the functions inc() and await(statenumber).

Consider the following example:
State 0. User 1 sends a message to User 2. The message is received by User 2 (State 1), User 2 replies. User1 replies again, the message is received by User 2 again (State 2).
The test constraint is that the test is successful iff State 2 was reached within a certain time.

	@Test
@Prerequisite(checker = TestEnvironment.class)
public void testReceiveSend_MultipleInteractions() throws Exception {
final String testmsgcontent1 = "Testmessagecontent1";
final String testmsgcontent2 = testmsgcontent1 + " >> really?";
final String testmsgcontent3 = testmsgcontent2 + " >> yeah, srsly!";
final Counter c = new Counter();
msgService2.registerReceiveMessageListener(
new IMessageReceiveListener() {
@Override
public void receivedMessage(UserId from_userid,
String content) {
c.inc(); // We reached our next control check
if (c.getValue() == 1) {
Assert.assertEquals(testUser1, from_userid);
Assert.assertEquals(testmsgcontent1, content);
try {
msgService2.sendMessage(from_userid,
content + " >> really?");
} catch (Exception e) {
log.error("", e);
Assert.fail("Unexpected exception");
}
} else if (c.getValue() == 2) {
Assert.assertEquals(testUser1, from_userid);
Assert.assertEquals(testmsgcontent3, content);
} else {
Assert.fail("Unexpected call");
}
}
});
msgService1.registerReceiveMessageListener(
new IMessageReceiveListener() {
// practically a echo service
@Override
public void receivedMessage(UserId from_userid,
String content) {
try {
msgService1.sendMessage(from_userid,
content + " >> yeah, srsly!");
Assert.assertEquals(testmsgcontent2, content);
} catch (Exception e) {
Assert.fail("Unexpected exception");
}
}
});
msgService1.sendMessage(testUser2, testmsgcontent1);
Assert.assertTrue(c.await(2, 5, TimeUnit.SECONDS));
}

Pattern Gamma

So this was very simple so far, but we most likely don’t know the order of events that might come in. Also, I’d like the events to have names rather than numbers.

So what I really want is

  • to enter a event in the queue: step(“myevent”);
  • to wait until a step is reached no matter if it is exactly the next: awaitStep(“something”); This removes the step from the list.
  • to assure that was all that was received (the list of events is empty): isDone()

This Tracer.java (java, 3 KB) class helps me with that.
It also allows you to check only specific events and ignore others you enter (don’t use isDone).

An example:

	@Test
public void testSocketMethod_accepting() throws Exception {
// ...
tfm.request(this.outrequest, new INegotiationSuccessListener() {
@Override
public void failed(Throwable reason) {
t.step("clientside negotiation failed");
Assert.fail();
}
@Override
public void succeeded(IFileTransfer ft) {
t.step("clientside negotiation succeeded");
Assert.assertEquals(filename, ft.getFileName());
// make the variable available
TestSocketFileTransfer.this.fileTransfer = ft;
}
});
Assert.assertTrue(this.t.awaitStep("clientside negotiation succeeded", 1,
TimeUnit.SECONDS));
// it is assured that fileTransfer is available now
while (!this.fileTransfer.isDone()) { // This is a form of waiting in the main thread because this might take longer
try {
log.debug(this.t.toString());
Thread.sleep(40);
} catch (InterruptedException e) {
// best effort, doesn't matter
}
}
Assert.assertTrue(this.t.await("getting content from fs,started on server", 40,
TimeUnit.MILLISECONDS));
log.debug(this.t.toString()); // print what else is in the Tracer
Assert.assertTrue("timeout", this.t.isDone(40, TimeUnit.MILLISECONDS));
}

As far as I know, there are no simple libraries for handling threaded testing, I don’t know if that is possible in a very simple yet flexible way.
Threaded testing is quite verbose (as you see), but once you saw these constructs, it is easier to read.

I welcome your postings or links to other approaches in threaded testing.

PS: My experience in threaded testing comes from working at Porsche Informatik and two semesters of a Software Engineering project for the university that handles project folders (modifying listeners for deleting/changing files) and transferring content over the network (XMPP, sockets, thus message and other state notifications). If you are interested, the project, called Jake will be release within a month.

2 Comments

Maven: Colorized

Maven was written by people who obviously have no idea on how to create good tui (Text User Interface)-tools. They should sit together with the portage, git or other Linux-devs.
The output is unreadable (not to mention that the startup is slow).

So, what I did was wrap maven in a script that colorizes the output. The result looks like this:
colorizedmaven

This is how to do it:
create the file ~/bin/mvn with the following content (mvn (0 KB))

#!/bin/bash
/usr/bin/mvn $* | sed -e 's/Tests run: \([^,]*\), Failures: \([^,]*\), Errors: \([^,]*\), Skipped: \([^,]*\)/Tests run: \1, Failures: \2, Errors: \3, Skipped: \4/g' \
-e 's/\(\[WARN\].*\)/\1/g' \
-e 's/\(\[INFO\].*\)/\1/g' \
-e 's/\(\[ERROR\].*\)/\1/g'

replace /usr/bin/mvn with wherever your mvn is (find out with which mvn).
Double-check that you get the encoding right, the weird sign should be hexadecimal 1b. Use a editor that supports encodings for copy+paste.
Give your ~/bin/mvn execute permissions (chmod +x ~/bin/mvn)

Try it out: call ~/bin/mvn in one of your maven projects

What is left to do is to register your new mvn-wrapper so it is called everytime.
Add the following line to your ~/.bashrc :

alias mvn=~/bin/mvn

Execute the command you just added in your running shells so you can use it there too.

You are done.

Changing the distributed mvn startup script

Even better, but a little more intrusive (you need root rights):
change the distributed mvn file. It is a bash script actually.
In gentoo:

 $ which mvn
/usr/bin/mvn
$ file /usr/bin/mvn
/usr/bin/mvn: symbolic link to `/usr/share/maven-bin-2.0/bin/mvn'
$ file /usr/share/maven-bin-2.0/bin/mvn
/usr/share/maven-bin-2.0/bin/mvn: Bourne shell script text executable
$ 

Change the last call in that file to:

exec "$JAVACMD" \
$MAVEN_OPTS \
-classpath "${M2_HOME}"/boot/classworlds-*.jar \
"-Dclassworlds.conf=${M2_HOME}/bin/m2.conf" \
"-Dmaven.home=${M2_HOME}"  \
${CLASSWORLDS_LAUNCHER} $QUOTED_ARGS |
sed -e 's/Tests run: \([^,]*\), Failures: \([^,]*\), Errors: \([^,]*\), Skipped: \([^,]*\)/Tests run: \1, Failures: \2, Errors: \3, Skipped: \4/g' \
-e 's/\(\[WARN\].*\)/\1/g' \
-e 's/\(\[INFO\].*\)/\1/g' \
-e 's/\(\[ERROR\].*\)/\1/g'

That way you have it there directly. Maybe the gentoo devs could add a color use-flag. That’d be fun…

,

No Comments

Bash: Timeouts

You have a command and want to kill it after a certain time if it hasn’t finished.
This script does it for you:

timeoutwrapper.sh

#!/bin/bash
# License: BSD License
# author: Ram
# author: Johannes Buchner
TIMEOUT=$1
shift
COMMAND="$*"
if [[ "$TIMEOUT" == "" ]] || [[ "$COMMAND" == "" ]]; then
echo "USAGE: $0 <seconds to wait> <command with arguments>"
exit
fi
$COMMAND &
PRODPID=$!
export PRODPID
# record own PID
export PID=$$
# define exit function
exit_timeout() {
echo "Timeout. Checking for unfinished."
for i in ${PRODPID} ; do
ps -p $i |grep -v "PID TTY"
if [ $? == 0 ] ; then
# process still alive
echo "Sending SIGTERM to process $i"
kill $i
fi
done
# timeout exit
exit
}
# Handler for signal USR1 for the timer
trap exit_timeout SIGUSR1
# starting timer in subshell. It sends a SIGUSR1 to the father if it timeouts.
export TIMEOUT
(sleep $TIMEOUT ; kill -SIGUSR1 $PID) &
# record PID of timer
TPID=$!
# wait for all production processes to finish
wait ${PRODPID}
# Normal exit
echo "All processes ended normal"
# kill timer
kill $TPID

Usage examples:

$ bash timeoutwrapper.sh
USAGE: timeoutwrapper.sh <seconds to wait> <command with arguments>
$ bash timeoutwrapper.sh 1 sleep 3
Timeout. Checking for unfinished.
26612 pts/3    00:00:00 sleep
Sending SIGTERM to process 26612
$ bash timeoutwrapper.sh 4 sleep 3
All processes ended normal
$ bash timeoutwrapper.sh 2 du -sh .
Timeout. Checking for unfinished.
26622 pts/3    00:00:00 du
Sending SIGTERM to process 26622
$

PS: I found the script here and adopted it
http://redflo.de/tiki-index.php?page=Bash+script+with+timeout+function

1 Comment

Artikel zu freien Software-Lizenzen

Im Zuge der LVA Daten&Informatik-Recht habe ich einen
Artikel zu freien Software-Lizenzen geschrieben. Dieser wurde nicht reviewt, bietet aber meiner Meinung nach einen guten Überblick und Einblick in das Thema.

Bitte Kommentare und mögliche Fehler hier in den Kommentaren posten.

3 Comments

SSH -R is even cooler than -L

To be honest with you, I thought for three years now that the -L option of ssh is a cool thing. It connects to the ssh server and offers a remote service (port) locally. Call it port tunnelling. Great against firewalls.

Anyway, consider you have a ssh server in the internet, and two computers behind different firewalls that only let traffic out. But you want to connect from computer A to computer B.
So you could connect to the ssh server from both computers, but you would need some software that reverses your TCP flow. One of the channels has to be the client and one the server. That might even be possible just using pipes and ssh -L.

Ok, so I thought I was clever until I found the -R option.
What it does is to connects to the ssh server and offers a local service (port) remotely. (-L offers a remote service (port) locally.)
Consequent. And works nicely too!

No Comments

Gnome Services

GNOME Services (ssh tunnels, …)

A GTK-Panel-widget for watching user-services. For example, I use ssh tunnels for pretty much everything (mail most importantly).
It should provide functionality to

  • Test if service is still alive
    • Test program: expected return parameter
    • Interval
    • don’t wait forever for the test program
  • Restart/Start service
    • automatically on start?
    • automatically if test program fails
    • manually

These are just the notes I have here. Python+PyGTK would be a good choice for implementing. Should be fairly simple.

No Comments

Mail client securing tool

Most mail servers provide encryption today. However, because people prefer to have stuff working rather than secure, and secure unfortunately very often comes with not working out of the box, they end up having insecure configurations (like in mail clients). And, more importingly: They will never change them, because stuff works. Also, the mail provider will never be able to shut down the insecure service, because it would break stuff, he’ll lose clients, and they will think the provider is unreliable.
Welcome to the world of the internet. This is the essential reason why we still don’t use encryption. Except for HTTP, there we couldn’t use encryption everywhere for cpu speed and caching reasons.

Enough rambling, Johannes, what is your project idea?

A tool that analyzes the mail client configuration. It checks if the mail server provides a more secure way of connecting (“port scanning” like). It tests the more secure configuration. If successful, the user is given the option to automatically change the configuration.
This should have read/write backends to Thunderbird, Outlook, etc.

Also, it could advise the use to change from Outlook Express to <Your favorite>.

Another feature would be to automate the process without a UI. Sysadmins could deploy and run it on a whole client network.
Deploy is a funny word by the way…

No Comments

POP server editor

POP server editor (online message management)

POP servers hold a list of messages. Modern mail clients usually just download and delete everything from the server. Or you can set them to leave the stuff on the server.
It would be interesting to make a tool that allows you to view the messages on the server (headers), optionally display the whole message, lets you selectively delete messages on the server. Maybe with a search function. It should not replace a mail client or try to take its functionality.
POP is a very very simple protocol, so this should be a easy one.

No Comments

Project Ideas

I’m going to start a new category. Cool project ideas that I came to think of (sometimes even with more technical technical requirements and design guidelines). Maybe I’ll pick them up to implement, maybe you will if you don’t know what your next project will be…

No Comments