Java: Loading a SVG into a BufferedImage

Unfortunately Java does not support SVG by default. But there is a great Apache Project aiming just for this purpose called batik.

Although the reference and documentation is pretty well, it does not cover loading an SVG and just saving it as a BufferedImage.

Here’s an example of how I did it:

Write a simple Transcoder

class BufferedImageTranscoder extends ImageTranscoder
{
  @Override
  public BufferedImage createImage(int w, int h)
  {
    BufferedImage bi = new BufferedImage(w, h, BufferedImage.TYPE_INT_ARGB);
    return bi;
  }
 
  @Override
  public void writeImage(BufferedImage img, TranscoderOutput output)
  {
    this.img = img;
  }
 
  public BufferedImage getBufferedImage()
  {
    return img;
  }
  private BufferedImage img = null;
}

Using the Transcoder

  public static BufferedImage loadImage(File svgFile, float width, float height)
  {
    BufferedImageTranscoder imageTranscoder = new BufferedImageTranscoder();
 
    imageTranscoder.addTranscodingHint(PNGTranscoder.KEY_WIDTH, width);
    imageTranscoder.addTranscodingHint(PNGTranscoder.KEY_HEIGHT, height);
 
    TranscoderInput input = new TranscoderInput(svgFile);
    imageTranscoder.transcode(input, null);
 
    return imageTranscoder.getBufferedImage();
  }

Posted in Java | Tagged , , , , | 3 Comments

HOWTO: Using JUnit with Eclipse with git hooks

This HOWTO shows using the git pre-commit hook to auto-run all JUnit tests before committing. This can be useful if you have a strict policy that no commit should fail the unit-test suite or if you just want to make sure that your committed changes pass the tests.

The build file

Larger projects usually have a build system. This build system automatically builds and runs your project and tests.

Creating an ant build file from Eclipse

Because many people nowadays use Eclipse, I give you a short introduction on howto create an ant build.xml file and integrate your JUnit tests into it.

  1. Right click your project in Eclipse and click Export
  2. Use General/Ant Buildfiles and follow the instructions.
  3. This will create a build.xml in your project folder which you now have to edit.
  4. Near the end you will find something like this:
        <target name="example">
            <mkdir dir="${junit.output.dir}"/>
            <junit fork="yes" printsummary="withOutAndErr">
                <formatter type="xml"/>
                <test name="example.Test1" todir="${junit.output.dir}"/>
                <test name="example.Test2" todir="${junit.output.dir}"/>
                <classpath refid="example.classpath"/>
            </junit>
        </target>
    
  5. Copy these lines and edit the following things:
    • Change the target name to test (target name="test")
    • Add the dependency: clean,build (target name="test" depends="clean,build")
    • Remove the printsummary=”withOutAndErr” attribute. (junit fork="yes")
    • Add the attribute haltonfailure=”yes” to the junit tag. (junit fork="yes" haltonfailure="yes")
    • Remove the mkdir line.
    • Remove the formatter line.
  6. It should now look something like this:
        <target name="test" depends="clean,build">
            <junit fork="yes" haltonfailure="yes">
                <test name="example.Test1" todir="${junit.output.dir}"/>
                <test name="example.Test2" todir="${junit.output.dir}"/>
                <classpath refid="example.classpath"/>
            </junit>
        </target>
    
  7. You can now test your junit tests by running ant test

Using another build system

If you use another build system you are on yourself. But it’s pretty simple. Just make sure you can run a command which fails with a non-zero exit code.

Creating the git hook

Create a file in your git repository .git/hooks/pre-commit and add the following lines:

#!/bin/sh

# Run the test suite.
# It will exit with 0 if it everything compiled and tested fine.
ant test
if [ $? -eq 0 ]; then
  exit 0
else
  echo "Building your project or running the tests failed."
  echo "Aborting the commit. Run with --no-verify to ignore."
  exit 1
fi

If you don’t run Windows you also have to add the executable flag: chmod +x .git/hooks/pre-commit.

Using the git hook

Before committing git will automatically run the test suite now. If it fails the commit will be aborted. If everything runs fine the commit will be created.
If you don’t want to run the test process (probably because you’re currently working on a development feature), you can pass the argument –no-verify to git commit.

Conclusion

This howto is not complete and does not guarantee to work. But it should give you a short introduction on how to do automatic unit-testing before every commit.

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

Java needs operator overloading

I like Java but I can’t understand why it still doesn’t have operator overloading.

Everyday operator overloading

Every Java object has two (and more) methods:

  1. String toString(): Returns a string representation of the object.
  2. boolean equals(Object obj): Indicates whether some other object is “equal to” this one.

