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”


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 11 2008

Rerouting Spring Security 2 Login Page Through a Spring Controller

Tag: acegi, java, jsp, springpmularien @ 12:13 am

Interestingly, a month or so after I posted my 5 Minute Guide to Spring Security 2, a commonly asked question was asked on the Spring forums. I figured I’d address it here, because (once again in Spring/Acegi Security integration) the answer wasn’t really obvious.

Essentially, the question goes something like this:

The examples I can find using Spring Security show this “login.jsp” page. How can I pull Spring content into this page?

Typically, you might want to display data on the login page that’s provided by Spring service-layer beans, or tie into the i18n bundles you’ve configured, or tens of other possibilities.

Fortunately, this is possible with a few tweaks to your Spring configuration. In this post, I’ll assume you’ve started with the configuration I wrote up in the initial 5 Minute Guide to Spring Security.

First, as with any Spring action, you will need a controller to handle the Login page display (the form POST is handled by the Spring Security interceptor). A simple annotated controller might look like this:

/**
 * Simple mapping for login page.
 * 
 * @author Mularien
 */
@Controller
public class LoginController {
	private static Logger logger = Logger.getLogger(LoginController.class);
 
	@Autowired
	// stuff required to display header, footer, etc.
 
	@RequestMapping("/login.do")
	public void login() {
 
	}
 
	@RequestMapping("/accessDenied.do")
	public ModelAndView accessDenied() {
		return new ModelAndView("redirect:/index.do");
	}
}

Now, you can see where we’re going with this. We’ll need a corresponding “login.jsp” page in our views directory, so that the “login.do” mapping works. You’ll need to tweak your Spring Security configuration:

    <http auto-config="true" access-denied-page="/accessDenied.do">
        <intercept-url pattern="/login.do*" filters="none"/>  
        <intercept-url pattern="/app/*.do" access="ROLE_USER,ROLE_ADMIN"  />
        <intercept-url pattern="/admin/**/*.do" access="ROLE_ADMIN"  />
    	<form-login login-page="/login.do" authentication-failure-url="/login.do?login_error=1"
    	   default-target-url="/app/index.do"/>
    	<logout logout-success-url="/login.do"/>
    </http>

Note the references to “login.do” and “accessDenied.do” here – these are the mappings we set up in our login controller. Pay attention to the access rules we’ve assigned – the URL intercept for “/login.do*” has no authorization checks applied to it, this is important otherwise users won’t be able to access the login page!

Hope this helps someone! As always, your comments are appreciated.


Sep 19 2008

How Open Source is Spring?: An Analytical Investigation

Tag: java, opensource, opinion, random, springpmularien @ 8:29 am

This post is to expand on some of the thoughts I posted on the SpringSource Blog in response to Rod Johnson’s excellent description of the SpringSource business model and its commitment to development of open source software.

Now that SpringSource has shown an ability to crank out new product releases on a seemingly weekly basis, I wanted to reflect on where Spring is positioned in the Java open source community, and how open the Spring Core project is to work done by the public.

The hypothesis of my experiment occurred to me when I happened to be reviewing Spring JIRA assignments one day. I was curious whether, following the bug assignments, the majority of development on the “Spring Core” projects (including Spring MVC and what we would consider “classic Spring”) is performed solely by SpringSource employees.

I decided to go about verifying this and would like to present my findings. Note that this is a purely objective study of a particular widely used open source project, and shouldn’t be construed as an opinion on the findings.

Edit Sept 22, 2008 Please note that although the publishing of this post by freakish timing occurred less than 24 hours after the announcement by SpringSource, I want to be clear that this article was drafted and published before I was aware of this news. As such, please don’t misread this investigation as a “response” to the announcement.

Since SpringSource is obviously a private company, I determined the list of employees by consulting publicly available information sources. Anyone is welcome to refute the claims in this article.

I have no direct working relationship with anyone at SpringSource; however, to verify the facts cited in my study, I did email an advance copy of the article to Juergen Hoeller, Spring Project Lead. Juergen kindly took the time to review it and clarify a couple facts that I wasn’t able to discern through public information. Juergen has always been friendly and considerate in the dealings we’ve had through Spring JIRA or the Spring forums, and I appreciate the help!

Read on for the analysis…
Continue reading “How Open Source is Spring?: An Analytical Investigation”


Aug 29 2008

When will the SpringSource blog spam end?

Tag: java, opensource, spring, wordpresspmularien @ 4:58 am

Since I spend a lot of time working with Spring, one of the many blogs in my daily read list is the SpringSource Team Blog, both articles and comments. I have gotten really tired, however, of the constant SEO spammers hitting the SpringSource blog.

It’s unfortunate that with SpringSource’s multi-million dollar funding rounds ($15M raised this summer, and $10M previously raised), they can’t find the resources to upgrade their very dated WordPress install with one that is more spam resistant, nor has anyone from the company even responded publicly to the many calls for fixing this issue.


Aug 18 2008

FYI: Eclipse 3.4 (“Ganymede”) + Hibernate IDE = NoClassDefFoundError

Tag: eclipse, hibernate, javapmularien @ 12:36 am

A heads up in case anyone is thinking about using these together. Currently (Aug 18, 2008), the release version of Hibernate IDE (aka the Hibernate Eclipse plugin) does not work with Eclipse 3.4 (“Ganymede”) without one of 2 things:

  • Unjarring, copying, and rejarring a file from Eclipse 3.3
  • Using the Hibernate IDE Nightly Update Site

Discussion for this is covered in the Hibernate Forums and in HBX-1068 in Hibernate JIRA.

Since it’s already fixed in the nightlies, your best bet is to hit the nightly build site for the tools. If you’re afraid of the nightlies and/or the harder install process and want to pull the missing class (“org/eclipse/ui/internal/util/SWTResourceUtil”) from Eclipse 3.3, do this:

  • Copy the “org.eclipse.ui.workbench” jar from your Eclipse 3.3 install/plugins directory to a temp directory (say, c:\temp). Mine was called “org.eclipse.ui.workbench_3.3.1.M20070921-1200.jar”
  • Extract the missing class file: jar xvf org.eclipse.ui.workbench_3.3.1.M20070921-1200.jar org/eclipse/ui/internal/util/SWTResourceUtil.class
  • Copy the “org.eclipse.ui.workbench” jar from your Eclipse 3.4 install/plugins directory to the same directory. Mine was called “org.eclipse.ui.workbench_3.4.0.I20080606-1300.jar”
  • Update the JAR file: jar uvf org.eclipse.ui.workbench_3.4.0.I20080606-1300.jar org/eclipse/ui/internal/util/SWTResourceUtil.class
  • Copy the Eclipse 3.4 JAR file back to your Eclipse 3.4 install/plugins directory (overwriting the original).

That should do it! Note that this information is only correct until the next version of the Hibernate IDE tools are make into a formal release. The last release date listed on the site was April 9, 2008, so I would guess a new release would occur soon.


Next Page »