Sascha Tayefeh's Homepage

Blogging about Information Technology

Archive for the ‘Java’ tag

OAuth and Spring Security

without comments

While Spring Framework – and in particular Spring Security – provides many ways to deal with authentication and authorization, there are some new approaches that are becoming increasingly popular. As in most cases, the requirements of the cloud along with that of mulitenant applications have been the driving force of this evolution.

For example, while SSL is definitely a secure layer, many (if not most) home grown applications simply do not want to pay for a signed certificate (even less in face of the fact that such a certificate is mostly restricted to a single domain) and, thus, simply do not use SSL. Of course, this is worst, but still common practice.

Also, basic authentification is, presumingly with respect to its simplicity, still widespread. However, basic authentification in combination with a non-secure transport layer is a security black hole.

And finally, with SaaS rising, comfortable single sign-on in a multitenant environment must be considered in modern software design. Latter issue, cloud based single sign-on, is supported by the Spring Security (see ref. manual).

There are some more requirements emerging from the evolving cloud: for example, RESTful web services as part of asynchronous data transfer need to be secured on user level. While such scenarios can definitely be realized with the Spring Security, it definitely focuses on securing classic synchronous data transfer and flows (for instance, I would rather not choose Spring Web Flow to implement the flow of an highly AJAXian web application). In order to implement flows based on highly asynchronous communication between the client and server, there is definitely some hacking to do (see e.g. this tutorial).

However, the most important issue in times of millions of home grown smartphone apps is sharing credentials with such a client. Using same password over and over again, because you cannot remember millions of different passwords? Of course, this is worst, but still common practice. Now, what if your credentials are misused by your app? Wouldn’t it be much better, if you would not share your credentials with the client at all?

OAuth is an open protocol to allow secure API authorization in a simple and standard method from desktop and web applications. It has been developed with most of the issues that emerged from cloud-based authentification and authorizastion in mind. Furthermore, it is being used by global players like Digg, Jaiku, Flickr, Twitter, and developers of OAuth are hopeful to see Google, Yahoo, and others soon to follow. With so many heavy weight service providers relying on OAuth, it may definitely be considered as quasi standard. Unfortunately, Spring Security is not (yet) shipped with out-of-the-box support of OAuth, although I am pretty sure that the extremely capable Springsource team will deliver Spring with OAuth support as soon as possible.

For those who cannot (and should not) wait, a promising approach is described in OAuth for Spring Security. The purpose of this project is to provide an OAuth implementation for Spring Security. I have tested their implementation, and hereby I strongly recommend their approach. For me, the most striking advantage of this design is the combined power of both, OAuth and Spring Security. While you still have the comfort of Spring and its AOP framework, you have implemented the security of OAuth.

Written by Sascha Tayefeh

July 25th, 2010 at 2:56 pm

How entity associations/relationships are mapped by an ORM

without comments

To demonstrate how mapping is carried out by ORM, Hibernate was used with JPA2 annotation syntax and MySQL as database. Two trivial entities are used, “Book” and “Store” for both, one-to-many/many-to-one and many-to-many demo. However, this is no particularly good design, since an individual book cannot be physically located in two places, but for this demo, it is an appropiate abstraction.

A book is considered as being owned by one (many) store(s).

1. One-To-Many/Many-To-One

1.1 Unidirectional

1.1.1 Many-To-One

First, let’s have a look at an excerpt the “Book” class. The association has got to be defined here, because many using unidirectional association of the many-to-one type, this one is the “many” side:

@Entity
public class Book extends BusinessObject {
    // Unidirectional Many-to-one
    // No assoc. in Book required
    // getters/setters required
    @ManyToOne
    @JoinColumn(name = "store_fk")
    private Store store;
...
}

Since this is an unidirectional association coming from the Book side, the Store (one) side needs no further association.

@Entity@Table(name = "store")
public class Store extends BusinessObject {
    // No assoc. required
...
}

Running this will result into two tables created, one per entity (ignoring the obligatory and hibernate specific “hibernate_sequences” table). “store_fk” as defined by @JoinColumn of the Book class is mapped as an attribute of the table “Book”.

mysql> show tables from dbjava;
+---------------------+
| Tables_in_dbjava    |
+---------------------+
| book                |
| hibernate_sequences |
| store               |
+---------------------+
3 rows in set (0.00 sec)

mysql> describe `dbjava`.BOOK;
+-------------+----------+------+-----+---------+-------+
| Field       | Type     | Null | Key | Default | Extra |
+-------------+----------+------+-----+---------+-------+
| id          | int(11)  | NO   | PRI | NULL    |       |
| store_fk    | int(11)  | YES  | MUL | NULL    |       |
+-------------+----------+------+-----+---------+-------+
6 rows in set (0.00 sec)

