Gravatar for Java applications

Gravatar for Java (actually Gravatar4Java) is a small library for the generation of Gravatar URLs. For those readers who don’t know Gravatar – Gravatar allows you to have one avatar everywhere by uploading it to the Gravatar website. Other websites can then automatically retrieve an avatar for a user by using the email address as an identifier.

There is already a Java library around Gravatar by Ralf Ebert but it lacks some of the newer functionality like avatar over HTTPS or custom default avatars. Additionally it’s not a Maven project nor hosted on Maven Central, thus enough reasons to write my own.

The Gravatar4Java project is hosted on GitHub and already available in Maven Central (actually my first project in Maven Central)! Following is the typical Maven dependency snippet, a plain Java example and a Spring beans definition for the library.

<dependency>
    <groupId>de.bripkens</groupId>
    <artifactId>gravatar4java</artifactId>
    <version>1.1</version>
 </dependency>

 

import de.bripkens.gravatar.DefaultImage;
import de.bripkens.gravatar.Gravatar;
import de.bripkens.gravatar.Rating;

// ...

String gravatarImageURL = new Gravatar()
    .setSize(50)
    .setHttps(true)
    .setRating(Rating.PARENTAL_GUIDANCE_SUGGESTED)
    .setStandardDefaultImage(DefaultImage.MONSTER)
    .getUrl("foobar@example.com");

 

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
       xmlns:p="http://www.springframework.org/schema/p">

    <!-- Gravatar -->
    <bean id="gravatar"
          class="de.bripkens.gravatar.Gravatar"
          p:size="75"
          p:rating="GENERAL_AUDIENCE"
          p:standardDefaultImage="MONSTER" />

</beans>

SVG path arc curve command

The basic SVG rect shape provides functionality for rounded corners. Unfortunately, you can only change it for all four corners. I needed a rectangle which supports something like the CSS3 top- and bottom-border-radius instructions.

#foo {
    border-top-left-radius: 10px;
    border-top-right-radius: 10px;
    border-bottom-right-radius: 20px;
    border-bottom-left-radius: 20px;
}

I needed this because of my GSoC project. In this project, there are different nodes types which have to be visualized. You can see the two node types (which are the reason for this blog post) in the following figure.

Two node types of the SBGN

The two node types which are the reason for this blog post.

Sticking to the Don’t-Repeat-Yourself paradigm, I abstracted the drawing of rectangular shapes into a base class RectangularNode from which the classes Macromolecule and NucleicAcidFeature inherit. Since the two node types are the same (with regard to implementation), except for the border radius, I put all the funtionality into the base class RectangularNode. Now the Macromolecule and NucleicAcidFeature classes are merely subclasses which set the border radius on the RectangularNode class.

Now to the drawing of rectangles with different border-radii, there is no basic SVG shape which supports such behavior. As a result, you need the SVG path element. The path element enables you to draw such things as curves and arcs and can be used to draw every possible shape. For this specific issue, the arc is needed. Please refer to the specification for an explanation of the various commands and the path element in general. In this post I’ll only cover the generation of rectangles with different border radii and the arc command. The arc command is defined the following way (expressed as a regular expression in JavaScript with an example parsing). Continue reading

HTML / JavaScript calculate text dimensions

As part of my Google Summer of Code 2011 I have to write a client side visualization library in JavaScript and of course textual elements are part of this visualizations. To calculate the dimensions of any text you can make use of an HTML DIV element. With the help of some specific styles it will then auto adapt its size to the text. That’s how you do it.

Add the following to your stylesheet (CSS).

.textDimensionCalculation {
    position: absolute;
    visibility: hidden;
    height: auto;
    width: auto;
    white-space: nowrap;
}

This snippet adds a CSS class named textDimensionCalculation which we will apply to the DIV for the calculation of the text dimensions. The next listing contains the interesting part. I’m using jQuery to simplify things in this example. Continue reading

Maintaining and testing scope in JavaScript

One could say that the behaviour of “this” in JavaScript is rather unconventional, at least when you have a strong object-oriented background like I do. For example, libraries like jQuery change the scope of event listeners which does not allow you to refer to a surrounding object (think an object’s method is used as an event listener and in this method you try to access the object’s properties through “this”).

To maintain the scope we can create closures which make sure that the appropriate scope is set when the function / listener is called.