So basically if you want to check whether Object a equals Object b, you type a.equals(b). But wait a second, there’s an operator == which checks if two integers are equal, so why not Objects? Well, because Java doesn’t know operator overloading.
And you can say whatever you want, but typing a == b is way more intuitive than typing a.equals(b).

Similar with toString(). Why not just cast this Object to a String object? (String)a is at least a little bit nicer to read than a.toString().

Any official statement?

I left out operator overloading as a fairly personal choice because I had seen too many people abuse it in C++.

James Gosling. (source)

So it people abuse a programming language feature you should not implement it? This is nonsense.
It’s like saying exceptions are evil because someone could abuse them as a return value.

Yeah. Someone could, someone will, but everyone who cares won’t use his code.

Java has operator overloading!

Yes, Java uses operator overloading. But unfortunately it can’t be influenced by the user.
Let’s see an example:

int a = 5, b = 10;
int c = a + b; // c = 15
		
String s = "foo", p = "bar";
String o = s + p; // o = "foobar"

So Java declares two completely different meanings to the + operator. It can’t be that evil if the Java Standard does it.

Style comparison

Let’s compare some code to see what looks better.

// Java
SomeComplexType a,b;
if(a.equals(b))
  foo();

Data d1,d2;
if(d1 < d2)
  bar();

Vector<String> v = /* ... create and fill ... */
String s = v.elementAt(42);

compared to

// C++
SomeComplexType a,b;
if(a == b)
  foo();

Date d1,d2; // Class overloading comparison operators
if(d1 < d2)
  bar();

vector<string> v;  /* fill */
string s = v[42];

Clearly if you re

There’s more than mumerical types

Whenever people argument about liking operator overloading others will counter with “yeah, but it’s only useful for numerical types”. Wrong.

Here are some examples:

  • Every comparable class: overloading == (and !=)
  • libpqxx (Postgres C++ library): [] to access rows/columns in a SELECT result.
  • glibmm: various overloadings for glib::ustring. (e.g. glib::ustring s = “foo”)
  • Various boost libraries for various reasons.
  • many many more

So why is operator overloading important? Well, it uses the programmers knowledge about operators and appends them to other objects. Therefore if the programmer knows that comparing two integers can be accomplished by typing a == b it should also be able to be used to compare any other object.

Posted in Java | Tagged , , | 5 Comments

Be careful when using post-increment++

Have a look at the following code to see a sample (dangerous) use of the post increment operator (i++).

#include <iostream>
 
class A
{
public:
  A()
  {
    i=0;
    f(i++);
  }
  void f(int p)
  {
    std::cout << "p=" << p <<" and i=" << i << std::endl;
  }
private:
  int i;
};
 
int main()
{
  A a; // output: p=0 and i=1
}

Let’s take a look what happens:

  1. i gets set to 0.
  2. f(i++)
    1. i is saved into a register (let’s call it R1 – so: R1=0)
    2. i is incremented and has now the value 1
    3. f(R1) is called. Remember R1=0
      1. The parameter (p) is 0
      2. The private attribute (i) is 1

This may look a little bit strange but it is intended. So please keep that in mind when using the post-increment operator.

My advice: Only use post-increment when you have good reason to do so.

Posted in C++ | Tagged , , , , | Leave a comment

Should we really trust Apple?

The latest news is all about the Cloud.

I’d like to quote one of my favorite Linux developers:

Never trust The Cloud. That is all.

Personally I trust some cloud services but only because those companies have never betrayed my trust.
But Apple? Should we really trust Apple?

Apple force people to use their products. Just some examples: iPhone Bluetooth, iTunes, and so on.
I even think Apple enforces a closer system than Microsoft ever has.

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

git’s missing features

Git is probably one of the best innovations (regarding Software Development) of the last 5 years. Although it was a really difficult to use software at the beginning, its usability has improved.
But it still lacks some features (and some of them probably just can’t be implemented due to git’s backend).

Easy code sharing

Git is all about distributed developing. You develop and when you finished you push your code to a main repository.
But in some cases you want to show your code to someone else to review it.
I’m currently doing a course called Advanced Software Engineering where you have to develop some piece of software in a group of 5 members. We often want to show someone else a piece of code so he can test it. We don’t want to push it to the main repository and therefore git doesn’t make this very easy. A nice way would be to set up a local git server (git-daemon) and tell someone to fetch it. But because of NAT, weird University WiFi, … we can’t.
We’ve set up a second repository (called demo) which we use for such occasions.
So what does git need? Git needs a git share which does one thing: Set up a git daemon and make it available to the whole Internet.

Access Control Lists