mysql> describe `dbjava`.STORE;
+----------+--------------+------+-----+---------+-------+
| Field    | Type         | Null | Key | Default | Extra |
+----------+--------------+------+-----+---------+-------+
| id_store | int(11)      | NO   | PRI | NULL    |       |
+----------+--------------+------+-----+---------+-------+
2 rows in set (0.00 sec)
1.1.2 One-To-Many

In this case, the association is defined from the inverse point of view, leaving Book without an association to be declared, while the association is now declared by the Store entity.

@Entity
public class Book extends BusinessObject {
    // No assoc. required
}
@Entity
public class Store extends BusinessObject {

    // Unidirectional One-To-Many
    // No assoc. in Book required
    // getters/setters required
    @OneToMany(cascade = CascadeType.ALL, fetch = FetchType.EAGER)
    @JoinColumn(name = "store_fk")
    private Set<Book> books;

    public Set<Book> getBooks() {
        return books;
    }

    public void setBooks(Set<Book> books) {
        this.books = books;
    }
    ...
}

And the resulting database which, using these queries, looks identically:

mysql> show tables from dbjava;
+---------------------+
| Tables_in_dbjava    |
+---------------------+
| book                |
| hibernate_sequences |
| store               |
+---------------------+
3 rows in set (0.00 sec)

mysql> describe `dbjava`.BOOK;
+-------------+----------+------+-----+---------+-------+
| Field       | Type     | Null | Key | Default | Extra |
+-------------+----------+------+-----+---------+-------+
| id          | int(11)  | NO   | PRI | NULL    |       |
| store_fk    | int(11)  | YES  | MUL | NULL    |       |
+-------------+----------+------+-----+---------+-------+
6 rows in set (0.00 sec)

mysql> describe `dbjava`.STORE;
+----------+--------------+------+-----+---------+-------+
| Field    | Type         | Null | Key | Default | Extra |
+----------+--------------+------+-----+---------+-------+
| id_store | int(11)      | NO   | PRI | NULL    |       |
+----------+--------------+------+-----+---------+-------+
2 rows in set (0.00 sec)

1.2 Bidirectional with the “many” side as the owner

In order to define a bidirectional association between both entities, one side is considered to be the owner. In this case, it is the Store that owns a Book. This fact is realized by the “mappedBy” parameter on the owner side, while the owned side carries the Owner’s id within the database.

@Entity
public class Store extends BusinessObject {

    // Bidirectional One-To-Many
    // This side is owner, thus, this collection is mappedBy
    // getters/setters required
    @OneToMany(mappedBy = "store")
    private Set<Book> books;

    public Set<Book> getBooks() {
        return books;
    }

    public void setBooks(Set<Book> books) {
        this.books = books;
    }
...
}
@Entity
public class Book extends BusinessObject {

    // Bidirectional Many-To-one
    // Book is owned by one store
    // getters/setters required
    @ManyToOne
    @JoinColumn(name="store_fk")
    private Store store;

    public Store getStore() {
        return store;
    }

    public void setStore(Store store) {
        this.store = store;
    }
...
}
mysql> show tables from dbjava;
+---------------------+
| Tables_in_dbjava    |
+---------------------+
| book                |
| hibernate_sequences |
| store               |
+---------------------+
3 rows in set (0.00 sec)

mysql> describe `dbjava`.BOOK;
+-------------+----------+------+-----+---------+-------+
| Field       | Type     | Null | Key | Default | Extra |
+-------------+----------+------+-----+---------+-------+
| id          | int(11)  | NO   | PRI | NULL    |       |
| store_fk    | int(11)  | YES  | MUL | NULL    |       |
+-------------+----------+------+-----+---------+-------+
6 rows in set (0.01 sec)

mysql> describe `dbjava`.STORE;
+----------+--------------+------+-----+---------+-------+
| Field    | Type         | Null | Key | Default | Extra |
+----------+--------------+------+-----+---------+-------+
| id_store | int(11)      | NO   | PRI | NULL    |       |
+----------+--------------+------+-----+---------+-------+
2 rows in set (0.00 sec)

2. Many-to-Many

Many-to-many relations typically need another table that provides the association of the associated entities. Both classes need to define the association, however, since one side is regarded as the owner, the definition is asymetric.

@Entity
public class Book extends BusinessObject {

    // Many to many, the other side is the owned
    // Getters & setters are required
    @ManyToMany(
            cascade = {CascadeType.PERSIST, CascadeType.MERGE},
            mappedBy = "books",
            targetEntity = Store.class
    )
    private Collection stores;

    public Collection getStores() {
        return stores;
    }