/**
 * @description
 * <p>We extend the prototype of all functions with the function
 * createDelegate. This method allows us to change the scope of a
 * function.</p>
 *
 * <p>This is useful when attaching listeners to jQuery events like click
 * or mousemove as jQuery normally uses this to reference the source
 * of the event. When using the createDelegate method, this will point to
 * the object that you want to reference with this.</p>
 *
 * <p>Source:
 * <a href="http://stackoverflow.com/questions/520019/controlling-the-value-of-this-in-a-jquery-event">
 *     Stackoverflow
 * </a></p>
 *
 * @param {Object} scope The scope which you want to apply.
 * @return {Function} function with maintained scope
 */
Function.prototype.createDelegate = function(scope) {
    var fn = this;
    return function() {
        // Forward to the original function using 'scope' as 'this'.
        return fn.apply(scope, arguments);
    };
};

I ran into this issue when I wrote my first bigger (> 7000 lines of code) object-oriented JavaScript application. Additionally, you can find a QUnit test in the following listing. It shows how you can tell whether the correct scope was applied.

test('function.createDelegate', function() {
    expect(1);

    var scope = { answer : 42 };

    var verify = function() {
        equal(this.answer, 42, 'Wrong scope applied.');
    }

    var delegate = verify.createDelegate(scope);

    delegate.call({ answer : 41})
});

Storing Mercurial repository passwords in a secure manner

To store passwords permanently for Mercurial repositories  you have two options. One possibility is to store it as clear text in your Mercurial configuration file in ~/.hgrc. Of course you should never do that and that’s why I won’t explain how this could be done. Instead you should use a Mercurial extension which allows you to store passwords in a keyring. This blog post summarizes how this can be done.

At first download this file and save it somewhere, e.g. ~/.hg/mercurial_keyring.py. As a next step open ~/.hgrc (create the file if it doesn’t already exist) and add the following lines.

[extensions]
hgext.mercurial_keyring = /home/?/.hg/mercurial_keyring.py

Make sure to change the path to the actual location of the file which you just downloaded. Now you just have to download the following two dependencies and you are done.

sudo pip install keyring
sudo pip install mercurial_keyring

Next time you push / pull something you should be asked for the last time for your password. If you run into any troubles you should consult this wiki page.

Getting accepted to Google Summer of Code

Even though I just got accepted for the Google Summer of Code 2011 I want to tell you about my experience regarding the application process.

Each year a lot of students are applying for the Google Summer of Code. To be one of the lucky students that are accepted you should follow a few general rules (and a few that I’m making up).

Study
Read the GSoC FAQ and the GSoC student guide. Both sources will provide you with invaluable information that is crucial to being accepted. I won’t list any advices that can be read in these sources.

Choosing an organization
Carefully chose your organization. There are big differences in how the organizations are going to select students. Some organizations, e.g. Mozilla or Django, are expecting you to fix a bug before applying. You can assume that your chances will be significantly lower than the chances of your fellow students if you don’t fix a bug, write documentation or participate in another way.
There are also organizations which don’t require this, e.g. universities. You can use this for your advantage when you know that you won’t be able to spend a significant amount of time before the actual GSoC coding starts.

State impediments
Every project has challenges – some require you to use a technology that you don’t know, while others are positioned in a domain (think business domain) which you haven’t come in contact with (yet). Make sure that you state these difficulties, how you want to solve them and plan additional time for removing impediments. This will tell the organization that you actually spend some time thinking about the project.
For example my GSoC project requires me to write a JavaScript library for the visualization of interactive reaction graphs. While I don’t know anything about biophysics, I have a strong visualization background. I stated this in my application and made sure that this information can also be seen when looking at the timeline (see GSoC student guide).

Share your ideas
With sharing I don’t mean to share your ideas on a public mailing list but instead state how you are going to tackle the project in your application. You might want to create some UML diagrams or architecture diagrams which illustrate your ideas.
I created a very generic class diagrams for graph structures which already incorporated some domain requirements and an architecture diagrams that stressed technologies and frameworks that I’m planning to use.

I hope this article gives you some good ideas and I wish you all the best of luck for the next GSoC period!

Participating in Google Summer of Code 2011

Last year I heard about the Google Summer of Code – a project that gives students the possibility to flip bits instead of burgers, i.e. Google enables students to work on open source software. Since then I have been planning to participate in this project and I’m happy to say that I got accepted!

Google Summer of Code 2011 logo

Google Summer of Code 2011 logo

Over the next three months I’ll be working on a JavaScript visualization library for interactive reaction graphs. The organization is the Theoretical Biophysics group of the Humboldt University (Berlin – Germany). Describing what I’m going to do is kinda complicated and I’m sure that I couldn’t explain it anyway (at least properly). Therefore just imagine client side (browser) rendering and modification of these diagrams.

