Archive for May, 2009|Monthly archive page

A Twitter – Google Maps mashup to view your friends network …

So it all started off with me wanting to see the geographical distribution of my Twitter friends (the Twitter-ers that I am following) and since I don’t host a website (and WordPress doesn’t allow JavaScript in blog posts) I had to do all this in Java.

In the end it worked out pretty well – it was actually quite simple using the Google Static Maps API. All you need to know is some scripting language and you need a Google Maps API Key.

So you start off with the Twitter REST API and get all your friends (the people that you are following) . I used a Java URL object but you can use cURL or any other scripting language that has HTTP URL support. The output looks something like this (the Twitter ids of all your friends) :

<?xml version="1.0" encoding="UTF-8"?>
<ids>
<id>14112660</id>
<id>798731</id>
<id>15256245</id>
<id>16824408</id>
<id>17191554</id>
<id>18743188</id>
<id>26459315</id>
<id>21276419</id>
<id>18702371</id>
<id>34632001</id>
<id>14576471</id>
<id>13954772</id>
<id>16038405</id>
<id>15880443</id>
</ids>

You have to now parse out the IDs from the above output and for each ID (and for yourself also), you have to once again use the Twitter API to get each user’s information. Now the output looks something like this :

<?xml version="1.0" encoding="UTF-8"?>
<user>
  <id>12683672</id>
  <name>Kartick Suriamoorthy</name>
  <screen_name>karticks</screen_name>
  <location>Munich, Germany</location>
  <description>Software professional (JAVA, Network Management, Open Source, Application Servers, etc.)</description>
  <profile_image_url>http://s3.amazonaws.com/twitter_production/profile_images/57456567/got-beer_normal.png</profile_image_url>
  <url>https://karticks.wordpress.com</url>
  <protected>false</protected>
  <followers_count>29</followers_count>
  <profile_background_color>9ae4e8</profile_background_color>
  <profile_text_color>000000</profile_text_color>
  <profile_link_color>0000ff</profile_link_color>
  <profile_sidebar_fill_color>e0ff92</profile_sidebar_fill_color>
  <profile_sidebar_border_color>87bc44</profile_sidebar_border_color>
  <friends_count>14</friends_count>
  <created_at>Fri Jan 25 14:36:13 +0000 2008</created_at>
  <favourites_count>0</favourites_count>
  <utc_offset>3600</utc_offset>
  <time_zone>Berlin</time_zone>
  <profile_background_image_url>http://static.twitter.com/images/themes/theme1/bg.gif</profile_background_image_url>
  <profile_background_tile>false</profile_background_tile>
  <statuses_count>109</statuses_count>
  <notifications></notifications>
  <following></following>
  <status>
    <created_at>Mon May 25 05:25:11 +0000 2009</created_at>
    <id>1909795818</id>
    <text>End of a long weekend (and a long vacation). Now trudging back to stuttgart with my morning kaffee and breze.</text>
    <source>&lt;a href=&quot;http://help.twitter.com/index.php?pg=kb.page&amp;id=75&quot;&gt;txt&lt;/a&gt;</source>
    <truncated>false</truncated>
    <in_reply_to_status_id></in_reply_to_status_id>
    <in_reply_to_user_id></in_reply_to_user_id>
    <favorited>false</favorited>
    <in_reply_to_screen_name></in_reply_to_screen_name>
  </status>
</user>

Now you have to parse out the location (4th element) and use the Google Geocode API to geocode the location. This is a little bit tricky – as sometimes the location attribute can be empty (you have to skip those users) or they can be iPhone lat-long coordinates (i.e. they are already geocoded – see below)

  <location>iPhone: 30.417343,-97.710770</location>
  <description>I do not fear you, gypsy. I only want your tears.</description>

Once you have all the geocodes, you construct a Google Static Maps URL by using your geocode as the center, and all the geocodes (including your location) as markers. I used a black marker to mark my location, and red markers to mark my friends. The result looks something like this …

Kartick's Twitter Network

Kartick's Twitter Network

Ok not very impressive, but still fun …