    public void setStores(Collection stores) {
        this.stores = stores;
    }
@Entity
@Table(name = "store")
public class Store extends BusinessObject {
    @ManyToMany(
            targetEntity = de.tayefeh.businessobjects.Book.class,
            cascade = {CascadeType.PERSIST, CascadeType.MERGE})
    @JoinTable(
            name="store_book",
            joinColumns = @JoinColumn(name = "store_id"),
            inverseJoinColumns = @JoinColumn(name = "book_id")
    )
    private Collection books;

    public Collection getBooks() {
        return books;
    }

    public void setBooks(Collection books) {
        this.books = books;
    }
...
}

In this case, the “store_book” table is actually created and we have three entity tables for two entities. However, there are no additional columns added to the tables of the original entities:

mysql> show tables from dbjava;
+---------------------+
| Tables_in_dbjava    |
+---------------------+
| book                |
| hibernate_sequences |
| store               |
| store_book          |
+---------------------+
4 rows in set (0.00 sec)

mysql> describe `dbjava`.BOOK;
+-------------+----------+------+-----+---------+-------+
| Field       | Type     | Null | Key | Default | Extra |
+-------------+----------+------+-----+---------+-------+
| id          | int(11)  | NO   | PRI | NULL    |       |
+-------------+----------+------+-----+---------+-------+
5 rows in set (0.00 sec)

mysql> describe `dbjava`.STORE;
+----------+--------------+------+-----+---------+-------+
| Field    | Type         | Null | Key | Default | Extra |
+----------+--------------+------+-----+---------+-------+
| id_store | int(11)      | NO   | PRI | NULL    |       |
+----------+--------------+------+-----+---------+-------+
2 rows in set (0.01 sec)

mysql> describe `dbjava`.STORE_BOOK;
+----------+---------+------+-----+---------+-------+
| Field    | Type    | Null | Key | Default | Extra |
+----------+---------+------+-----+---------+-------+
| store_id | int(11) | NO   | MUL | NULL    |       |
| book_id  | int(11) | NO   | MUL | NULL    |       |
+----------+---------+------+-----+---------+-------+
2 rows in set (0.01 sec)

Written by Sascha Tayefeh

July 16th, 2010 at 8:52 pm

JUnit4 and Maven – minimal example

with 2 comments

When I migrated an old project from JUnit3 to JUnit4, I ran into some problems. mvn:test produced an error:

junit.framework.AssertionFailedError: No tests found in minimal.DoSomeActionTest

>The test classes were no longer available. I found that I had to remove inheritance from :TestCase() and annotate all test methods with @Test. Here is a trivial example:

package minimal;
import org.junit.Assert;
import org.junit.Test;
public class DoSomeActionTest {
    @Test
    public void testIsThisReallyTrue() {
        Assert.assertTrue(true);
    }
}

In case you have your project managed by maven, remember to make use of the maven-compiler-plugin to enforce Java 1.6 (required for annotations):

            <plugin>
                <groupId>
                  org.apache.maven.plugins
                </groupId>
                <artifactId>
                  maven-compiler-plugin
                </artifactId>
                <version>2.3.1</version>
                <configuration>
                    <source>1.6</source>
                    <target>1.6</target>
                    <encoding>UTF-8</encoding>
                </configuration>
            </plugin>

When running mvn:test you should get following positive message:

-------------------------------------------------------
 T E S T S
-------------------------------------------------------
Running minimal.DoSomeActionTest

Tests run: 1, Failures: 0, Errors: 0, Skipped: 0, Time elapsed: 0.047 sec

Results :

Tests run: 1, Failures: 0, Errors: 0, Skipped: 0
[INFO] ------------------------------------------------------------------------
[INFO] BUILD SUCCESSFUL
[INFO] ------------------------------------------------------------------------
[INFO] Total time: 2 seconds
[INFO] Finished at: Sun Jul 11 17:22:44 CEST 2010
[INFO] Final Memory: 10M/19M
[INFO] ------------------------------------------------------------------------

I have prepared a working maven project. It was published at github. Get your local copy by cloning with git:

git clone git://github.com/sastay/JUnit4-and-Maven-Example.git

Written by Sascha Tayefeh

July 13th, 2010 at 6:31 pm

Posted in Coding

Tagged with , , , , , , ,

NetBeans 6.8 and JSF 2.0

without comments

As NetBeans 6.8 was published today, I could not resist to updated all my Sun stuff. Suprisingly, I realized that NetBeans 6.8 comes with integrated JSF2.0 support:

NetBeans 6.8 and JSF

Now, I am giving it a try and will be reporting here any groundbreaking progress.

Written by Sascha Tayefeh

December 20th, 2009 at 9:57 pm

Posted in Coding,Internet

Tagged with , , , , ,

Geocoding APIs for PHP, iPhone, and Android

with 3 comments

There are several approaches to determine a location (in terms of longitude and latitude) from an address and vice versa (latter is referred to as “reverse geocoding”). A quick research with Google unveiled following interesting APIs and web-services (fully sufficient for my needs, yet, incomplete and far from exhausting). I will focus here on