Gitolite is an access control layer on top of git which makes things very easy and powerful.
It helps restricting access for a specific branch, directory and file.
Unfortunately with git read access can only be defined at the root level. So you can’t allow a user to only read a certain directory. The only way to achieve this is to use multiple repositories and git submodule.
So at the end I think git has a Access Control System quite good enough for anything I can think of right now.

A good Tutorial for CVS/SVN users

There are some guides for SVN users to git, some of them better than others.
But I think most of them fail at one thing: They try explain how you work with git like you did with SVN. But that’s totally wrong!
Most of the times I speak with SVN fanboys about git vs. SVN I hear “I don’t branch”. Yeah, of course they don’t because they use SVN. Branchin in SVN is useless, not because branching is painful but because merging is.
Basically SVN does two things:

  1. give every changeset a number
  2. distribute code

So basically 90% of the SVN users just want to share their code with others. They use their VCS (Version Control System) only to upload their stuff to a server so that users can download it.
But git doesn’t focus on this (not so important) part but on developing software. It’s a SCM (Source Code Management) tool!. Git helps you develop software, SVN does not.
So all those SVN users out there: Keep in mind that if you want to use git like SVN, you’re missing 99% of git’s features!

A clean way to distribute project meta files

Maybe I’m missing something here but git doesn’t like project meta files (such as Eclipse/Netbeans/whatever project files).
You don’t want them to be included in the git repository because if someone starts their IDE it will modify those files and therefore cause a weird merge conflict.
But why does everyone has to configure their IDE on every machine? I basically see two solutions to this problem:

  1. IDEs should split the config files into two categories: Things everyone is interested in, things only I’m interested in. The problem with this solution is that you still have to setup your IDE (the second category).
  2. A second git layer for project files. Let’s imagine you can set up multiple git repositories (and I don’t mean remotes!) in one directory. This would help distribute your project files to your other machines and keep the main project repository clean.

Eclipse GUI

I don’t think git needs a Eclipse GUI, but one of the arguments why people don’t use git is because it doesn’t have an Eclipse GUI.
Personally I can’t understand this. If you really want to use a GUI (and you don’t) use TortoiseGIT. It’s usability has improved a LOT in the last years.

So at the end I can only recommend using git. You will NOT regret it. Believe me.

Posted in git, Uncategorized | Tagged , , , , | 1 Comment

String to int argc, char** argv

I’ve recently needed a simple command line string parser, which does some basic things. Nothing special.

It’s not 100% compatible with Linux or Windows, but should work for most cases.

What it does:

  • parsing std::string to std::vector
  • parsing std::string to int argc, char** argv
  • Using " and ' for "ignoring whitespaces"
  • Escaping whitespaces under Linux
  • Escaping ” and \
  • "foo'bar" and 'foo"bar'
  • Distinguish behaviour between Linux and Windows

What it does not:

/* stringtoargcargv.cpp -- Parsing a string to std::vector<string>
 
  Copyright (C) 2011 Bernhard Eder
 
  This software is provided 'as-is', without any express or implied
  warranty.  In no event will the authors be held liable for any damages
  arising from the use of this software.
 
  Permission is granted to anyone to use this software for any purpose,
  including commercial applications, and to alter it and redistribute it
  freely, subject to the following restrictions:
 
  1. The origin of this software must not be misrepresented; you must not
   claim that you wrote the original software. If you use this software
   in a product, an acknowledgment in the product documentation would be
   appreciated but is not required.
  2. Altered source versions must be plainly marked as such, and must not be
   misrepresented as being the original software.
  3. This notice may not be removed or altered from any source distribution.
 
  Bernhard Eder blog_at_bbgen.net
 
*/
 
#include <iostream>
#include <sstream>
#include <stdexcept>
#include <vector>
#include <string>
 
#include <cstdlib>
#include <cstring>
 
bool _isQuote(char c);
bool _isEscape(char c);
bool _isEscape(char c);
bool _isWhitespace(char c);
std::vector<std::string> parse(const std::string& args);
void stringToArgcArgv(const std::string& str, int* argc, char*** argv);
 
/*
 * Usage:
 * int argc;
 * char** argv;
 * stringToArgcArgv("foo bar", &argc, &argv);
 */
void stringToArgcArgv(const std::string& str, int* argc, char*** argv)
{
  std::vector<std::string> args = parse(str);
 
  *argv = (char**)std::malloc(args.size() * sizeof(char*));
 
  int i=0;
  for(std::vector<std::string>::iterator it = args.begin();
      it != args.end();
      ++it, ++i)
  {
    std::string arg = *it;
    (*argv)[i] = (char*)std::malloc((arg.length()+1) * sizeof(char));
    std::strcpy((*argv)[i], arg.c_str());
  }
 
  *argc = args.size();
}
 
