Articles

Gentoo XBMC Pre-Setup

In Gentoo, XBMC on 18/04/2011 by pier0w

There is some extra configuration that is required before XBMC can be installed. This is mostly to do with unmasking some packages and setting up some USE flags.

So first create the /etc/portage/ directory, this is where the unmask, keyword, and use files will go.

Next create the following files:

/etc/portage/package.use:
media-video/mplayer fbcon
x11-base/xorg-server udev
x11-base/xorg-x11 udev opengl
sys-fs/udev extras
sys-auth/pambase consolekit
x11-libs/cairo X
dev-libs/libgcrypt static-libs
dev-libs/libgpg-error static-libs
media-libs/libsdl X opengl
sys-auth/consolekit policykit
sys-block/parted device-mapper
media-tv/xbmc webserver

/etc/portage/package.keywords:
dev-util/debhelper ~*
app-misc/cwiid ~*
net-libs/libmicrohttpd ~*
media-tv/xbmc ~*

/etc/portage/package.unmask:
app-misc/cwiid
net-libs/libmicrohttpd
media-tv/xbmc

With that done XBMC should now be able to be emerged.

Articles

Gentoo Installation (Inspiron 6400)

In Gentoo on 17/04/2011 by pier0w

Here is a run down of the Gentoo installation I did on an Inspiron 6400. I will walk through the configuration I used in the different stages of the Gentoo Handbook installation.

I chose to install the x86 version of Gentoo because it has better compatibility with closed sources applications like Java and Flash.

I’m not going to walk through how I set up my network for the install.

4. Preparing the Disks

The disk layout I chose is the same as the one the Gentoo Handbook recommends. That is a very small boot partition at the start of the disk, then a 512Meg swap partition after that, and lastly the rest of the disk is an ext3 partition that will be used for the root file system.

Here is the output of fdisk -l:

Disk /dev/sda: 250.1 GB, 250059350016 bytes
255 heads, 63 sectors/track, 30401 cylinders, total 488397168 sectors
Units = sectors of 1 * 512 = 512 bytes
Sector size (logical/physical): 512 bytes / 512 bytes
I/O size (minimum/optimal): 512 bytes / 512 bytes
Disk identifier: 0xab6ad924

   Device Boot      Start         End      Blocks   Id  System
/dev/sda1            2048       67583       32768   83  Linux
/dev/sda2           67584     1116159      524288   82  Linux swap / Solaris
/dev/sda3         1116160   488397167   243640504   83  Linux

As you can see I have added a larger hard drive to this laptop but otherwise the partition layout is nice and simple. I decided not to use ext4 because I don’t think I will require any of it’s new features and maybe it’s not as light wait as ext3, but I am not certain of that.

5. Installing the Gentoo Installation Files

The only thing that I did different in this section was to set the MAKEOPTS to use three threads.

MAKEOPTS="-j3"

6. Installing the Gentoo Base System

I have added a large number of USE flags to the make.conf file, this is just to make sure that all the required features are compiled in. Also the video card driver has been set to the intel driver.

Here is the make.conf file:

# These settings were set by the catalyst build script that automatically
# built this stage.
# Please consult /usr/share/portage/config/make.conf.example for a more
# detailed example.
CFLAGS="-O2 -march=i686 -pipe"
CXXFLAGS="${CFLAGS}"
# WARNING: Changing your CHOST is not something that should be done lightly.
# Please consult http://www.gentoo.org/doc/en/change-chost.xml before changing.
CHOST="i686-pc-linux-gnu"
MAKEOPTS="-j3"

USE="a52 aac acpi aim alsa cdda cddb cdr css dts dv dvd dvdr encode ffmpeg flac gif
gphoto2 icq ios ipod jpeg jpeg2k lame lirc matroska mmx mp3 mp4 mpeg mplayer msn
musicbrainz ogg opengl png quicktime raw samba smp sound sse sse2 svg svga theora truetype
udev usb v4l v4l2 vcd vorbis wifi win32codecs wmf x264 xvid"

GENTOO_MIRRORS="ftp://mirror.bytemark.co.uk/gentoo/ http://mirror.bytemark.co.uk/gentoo/ rsync://mirror.bytemark.co.uk/gentoo/ ftp://mirror.qubenet.net/mirror/gentoo/ http://mirror.qubenet.net/mirror/gentoo/ rsync://rsync.mirrorservice.org/www.ibiblio.org/gentoo/ http://www.mirrorservice.org/sites/www.ibiblio.org/gentoo/ ftp://ftp.mirrorservice.org/sites/www.ibiblio.org/gentoo/ ftp://gentoo.virginmedia.com/sites/gentoo http://gentoo.virginmedia.com/"

SYNC="rsync://rsync.uk.gentoo.org/gentoo-portage"

VIDEO_CARDS="intel"

7. Configuring the Kernel

I have customised the kernel (2.6.36-gentoo-r8) quite a bit to fit this laptop and to add some extra functionality for wireless and XBMC support.

Below are the custom settings that I used.

Processor:
Processor type and features  --->
    Processor family (Core 2/newer Xeon)  --->
        (X) Core 2/newer Xeon

File System:
File systems  --->
    <*> Second extended fs support
    [*]   Ext2 extended attributes
    [*]     Ext2 POSIX Access Control Lists
    [*]     Ext2 Security Labels
    [*]   Ext2 execute in place support
    <*> Ext3 journalling file system support
    [*]   Ext3 extended attributes
    [*]     Ext3 POSIX Access Control Lists
    [*]     Ext3 Security Labels
    <*> The Extended 4 (ext4) filesystem
    [*]   Ext4 extended attributes
    [*]     Ext4 POSIX Access Control Lists
    [*]     Ext4 Security Labels
    [*] Dnotify support
    [*] Inotify support for userspace
    [*] Quota support
    [*] Report quota messages through netlink interface
    <*> Quota format vfsv0 and vfsv1 support
    <*> Kernel automounter version 4 support (also supports v3)
    <*> FUSE (Filesystem in Userspace) support
    CD-ROM/DVD Filesystems  --->
        <*> ISO 9660 CDROM file system support
        [*]   Microsoft Joliet CDROM extensions
        [*]   Transparent decompression extension
        <*> UDF file system support 
    DOS/FAT/NT Filesystems  --->
        <*> MSDOS fs support
        <*> VFAT (Windows-95) fs support
        (437) Default codepage for FAT
        (iso8859-1) Default iocharset for FAT
        <*> NTFS file system support
        [*]   NTFS write support
    [*] Network File Systems  --->
        <*>   NFS client support
        [*]     NFS client support for NFS version 3
        [*]       NFS client support for the NFSv3 ACL protocol extension
        [*]     NFS client support for NFS version 4
        [*]     Root file system on NFS
        <*>   CIFS support (advanced network filesystem, SMBFS successor)

Intel Graphics: (Intel GMA, Gentoo 3D Acceleration, GLX)
Device Drivers  --->
    Graphics support  --->
        Direct Rendering Manager (XFree86 4.1.0 and higher DRI support)  --->
            <*>   Intel I810
            <*>   Intel 830M, 845G, 852GM, 855GM, 865G (i915 driver)  --->
                (X) i915 driver
            [*]     Enable modesetting on intel by default

Sound: (Gentoo Alsa)
Device Drivers  --->
    <*> Sound card support  --->
        <*>   Advanced Linux Sound Architecture  --->
            [*]   PCI sound devices  --->
                <*>   Intel HD Audio  --->
                    [*]   Build hwdep interface for HD-audio driver
                    [*]   Build Realtek HD-audio codec support
                    [*]   Build Analog Device HD-audio codec support
                    [*]   Build IDT/Sigmatel HD-audio codec support
                    [*]   Build VIA HD-audio codec support
                    [*]   Build ATI HDMI HD-audio codec support
                    [*]   Build NVIDIA HDMI HD-audio codec support
                    [*]   Build INTEL HDMI HD-audio codec support
                    [*]   Build Cirrus Logic codec support
                    [*]   Build Conexant HD-audio codec support
                    [*]   Build Creative CA0110-IBG codec support
                    [*]   Build C-Media HD-audio codec support
                    [*]   Build Silicon Labs 3054 HD-modem codec support
                    [*]   Enable generic HD-audio codec parser

Network:
Device Drivers  --->
    [*] Network device support  --->
        <*>   Broadcom 440x/47xx ethernet support

Wireless: (Iwlwifi, Gentoo Wireless):
The wireless drivers are loaded as modules because they need to access the file system (/lib/firmware) which is loaded AFTER the kernel loads.
General setup  --->
    [*] Prompt for development and/or incomplete code/drivers
[*] Networking support  --->
    -*-   Wireless  --->
        <*>   cfg80211 - wireless configuration API
        [*]     nl80211 testmode command
        [*]     enable powersave by default
        [*]     cfg80211 wireless extensions compatibility
        [*]   Wireless extensions sysfs files
        <*>   Common routines for IEEE802.11 drivers
        <*>   Generic IEEE 802.11 Networking Stack (mac80211)
        [*]   Enable LED triggers
Device Drivers  --->
    Generic Driver Options  --->
        -*- Userspace firmware loading support
    [*] Network device support  --->
        [*]   Wireless LAN  --->
            <M>   Intel Wireless Wifi
            [*]     Enable full debugging output in iwlagn and iwl3945 drivers
            <M>     Intel Wireless WiFi Next Gen AGN (iwlagn)
            [*]       Intel Wireless WiFi 4965AGN
            [*]       Intel Wireless-N/Advanced-N/Ultimate-N WiFi Link
            <M>     Intel PRO/Wireless 3945ABG/BG Network Connection (iwl3945)