Caveats :
– Google Static Maps API allows only 50 markers, so if your friends list is more than 50, you will have to prune out the unwanted ones 😉
– The Google Geocode API returns coordinates of a point as a longitude-latitude pair but the markers in the Google Static Maps API expect it in latitude-longitude format and it took me some time to figure out this (I was wondering why my markers were located in Antarctica and sometimes way outside any conceivable point in the globe !!). I wonder why Google did that (iPhone actually got it right and it was trivial to take the iPhone Geocode and insert it into the Google Maps URL) – it would have been just so easy to pass the lat-long pair from the geocode output into the Google Maps URL (to construct the marker’s coordinates) but now I had to add parsing logic to swap the lat-long locations (ugly).

Anyway, I hope this was fun and enjoyable, and as always, the code (TwitterGoogleMashup.java) can be found in the Google Code project, DalalStreet (in the FunStuff project). You can run this class with your own Twitter username (and Google Maps API key) by checking out the project into Eclipse. It will print out a URL when it finishes running and all you need to do is copy and paste this URL into your browser.

Until next time …

Hibernate One-to-One Mapping using Annotations

In an earlier post I had written about getting your development environment setup to start using Hibernate. I had talked about generating a schema, and now it makes sense to proceed to the next logical step, which is persisting data.

As usual, all the code discussed in this post is available at the Google Code Project – DalalStreet.

The objective of this post is to successfully persist a heirarchy of objects using Hibernate. The model consists of a Customer entity, this Customer entity contains an Address entity and a ContactInformation entity. The Address or ContactInformation entity cannot exist independently without a Customer – or in other words – Customer has a one-to-one relationship with Address and ContactInformation.

Hibernate documentation along with a couple of blogs (1, 2) provide insufficient information on how to model one-to-one relationships in Hibernate.

Unfortunately modeling one-to-one relationships in Hibernate is non-trivial and the correct way to model is illustrated in the following code snippets.

Source code for “Customer” entity :

@Entity
@Table(name = "entity_customer")
public class Customer
{
	@Id @GeneratedValue(strategy = GenerationType.IDENTITY)
	@Column (name = "customer_id")
	private Long id = null;
	
	@Column(name = "first_name")
	private String firstName = null;
	
	@Column(name = "middle_name")
	private String middleName = null;
	
	@Column(name = "last_name")
	private String lastName = null;
	
	@Column(name = "salutation")
	private String salutation = null;
	
	@Column(name = "account_number")
	private String accountNumber = null;
	
	@OneToOne(cascade=CascadeType.ALL)
	@JoinColumn (name = "customer_id")
	private Address address = null;
	
	@OneToOne(cascade=CascadeType.ALL)
	@JoinColumn (name = "customer_id")
	private ContactInformation contactInfo = null;

Source code for “Address” entity :

@Entity
@Table(name = "entity_address")
public class Address
{
	@Column(name = "street_address1")
	private String streetAddress1 = null;

	@Column(name = "street_address2")
	private String streetAddress2 = null;

	@Column(name = "city")
	private String city = null;

	@Column(name = "state")
	private String state = null;

	@Column(name = "postal_code")
	private String postalCode = null;

	@Column(name = "country")
	private String country = null;
	
	@Id
	@GeneratedValue(generator = "foreign")
	@GenericGenerator(name = "foreign", strategy = "foreign", parameters = { @Parameter(value = "customer", name = "property") })
	@Column(name = "customer_id")
	// this is id of the customer - as an address is always associated with a
	// customer (it cannot exist independent of a customer)
	private Long customerID = null;
	
	
	@OneToOne
	@JoinColumn(name = "customer_id")
	// reference to the customer object. hibernate requires two-way object
	// references even though we are modeling a one-to-one relationship.
	private Customer customer = null;

In plain-speak this translates into the following :
Address does not have its own “ID” attribute. It will use the “ID” of the
Customer and the Customer table and the Address table are joined via this
“ID” attribute (i.e. “customer_id”).

Test code :