std::vector<std::string> parse(const std::string& args)
{
  std::stringstream ain(args);    // used to iterate over input string
  ain >> std::noskipws;           // do not skip white spaces
  std::vector<std::string> oargs; // output list of arguments
 
  std::stringstream currentArg("");
  currentArg >> std::noskipws;
 
  // current state
  enum State {
    InArg,      // currently scanning an argument
    InArgQuote, // currently scanning an argument (which started with quotes)
    OutOfArg    // currently not scanning an argument
  };
  State currentState = OutOfArg;
 
  char currentQuoteChar = '\0'; // to distinguish between ' and " quotations
                                // this allows to use "foo'bar"
 
  char c;
  while(!ain.eof() && (ain >> c)) { // iterate char by char
 
    if(_isQuote(c)) {
      switch(currentState) {
        case OutOfArg:
          currentArg.str(std::string());
        case InArg:
          currentState = InArgQuote;
          currentQuoteChar = c;
          break;
 
        case InArgQuote:
          if(c == currentQuoteChar)
            currentState = InArg;
          else
            currentArg << c;
          break;
      }
 
    }
    else if(_isWhitespace(c)) {
      switch(currentState) {
        case InArg:
          oargs.push_back(currentArg.str());
          currentState = OutOfArg;
          break;
        case InArgQuote:
          currentArg << c;
          break;
        case OutOfArg:
          // nothing
          break;
      }
    }
    else if(_isEscape(c)) {
      switch(currentState) {
        case OutOfArg:
          currentArg.str(std::string());
          currentState = InArg;
        case InArg:
        case InArgQuote:
          if(ain.eof())
          {
#ifdef WIN32
            // Windows doesn't care about an escape character at the end.
            // It just adds \ to the arg.
            currentArg << c;
#else
            throw(std::runtime_error("Found Escape Character at end of file."));
#endif
          }
          else
          {
#ifdef WIN32
            // Windows only escapes the " character.
            // Every other character is just printed and the \ is added itself.
            char c1 = c;
            ain >> c;
            if(c != '\"')
              currentArg << c1; // only ignore \ when next char is "
            ain.unget();
#else
            ain >> c;
            currentArg << c;
#endif
          }
          break;
      }
    }
    else {
      switch(currentState) {
        case InArg:
        case InArgQuote:
          currentArg << c;
          break;
 
        case OutOfArg:
          currentArg.str(std::string());
          currentArg << c;
          currentState = InArg;
          break;
      }
    }
  }
 
  if(currentState == InArg)
    oargs.push_back(currentArg.str());
  else if(currentState == InArgQuote)
    throw(std::runtime_error("Starting quote has no ending quote."));
 
  return oargs;
}
 
bool _isQuote(char c)
{
  if(c == '\"')
    return true;
  else if(c == '\'')
    return true;
 
  return false;
}
 
bool _isEscape(char c)
{
  if(c == '\\')
    return true;
 
  return false;
}
 
bool _isWhitespace(char c)
{
  if(c == ' ')
    return true;
  else if(c == '\t')
    return true;
 
  return false;
}

(Download: stringtoargcargv.cpp)

If you’re interested in 100% compatible parsing, you should have a look at parse-string-into-argv-argc or CommandLineToArgvW (Windows).

Posted in C++ | Tagged , , , , , | Leave a comment

CommandLineToArgvW weirdness

Windows has a really weird behaviour for CommandLineToArgvW or it’s directly argc/argv parsing.

If you have a command line string with multiple ” in a row, it’s count is divided by three. So for example foo"""bar is encoded to foo"bar.
But it get’s interesting, when you don’t have them in a row. Let’s take a look at the following encodings:

a"b"c"d  -> abcd
a""b"c"d -> abcd
a"b""c"d -> ab""cd
a"b"c""d -> abcd

I have no idea why it encodes them like this. And it probably doesn’t really matter. But it’s really strange.

The above have been tested using argc.cpp.

Posted in C, C++, Coding | Tagged , , , | Leave a comment

I love error messages

I love how they tell you not only what’s wrong but also what to do.

Just take the following Error message from Adobe Flash Player I just got this morning.

Flash Error message
Error occoured during installation:
There is no error information available.

Posted in Error messages | Tagged , , , | Leave a comment

Hello bloggers out there!

It’s been a couple years now I’ve deleted my own blog. Mainly because I hadn’t any time to update it regularly. Although my spare time is probably a tenth now I feel like I have many things I would like to say something about.

So here I am starting a new blog on my old domain.

This blog will be written entirely in English and will focus on IT stuff.

So stay tuned for new and interesting posts!

Posted in Uncategorized | Leave a comment