-*- Cryptographic API  --->
    -*-   Cryptographic algorithm manager
    [*]   Disable run-time self tests
    -*-   Authenc support
    -*-   CBC support
    -*-   ECB support
    <*>   PCBC support
    -*-   HMAC support
    -*-   MD5 digest algorithm
    <*>   Michael MIC keyed digest algorithm
    -*-   SHA1 digest algorithm
    <*>   SHA224 and SHA256 digest algorithm
    -*-   AES cipher algorithms
    <*>   AES cipher algorithms (i586)
    -*-   ARC4 cipher algorithm
    -*-   DES and Triple DES EDE cipher algorithms

SD Card:
Device Drivers  --->
    <*> MMC/SD/SDIO card support  --->
        <*>   MMC block device driver
        [*]     Use bounce buffer for simple hosts
        <*>   Secure Digital Host Controller Interface support
        <*>   SDHCI support on PCI bus
        <*>   SDHCI support on the platform specific bus

You’ll notice that in the wireless section some of the drivers have been compiled as modules so they need to be registered to load on start up. I have added them to my /etc/modules.autoload.d/kernel-2.6 file, they are the only modules in there.

# /etc/modules.autoload.d/kernel-2.6:  kernel modules to load when system boots.
#
# Note that this file is for 2.6 kernels.
#
# Add the names of modules that you'd like to load when the system
# starts into this file, one per line.  Comments begin with # and
# are ignored.  Read man modules.autoload for additional details.

# For example:
# aic7xxx

iwlcore
iwlagn
iwl3945

Also for the sound to work the alsa needs to be configured. So first install alsa.
#> emerge -av alsa-utils

Once alsa has finished installing start it up.

#> /etc/init.d/alsasound start

Next unmute the volume so that it is possible to actually hear something. Do this by starting alsamixer then highlighting the Master and PCM channels and pressing the ‘m’ key to make sure they have 00 instead of MM at the bottom.

#> alsamixer

Lastly set alsa to start at boot.

#> rc-update add alsasound boot

8. Configuring your System

I set up fstab in the a exact same way as the handbook, but the networking I had to do a little differently.

Firstly to get the wireless working I had to install an extra package called iwl3945-ucode which is used by the drivers.

#> emerge -av iwl3945-ucode

Also a symlink needs to be created in the /etc/init.d/ directory for the wireless network.

#> cd /etc/init.d/
#> ln -s net.lo net.wlan0

Now the Gentoo handbook says to register the net.eth0 interface to start at boot, don’t do this because it will be started anyway. One thing that can be done is to tell Gentoo which interface to start net.eth0 or net.wlan0, this is done within the /etc/conf.d/rc script in the RC_PLUG_SERVICES variable.

Below is the RC_PLUG_SERVICES setting that I used to only start the wlan0 interface.

RC_PLUG_SERVICES="net.lo net.wlan0 !net.eth*"

Next the wired and wireless network need to be setup so they start correctly, I have configured them both with static IP’s, this is so that later I will be able to control XBMC with the Android remote.

/etc/conf.d/net:
# This blank configuration will automatically use DHCP for any net.*
# scripts in /etc/init.d.  To create a more complete configuration,
# please review /etc/conf.d/net.example and save your configuration
# in /etc/conf.d/net (this file :]!).

config_eth0=( "192.168.1.32 netmask 255.255.255.0 brd 192.168.1.255" )
routes_eth0=( "default via 192.168.1.254" )

# Prefer wpa_supplicant over wireless-tools
modules=( "wpa_supplicant" )

# It's important that we tell wpa_supplicant which driver we should
# be using as it's not very good at guessing yet
wpa_supplicant_wlan0="-Dwext"

config_wlan0=( "192.168.1.42 netmask 255.255.255.0 brd 192.168.1.255" )
routes_wlan0=( "default via 192.168.1.254" )

My wpa_supplicant configuration is very simple.

/etc/wpa_supplicant/wpa_supplicant.conf:
# The below line not be changed otherwise we refuse to work
ctrl_interface=/var/run/wpa_supplicant

# Ensure that only root can read the WPA configuration
ctrl_interface_group=0

# Let wpa_supplicant take care of scanning and AP selection
ap_scan=1

# Simple case: WPA-PSK, PSK as an ASCII passphrase, allow all valid ciphers
network={
    ssid="MyWireless"
    psk="password"
    # The higher the priority the sooner we are matched
    priority=5
}

# Same as previous, but request SSID-specific scanning (for APs that reject
# broadcast SSID)
network={
    ssid="MyWireless"
    scan_ssid=1
    psk="password"
    priority=2
}

The last extra piece of configuration that I carried out is to do with the key mapping, I created mappings for the buttons on the front of the laptop that are meant to be used to control the DVD drive. I have mapped these keys to the keyboard letters that correspond to the volume and play controls of XBMC.

Custom key mappings need to be placed in a file under the /usr/share/keymaps/include/ directory and can have any name as long as they have the “.map” extension.

The file I created was called facebuttons.map and had the following content.
/usr/share/keymaps/include/facebuttons.map:
keycode 113 = 0x0030
keycode 114 = 0x002d
keycode 115 = 0x002b
keycode 164 = 0x0020
keycode 165 = 0x0072
keycode 163 = 0x0066
keycode 166 = 0x0078

This creates the following mapping:
Mute Button -> 0
Volume Down Button -> –
Volume Up Button -> +
Play Button -> Space
Track Back Button -> r
Track Forward Button -> f
Stop Button -> x

To find the values of the face buttons use the showkey program, just run it and start pressing the face buttons you should get output like this:
#> showkey
...
keycode 113 press    <-- When I Pressed Mute
keycode 113 release
keycode 114 press    <-- When I Pressed Volume Down
keycode 114 release
keycode 115 press    <-- When I Pressed Volume Up
keycode 115 release
keycode 164 press    <-- When I Pressed Play
keycode 164 release

Now to find the “keysym” (the last value in the key mapping) for the keys that you want the buttons to represent run the dumpkeys -l command and grep the keys you want.
#> dumpkeys -l | grep zero
0x0030    zero
0x0830    Meta_zero
#> dumpkeys -l | grep plus
0x002b    plus
0x00b1    plusminus
0x082b    Meta_plus
#> dumpkeys -l | grep minus
0x002d    minus
0x00b1    plusminus
0x082d    Meta_minus
#> dumpkeys -l | grep space
0x0020    space
0x00a0    nobreakspace
0x0820    Meta_space
no-break_space  for nobreakspace
#> dumpkeys -l | grep "r$"
0x0012    Control_r
0x0024    dollar
0x0034    four
0x003e    greater
0x0072    r
0x007c    bar
0x00a6    brokenbar
0x00b2    twosuperior
0x00b3    threesuperior
0x00b9    onesuperior
0x00bc    onequarter
0x0118    Prior
0x030e    KP_Enter
0x0701    AltGr
0x0812    Meta_Control_r
0x0824    Meta_dollar
0x0834    Meta_four
0x083e    Meta_greater
0x0872    Meta_r
0x087c    Meta_bar
0x0c01    SAltGr
PageUp          for Prior
AltR            for AltGr
Alt_R           for AltGr
AltGr_R         for AltGr
#> dumpkeys -l | grep "f$"
    0x0000 - 0x00ff
    0x0100 - 0x01ff
    0x0500 - 0x05ff
    0x0800 - 0x08ff
    0x0b00 - 0x0bff
    0x0d00 - 0x0dff
0x0006    Control_f
0x0066    f
0x00bd    onehalf
0x0806    Meta_Control_f
0x0866    Meta_f
#> dumpkeys -l | grep "x$"
0x0018    Control_x
0x0036    six
0x0078    x
0x00c2    Acircumflex
0x00ca    Ecircumflex
0x00ce    Icircumflex
0x00d4    Ocircumflex
0x00db    Ucircumflex
0x00e2    acircumflex
0x00ea    ecircumflex
0x00ee    icircumflex
0x00f4    ocircumflex
0x00fb    ucircumflex
0x0402    dead_circumflex
0x0818    Meta_Control_x
0x0836    Meta_six
0x0878    Meta_x
dead_caron      for dead_circumflex

Now that the mappings have been setup we need to tell Gentoo to use them, this is done by putting the name of our mappings file minus the extension into the EXTENDED_KEYMAPS variable of the /etc/conf.d/keymaps file.

# /etc/conf.d/keymaps

# Use KEYMAP to specify the default console keymap.  There is a complete tree
# of keymaps in /usr/share/keymaps to choose from.

KEYMAP="us"

# Should we first load the 'windowkeys' console keymap?  Most x86 users will
# say "yes" here.  Note that non-x86 users should leave it as "no".

SET_WINDOWKEYS="no"

# The maps to load for extended keyboards.  Most users will leave this as is.

EXTENDED_KEYMAPS="facebuttons"

# Tell dumpkeys(1) to interpret character action codes to be 
# from the specified character set.
# This only matters if you set UNICODE="yes" in /etc/rc.conf.
# For a list of valid sets, run `dumpkeys --help`

DUMPKEYS_CHARSET=""

That is the end of the extra configuration for this section.

10. Configuring the Bootloader

I installed GRUB and used the following kernel line so that the console runs in a nice frame buffer.

kernel /boot/kernel-2.6.36-gentoo-r8 root=/dev/sda3 video=uvesafb:mtrr:3,ywrap,1280x800-32@60

11. Finalizing your Gentoo Installation

The very last peace of Gentoo specific configuration I did was to create an xbmc user. I made sure the user had video, audio, usb, and dvd privileges.