  1. Google Maps-API (Recommended for PHP and JavaScript …)
  2. Geonames.org-API (Recommended for Java, C#/.NET, VB/.NET …)
  3. Android (Android only)
  4. iPhone (iPhone only)

Google Maps-API

Particularly useful if you need to carry out implementation in PHP or JavaScript. Google’s API provides a class which is solely dedicated to the task of geocoding: GClientGeocoder. You could make use of it embedding it within your application making it a client site geocoder. With this API, “Reverse Geocoding” is possible too.

They may be cases, where you do not want or just cannot make use of client site geocoding (e.g. absence of Javascript, performance, etc.). Here you may the HTML Geocoding web service of Google. You may choose between XML, KML, CSV, and JSON response – of which latter is particularly useful for the communication between Google and mobile devices. All you need to do is to create a string like

$Address = 'Germany, Frankfurt, Friedberger Landstrasse 20';
$myString = 'http://maps.google.com/maps/geo?q=' . $Address . '&output=xml&key=' . $GoogleApiKey;'

where $Address is, of course, the (relatively) free format address and $GoogleApiKey is a key you need to obtain from Google in order to get access to its services.

Here is a strategy for a PHP implementation. It is based on send the Client URL (cURL) Library shipped with PHP. In particular, you could implement the following sequence in order to send the request and retrieve the response:

  1. Initialize a cURL session with the curl_init() function: $csession = curl_init()
  2. $csession is a state machine. You need to set some of its parameters with the curl_setopt(…) command: Set CURLOPT_RETURNTRANSER to TRUE, CURLOPT_HEADER to 0, CURLOPT_FOLLOWLOCATION to 1 and CURLOPT_URL to the above mentioned $myString. Example: curl_setopt($csession, CURLOPT_RETURNTRANSFER, TRUE)
  3. Finally, use curl_exec() to carry out the request: $response = curl_exec($csession); curl_close($csession)

Now, what you get here is some data stored in $response. You may access them using PHP’s SimpleXMLElement class: $xml = new SimpleXMLElement($response) and then accessing the XML elements by e.g. $xml->Response->Status->code or explode(',',$xml->Response->Placemark->Point->coordinates).

A good implementation of this strategy in form of a PHP class can be found here.

Geonames.org

Geonames provides a web interface and an API in form of a standard web service interface to access its geocoding service. This very fact – the use of a web service interface – makes it particularly interesting for all languages. However, I would like to advise to make this the choice if using .NET languages and Java, since these languages have developed an excellent workflow of referring to web services by using IDEs like Visual Studio and Eclipse, respectively. BTW, JSON format is also provided ;-)

And since web services are so common, I won’t give any details here dealing with the implementation. Just refer to the web service documentation of Geonames.org and the list of web services provided by Geonames.org.

Nevertheless, I simply must mention some very interesting thing about this provider: It does not only return simple (reverse) geocoding data, but it also offers web service methods like findNearbyWikipedia (which returns a list of wikipedia entries) and findNearByWeather (which returns a weather station with the most recent weather observation). This surplus is really worth considering this service for your implementation.

Android

Since Android is a project by Google, it is somehow related to the last section. However, the approach describes in the last section is a very general one while this one is recommended for Android mobile implementation.

The base class android.location is provided by the Android SDK. The specialized android.location.Geocoder is just what is needed for all sort of geocoding. It is possible to carry out both, geocoding and reverse geocoding. This is particularly powerful in combination with android.location.LocationManager, which can be used to determine the current location using the cell phones GPS device, and android.location.Location to store the time-dependent location.

Instead of going into the coding details here, I would like to give some good references you may find useful:

You should be able to create your own implementation from this input.

iPhone

Apple, too, has implemented a very good framework to cope with the GPS capabilities of its iPhone. It comes with its Core Services and is called “Core Location”. Apple’s developer pages are so exhausting that no further details are needed here. The above mentioned link to the “Core Location” framework leads to a page with many source examples, however, you need to be member of the apple developer community in order to access them.

There is a very good geocoding example @ cloudmade.com that shows how to make use of Apple’s API. You should take this as your starting point.

Written by Sascha Tayefeh

August 23rd, 2009 at 4:27 pm

Switch to our mobile site