	private void testSingleObjectPersistence()
	{
		Customer customer = setupSingleCustomer();

		// save an object
		Session session = HibernateUtil.getSessionFactory().openSession();
		Transaction tx = session.beginTransaction();

		Long custID = (Long) session.save(customer);

		tx.commit();
		session.close();

		System.out.println("Customer id : " + custID);
	}

	private Customer setupSingleCustomer()
	{
		Address address = new Address();
		address.setCity("Austin");
		address.setCountry("U.S.A");
		address.setPostalCode("78701");
		address.setState("Texas");
		address.setStreetAddress1("301 Lavaca Street");

		ContactInformation ci = new ContactInformation();
		ci.setEmailAddress("info@gingermanpub.com");
		ci.setWorkPhone("512-473-8801");

		Customer customer = new Customer();
		customer.setAccountNumber("90000200901");
		customer.setFirstName("Gingerman");
		customer.setLastName("Pub");
		customer.setMiddleName("Beer");
		customer.setSalutation("Sir");
		customer.setAddress(address);
		customer.setContactInfo(ci);

		address.setCustomer(customer);
		ci.setCustomer(customer);

		return customer;
	}

Once all the above changes have been made, Hibernate is actually able to persist the objects.

Here are the links to the files in case you want to take a detailed look at the code.

Hopefully you found this post helpful, and as always, please feel free to leave your feedback …

Your first cup of Hibernate …

Hibernate is pretty much the defacto tool/library/framework to implement Object Relational Mapping (ORM) in Java nowadays and it has definitely become a much larger project than when I first started using it in 2004. It has so many downloads (Core, Annotations, Shards, etc.) and so many jars and dependencies that it is quite difficult to decide what is required and what is not required (and what is important and what is optional).

Here I try to provide some clarity by starting with a basic Hibernate project and slowly working up (using more advanced features of Hibernate) and in the process discovering the different features of Hibernate (and their dependencies).

All the code mentioned here is available via the Google Code Project – DalalStreet.

So let us start from scratch – which means no downloads from hibernate.org, unless we absolutely need it – and proceed step by step :

  • I downloaded Eclipse 3.4.1 and created a Java Project – DalalStreet.
  • I decided to use Java annotations and Eclipse immediately gave me an error (see screenshot below)
  • Annotation Errors

    Annotation Errors

  • This can be resolved by adding ejb3-persistence.jar to the classpath of your Eclipse project. For this you need to download the hibernate annotations (I decided to use version 3.2.1 – pay special attention to the compatibility matrix) and the ejb3-persistence.jar is located in the lib folder.
  • After finishing all the annotations, you will want to export the schema, but before you can do that you need to define a hibernate config file.
  • To export the schema, I decided to use the Ant HibernateToolTask. Of course Ant didn’t know where to find this class. For this, you need to download the hibernate tools (I am using version 3.2.4), unzip it, and navigate to the plugins folder. Now navigate to the lib/tools folder inside the org.hibernate.eclipse_<version_number> folder and you will find hibernate-tools.jar (add this to the classpath of ANT).
  • After you have added the hibernate-tools.jar to the classpath you will require the following jars (to be added to the classpath of ANT)
    • hibernate3.jar from hibernate core (for obvious reasons, download hibernate core and add hibernate3.jar – found in the top level folder)
    • commons-logging-1.0.4.jar (in the above hibernate core download, lib folder)
    • hibernate-annotations.jar (in hibernate annotations download, root folder)
    • dom4j-1.6.1.jar (in hibernate core download, lib folder)
    • commons-collection-2.1.1.jar (in hibernate core download, lib folder)
    • freemarker.jar (in the hibernate tools download, inside the lib/tools folder of the org.hibernate.eclipse_<version_number> folder)
    • and finally the jdbc driver jar which is of course dependent on the database you are using (I am using the MySQL database and the following driver jar : mysql-connector-java-5.1.7-bin.jar)

    Once you have all this in place, your ANT task should complete successfully and you should have a valid schema in your database.

    A final screenshot with all the jars in your lib folder :

    Hibernate and dependent jars

    Hibernate and dependent jars

    Hope you found this post helpful. The next post will discuss the next logical step – actually persisting some data into the database using Hibernate.

Design a site like this with WordPress.com
Get started