#> useradd -d /home/xbmc -m -G audio,cdrom,video,cdrw,usb,users xbmc

Now reboot the laptop and hopefully everything works, if it does now would be a good time to run a global update.

#> emerge --update --deep world

Once this has completed there is a good chance that Python will have been updated to version 3. XBMC and it’s dependencies do not like this version of Python so will fail to compile or run. To fix this use eselect to set Python back to version 2.6.

#> eselect python list
Available Python interpreters:
  [1]   python2.6
  [2]   python3.1 *

#> eselect python set 1
#> eselect python list
Available Python interpreters:
  [1]   python2.6 *
  [2]   python3.1

Articles

Maven – Debug Test

In Debug, Maven, Test on 17/03/2011 by pier0w

So if you happen to program in Intellij IDEA like my self you may have come across a situation where your tests pass within your IDE but fail when running mvn clean install. Generally this is because you did something silly in one of your tests that is now infecting all the following tests.

Now it’s all well and good knowing you’ve done something wrong, but it’s not so helpful if you don’t actually know WHAT that something is. So now you’ll be thinking “I KNOW! I’ll run mvn clean install within Intellij IDEA in debug mode then step through them there tests. I SO SMART!”. Then with your maven build profile all configured within Intellij and your break points all precisely set you click on run debug and… the tests run to the end without a pause in site.

Now is when you’re wondering what the duce just happened. Well it turns out that maven runs it’s test in forked processes, this means that you may be happily debugging the maven process but you have absolutely no connection to the forked processes that are running the tests. So what to do?

The first, easiest and maybe even best thing to do is add the -DforkMode=never parameter to your mvn clean install command to become…

mvn clean install -DforkMode=never

Who’d of thought?

In regards to your profile, put it in the Goals text field.

This will stop maven forking the tests so they will stay within the maven process you are actually debugging. So problem solved.

Though, what if you want to debug some tests that are running on another server? Well that is actually very simple as well. Simple kick the tests off with the -Dmaven.surefire.debug parameter included within your command. The maven tests will now pause at the beginning and expose a debug socket on port 5005 where you can then connect your favourite IDE to carry out the debugging. This works weather the tests are forked or not.

mvn clean install -Dmaven.surefire.debug

And that’s it, now you know how to debug your maven tests no matter where they are.

Articles

Hibernate Tutorial

In Hibernate on 23/02/2011 by pier0w

What is Hibernate? Hibernate is an Object-relational Mapper or ORM. What this means is that hibernate will map database tables into Java objects.

So for example if we have the table “user” in our ASCIISQL database like so:

 --------------------------------------------
| id | first_name | last_name | age | gender |
| 1  | Some       | One       | 25  | MALE   |
 --------------------------------------------

Then hibernate could automatically map the values from that table into the following class:

package org.project.hibernate.domain.enums;

public enum GENDER {
    FEMALE,
    MALE
}

package org.project.hibernate.domain;

import org.project.hibernate.domain.enums.GENDER;

public class User {

    private Long id;
    private String firstName;
    private String lastName;
    private Long age;
    private GENDER gender;

    public User() {
    }

    public User(String firstName, String lastName, Long age, GENDER gender) {
        this.firstName = firstName;
        this.lastName = lastName;
        this.age = age;
        this.gender = gender;
    }

    public User(Long id, String firstName, String lastName, Long age, GENDER gender) {
        this.id = id;
        this.firstName = firstName;
        this.lastName = lastName;
        this.age = age;
        this.gender = gender;
    }

    public Long getId() {
        return id;
    }

    public void setId(Long id) {
        this.id = id;
    }

    public String getFirstName() {
        return firstName;
    }

    public void setFirstName(String firstName) {
        this.firstName = firstName;
    }

    public String getLastName() {
        return lastName;
    }

    public void setLastName(String lastName) {
        this.lastName = lastName;
    }

    public Long getAge() {
        return age;
    }

    public void setAge(Long age) {
        this.age = age;
    }

    public GENDER getGender() {
        return gender;
    }

    public void setGender(GENDER gender) {
        this.gender = gender;
    }
}

This means that you can now try to ignore that fact that all your data is kept in a relational database. I mean TRY, because in reality that is something you will never succeed at.

But hibernate is still very helpful when it is working correctly.

So lets begin our first very simple hibernate project. So the first thing to do is create a project and then get git to track your changes.

Project naming suggestions:
groupId: org.project.hibernate
artifactId: hibernate
version: 1.0
package: hibernate

Once that is complete open the project in Intelij IDEA and create a package called “domain” under the “hibernate” package. This is where we will put any of the Java objects that are going to be mapped to their equivalent tables, these will be Domain Objects. Domain Objects are there to provide a representation of our applications data that is not tied to the way the data is stored. So basically if all the data just ends up in domain objects it can easily be used within logic code without the need to care how it got there. For this tutorial Hibernate is going to be what got it there.

Now in the domain directory create the User class that was mentioned above along with the GENDER enum. We now have a user domain object.

Next create a Hibernate class in the hibernate package and give it a main method. Also create a JUnit 4 unit test class for the Hibernate class. You may have to update the version of the JUnit dependency in your pom file. Lastly delete the App class and it’s test class.

Now that we have the beginning of our project lets add the hibernate dependencies.

...
    <dependencies>
        <dependency>
            <groupId>junit</groupId>
            <artifactId>junit</artifactId>
            <version>4.7</version>
            <scope>test</scope>
        </dependency>

        <!--Hibernate and it's annotation dependencies.-->
        <dependency>
            <groupId>org.hibernate</groupId>
            <artifactId>hibernate</artifactId>
            <version>3.2.7.ga</version>
        </dependency>
        <dependency>
            <groupId>org.hibernate</groupId>
            <artifactId>ejb3-persistence</artifactId>
            <version>1.0.2.GA</version>
        </dependency>
        <dependency>
            <groupId>org.hibernate</groupId>
            <artifactId>hibernate-annotations</artifactId>
            <version>3.4.0.GA</version>
            <exclusions>
                <exclusion> <!-- Exclude included slf4j-api dependency to allow chosen version -->
                    <groupId>org.slf4j</groupId>
                    <artifactId>slf4j-api</artifactId>
                </exclusion>
            </exclusions>
        </dependency>
        <dependency>
            <groupId>javax.transaction</groupId>
            <artifactId>jta</artifactId>
            <version>1.1</version>
        </dependency>

        <!--Hibernates logging dependencies.-->
        <dependency>
            <groupId>org.slf4j</groupId>
            <artifactId>slf4j-log4j12</artifactId>
            <version>1.5.11</version>
        </dependency>
        <dependency>
            <groupId>org.slf4j</groupId>
            <artifactId>slf4j-api</artifactId>
            <version>1.5.11</version>
        </dependency>
        <dependency>
            <groupId>org.slf4j</groupId>
            <artifactId>slf4j-api</artifactId>
            <version>1.5.11</version>
        </dependency>

        <!--The embedded database that is going to be used.-->
        <dependency>
            <groupId>org.apache.derby</groupId>
            <artifactId>derby</artifactId>
            <version>10.4.2.0</version>
        </dependency>
    </dependencies>
...

Wow, that is a LOT of dependencies. You’ll notice that 3 of the dependencies are just logging api’s “slf4j“, hibernate seems to need you to include these dependencies your self. Don’t ask me why…

So now that we have all the dependencies we need lets configure hibernate so that we can start it up. How is that done? Well you create a hibernate configuration file of course. This is an XML file that tells hibernate where to find the database, how to log into the database, what type of SQL that database uses, where the domain classes are, what type of connection pooling should be used, if any, and loads of other stuff.

Create the resources directory and then a file within it called hibernate.cfg.xml and past the following into it.

<?xml version='1.0' encoding='utf-8'?>
<!DOCTYPE hibernate-configuration PUBLIC
        "-//Hibernate/Hibernate Configuration DTD 3.0//EN"
        "http://hibernate.sourceforge.net/hibernate-configuration-3.0.dtd">
<hibernate-configuration>
    <session-factory>
        <!-- Database connection settings -->
        <property name="connection.driver_class">org.apache.derby.jdbc.EmbeddedDriver</property>
        <property name="connection.url">jdbc:derby:derbydb;create=true</property>
        <!-- JDBC connection pool (use the built-in) -->
        <property name="connection.pool_size">1</property>
        <!-- SQL dialect -->
        <property name="dialect">org.hibernate.dialect.DerbyDialect</property>
        <!-- Enable Hibernate's automatic session context management -->
        <property name="current_session_context_class">thread</property>
        <!-- Disable the second-level cache -->
        <property name="cache.provider_class">org.hibernate.cache.NoCacheProvider</property>
        <!-- Echo all executed SQL to stdout -->
        <property name="show_sql">true</property>
        <!-- Drop and re-create the database schema on startup -->
        <property name="hbm2ddl.auto">update</property>
        <!-- Boolean substitution -->
        <property name="query.substitutions">true 'T', false 'F'</property>

    </session-factory>
</hibernate-configuration>

This configuration will set up the database, but we are yet to configure any table mapping. Also it should be noted that this configuration will create the database by inferring it’s structure from the domain objects that we ask it to map. Since we haven’t asked it to map anything it won’t actually create a database at this stage.

Now lets start hibernate for the first time. To do this we use the hibernate configuration we just carried out to create a hibernate session factory. The session factory provides access to an instances of a hibernate session, the session is then used to carry out any request or updates to the database using the domain objects.

All of this must be done inside of a hibernate transaction, when in a transaction and before a transaction is started the session returned by the session factory will always be the same, but once a transaction has finished the session factory will return a brand new session.

