Dec 01 2009

[Tutorial] URL Shortening in Java using bit.ly

Tag: bitly, java, tinyurl, tutorial, twitterpmularien @ 12:19 am

A while ago, I had written up a tutorial on accessing the TinyURL API from Java. I was recently playing with the bit.ly API and decided to write up a quick tutorial on generating bit.ly URLs from Java.

Why bit.ly?

Since Twitter switched from TinyURL to bit.ly, I decided I’d take a look at it. Personally, I love the stats tracking features of bit.ly, and the ability to store history, and parse the results of the API call in XML or JSON (I use XML in this tutorial).

What you Need

First, you’ll need a bit.ly account in order to be assigned an API key. Your API key will show up under the “API Key” heading in your bit.ly account page.

You’ll also need the Apache Commons HTTP (3.x) library and a recent version of Java.

Calling bit.ly’s REST API

bit.ly’s API is slightly more complex than TinyURL’s, but only very slightly so. Here’s an example of calling the API:

		HttpClient httpclient = new HttpClient();
		HttpMethod method = new GetMethod("http://api.bit.ly/shorten");
		method.setQueryString(
				new NameValuePair[]{
						new NameValuePair("longUrl","http://www.amazon.com/),
						new NameValuePair("version","2.0.1"),
						new NameValuePair("login","mybitlylogin"),
						new NameValuePair("apiKey","R_abcdefmyguid"),
						new NameValuePair("format","xml"),
						new NameValuePair("history","1")
						}
				);
		httpclient.executeMethod(method);
		String responseXml = method.getResponseBodyAsString();

Obviously, you would substitute “login” with your bit.ly login name, and “apiKey” with your API key. This will result in the “longUrl” you pass being returned in an XML structure that looks like the following:

<bitly>
	<errorCode>0</errorCode>
	<errorMessage></errorMessage>
	<results>
		<nodeKeyVal>
			<userHash>JTKXY</userHash>
			<shortKeywordUrl></shortKeywordUrl>
			<hash>1L2iWb</hash>
			<nodeKey><![CDATA[http://www.amazon.com/]]></nodeKey>
			<shortUrl>http://bit.ly/JTKXY</shortUrl>
		</nodeKeyVal>
	</results>
	<statusCode>OK</statusCode>
</bitly>

Processing the Returned XML

To do a “dumb” processing of the returned XML, we can simply do something like the following (depending on what XML APIs you have available, you can get much more sophisticated :) ):

		String retVal = null;
		if(responseXml != null) {
			// parse the XML
			DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
			DocumentBuilder db = dbf.newDocumentBuilder();
			StringReader st = new StringReader(responseXml);
			Document d = db.parse(new InputSource(st));
			NodeList nl = d.getElementsByTagName("shortUrl");
			if(nl != null) {
				Node n = nl.item(0);
				retVal = n.getTextContent();
			}
		}
 
		return retVal;

It appears there is also a very early stage project at Google Code called “bitlyj”, which seems to offer a very straightforward API. I’ll try to post a tutorial for this soon, in the meantime, feel free to check it out here: bitlyj at Google Code. As always, feedback is appreciated!


Aug 13 2009

[Tutorial] Amazon SOAP Product Advertising API from Java – Including Signing of Requests with WS-Security

Tag: amazon, axis, development, java, opensource, tutorial, webservicespmularien @ 11:10 pm

Amazon has made a lot of affiliates unhappy with their updates to the Product Advertising API (ex-Affiliate API). I first covered invoking this API a couple years ago – my, have things changed since then.

On August 15, 2009, Amazon will be requiring all affiliates using the Product Advertising API to digitally sign their API requests. Previously, calls to the web service required only the AWS Access Key ID. Now, affiliates are required to sign the requests with a private key (and supply the AWS Access Key ID!) in order for the request to be accepted.

Unfortunately, many affiliates feel that Amazon has really botched this transition. Very little documentation is available on how to sign requests, and the majority of the responses in the affiliate community forum are unanswered by Amazon staff. Additional bad news for Java users is that Amazon has apparently dropped their Java library (Amazon A2S), which used to nicely abstract the ugliness of making requests to the web service.

In this tutorial, we’ll implement an Amazon Product Advertising API client using Apache Axis2 1.5, invoking the API’s SOAP methods. We’ll sign the requests using a PKCS 12 (.p12) file. Get some popcorn – this is a very long and involved process :( Continue reading “[Tutorial] Amazon SOAP Product Advertising API from Java – Including Signing of Requests with WS-Security”


Jun 23 2009

[Quick Tip] Printing out all matches in an Ant fileset

Tag: ant, java, quicktippmularien @ 10:17 pm

This is one of those things that’s so handy, I can’t believe it hasn’t been posted before. I found a 2006 post from JavaLobby, where R.J. Lorimer writes about how to print out a classpath.

Also useful, but the particular use case I ran into was – one of our build scripts uses a fileset to select incrementally more complex test suites to run. Developers can do a quick check locally with the “short tests” – however, since these are specified as a fileset, it’s hard to know exactly what will run. I wanted to create a simple ant task to take the fileset, and print out everything that matched.
Continue reading “[Quick Tip] Printing out all matches in an Ant fileset”


Jun 01 2009

5 Common Log4J Mistakes

Tag: development, java, learning, log4j, opensourcepmularien @ 10:22 pm

I’ve seen these antipatterns over and over again, and I thought it was time to write about them to help any folks who are new to Log4J out there. Senior developers – please share this with your junior peers and save yourself the pain of refactoring later! I’m interested in common mistakes or points of confusion that you’ve seen as well.

Read on to get a quick tutorial, or reference to point your developers at…

Continue reading “5 Common Log4J Mistakes”


May 21 2009

Flash Player Settings Manager

Tag: flash, security, webpmularien @ 8:00 pm

For those who don’t already have this bookmarked, you can use the Flash Player settings manager movie on the Adobe Support Web site to adjust the following:

  • Website privacy and storage settings (did you know that Flash keeps a list of all sites you’ve visited with Flash movies?)
  • Global security settings (setting trusted locations, etc.)

Also, remember there’s a separate global security settings panel for content creators (i.e. running Flash in debug mode). Personally, it seems kind of odd that Flash itself doesn’t have this functionality within the player, but it is what it is.

Basically, I’m just writing this so I don’t forget where it is next time I’m doing Flash development.


Mar 24 2009

SourceForge-hosted PDFCreator Trojan/Toolbar Warning

Tag: opensource, opinion, randompmularien @ 11:46 pm

I decided to post this as a public safety announcement, since I (surprisingly) didn’t see this blogged elsewhere. I have, for many years now, used the free/open source PDFCreator software for simple PDF generation and testing.

I recently updated to the most recent version (0.9.7) of the software (now hosted at pdfforge.org), and have made an interesting discovery.

The software is bundled with a browser toolbar component that has behavior which I would consider malware or trojan-like behavior. The notable difference is that it redirects certain types of browser traffic to www.searchsettings.com, which is a linkbait/parking-type site.

In Firefox, I noticed an extension called “Search Settings 1.2″ which, once removed, killed this behavior. After more research, I saw that IE had 2 Add-Ins installed (these were also removed). I did some more digging, and that’s when things got interesting.

There is a SourceForge Bug 2607106 “Remove trojan from download!” filed against this project. There’s the report at SiteAdvisor on pdfforge.org hosting this malware. There’s the post from an angry user on the pdfforge.org message boards.

To clarify, there are other “free” PDF creation projects that are questionable at best. However, I always took PDFCreator (sf.net) as a legitimate open source project.

The PDFCreator Toolbar is apparently implemented using “mybrowserbar”. As per their terms of service, they indicate:

f) modify your Microsoft Internet Explorer and/or Mozilla Firefox browser settings for the default search engine, address bar search, “DNS error” page, “404 error” page, and new tab page to facilitate more informative responses as determined by The Toolbar;

mybrowserbar.com “Company Information” redirects to www.spigot.com, which claims to be “Coming in March 2009″. spigot.com is a proxied domain, so there’s no further information available.

I downloaded and investigated the source tarball for the PDFCreator project, and the source of the browser toolbar installer is nowhere to be found (indeed, the .exe included with the installer isn’t present). There’s a response from Philip, one of the developers, in the pdfforge.org forum which sheds a little light on the browser toolbar. I completely empathize with his desire to make some money from his open source work; however, I’d disagree that this is an appropriate approach, and at the very least, the toolbar install option should be more up-front about it.

It’s unfortunate to see a long-time, responsible open source project act this way, and I do hope it’s an honest mistake. I wanted to give people the heads-up who may not be aware of this.


Feb 27 2009

Quote of the Day: for Software Architects

Tag: architecture, highlevel, opinion, randompmularien @ 8:37 am

Conveying a significant point about software architecture in 300 words is a challenge, particularly if those 300 words need to come from a software architect. ;-)Barry Hawkins

Seen at TheServerSide. Read more architecture goodness at 97 Things. Which of these precepts do you like? Which have you heard before from architects or teammates?


Dec 04 2008

[Tutorial] Accessing the TinyURL “API” from Java

Tag: apache, httpclient, java, tinyurl, tutorial, web, webservicespmularien @ 10:13 pm

TinyURL is a service that has been around for a while, but recently regained popularity due to its widespread use on Twitter.

Recently, I poked around and wrote up a simple Java method to, given a URL (TinyURL supports only GET requests), generate a TinyURL from it in Java. This is really the only “API” supported by the TinyURL service, but it’s a handy one!

You’ll need Apache HttpClient 3.1 for this.

Without further ado, here’s the code:

import org.apache.commons.httpclient.HttpClient;
import org.apache.commons.httpclient.HttpException;
import org.apache.commons.httpclient.HttpMethod;
import org.apache.commons.httpclient.NameValuePair;
import org.apache.commons.httpclient.methods.GetMethod;
 
public abstract class TinyURLUtils {
	public static String getTinyUrl(String fullUrl) throws HttpException, IOException {
		HttpClient httpclient = new HttpClient();
 
		// Prepare a request object
		HttpMethod method = new GetMethod("http://tinyurl.com/api-create.php"); 
		method.setQueryString(new NameValuePair[]{new NameValuePair("url",fullUrl)});
		httpclient.executeMethod(method);
		String tinyUrl = method.getResponseBodyAsString();
		method.releaseConnection();
		return tinyUrl;
	}
}

Then you’d call the method as follows:

String tinyUrl = TinyURLUtils.getTinyUrl("http://www.mularien.com/blog/");
System.out.println(tinyUrl); // --> http://tinyurl.com/5cporq

You’re welcome to use / improve this code in any way (obviously, I didn’t consider or care about proper exception handling), ideally linking to my blog as the source.

Enjoy!

Note that this makes an HTTP request directly, so this will require some modification if you’re making the call from behind a proxy server. If there’s a need, I can post a follow-up entry on how to set up a proxy server with Apache HTTP Client.


Nov 19 2008

[Tutorial] Twittering from Java with Twitter4J

Tag: java, tutorial, twitterpmularien @ 7:18 am

Really, this is so easy it’s almost not worthy of a blog post. Twitter4J is a tiny library wrapping interaction with Twitter APIs.

Creating a new tweet is as simple as:

	    Twitter twitter = new Twitter("username","password");
	    Status status = twitter.update(title);

The Twitter4J page has a series of simple examples covering timelines and direct messages. Great job and thanks to Yusuke Yamamoto, the author.


Nov 19 2008

Corporate Blog Post: Building a Collaborative Enterprise: Twitter (Part 1)

Tag: corporate, enterprise, opinion, twitter, webpmularien @ 7:16 am

Cross-posting in case readers here are interested.

Building a Collaborative Enterprise: Twitter (Part 1)


Next Page »