In my application I summarized it the following way:

Currently no library is available for client side visualization of reaction networks. As a result a JavaScript library for interactive reaction graphs is to be designed and developed. Besides presentation the framework should provide functionality for scrolling, dragging, zooming, modification and export to JPEG, PNG, SVG and PDF.

I’m planning to post a bunch of blog entries during that time to document the whole experience. So if you are interested in this you should bookmark / subscribe to my blog.

Learning regular expressions

There are times in which I hear about or start investigating something and suddenly I notice that I could use this knowledge, technology, pattern or term in various situations. Just recently I started diving into regular expressions. Even though I’m developing software for several years now I never took the time to really learn them.

Everything started with a small module that I developed for a project that I’m contributing to – the so called Open Decision Repository which I have been referring to in a few blog posts. I wanted to apply some of the neat URL rewriting techniques that Django or Spring use. Especially nice are Django’s capabilities with regard to reverting a regular expression, i.e. it can build a URL from a regular expression. For example you might define a RESTful URL for an entity Customer. From a view you could now say give me the URL to the Customer with id ten. Django now uses the regular expressions from your URL configuration to build the URL.

Besides the URL rewriting module I’m working for company which requested a better output format for ROBOdoc. This also required a fair amount of regular expressions and XML parsing using xmllib2 for Python but that’s a whole other story and subject to non-disclosure.

To document a small example I created the following Python program which replaces Twitter like links to users, e.g. @BenRipkens, with a link to the user’s profile.

#/usr/bin/env python2.6
#
# Copyright 2011 Ben Ripkens
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
#   http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.

__authors__ = [
    '"Ben Ripkens" <bripkens.dev@gmail.com>',
]

import re

user_name_pattern = re.compile(r"""
    @                 # the 'at sign' must be used to reference a user
    (?P<user_name>    # the user name is contained within the 'user_name' group
      [a-z]           # at least one character (a-z) is required
      \w{0,19}        # the shortest user name may be one character, max 20
    )
    \b                # it must end through a word boundary character
    """, re.IGNORECASE | re.VERBOSE)

def generate_link_to_user_page(match):
    """Callable for every user name match

    Keyword arguments:
    match -- A regex match object which contains a user_name group

    Returns:
    Link to the user detail page.
    """
    user_name = match.group('user_name')

    # verify that the user exists and create a user slug / id
    user_link = user_name

    return """<a href="/user/details/%s"
        title="Retrieve more information about this user'>
            %s
        </a>
        """ % (user_link, user_name)

if __name__ == '__main__':
    tweet = """Example regex use case. We are going to capture the link to
        @BenRipkens and transform it into a HTML 'a' element.
        """

    print re.sub(user_name_pattern, generate_link_to_user_page, tweet)

Using Sass with Django

Sass is great as it adds some neat functionality to your stylesheets, e.g. nesting, mixins, variables and math. Since it is a command line tool you can execute it like

sass --watch input.scss:output.css

Having to type this command is tedious and creating a .sh or .bat script for this requires you to maintain two files.  My approach is to create a custom django-admin command watchsass for this. How this is generally done can be read on this page. The following listing shows the command which I’m using in a small project right now.

#/usr/bin/env python2.6
# Copyright 2011 Ben Ripkens
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
#   http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.

__authors__ = [
        '"Ben Ripkens" <bripkens.dev@gmail.com>',
]

from django.core.management.base import NoArgsCommand
import os
import time
import datetime

class Command(NoArgsCommand):
    """
    Watch for changes in the common.scss file and convert it to common.css
    using sass. Sass needs to be on the path.

http://sass-lang.com/

    """
    help = 'Convert scss to css'

    def handle_noargs(self, **options):
        scss = os.path.abspath("media/css/common.scss")
        css = os.path.abspath("media/css/common.css")

        command = "sass \"" + scss + "\":\"" + css + "\" --style compressed"

        print "Executing command '%s'" % command
        print "Sass watch parameter is not used due to some bug."

        last_update = os.stat(scss).st_mtime
        os.system(command)

        while True:
            if not last_update == os.stat(scss).st_mtime:
                os.system(command)
                last_update = os.stat(scss).st_mtime
                print "Updated stylesheet at %s" % datetime.datetime.now()
            time.sleep(0.5)

As you can see I’m not using the –watch flag. This is because its not working on my system.