So with that all as clear as mud lets start up hibernate and see if we can’t request our first session.

package org.project.hibernate;

import org.hibernate.SessionFactory;
import org.hibernate.cfg.Configuration;
import org.hibernate.Session;

public class Hibernate {

    private static final SessionFactory SESSION_FACTORY;

    static {
        // Create a session factory with the config file.
        SESSION_FACTORY = new Configuration().configure().buildSessionFactory();
    }

    public static void main(String[] args) {
        Session session = SESSION_FACTORY.getCurrentSession(); // Request for the current hibernate session.

        // YAY! we found a session or BOO! we didn't.
        System.out.println(session != null ? "YAY!" : "BOO!");
    }
}

Ok now that we know hibernate can be started lets map the User file with a hibernate mapping file. We could also map the file using annotations especially since we have the hibernate annotations dependency in our pom file. But I personally think that using mapping files is a better option for two reasons. First, mapping files provide a few features that have yet to be implemented for the annotations and secondly if you use annotations at some point you will find you need to use a custom hibernate annotation. This means you will have hibernate code within your code, so you will have some tight coupling to the hibernate framework which means if you ever want to use your domain classes somewhere else you will have to also bring in the hibernate dependencies which may not be necessary for the other project. Either that or you will have to create a second lot of identical code that just doesn’t contain the hibernate annotations. This of course is terribly bad for the maintainability of your code.

So here is the User mapping file. Create a directory called mapping within your resources directory then create a file called User.hbm.xml with that directory and past the following XML into it. We only create the mapping directory to keep the config files separate and tidy not for any strict reason.

<?xml version="1.0"?>
<!DOCTYPE hibernate-mapping PUBLIC
        "-//Hibernate/Hibernate Mapping DTD 3.0//EN"
        "http://hibernate.sourceforge.net/hibernate-mapping-3.0.dtd">

<hibernate-mapping package="org.project.hibernate.domain">

    <!-- Map the User class to the user_table table. It is called user_table -->
    <!-- because the word "user" is a key word in the Derby database. -->
    <class name="User" table="user_table">

        <id name="id">
            <!-- Map the id property for the User class and tell hibernate to -->
            <!-- automatically populate it with what ever method best -->
            <!-- suits the current database. -->
            <generator class="native"/>
        </id>

        <!-- Map the firstName property to the first_name column. -->
        <property name="firstName" column="first_name" not-null="true"/>

        <!-- Map the lastName property to the last_name column. -->
        <property name="lastName" column="last_name" not-null="true"/>

        <!-- Map the age property to the age column. If you don't ->
        <!-- give a column name hibernate will assume the column name -->
        <!-- matches the property name. -->
        <property name="age" not-null="true"/>

        <!-- Map the gender property to the gender column -->
        <property name="gender" not-null="true">
            <!-- Tell hibernate that this property is an enum and what type of enum it is. -->
            <type name="org.hibernate.type.EnumType">
                <param name="enumClass">org.project.hibernate.domain.enums.GENDER</param>
            </type>
        </property>

    </class>

</hibernate-mapping>

We now need to tell hibernate about this mapping file by adding a mapping reference to the hibernate config file.

<?xml version='1.0' encoding='utf-8'?>
<!DOCTYPE hibernate-configuration PUBLIC
        "-//Hibernate/Hibernate Configuration DTD 3.0//EN"
        "http://hibernate.sourceforge.net/hibernate-configuration-3.0.dtd">
<hibernate-configuration>
    <session-factory>
        <!-- Database connection settings -->
        <property name="connection.driver_class">org.apache.derby.jdbc.EmbeddedDriver</property>
        <property name="connection.url">jdbc:derby:derbydb;create=true</property>
        <!-- JDBC connection pool (use the built-in) -->
        <property name="connection.pool_size">1</property>
        <!-- SQL dialect -->
        <property name="dialect">org.hibernate.dialect.DerbyDialect</property>
        <!-- Enable Hibernate's automatic session context management -->
        <property name="current_session_context_class">thread</property>
        <!-- Disable the second-level cache -->
        <property name="cache.provider_class">org.hibernate.cache.NoCacheProvider</property>
        <!-- Echo all executed SQL to stdout -->
        <property name="show_sql">true</property>
        <!-- Drop and re-create the database schema on startup -->
        <property name="hbm2ddl.auto">update</property>
        <!-- Boolean substitution -->
        <property name="query.substitutions">true 'T', false 'F'</property>

        <!-- Reference to the User mapping file -->
        <mapping resource="mapping/User.hbm.xml" />

    </session-factory>
</hibernate-configuration>

So now that hibernate knows how to map the User class we will be able to add and retrieve users from the database. Also because we have the hbm2ddl.auto property set to update hibernate will create the user_table table from the mapping information we have provided.

So since we can now do stuff with the database lets go and well… do stuff.

package org.project.hibernate;

import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.Transaction;
import org.hibernate.cfg.Configuration;
import org.project.hibernate.domain.User;

import java.util.List;

import static org.project.hibernate.domain.enums.GENDER.MALE;

public class Hibernate {

    private static final SessionFactory SESSION_FACTORY;

    static {
        // Create a session factory with the config file.
        SESSION_FACTORY = new Configuration().configure().buildSessionFactory();
    }

    public static void main(String[] args) {
        Session session = SESSION_FACTORY.getCurrentSession(); // Request for the current hibernate session.

        if (session != null) {
            // YAY! we found a session.
            System.out.println("YAY!");

            // First when using Hibernate to access a database you must create a transaction.
            // When ever you work inside a transaction there is less chance you will corrupt
            // the data within your database. This is because any changes you make will not
            // be committed until the transaction completes. So if something breaks while in
            // the transaction any changes you made to the database will be rolled back.
            Transaction transaction = session.beginTransaction();

            // Now we create a new user to place within the database. Notice we are using
            // the constructor that does not set the "id" property. This is because in the
            // mapping file we told hibernate to set the "id" property for us.
            User user = new User("Some", "One", 25L, MALE);

            // Now save the new user to the database.
            session.save(user);

            // Complete/commit the transaction so the changes get saved to the database.
            // This will also close the session.
            transaction.commit();

            // Display the id of the user we just save to show that hibernate 
            // did in fact generate the id for us.
            System.out.println("User saved. ID set to (" + user.getId() + ")");
            System.out.println();

            // Now lets display the users in the database so that we can see the users that
            // accumulate within the database after each time we run this project.
            System.out.println("Users in the database:");

            // To access the database again we need to get a new session since we closed the last one.
            session = SESSION_FACTORY.getCurrentSession();
            // Also we will need to start a new transaction.
            transaction = session.beginTransaction();

            // Now we will request all the users from the database by using hibernates criteria API.
            // This provides a nice way of building up SQL queries problematically.
            // Notice we have to cast the list that is returned by hibernate into a list of Users. I really
            // do not see why this is required since we have told hibernate the class type that we are
            // looking for and the List that hibernate returns is actual contains Users.
            List users = (List) session.createCriteria(User.class).list();

            // We can now commit the transaction since we have all the data we want. Though if we
            // wanted to make changes to the users in the list we retrieved and then save those
            // changes to the database we would not be able to close the transaction here.
            transaction.commit();

            // Now we iterate through the users and display their values.
            for (User u : users) {
                System.out.println("User");
                System.out.println(" - id: " + u.getId());
                System.out.println(" - First Name: " + u.getFirstName());
                System.out.println(" - Last Name: " + u.getLastName());
                System.out.println(" - Age: " + u.getAge());
                System.out.println(" - Gender: " + u.getGender());
                System.out.println();
            }

        } else {
            // BOO! we didn't find a session.
            System.out.println("BOO!");
        }
    }
}

Well that’s it we have created a working hibernate application. If you run this application over and over again it will keep adding users to the database. You can clear the database by just deleting the derby directory that is created under the root directory of your project .

Articles

Spring Tutorial Two (Spring MCV)

In Tutorial on 13/02/2011 by pier0w

This next Spring tutorial is going to look at Spring MVC. This is Springs implementation of the Model View Controller architecture, with it you can configure your Model layer, configure the View template you wish to use, and create very simple and concise Controllers.

Now just like all Java web application frameworks Spring MVC must be wrapped up within a WAR file and run from within a Java web container. A web container can just be thought of as an environment that provides all the required boilerplate to allow the easy creation of web applications. It will automatically handle the creation of a thread pool to handle any requests, create sessions so that you can keep state across a users time on your web app, and lots of other great stuff.

There are quite a lot of Java web containers out there, there is Tomcat, Jetty, Glassfish, and JBoss just to name a few.

The one we are going to use is Jetty, this is a Java web app container that can be embedded within an application. It is not the only one of course, Tomcat can also be embedded, but Jetty was specifically created for this purpose.

This tutorial is going to build on the previous Spring tutorial, so open that within Intellij IDEA.

Since we are working with the project from the first tutorial lets make a tag to preserve the code in it’s current state. To do this navigate to the projects directory and type the following command.

#> git tag -a tutorial_one -m "A tag taken at the end of the first Spring tutorial."

You can check to make sure that tag was created with this command.

#> git tag -l -n1

The -l tells git to list the tags and the -n1 tells git to display one line of the tags message. You can use a higher number to display more lines.

The first thing we will do is add the Jetty maven dependency to our pom file, so open the file and add the dependency to the <dependencies> tag.

