last.fm API bindings for Java / Documentation

This document contains a basic documentation for the last.fm API bindings for Java.

What are the bindings and what can I do with them?

They are a BSD licensed API providing a Java interface to Audioscrobbler/Last.fm web services. The API contains the following features:

Preparations and requirements

The API requires at least Java 1.5. To use the API add the lastfm-bindings.jar to your classpath. You can then find the API classes in the net.roarsoftware.lastfm package.
Before you can use the Last.fm APIs you'll have to obtain an API key from here.
Before you invoke any methods you must set a user-agent string via:
	Caller.getInstance().setUserAgent(userAgent);
or use "tst" as user-agent while developing.
Also while developing you may want to enable the debug mode which will display debug information on the console:
	Caller.getInstance().setDebugMode(true);

Proxies

The bindings provide standard proxy support. You can set a proxy via:
	Caller.getInstance().setProxy(myProxy);
which will be used in all HTTP calls, including those done by the submission service provided by the Scrobbler class.

Invoking API methods

API method bindings are available via the static methods in the classes named Artist, Track, User and the like.
The Java class and method names follow the original method names of the Last.fm API, that means you can find the method user.getRecentTracks in the class User with the method name getRecentTracks, which takes the same parameters as the REST method documented in the link above plus your API key.
An example for a method call looks like that:
	String key = "b25b959554ed76058ac220b7b2e0a026"; //this is the key used in the last.fm API examples online.
	String user = "JRoar";
	Chart<Artist> chart = User.getWeeklyArtistChart(user, 10, key);
	DateFormat format = DateFormat.getDateInstance();
	String from = format.format(chart.getFrom());
	String to = format.format(chart.getTo());
	System.out.printf("Charts for %s for the week from %s to %s:%n", user, from, to);
	Collection<Artist> artists = chart.getEntries();
	for (Artist artist : artists) {
		System.out.println(artist.getName());
	}
Calls that require authentication require a Session parameter. Sessions can be obtained via the Authenticator class. See here for different authentication methods.
An example for a authenticated method call looks like that:
	String key = "...";      // api key
	String secret = "...";   // api secret
	String user = "...";     // user name
	String password = "..."; // user's password
	Session session = Authenticator.getMobileSession(user, password, key, secret);
	Playlist playlist = Playlist.create("example playlist", "description", session);

Requests that fail because of bad authentication or bad parameters (bad artist, album or track names) will return either a null value or an empty Collection.

Paginated Results

Some methods return a PaginatedResult instead of a plain Collection, for example geo.getEvents. In this case you can access the data you're looking for via the PaginatedResult.getPageResults() method. Call Geo.getEvents() subsequently with incremented page numbers to load all pages if necessary. Note that page numbers start with 1 not 0.

Charts

All getXXXChart methods return an instance of Chart, instead of a plain Collection, for example user.getWeeklyArtistChart. You can access the data you're looking for via the Chart.getEntries() method.

Results

Authenticated write calls, such as artist.share don't return any data. These methods will return an instance of the Result class, which contains an error code and error message and/or an HTTP error code for debugging, if the call failed. Otherwise Result.isSuccessful() will return true.

Scrobbling songs

Support for scrobbling songs to your Audioscrobbler/Last.fm profile is available via the Scrobbler class. An example for scrobbling a song looks like this:
	Scrobbler scrobbler = Scrobbler.newScrobbler("tst", "1.0", user);
	ResponseStatus status = scrobbler.handshake(password);
	System.out.println("handshake ok: " + status.ok());
	status = scrobbler.nowPlaying("Pixies", "Where Is My Mind?");
	System.out.println("now playing ok: "+ status.ok());
	status = scrobbler.submit("Pixies", "Where Is My Mind?", "Surfer Rosa", 233, 7, Source.USER,
			(System.currentTimeMillis() / 1000) - 117); // see javadoc for parameter explanation
	System.out.println("submission: " + status.ok());

Radio stations

The API contains support for tuning into Last.fm radio stations. Before you start using the radio API be aware, that you can only stream to users with a paid subscription account (or you will have to have a special API key), and that streaming to mobile devices is not allowed. For more information consult the official documentation.

To use the radio API first call the Radio.tune() method, which will tune into a specific radio station and returns a corresponding Radio instance. Then use Radio#getPlaylist to obtain a playlist. Playlists contain track information, including the URL to an mp3 file to stream. Note that these playlists only contain a small number of tracks, so you may have to call getPlaylist() multiple times.

Example:
	Session session = Authenticator.getMobileSession(user, password, key, secret); // authenticate user
	Radio radio = Radio.tune(Radio.RadioStation.similarArtists("Depeche Mode"), session); // tune into station
	System.out.println("name: "+ radio.getStationName()); // prints out the station name (in this case: "Depeche Mode Radio")
	Playlist playlist = radio.getPlaylist(); // retrieve the playlist
	for (Track track : playlist.getTracks()) {
		System.out.printf("%s - %s: %s%n", track.getArtist(), track.getName(), track.getLocation());
	}

Note that this API does not cover mp3 playback, it only manages tuning into radio stations and retrieving playlists and the URLs of mp3 files. For mp3 decoding and playback support you will need another third party library, for example JLayer.

Caching

The Last.fm API Terms of Service claim:
4.4
	You will implement suitable caching in accordance with the HTTP headers sent with web service responses.
	You will not make more than 5 requests per originating IP address per second, averaged over a 5 minute period,
	without prior written consent. You agree to cache similar artist and any chart data (top tracks, top artists,
	top albums) for a minimum of one week.
Therefore the bindings are capable of caching data returned by the APIs. Cache management is implemented in the net.roarsoftware.lastfm.cache package and the Caller#setCache() method. By default there is a FileSystemCache activated which will cache the Last.fm data in a directory on your file system (by default user home dir/last.fm-cache).
In addition there is an ExpirationPolicy interface which defines the expiration date for cached data if no expiration HTTP headers were sent.
If you want to cache to a Database you can use the net.roarsoftware.lastfm.cache.DatabaseCache class. It should be compatible with all standard SQL compliant databases.
Note that the API bindings do not protect you from violating against the 5-requests-per-second limit. Scheduling and optimizing your API calls so that your app complies to the TOS is in your hands.
Pending: there might be an opt-in solution for that in a future release.

Donate

If this project helped you, you are able to send a donation via PayPal or get me ("JRoar") a last.fm gift subscription, Thank You! :-)