Feeds:
Posts
Comments

I am working on a project and I needed to inject a spring bean into a utility class static attribute, but then I found out that spring doesn’t have any way of injecting static attributes directly.

So after playing a little with spring I came with the following solution:


@Component
public class MessageResourceUtil {

    private static ResourceBundleMessageSource messageSource;

    @Autowired(required=true)
    public void setMessageSource(ResourceBundleMessageSource messageSource) {
        MessageResourceUtil.messageSource = messageSource;
    }

    public static String getMessage(String message, Object[] params, Locale locale) {
        return messageSource.getMessage(message, params, locale);
    }
}

Here is the code description:

  • Annotate your class with @Component so spring can inject its attributes;
  • Then create the static attribute without annotations;
  • Create a public non static method to set the attribute;
  • Annotate the setter method with @Autowired(Required=true).

Then you will be able to use your class’ static methods that use its static attribute:


MessageResourceUtil.getMessage("message.key", params, locale);

I thought that setting up a git server would be more difficult then it really is!

In this post I will explain the steps that I followed to get an up and running git remote repository.

I installed git from source, so I downloaded git source (http://git-scm.com/download) and, as root, executed the following commands:

Extract:

tar -xzvf git-1.6.1.2.tar.gz

Configure to install in /usr/local:

cd git-1.6.1.2
make configure
./configure --prefix=/usr/local

Install:

make all doc
make install install-doc install-html

“Alright, git is installed, cooool!”

“But I still don’t have a repository. How do I create a remote repository?”

To create a remote repository I’ve created a git user and decided to put all repositories in git user’s home directory.

So create git user:

adduser git

Create the repository (I named it repo, you can name it whatever you like):

mkdir repo.git
cd repo.git
git --bare init

Notice that using –bare in git init command we are telling git not to store the current files in the repository only the diffs.

Now you are able to clone your remote repository and start using it!

git clone git@gitserver:repo.git

“Alright! I’ve installed git, created a remote repository and started using it, but every time I try to git clone or git push I have to enter git user password. Can I use public-key cryptography and SSH to authenticate users during git’s command?”

Yes you can!

First you have to create a public/private key pair for your users if they don’t have one already.

Check if they have a key pair in their ~/.ssh directory, they are always named file_name and file_name.pub.

If they don’t have any key they need to create using the ssh-keygen.

ssh-keygen

Depending on their system it will generate something like this:

Generating public/private rsa key pair.
Enter file in which to save the key (/home/dkamakura/.ssh/id_rsa): (here you can hit enter)
Enter passphrase (empty for no passphrase): (here you can hit enter or enter a passfrase)
Enter same passphrase again: (here you have to enter the same you did above)
Your identification has been saved in /home/dkamakura/.ssh/id_rsa.
Your public key has been saved in /home/dkamakura/.ssh/id_rsa.pub.
The key fingerprint is:
01:23:e5:35:0b:a2:48:54:a9:36:a6:15:a0:23:e9:f0 dkamakura@AMSP01010

After generating the key pair you have to copy all public keys (in this case named id_rsa.pub) to the authorized_keys file in git user’s .ssh directory in the repository server.

cat id_rsa.pub | ssh git@gitserver 'cat >> .ssh/authorized_keys'

That’s it! Now you have your git server up and running and your users are authenticated using public key cryptography and SSH!

Ruuuulez!

Javascript is a very flexible language, but sometimes we can get lost in its nuances. The following code is a typical mistake many programmers do using closures.

var divElements = document.getElementsByTagName("div");

for(var i = 0; i < divElements.length; i++) {
    divElements[i].addEventListener("click", function() {
        alert( "Element #" + i + " was clicked." );
    }, false);
}

In this code we have a common issue with closure and looping where the iterator is not maintained in the closure.

The problem occurs because the closure keeps only the references to variables (in this case “i”), not their current values at the time the closure is created.  So every time the user clicks on the elements the program will show the last value of i (divElements.length - 1).

One way we can fix this is using an executed anonymous function to wrap the iterator:

var divElements = document.getElementsByTagName("div");

for (var i = 0; i < div.length; i++) {
    (function(x) {
        divElements[x].addEventListener("click", function() {
            alert( "Element #" + x + " was clicked." );
        }, false);
    })(i);
}

An executed anonymous function is written as (function(){})(). This means that first we create an anonymous function (function(){})... and then we execute it (...)(), so we have a code block that is instantly created, executed and discarded.

So in the example above we pass to the anonymous function the iterator value giving our click handler closure the value that it expects. 🙂

Now that I learned we can write ruby scripts to run in Unix-like operating systems I wrote a script to do the same thing I did in the previous post: remove empty directories.

In this case we use the characters “#!” (called shebang, hashbang, hashpling, or pound bang) as the first two characters in the file to indicate that the file is a script, after the shebang sign we need to specify which interpreter to use to execute the file (for Ruby scripts /usr/bin/ruby).

The resulting code for removing empty directories is:

#!/usr/bin/ruby

def remove_empty_subdir(dir)
    (Dir.entries(dir) - [".", ".."]).each do |subdir|
        subdir = "#{dir}/#{subdir}"
        if File.directory?(subdir)
            remove_empty_subdir(subdir)
            Dir.delete(subdir) if Dir.entries(subdir).size == 2
        end
    end
end

remove_empty_subdir(Dir.pwd)

As I am not a Ruby expert (yet 🙂 ) there should be better ways to do that.

And we have to notice that this code can cause race condition, for example, empty directories can be created after we read all entries. In my case race condition was not a problem.

Well, it was good for learning some Ruby stuffs, but it is much easier to write

find . -type d -empty | xargs rmdir

in your shell then all this code above. 🙂

Last week I had a problem with a program that creates a directory structure to separate temporary text files from various companies based on company id. Basically if the directory exists the program moves the file into it, otherwise, the program creates the directory before it moves the file. After a period of time the files are deleted.

The problem occurred because the program were removing the files, but not removing the empty directories, so when the number of sub directories reached 32000, every time we tried to create a new directory we got:

mkdir: cannot create directory 'xpto'': Too many links

That happens because Linux set a limit for the number of hard links we can create in a directory.

We easily fixed the bug, and we needed to remove all empty directories.

“It’s easy! All we need to do is:”

rmdir --ignore-fail-on-non-empty *

No good… rmdir resulted in too many arguments

“Alright it didn’t work. Now what?”

“C’mon, we’re hackers, we can use du to see disk usage and filter empty directories using grep, then we can pass the results to awk and execute rmdir for each empty directory.”

So we ended up with this totally hacker command:

du -bh | grep "^4\.0K" | awk {'system("rmdir --ignore-fail-on-non-empty " $2);'}

After a little search we figured out that we could simply do:

find . -type d -empty | xargs rmdir

find returns all empty dirs and xargs pass each result to rmdir.

Much better! 🙂

While I’m studying Ruby I am also giving a try with Git, an open source, distributed version system.

Differently of CVS or SVN, Git is distributed, meaning that every Git clone is a full-fledged repository with complete history and full revision tracking capabilities, not dependent on network access or a central server. Besides that Git is very fast executing its functions.

Installing git on Ubuntu is very straightforward, all you have to do is:

$ sudo apt-get install git-core

And Git will be installed, also you can get the source code in Git’s page and compile it yourself.

After installing Git you can set git cheat-sheet (a helper for reminding Git commands) as your desktop background and watch some screencasts at Gitcasts (videos demonstrations on how to use Git).

Then you will be able to add all your projects at Github, a Git repository host.

I just got my copy of Programming Ruby: The Pragmatic Programmers’ Guide book. I will study Ruby based on this book, I heard that this is one of the best books to learn the language itself. It goes trhough the language basics, like classes, objects and variables to more advanced aspects of the language, like reflection and ruby extensions.

Now I can start to write my own “Hello, World!” Ruby programs! 🙂