...
    <dependencies>
        <dependency>
            <groupId>junit</groupId>
            <artifactId>junit</artifactId>
            <version>4.7</version>
            <scope>test</scope>
        </dependency>
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-context</artifactId>
            <version>3.0.3.RELEASE</version>
        </dependency>
        <dependency>
            <groupId>org.eclipse.jetty.aggregate</groupId>
            <artifactId>jetty-webapp</artifactId>
            <version>7.1.4.v20100610</version>
        </dependency>
    </dependencies>
...

Now lets remove pretty much all of the code we wrote in the first tutorial because it won’t be of any use to us in this new tutorial. Delete the context file in the resources directory, the MyClassOne, MyClassTwo, and MyHolder classes, all the code from within the MainTest leaving the shell of the test method, the toStuff method from within the Main class as well as all the code within the main method. Once that is done commit the changes into git.

package org.project;

public class Main {

    public static void main(String[] args) {
    }
}
package org.project;

import org.junit.Test;

public class MainTest {

    @Test
    public void testDoStuff() throws Exception {
    }
}

If you wish to get the old code back you can just checkout the tag.

#> git checkout tutorial_one

Note that when you commit changes to the tag they will not actually be saved if you then move off the tag. To save your changes you will have to create a branch from the tag with the git branch method.

If you wish to then get back to the code we just committed then us this command.

#> git checkout master

Now that we are back looking at our new code lets see if we can’t start up a Jetty server in preparation for our Spring code. First create an instance of a Jetty Server class, start the server, then join the server to the main thread so that the main thread doesn’t just exit right after starting the server.

package org.project;

import org.eclipse.jetty.server.Server;

public class Main {

    public static void main(String[] args) throws Exception {
        Server server = new Server(8080); // Create a server instance that listens on port 8080.
        server.start(); // Start the server.
        server.join(); // Join the main thread to the server so that the main thread doesn't exit.
    }
}

Pro tip: Only copy the code from within the main method and past it into yours. Then use ALT-ENTER to get Intellij IDEA to import the jetty Server class for you. The start and join method calls will now be underlined in red so click within the code of one of them and in a moment a small red light build should show up off to the left. Click on it and select the Add Exception(s) to Method Signature option. This will make the main method throw the correct exception for the methods.

You can now run the main method and see the server start up. Though it is a rather useless application server because there is nothing running within it.

To get Jetty to run something he have to give it a Handler. It is possible to either create your own handler or use one of the pre-made handlers that Jetty provides. Since we are making a web application that will be running Spring MVC we will be using Jetty’s WebAppContext handler. To instantiate this handler you need to give it the path to where your web application configuration files will be and also the context of your web application. A context is simply some text that comes after the domain name of the web app where all of the web apps pages will fall under. So if a web app is found at the following URL.

http://localhost:8080/myapp/index.html

Then the context would be myapp and all the wep apps pages like index.html will be found under that context.

So lets instantiate a WebAppContext handler and give it the path webapp and the context / which means there actually will not be a context.

To get the proper path to the webapp directory we will need to get the resource URL and then get the external form from that. This is because we are running within the environment of a JAR file, so it is unfortunately not as simple as giving it the name of the directory.

We will also need to tell Jetty not to extract the web apps directory, this is again because we running the project from within a JAR environment.

package org.project;

import org.eclipse.jetty.server.Server;
import org.eclipse.jetty.webapp.WebAppContext;

import java.net.URL;

public class Main {

    public static void main(String[] args) throws Exception {
        Server server = new Server(8080); // Create a server instance that listens on port 8080.

        URL webAppURL = server.getClass().getClassLoader().getResource("webapp"); // Find the webapp dir from within the JAR.

        String webAppPath = webAppURL.toExternalForm(); // Then get it's actual path string.

        WebAppContext webAppContext = new WebAppContext(webAppPath, "/"); // The config dir will be in resources/webapp.
        webAppContext.setExtractWAR(false); // Make sure not to extract the web app directory because we will run this in a JAR file.

        server.setHandler(webAppContext); // Add the WebAppContext handler to the Jetty server.

        server.start(); // Start the server.
        server.join(); // Join the main thread to the server so that the main thread doesn't exit.
    }
}

You can now try and run the Jetty server again but as you might expect it will crash, this is because we haven’t created the webapp directory under the resources directory. Also we haven’t created the web.xml file that is required by the WebAppContext handler.

Lets do both of those things now, first create the webapp directory under the resources directory, then create another directory under that called WEB-INF, lastly under that directory create an empty file called web.xml. In the end you should have a path to the web.xml file as follows.

src/main/resources/webapp/WEB-INF/web.xml

Now past the following into the web.xml file.

<web-app id="WebApp_9" version="2.5"
         xmlns="http://java.sun.com/xml/ns/javaee"
         xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="   http://java.sun.com/xml/ns/javaee
                                http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd">

    <display-name>Spring Tutorial Two</display-name>
</web-app>

Now run the main method again and Jetty should start up happily.

It is also a good idea to add a thread pool to Jetty, this will make it run a lot more efficiently and faster. We will start up a queued thread pool with a minimum of 10 threads and a maximum of 50 threads.

package org.project;

import org.eclipse.jetty.server.Server;
import org.eclipse.jetty.util.thread.QueuedThreadPool;
import org.eclipse.jetty.webapp.WebAppContext;

import java.net.URL;

public class Main {

    public static void main(String[] args) throws Exception {
        Server server = new Server(8080); // Create a server instance that listens on port 8080.

        URL webAppURL = server.getClass().getClassLoader().getResource("webapp"); // Find the webapp dir from within the JAR.

        String webAppPath = webAppURL.toExternalForm(); // Then get it's actual path string.

        WebAppContext webAppContext = new WebAppContext(webAppPath, "/"); // The config dir will be in resources/webapp.
        webAppContext.setExtractWAR(false); // Make sure not to extract the web app directory because we will run this in a JAR file.

        server.setHandler(webAppContext); // Add the WebAppContext handler to the Jetty server.

        QueuedThreadPool threadPool = new QueuedThreadPool(); // Instantiate the thread pool.
        threadPool.setMinThreads(10); // Set the minimum threads to 10.
        threadPool.setMaxThreads(50); // Set the maximum threads to 50.

        server.setThreadPool(threadPool); // Add the thread pool to the Jetty server.

        server.start(); // Start the server.
        server.join(); // Join the main thread to the server so that the main thread doesn't exit.
    }
}

Right, so now the programmatical configuration of the Jetty server is complete. All the rest of our configuration will be done within the web.xml file.

The web.xml is where we will configure our Spring context. Remember in the first tutorial we started the Spring context within the main method. This time by configuring the Spring context object within the web.xml file we will get the web app container to start it.

Now to return a successful response to an HTTP request a Java Web Application Container needs to contain a Servlet. Servlets are J2EE classes that contain all the logic to handle request for a given URL pattern. That is all you will ever need to know about them because no one ever manually programs Servlets any more and all we will be doing is configuring the Spring context so that it behaves like a Servlet.

So as always when starting a Spring project the first thing we need to do is create a XML context configuration file and place it in the resources directory.

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
       xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
       xsi:schemaLocation=" http://www.springframework.org/schema/beans
                            http://www.springframework.org/schema/beans/spring-beans-3.0.xsd">
</beans>

Now that we have the context file we need to configure the Spring context class. We will use is the Spring DispatcherServlet class which configures the Spring context and wraps it in a J2EE Servlet. We will need to add the Spring MVC dependency to the pom file so that we have access the DispatcherServlet class and all the other classes within the Spring MVC module.

    <dependencies>
        <dependency>
            <groupId>junit</groupId>
            <artifactId>junit</artifactId>
            <version>4.7</version>
            <scope>test</scope>
        </dependency>
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-context</artifactId>
            <version>3.0.5.RELEASE</version>
        </dependency>
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-webmvc</artifactId>
            <version>3.0.5.RELEASE</version>
        </dependency>
        <dependency>
            <groupId>org.eclipse.jetty.aggregate</groupId>
            <artifactId>jetty-webapp</artifactId>
            <version>7.1.4.v20100610</version>
        </dependency>
    </dependencies>

To correctly configure this class we need to give it a name, the full name of the DispatcherServlet class, the path to the context file, and lastly the order in which it should be started. For our project we will want it to be the very first thing the web container starts.

<web-app id="WebApp_9" version="2.5"
         xmlns="http://java.sun.com/xml/ns/javaee"
         xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="   http://java.sun.com/xml/ns/javaee
                                http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd">

    <display-name>Spring Tutorial Two</display-name>

    <servlet>
        <servlet-name>dispatcher</servlet-name>
        <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
        <init-param>
            <param-name>contextConfigLocation</param-name>
            <param-value>classpath:context.xml</param-value>
        </init-param>
        <load-on-startup>0</load-on-startup>
    </servlet>

    <servlet-mapping>
        <servlet-name>dispatcher</servlet-name>
        <url-pattern>/*</url-pattern>
    </servlet-mapping>

</web-app>

We can now run the main method again and we should see the Jetty server start as well as the Spring framework.

It is now possible to start actually writing some code for a very simple Spring MVC web app. The first place to start is the Model or the M in MVC. The model is the data layer of the application, we shall make our model exceptionally simple, it will just be a class that contains some data. So lets create a Model class.

package org.project.model;

import java.util.Date;
import java.util.List;

public class Model {

    private String name;
    private Date date;
    private List data;
    private String message;

    public Model() {
    }

    public Model(String name, Date date, List data, String message) {
        this.name = name;
        this.date = date;
        this.data = data;
        this.message = message;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public Date getDate() {
        return date;
    }

    public void setDate(Date date) {
        this.date = date;
    }

    public List getData() {
        return data;
    }

    public void setData(List data) {
        this.data = data;
    }

    public String getMessage() {
        return message;
    }

    public void setMessage(String message) {
        this.message = message;
    }
}

And now lets wire it up within the Spring context file.

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
       xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
       xsi:schemaLocation=" http://www.springframework.org/schema/beans
                            http://www.springframework.org/schema/beans/spring-beans-3.0.xsd">

    <bean id="model" class="org.project.model.Model">
        <property name="name" value="Model"/>
        <property name="date">
            <bean class="java.util.Date"/>
        </property>
        <property name="data">
            <list>
                <bean class="java.lang.Integer"><constructor-arg value="1"/></bean>
                <bean class="java.lang.Integer"><constructor-arg value="2"/></bean>
                <bean class="java.lang.Integer"><constructor-arg value="3"/></bean>
                <bean class="java.lang.Integer"><constructor-arg value="4"/></bean>
            </list>
        </property>
        <property name="message" value="Message from the model."/>
    </bean>
</beans>

Now that we have a model lets configure our view, the V in MVC. The view is the framework that we will use to present the data from our model to the user, this is generally done with HTML. We will use Freemarker as our view, so lets first add it’s dependency to our pom file.

    <dependencies>
        <dependency>
            <groupId>junit</groupId>
            <artifactId>junit</artifactId>
            <version>4.7</version>
            <scope>test</scope>
        </dependency>
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-context</artifactId>
            <version>3.0.5.RELEASE</version>
        </dependency>
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-webmvc</artifactId>
            <version>3.0.5.RELEASE</version>
        </dependency>
        <dependency>
            <groupId>org.eclipse.jetty.aggregate</groupId>
            <artifactId>jetty-webapp</artifactId>
            <version>7.1.4.v20100610</version>
        </dependency>
        <dependency>
            <groupId>org.freemarker</groupId>
            <artifactId>freemarker</artifactId>
            <version>2.3.16</version>
        </dependency>
    </dependencies>

Now that we have access to the Freemarker classes we can configure it in the Spring context file. There are two classes that need to be configured, the first is the FreeMarkerConfigurer class, here we set the path to the Freemarker files. The next class is the FreeMarkerViewResolver which is the class that will actually parse the Freemarker files. We will configure this so that it doesn’t cache the pages, so that it knows what files are our Freemarker files, enable the Spring extensions, and lastly set the Freemarker resolver to always be the first resolver that is picked by Spring when it tries to resolve a view.

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
       xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
       xsi:schemaLocation=" http://www.springframework.org/schema/beans
                            http://www.springframework.org/schema/beans/spring-beans-3.0.xsd">

    <bean id="model" class="org.project.model.Model">
        <property name="name" value="Model"/>
        <property name="date">
            <bean class="java.util.Date"/>
        </property>
        <property name="data">
            <list>
                <bean class="java.lang.Integer">
                    <constructor-arg value="1"/>
                </bean>
                <bean class="java.lang.Integer">
                    <constructor-arg value="2"/>
                </bean>
                <bean class="java.lang.Integer">
                    <constructor-arg value="3"/>
                </bean>
                <bean class="java.lang.Integer">
                    <constructor-arg value="4"/>
                </bean>
            </list>
        </property>
        <property name="message" value="Message from the model."/>
    </bean>

    <bean id="freemarkerConfig" class="org.springframework.web.servlet.view.freemarker.FreeMarkerConfigurer">
        <property name="templateLoaderPath" value="/WEB-INF/pages/"/>
    </bean>

    <bean id="freemarkerViewResolver" class="org.springframework.web.servlet.view.freemarker.FreeMarkerViewResolver">
        <property name="cache" value="false"/>
        <property name="prefix" value=""/>
        <property name="suffix" value=".ftl"/>
        <property name="exposeSpringMacroHelpers" value="true"/>
        <property name="order" value="0"/>
    </bean>

</beans>

Now that our view framework is configured we can create a simple view page. This page will display the name and message properties of the model class. This class will be passed to the view by the controller which we will write next. To created the page first create the pages directory under the WEB-INF directory. This is where we said the Freemarker files would be when we configured the FreeMarkerConfigurer above. Then create a file called view.ftl and passed the following HTML into it.

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"
        "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
    <title>Spring Tutorial Two</title>
</head>
<body>
    <h1>${model.name}</h1>
    <p>${model.message}</p>
</body>
</html>

The ${model.name} and ${model.message} within the page are the very small snippets of Freemarker that we are going to use in this tutorial. It is this syntax that is used to access a domain class and it’s properties. A domain class is a class that has been placed into the domain of a view by the controller. We will see how this is done soon.

Now that the view file is created we can move onto the controller, the C in MVC. A controller is a class to simply take data classes from the model and sends them into the view. This is usually done by the controller calling on a service layer that abstracts away any logic and decouples the Controllers and Views from the Model layer, but for simplicities sake we are just going to pass the Model class straight into the controller.

The annotations we are going to use are:
@Controller – This is used to annotate a class to mark it as a Spring Controller.
@RequestMapping – This is used to annotate a class or method to map them to a specific request URL pattern. When the annotation is used on a class it is usually used to map a common context that all the methods in that class will then fall under. Though it is also possible to map a class to a URL pattern then just have a method that handles all the GET request for that class. Other wise methods can have their own unique request URL patterns mapped to them.
@Resource – This annotation is another way of telling Spring to inject a class, the difference between this and @Autowired is that with this annotation you can specify the name of the bean you would like to inject.

So after those explanations here is the controller.

package org.project.controllers;

import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.RequestMapping;
import org.project.model.Model;

import javax.annotation.Resource;

@Controller
@RequestMapping(value = "/model")
public class ModelController {

    @Resource(name = "model")
    private Model model;

    @RequestMapping(value = "/view")
    public String view(ModelMap modelMap) {

        modelMap.addAttribute("model", model);

        return "view";
    }
}

For this controller we have used the combination of providing a request mapping for the class and the method. This means that Spring with route all request that begin with /model to the ModelController class, then it will finally route the complete pattern /model/view to the view method within that class.

We have given the method a ModelMap argument. Any ModelMap argument that you give to a request method will automatically be injected by Spring with the responses ModelMap. The ModelMap is a map that is forwarded by Spring to the view. So any classes you place into this map will become domain classes in the view. That is why we are placing the Model object into this map. It can get a bit confusing that the word Model is used by Spring to label classes that will be passed to the view, since this is also the name for the data layer of an application that uses the MVC pattern. This is also Spring MVC we are talking about so you would have thought they might have seen how that could be confusing, but oh well…

The last thing to explain about this controller is that the request method is returning a static String "view". If Spring sees that your request method returns a String it will assume that that String will be that name of a view file that it should use to render the response. It is possible to have your request methods return far more complicated things but that is outside the scope of this tutorial. So with that in mind you can see that Spring will select out view.ftl file to render the response.

Now the very last thing we have to do is to tell Spring were our controller is. This is done in the same way that we told it how to find the HyHolder class at the end of the last tutorial.

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
       xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
       xmlns:context="http://www.springframework.org/schema/context"
       xsi:schemaLocation=" http://www.springframework.org/schema/beans
                            http://www.springframework.org/schema/beans/spring-beans-3.0.xsd
                            http://www.springframework.org/schema/context
                            http://www.springframework.org/schema/context/spring-context-3.0.xsd">

    <bean id="model" class="org.project.model.Model">
        <property name="name" value="Model"/>
        <property name="date">
            <bean class="java.util.Date"/>
        </property>
        <property name="data">
            <list>
                <bean class="java.lang.Integer">
                    <constructor-arg value="1"/>
                </bean>
                <bean class="java.lang.Integer">
                    <constructor-arg value="2"/>
                </bean>
                <bean class="java.lang.Integer">
                    <constructor-arg value="3"/>
                </bean>
                <bean class="java.lang.Integer">
                    <constructor-arg value="4"/>
                </bean>
            </list>
        </property>
        <property name="message" value="Message from the model."/>
    </bean>

    <bean id="freemarkerConfig" class="org.springframework.web.servlet.view.freemarker.FreeMarkerConfigurer">
        <property name="templateLoaderPath" value="/WEB-INF/pages/"/>
    </bean>

    <bean id="freemarkerViewResolver" class="org.springframework.web.servlet.view.freemarker.FreeMarkerViewResolver">
        <property name="cache" value="false"/>
        <property name="prefix" value=""/>
        <property name="suffix" value=".ftl"/>
        <property name="exposeSpringMacroHelpers" value="true"/>
        <property name="order" value="0"/>
    </bean>

    <context:component-scan base-package="org.project.controllers"/>
</beans>

With that complete we can finally run our web application and the simple view we created should be able to be seen at the following URL displaying the data that we configured in the model.

http://localhost:8080/model/view

Articles

Spring Tutorial One

In Uncategorized on 12/02/2011 by pier0w

Right so… what is Spring? Well the Spring About page has a good description of what it does but not how it does it or how you can does stuff with it. My self, I see Spring as a container that initialises and sticks all your classes together. This is handy because it means you don’t have to bother writing factory classes or singletons because Spring will start up a single instance of each class then propagate those single instances throughout any classes that require them. So you could almost think of Spring as duct tape for Java.

Springs main goal is to provide a paradigm called Inversion of Control or IoC. The wikipedia explanation is ok but it doesn’t really give you any idea about how this relates to Spring. Springs version of IoC can be easily summed up with the term Dependency Injection. Now coming from a unix background and being quite used to the dependency resolution of package managers, when I first heard that term I instantly thought Spring must be dynamically pulling down all the dependant libraries you have used and injecting them into your class path and maybe even dynamically adding the imports at compile time. This is of course not the case at all, but oddly is pretty much exactly what Maven does except for adding the imports, that’s what your IDE is for. Springs dependency injection refers to the dynamic injection of a classes properties during the start up of an application.

So say we have the following classes:

public class MyClassOne {

        private Integer one;

        public MyClassOne () {
        }

        public MyClassOne (Integer one) {
                this.one = one;
        }

        public Integer getOne() {
                return one;
        }

        public void setOne(Integer one) {
                this.one = one;
        }
}
public class MyClassTwo {

        private Integer two;

        public MyClassTwo () {
        }

        public MyClassTwo (Integer two) {
                this.two = two;
        }

        public Integer getTwo() {
                return two;
        }

        public void setTwo(Integer two) {
                this.two = two;
        }
}
public class MyHolder {

        private MyClassOne one;
        private MyClassTwo two;

        public MyHolder() {
        }

        public MyHolder(MyClassOne one, MyClassTwo two) {
                this.one = one;
                this.two = two;
        }

        public MyClassOne getMyClassOne() {
                return one;
        }

        public void setMyClassOne(MyClassOne one) {
                this.one = one;
        }

        public MyClassTwo getMyClassTwo() {
                return two;
        }

        public void setMyClassTwo(MyClassTwo two) {
                this.two = two;
        }

}

It is then possible to configure Spring to instantiate these and populate these three classes.

For my example I have only used concrete classes, it should also be noted that it is of course possible for Spring to inject a property with any object that can be cast into the properties type. So a property could just have the type of an interface which is great because your code then becomes a lot more generic since you don’t ever have to care about the implementation of your properties, you can let Spring decide on the best implementation for you.

Spring can do the injection in three different ways. First it can be told to instantiate the MyHolder class using the constructor that contains the arguments one and two and place the new MyClassOne and MyClassTwo instances in the correct slots. If this method is used the MyHolder class would not require a default constructor.
Secondly Spring could instantiate an empty MyHolder class then use the setter and getter methods to populate the one and two properties.
Lastly through the use of annotations Spring could then use reflection to directly access and set the values for the one and two properties.

If the last method is used it is actually possible to create classes that look like they would be impossible to use. For example it would be quite valid for the MyHolder classes code to be as follows:

public class MyHolder {

        @Autowired // Spring annotation that will be explained later.
        private MyClassOne one;

        @Autowired
        private MyClassTwo two;
}

It now looks like there is no way to set the properties in the MyHolder class but Spring can do this quite happily. It also looks rather clean and wizz bang nifty. Personally I don’t like using Spring like this because it tightly couples your cope to the Spring framework which I guess in reality is fine because you’ll rewrite your application before you’ll actually ever move away from Spring. But I personally think it is bad practice, if you wish to use Spring in this way I would still make sure to add all the getters and setters at the very least. I my self also add the property constructor as well.

So that is what the very basic core of Spring does, though there are now quite a lot of extra modules that make up the core Spring echo system that provide far more functionality including, web interface security, data validation, data base transacting and even more.

For this initial tutorial we will only be looking at the different types of dependency injection and how to start the Spring container outside of a J2EE container, which is the most common place to use Spring. The next tutorial will look at how to use Spring with the J2EE containers Tomcat and Jetty.

Before starting this tutorial we need to make sure we have all the right equipment.

First the build tool we will be using is Maven, so make sure to have this installed and that you are connected to the internet. Though odds are if you are reading this you should have the second half of that done. Installing maven is very simple so I won’t be discussing how to do it here. We will just be using the default maven config so no extra configuration is required.

Secondly the SCM we will be using is git. Again this just has to be installed and working, there is no need for any extra configuration, we won’t even be using a remote repository so that doesn’t even have to be set up.

Lastly the IDE I will be using for these examples will be Intellij IDEA. I am going to use the free Community Edition.

Once your environment is set up we can begin.

First we need to generate a maven project. This can be done by following the Maven New Project Tutorial.

Ok so next we need get git to start tracking the changes on the project so move into the projects directory and run through the Initialise GIT Project Tutorial.

Git should now be tracking all of our files so it is time to open the project in our IDE. If you are using Intellij IDEA select File->Open Project... then find the project directory select it and click the OK button. Once the project is open click on the Project tab in the top left hand corner and you will see the project structure and all it’s files.
Intellij will create some of it’s own project files within the spring directory, we do not want git to track these so to tell git to ignore them create a file called .gitignore within the project directory and enter the following into it.

# Ignore intellij IDEA project files.
*.iml
*.ipr
*.iws

# Ignore the maven temporary build directory.
target/

Notice we are also going to ignore the maven build directory. Once that file is created add it to git and commit.

#> git add .gitignore
#> git commit -m "Created .gitignore file to stop tracking IDE project files and maven build directory."

You can now tell Intellij to recheck the git status by selecting Version Control->Refresh File Status. You will now see that the project files are no longer being tracked.

Now lets create our main class that we will use to run this project. Right click on the org.project package under the java directory and select New->Java Class and give the class the name Main. If you are asked whether you would like to add the new file to git tick the box to tell Intellij to stop asking and then click Yes.
We now have an empty main class, lets give it a method called doStuff so we have something to test.

package org.project;

public class Main {

    public String doStuff() {
        return "Do Stuff.";
    }
}

You will now notice something odd, Intellij doesn’t seem to recognise the Java String class. This doesn’t seem right since that is part of the Java core library. The reason for this is that you have to tell Intellij which Java compiler it should use on your code. To do this place the cursor inside the word String that is the return type of the method. After a few moments you should see a red light bulb appear to the left of the word public. Now hover the cursor over the red light buld and click on the drop down arrow that appears and select the Setup JDK option, then click the Configure... button. Next click the small + button at the top left of the Configure SDK window, then select the JSDK option. Intellij should now be showing you the home directory of you JDK, select it and click OK, then click ok in the Configure SDK window, then finally click OK in the Select Project SDK window. Your Java compiler should now be setup.

The next thing to do will be to create a test class for Main. But before we do that we should update two things within our maven pom file.

First is the Java Compiler version, by default this is set to 1.4 which is far too old so we are going to upgrade it to 1.6 by adding the following to the root of the pom file.

    <build>
        <plugins>
            <plugin>
                <groupId>org.apache.maven.plugins</groupId>
                <artifactId>maven-compiler-plugin</artifactId>
                <configuration>
                    <compilerVersion>1.6</compilerVersion>
                    <fork>true</fork>
                    <source>1.6</source>
                    <target>1.6</target>
                </configuration>
            </plugin>
        </plugins>
    </build>

Pro tip: Press CTRL-ALT-L to format any code including XML.

Then we are going to update the JUnit verion to 4.7 by changing the version tag within the dependency.

    <dependencies>
        <dependency>
            <groupId>junit</groupId>
            <artifactId>junit</artifactId>
            <version>4.7</version>
            <scope>test</scope>
        </dependency>
    </dependencies>

Pro tip: Delete the number inside the version tag then press CTRL-SPACE to get a list of all the versions that are available for any maven dependency. This will work in most of the tags within the maven pom file so you could also use it to find all the artefacts within the junit group.

After editing the pom file Intellij will pop out a small message at the top of the code window asking to import the new changes from the pom file, click the Import Changes link in this pop out to tell Intellij to process the changes. Now that we have finished editing the pom file lets commit the changes by right clicking on the code and then selecting Git->Commit File..., this will pop up the commit changes window. The first thing to do here is to untick the Perform code analyses for affected file tick box. This will speed up your commits and also stop you getting bugged by Intellij. Then write your commit message into the Commit text area and click Commit.

Now click back into the Main class’s code and make sure the cursor is somewhere within the code for the class, clicking in it’s name is good then press CTRL-SHIFT-T to start the process of generating a JUnit test class. Click on the Creat New Test... option then make sure to select the JUnit4 radio button at the top of the Create Test window, also tick the doStuff method to generate a test method, then click ok.
We now have a test class so lets right a pointless test to make sure that the doStuff method is returning the correct string. For this we will need to statically import the junit assert methods.

package org.project;

import org.junit.Test;

import static junit.framework.Assert.*;

public class MainTest {
    
    // Test strings and other variables should be set up as constants so that they 
    // can be easily modified and used across multiple tests.    
    private static final String DO_STUFF = "Do Stuff.";

    @Test
    public void testDoStuff() throws Exception {
        Main main = new Main();

        // Assert that the method is returning the correct value.
        assertEquals("test do stuff method's return string", DO_STUFF, main.doStuff());
    }
}

To run the test right click on the method name and select Run "testDoStuff()".

Now that we have a new class and it’s corresponding test class we can safely delete the generated AppTest and App classes, in that order so that Intellij’s safe delete doesn’t complain. Once that is done it would also be a good idea to commit the new Main files to git. From now on I’m going to leave the commiting up to you.

At this point we should now have a very simple and completely useless maven project. You can test to see if it will build with the following command.

#> mvn clean install

You should get a pointless yet successful build. Lets take this one step further by making a pointless yet executable project by creating a main method within the main class that outputs the string from the doStuff method.

package org.project;

public class Main {

    public static void main(String[] args) {
        Main main = new Main();

        System.out.println(main.doStuff());
    }

    public String doStuff() {
        return "Do Stuff.";
    }
}

Pro tip: Type psvm inside the class and press the TAB key, this will automatically generate a main method. Also then type sout within the main method and press TAB, this will generate System.out.println().

We can now execute our class, try it by right clicking on the main method or the class in the Project pain and select Run "Main.main()". Similar to how you previously ran the test.

Ok so far for a Spring tutorial there is very little about Spring so lets fix that.
To be able to use Spring in our project we are going to need to add it as a dependency within our pom file.

   <dependencies>
        <dependency>
            <groupId>junit</groupId>
            <artifactId>junit</artifactId>
            <version>4.7</version>
            <scope>test</scope>
        </dependency>
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-context</artifactId>
            <version>3.0.5.RELEASE</version>
        </dependency>
    </dependencies>

We have added the spring-context module which will give us access to the Spring context which is where Spring stores all of it’s instantiated objects.

Now that we have access to all the classes we can start up the Spring container, so to do this we first have to create a context (config) file for the container to use on startup.
To create the context file first create a directory called resources in the directory called main within the project, then create a file called context.xml and place the following inside it. The resources directory within a maven project is where all config and “resource” files should be placed.

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
       xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
       xsi:schemaLocation=" http://www.springframework.org/schema/beans
                            http://www.springframework.org/schema/beans/spring-beans-3.0.xsd">
</beans>

You now have an empty context file that can be used to start up a Spring container. So lets start it up, to do that we have to instantiate the ClassPathXmlApplicationContext class and give it the path to the context file as an argument.

package org.project;

import org.springframework.context.support.AbstractApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;

public class Main {

    public static void main(String[] args) {
        AbstractApplicationContext context = new ClassPathXmlApplicationContext("context.xml");

        Main main = new Main();

        System.out.println(main.doStuff());
    }

    public String doStuff() {
        return "Do Stuff.";
    }
}

Run the main class again and you should get some Spring output, but not much else. Now as I mentioned before Spring’s main feature is Dependency Injection, so lets inject some classes.

Before we can inject anything we need something to inject, so lets create the same classes that were mentioned at the start of this tutorial. MyClassOne, MyClassTwo, and MyHolder.

Once these classes have been created you can use Spring to inject and instantiate them by adding bean definitions to the context file. For the two my classes we are going to us property injection then for the holder we are going to use constructor injection.

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
       xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
       xsi:schemaLocation=" http://www.springframework.org/schema/beans
                            http://www.springframework.org/schema/beans/spring-beans-3.0.xsd">

    <bean id="myClassOne" class="org.project.MyClassOne">
        <property name="one" value="1"/>
    </bean>

    <bean id="myClassTwo" class="org.project.MyClassTwo">
        <property name="two" value="2"/>
    </bean>

    <bean id="myHolder" class="org.project.MyHolder">
        <constructor-arg name="one" ref="myClassOne"/>
        <constructor-arg name="two" ref="myClassTwo"/>
    </bean>
</beans>

Now lets access the new beans from the Spring context with the following code.

package org.project;

import org.springframework.context.support.AbstractApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;

public class Main {

    public static void main(String[] args) {
        Main main = new Main();

        System.out.println(main.doStuff());

        AbstractApplicationContext context = new ClassPathXmlApplicationContext("context.xml");

        // Retrieve MyClassOne using just the id. Casting required because no type set.
        MyClassOne one = (MyClassOne) context.getBean("myClassOne");

        // Retrieve MyClassTwo using the id and type. No cast required.
        MyClassTwo two = context.getBean("myClassTwo", MyClassTwo.class);

        System.out.println("Spring instantiated MyClassOne one value: " + one.getOne());
        System.out.println("Spring instantiated MyClassTwo two value: " + two.getTwo());

        // Retrieve MyHolder with just the type because there is only ever one instance instantiated.
        MyHolder holder = context.getBean(MyHolder.class);

        System.out.println("Spring instantiated MyHolder one value: " + holder.getOne().getOne());
        System.out.println("Spring instantiated MyHolder two value: " + holder.getTwo().getTwo());
    }

    public String doStuff() {
        return "Do Stuff.";
    }
}

Now if we run the application we should get output similar to the following.

Do Stuff.
06-Feb-2011 19:44:27 org.springframework.context.support.AbstractApplicationContext prepareRefresh
INFO: Refreshing org.springframework.context.support.ClassPathXmlApplicationContext@1815859: startup date [Sun Feb 06 19:44:27 GMT 2011]; root of context hierarchy
06-Feb-2011 19:44:27 org.springframework.beans.factory.xml.XmlBeanDefinitionReader loadBeanDefinitions
INFO: Loading XML bean definitions from class path resource [context.xml]
06-Feb-2011 19:44:27 org.springframework.beans.factory.support.DefaultListableBeanFactory preInstantiateSingletons
INFO: Pre-instantiating singletons in org.springframework.beans.factory.support.DefaultListableBeanFactory@1d2fc36: defining beans [myClassOne,myClassTwo,myHolder]; root of factory hierarchy
Spring instantiated MyClassOne one value: 1
Spring instantiated MyClassTwo two value: 2
Spring instantiated MyHolder one value: 1
Spring instantiated MyHolder two value: 2

The Spring project now actually does something interesting, it instantiates and injects some beans then retrieves and displays their content.

Lastly lets do some injection with Spring annotations. First we need to update the context file so that Spring knows where to look for the annotated classes. To do this add the spring context XSD to the context file to enable access to the context tags then add the component scan tag to scan for any annotated classes under the org.project package. Lastly comment out the wiring of the holder object in the context file.

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
       xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
      xmlns:context="http://www.springframework.org/schema/context"
       xsi:schemaLocation="http://www.springframework.org/schema/beans
            http://www.springframework.org/schema/beans/spring-beans-3.0.xsd
            http://www.springframework.org/schema/context
            http://www.springframework.org/schema/context/spring-context-3.0.xsd">

    <bean id="myClassOne" class="org.project.MyClassOne">
        <property name="one" value="1"/>
    </bean>

    <bean id="myClassTwo" class="org.project.MyClassTwo">
        <property name="two" value="2"/>
    </bean>

    <context:component-scan base-package="org.project"/>

    <!--<bean id="myHolder" class="org.project.MyHolder">-->
    <!--<constructor-arg name="one" ref="myClassOne"/>-->
    <!--<constructor-arg name="two" ref="myClassTwo"/>-->
    <!--</bean>-->

</beans>

Now we need to add the right annotations to the MyHolder class. First we annotate the class with the org.springframework.stereotype.Component annotation. This tells Spring that this class should be instantiated and injected. Then we annotate the properties with org.springframework.beans.factory.annotation.Autowired, this tells Spring that the properties should be populated with beans in the context that match their type. You’ll also notice that for the second property the name of the bean to inject has been set with the org.springframework.beans.factory.annotation.Qualifier annotation. It is also possible to just annotate the property constructor and then Spring will instantiate the class in the same way that it did with the previous context file configuration.

package org.project;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.stereotype.Component;

@Component
public class MyHolder {

    @Autowired
    private MyClassOne one;

    @Autowired
    @Qualifier("myClassTwo")
    private MyClassTwo two;

    public MyHolder() {
    }

    public MyHolder(MyClassOne one, MyClassTwo two) {
        this.one = one;
        this.two = two;
    }

    public MyClassOne getOne() {
        return one;
    }

    public void setOne(MyClassOne one) {
        this.one = one;
    }

    public MyClassTwo getTwo() {
        return two;
    }

    public void setTwo(MyClassTwo two) {
        this.two = two;
    }
}

And there you have it the end of the first Spring tutorial, where you have learned a little about what Spring does, how it does it, and the different ways to does things with it.

Articles

Initialise GIT Project Tutorial

In Uncategorized on 12/02/2011 by pier0w

Git is a really nice distributed source control system. A distributed source control system allows every person working with it to have a local copy of the entire source repository including all of it’s change history, so the only difference between the copy of the repository on your machine and the central repository is that everyone has decided to push their changes to the central repository.

This means you are able to make local commits without ever worrying about clashing with other developers. Clashes can only ever then occur when you finally decide to push all your changes to the central repository and since GIT has such fantastic auto merge capabilities you will very rarely have to worry about dealing with clashes your self. I find that this ease of committing makes me commit much more than I usually would with SVN since all of my commits will succeed every time.

So to get git to start monitoring your files move into your projects directory and run the git init command.

#> cd project/
#> git init
Initialized empty Git repository in /some/dir/project/.git/

You can now check to see what git has found in your project with the git status command.

#> git status
# On branch master
#
# Initial commit
#
# Untracked files:
#   (use "git add ..." to include in what will be committed)
#
#	pom.xml
#	src/
nothing added to commit but untracked files present (use "git add" to track)

Since this is a maven project It has found the maven pom file and the source directory for your project. Now you can actually tell git to start tracking these by adding them to the repository and then carrying out our first commit.

#> git add pom.xml src/
#> git status # Just running git status again to check what files have been added.
# On branch master
#
# Initial commit
#
# Changes to be committed:
#   (use "git rm --cached ..." to unstage)
#
#	new file:   pom.xml
#	new file:   src/main/java/org/project/App.java
#	new file:   src/test/java/org/project/AppTest.java
# 
#> git commit -m "First commit." # Our first commit. Ignore the warnings, you can do what it says to stop git complaining if you like.
[master (root-commit) 4100aeb] First commit.
 Committer: Some One 
Your name and email address were configured automatically based
on your username and hostname. Please check that they are accurate.
You can suppress this message by setting them explicitly:

    git config --global user.name "Your Name"
    git config --global user.email you@example.com

If the identity used for this commit is wrong, you can fix it with:

    git commit --amend --author='Your Name '

 3 files changed, 76 insertions(+), 0 deletions(-)
 create mode 100644 pom.xml
 create mode 100644 src/main/java/org/project/App.java
 create mode 100644 src/test/java/org/project/AppTest.java

Git is now tracking all the files within your project and will pick up any changes you make.