<?xml version="1.0" encoding="UTF-8"?>
<rss version="2.0"
	xmlns:content="http://purl.org/rss/1.0/modules/content/"
	xmlns:wfw="http://wellformedweb.org/CommentAPI/"
	xmlns:dc="http://purl.org/dc/elements/1.1/"
	xmlns:atom="http://www.w3.org/2005/Atom"
	xmlns:sy="http://purl.org/rss/1.0/modules/syndication/"
	xmlns:slash="http://purl.org/rss/1.0/modules/slash/"
	>

<channel>
	<title>Martin&#039;s Weekend Coding &#187; Jersey</title>
	<atom:link href="http://blog.alutam.com/tag/jersey/feed/" rel="self" type="application/rss+xml" />
	<link>http://blog.alutam.com</link>
	<description>Sharing useful tips from my &#34;weekend projects&#34;</description>
	<lastBuildDate>Sun, 02 Oct 2011 03:15:06 +0000</lastBuildDate>
	<language>en</language>
	<sy:updatePeriod>hourly</sy:updatePeriod>
	<sy:updateFrequency>1</sy:updateFrequency>
	<generator>http://wordpress.org/?v=3.2.1</generator>
		<item>
		<title>Jersey 1.9.1 Released</title>
		<link>http://blog.alutam.com/2011/09/16/jersey-1-9-1-released/#utm_source=feed&#038;utm_medium=feed&#038;utm_campaign=feed</link>
		<comments>http://blog.alutam.com/2011/09/16/jersey-1-9-1-released/#comments</comments>
		<pubDate>Fri, 16 Sep 2011 12:07:14 +0000</pubDate>
		<dc:creator>Martin</dc:creator>
				<category><![CDATA[Java]]></category>
		<category><![CDATA[REST]]></category>
		<category><![CDATA[JavaOne]]></category>
		<category><![CDATA[JAX-RS]]></category>
		<category><![CDATA[Jersey]]></category>
		<category><![CDATA[release]]></category>

		<guid isPermaLink="false">http://blog.alutam.com/?p=131</guid>
		<description><![CDATA[Over the past two weeks, I&#8217;ve been working with Pavel on finalizing and staging the bits for the hands-on-lab on OAuth, we are going to do at this year&#8217;s JavaOne. As part of that, I had to make a few more clean-ups in the Jersey OAuth client library, so we decided to make a branch [...]]]></description>
			<content:encoded><![CDATA[<p>Over the past two weeks, I&#8217;ve been working with <a href="http://blogs.oracle.com/PavelBucek/">Pavel</a> on finalizing and staging the bits for the <a href="https://oracleus.wingateweb.com/scheduler/modifySession.do?SESSION_ID=24761">hands-on-lab on OAuth</a>, we are going to do at this year&#8217;s <a href="http://www.oracle.com/javaone/index.html">JavaOne</a>. As part of that, I had to make a few more clean-ups in the <a href="http://jersey.java.net/nonav/apidocs/latest/contribs/jersey-oauth/oauth-client/index.html">Jersey OAuth client library</a>, so we decided to make a branch for 1.9.1 and make those clean-ups along with some other small fixes there. Now, 2 weeks after 1.9, we released it. This is the release we&#8217;ll be using for JavaOne and although the release cycle was so short, it does have two nice additions worth highlighting.</p>
<ul>
<li><strong>Un-/marshalling collection types</strong><br />
Until 1.9.1, JAXB un-/marshalling in Jersey worked only for Collection and List interfaces. I.e. if your resource method returned (or took as a parameter) Collection&lt;Foo&gt; or List&lt;Foo&gt; (where Foo was a JAXB bean), de-/serialization from/to XML/JSON would work, but if it returned LinkedList&lt;Foo&gt; or Set&lt;Foo&gt; or any other Collection subtype, it would not work. This is fixed in 1.9.1 and you can now return and retrieve any well-known interfaces that extend Collection (such as Set, Queue, etc.) and their implementations which have default public constructor.</li>
<li><strong>PostReplaceFilter improvements</strong><br />
<a href="http://jersey.java.net/nonav/apidocs/latest/jersey/com/sun/jersey/api/container/filter/PostReplaceFilter.html">PostReplaceFilter</a> can be used to support clients which can&#8217;t send the full range of HTTP methods. It enables converting POST requests to other methods such as PUT or DELETE. If a POST request comes with a different method specified in X-HTTP-Method-Override header, the filter will replace POST in the request with that specified method. This has been in Jersey for a while, but only supported method overriding using the X-HTTP-Method-Override header. In 1.9.1 you can now use &#8220;_method&#8221; query parameter as well, and when overriding POST to GET the filter will convert all the form parameters to query parameters. Whether both header and query parameter are looked at by the filter (or only the header or only the query parameter) is configurable. Thanks to <a href="http://java.net/jira/secure/ViewProfile.jspa?name=gk5885%40java.net">gk5885</a>, <a href="http://java.net/jira/secure/IssueNavigator.jspa?reset=true&amp;customfield_10010=ferdy_nagy%40java.net">Fredy Nagy</a> and <a href="http://java.net/jira/secure/IssueNavigator.jspa?reset=true&amp;customfield_10010=fhars%40java.net">Florian Hars</a> for sharing their views and patches.</li>
</ul>
<div>You can see the full list of changes in our <a href="http://java.net/projects/jersey/sources/svn/content/branches/jersey-1.9.1/jersey/changes.txt?rev=5399">changelog</a>. For more info on Jersey see <a href="http://jersey.java.net">http://jersey.java.net</a>.</div>
]]></content:encoded>
			<wfw:commentRss>http://blog.alutam.com/2011/09/16/jersey-1-9-1-released/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Jersey and Cross-Site Request Forgery (CSRF)</title>
		<link>http://blog.alutam.com/2011/09/14/jersey-and-cross-site-request-forgery-csrf/#utm_source=feed&#038;utm_medium=feed&#038;utm_campaign=feed</link>
		<comments>http://blog.alutam.com/2011/09/14/jersey-and-cross-site-request-forgery-csrf/#comments</comments>
		<pubDate>Tue, 13 Sep 2011 22:13:54 +0000</pubDate>
		<dc:creator>Martin</dc:creator>
				<category><![CDATA[REST]]></category>
		<category><![CDATA[CSRF]]></category>
		<category><![CDATA[Jersey]]></category>

		<guid isPermaLink="false">http://blog.alutam.com/?p=119</guid>
		<description><![CDATA[About two weeks back we released Jersey 1.9. See Jakub&#8217;s blog for more info on what&#8217;s new. One thing Jakub didn&#8217;t mention is that Jersey 1.9 also includes a new server side filter for Cross Site Request Forgery prevention. I won&#8217;t go into the details on what CSRF is &#8211; please refer to the OWASP [...]]]></description>
			<content:encoded><![CDATA[<p>About two weeks back we released <a href="http://jersey.java.net">Jersey 1.9</a>. See <a href="http://blogs.oracle.com/japod/entry/jersey_1_9_is_released">Jakub&#8217;s blog</a> for more info on what&#8217;s new. One thing Jakub didn&#8217;t mention is that Jersey 1.9 also includes a new server side filter for Cross Site Request Forgery prevention. I won&#8217;t go into the details on what CSRF is &#8211; please refer to the <a href="https://www.owasp.org/index.php/CSRF">OWASP CSRF page</a> for that. Unfortunately, the generally recommended prevention is to generate per-request or per-session tokens on the server side, which client then has to include in its subsequent requests. This is quite easy to implement and there are servlet filters for doing that, however it does require a session state to be maintained and thus is not very RESTful. I was trying to implement something that would not require a session. After some searching I found the following two papers which both suggest there is a solution which works, and is not based on sessions:</p>
<ul>
<li><a href="http://www.nsa.gov/ia/_files/support/guidelines_implementation_rest.pdf">Guidelines for Implementation of REST</a> from NSA</li>
<li><a href="http://seclab.stanford.edu/websec/csrf/csrf.pdf">Robust Defenses for Cross-Site Request Forgery</a> from Standford University</li>
</ul>
<p>The main idea is to check the presence of a custom header (agreed-upon between the server and a client &#8211; e.g. X-CSRF or X-Requested-By) in all state-changing requests coming from the client. The value of the header does not really matter. It works, because the browser would not send custom headers unless the web page makes a request using XMLHttpRequest, which only allows requests to the same site.</p>
<p>So, in Jersey 1.9 we added a server-side filter which does exactly that. You can find it here: <a href="http://java.net/projects/jersey/sources/svn/content/trunk/jersey/jersey-server/src/main/java/com/sun/jersey/api/container/filter/CsrfProtectionFilter.java?rev=5392">server-side CsrfProtectionFilter.java</a></p>
<p>And, to make it easy to build clients, a corresponding client filter (that attaches the custom header to all potentially state-changing requests) is there as well: <a href="http://java.net/projects/jersey/sources/svn/content/trunk/jersey/jersey-client/src/main/java/com/sun/jersey/api/client/filter/CsrfProtectionFilter.java?rev=5392">client-side CsrfProtectionFilter</a>.</p>
<p>This can be further extended based on the feedback &#8211; we may add a check for the Referrer header and eventually even implement the session-based solution as an available configuration option. Just let us know, if you have an opinion.</p>
]]></content:encoded>
			<wfw:commentRss>http://blog.alutam.com/2011/09/14/jersey-and-cross-site-request-forgery-csrf/feed/</wfw:commentRss>
		<slash:comments>7</slash:comments>
		</item>
		<item>
		<title>Jersey Hands-On Lab</title>
		<link>http://blog.alutam.com/2009/09/16/jersey-hands-on-lab/#utm_source=feed&#038;utm_medium=feed&#038;utm_campaign=feed</link>
		<comments>http://blog.alutam.com/2009/09/16/jersey-hands-on-lab/#comments</comments>
		<pubDate>Wed, 16 Sep 2009 19:31:49 +0000</pubDate>
		<dc:creator>Martin</dc:creator>
				<category><![CDATA[REST]]></category>
		<category><![CDATA[JavaOne]]></category>
		<category><![CDATA[JAX-RS]]></category>
		<category><![CDATA[Jersey]]></category>

		<guid isPermaLink="false">http://blog.alutam.com/?p=94</guid>
		<description><![CDATA[Earlier this year, me and Naresh created an introductory level Jersey hands-on lab for JavaOne &#8217;09. As I realized just recently, the hands-on labs had been made available for download to all SDN members (free registration) shortly after JavaOne. It may be another useful resource for you to get started with Jersey. The lab provides [...]]]></description>
			<content:encoded><![CDATA[<p>Earlier this year, me and <a href="http://blogs.sun.com/naresh/">Naresh</a> created an introductory level Jersey hands-on lab for JavaOne &#8217;09. As I realized just recently, the hands-on labs had been made available for download to all SDN members (free registration) shortly after JavaOne. It may be another useful resource for you to get started with Jersey. The lab provides detailed step-by-step instructions on how to set up your environment and then guides you through 3 exercises:</p>
<ol>
<li>Hello world! &#8211; leading you through your first JAX-RS/Jersey application, explaining the JAX-RS basics</li>
<li>Advanced JAX-RS/Jersey Features &#8211; showing how to develop a little more complex web application using JAX-RS/Jersey features such as path parameters, multiple representations for a resource, writing your own MessageBodyReader/Writer, Jersey MVC and some more</li>
<li>Using Jersey Client API &#8211; showing how to access web resources using the Client API provided by Jersey</li>
</ol>
<p>You can download the Hands-On Lab as well as get more info <a href="http://developers.sun.com/learning/javaoneonline/j1lab.jsp?lab=LAB-5542&#038;yr=2009&#038;track=1">here</a>. I&#8217;ve also added this link to our <a href="http://wikis.sun.com/display/Jersey">Jersey Wiki</a>. After you download the lab, just unzip the file and open <i>index.html</i> in <i>restwebservice</i> directory. The zip also contains solution directories for all three exercises. I hope the lab will be of help. Let me know in case you have any questions or feedback on it.</p>
]]></content:encoded>
			<wfw:commentRss>http://blog.alutam.com/2009/09/16/jersey-hands-on-lab/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Using Jersey Client OAuth Support with SmugMug</title>
		<link>http://blog.alutam.com/2009/08/10/using-jersey-client-oauth-support-with-smugmug/#utm_source=feed&#038;utm_medium=feed&#038;utm_campaign=feed</link>
		<comments>http://blog.alutam.com/2009/08/10/using-jersey-client-oauth-support-with-smugmug/#comments</comments>
		<pubDate>Sun, 09 Aug 2009 23:41:18 +0000</pubDate>
		<dc:creator>Martin</dc:creator>
				<category><![CDATA[REST]]></category>
		<category><![CDATA[JAX-RS]]></category>
		<category><![CDATA[Jersey]]></category>
		<category><![CDATA[OAuth]]></category>
		<category><![CDATA[SmugMug]]></category>

		<guid isPermaLink="false">http://blog.alutam.com/?p=6</guid>
		<description><![CDATA[Recently I decided to use SmugMug to store my photo galleries. They have an API people can use to access the features of the site programmatically and I noticed they added OAuth in the latest version. So, I thought I would give it a try and see if I can use the OAuth Support in [...]]]></description>
			<content:encoded><![CDATA[<p>Recently I decided to use <a href="http://smugmug.com">SmugMug</a> to store my photo galleries. They have an <a href="http://wiki.smugmug.net/display/SmugMug/API">API</a> people can use to access the features of the site programmatically and I noticed they added OAuth in the <a href="http://wiki.smugmug.net/display/API/Home">latest version</a>. So, I thought I would give it a try and see if I can use the <a href="http://wikis.sun.com/display/Jersey/OAuth">OAuth Support</a> in <a href="http://jersey.dev.java.net/">Jersey</a> to authorize and authenticate my client application with SmugMug. Turned out it works! Here is how to do it:</p>
<ol>
<li>First you have to request an API Key from SmugMug. You can do it <a href="http://www.smugmug.com/hack/apikeys">here</a>.</li>
<li>They probably approve these automatically &#8211; mine was approved immediately and I got the key along with a &#8220;secret&#8221; (another number used as a consumer secret key in OAuth).</li>
<li>Now you can create a new maven project, adding jersey-client, jersey-json, oauth-signature and oauth-client as the dependencies &#8211; here is a pom file snippet:
<pre class="brush:xml">    &lt;dependency&gt;
      &lt;groupId&gt;com.sun.jersey&lt;/groupId&gt;
      &lt;artifactId&gt;jersey-client&lt;/artifactId&gt;
      &lt;version&gt;1.1.2-ea-SNAPSHOT&lt;/version&gt;
    &lt;/dependency&gt;
    &lt;dependency&gt;
      &lt;groupId&gt;com.sun.jersey&lt;/groupId&gt;
      &lt;artifactId&gt;jersey-json&lt;/artifactId&gt;
      &lt;version&gt;1.1.2-ea-SNAPSHOT&lt;/version&gt;
    &lt;/dependency&gt;
    &lt;dependency&gt;
      &lt;groupId&gt;com.sun.jersey.oauth&lt;/groupId&gt;
      &lt;artifactId&gt;oauth-signature&lt;/artifactId&gt;
      &lt;version&gt;1.1.2-ea-SNAPSHOT&lt;/version&gt;
    &lt;/dependency&gt;
    &lt;dependency&gt;
      &lt;groupId&gt;com.sun.jersey.oauth&lt;/groupId&gt;
      &lt;artifactId&gt;oauth-client&lt;/artifactId&gt;
      &lt;version&gt;1.1.2-ea-SNAPSHOT&lt;/version&gt;
    &lt;/dependency&gt;</pre>
</li>
<li>The first thing you need to do according to the <a href="http://oauth.net/core/1.0#anchor9">OAuth spec</a> is to get an unauthorized request token from the provider (SmugMug in this case). You will need the key and the secret you obtained in step 1. The <a href="http://wiki.smugmug.net/display/API/API+1.2.2">SmugMug API</a> provides a method for requesting these tokens &#8211; <a href="http://wiki.smugmug.net/display/API/show+1.2.2?method=smugmug.auth.getRequestToken">getRequestToken</a>. Here is an example of how you can call this method using Jersey client API and the Jersey OAuth library:
<pre class="brush:java">public class App {
    // base URL for the API calls
    private static final String URL_API =
            "http://api.smugmug.com/services/api/json/1.2.2/";

    private static final String CONSUMER_SECRET = /* your API Key */;
    private static final String CONSUMER_KEY = /* your secret key */;

    public static void main( String[] args ) throws Exception {
        // Create a Jersey client
        Client client = Client.create();

        // Create a resource to be used to make SmugMug API calls
        WebResource resource = client.resource(URL_API).
                queryParam("method", "smugmug.auth.getRequestToken");

        // Set the OAuth parameters
        OAuthSecrets secrets = new OAuthSecrets().consumerSecret(CONSUMER_SECRET);
        OAuthParameters params = new OAuthParameters().consumerKey(CONSUMER_KEY).
                signatureMethod("HMAC-SHA1").version("1.0");
        // Create the OAuth client filter
        OAuthClientFilter filter =
                new OAuthClientFilter(client.getProviders(), params, secrets);
        // Add the filter to the resource
        resource.addFilter(filter);

        // make the request and print out the result
        System.out.println(resource.get(String.class));
    }
}</pre>
</li>
<li>The next step in the OAuth flow is to obtain user authorization. To do this, the user needs to be redirected to the SmugMug authorization URL &#8211; http://api.smugmug.com/services/oauth/authorize.mg (see the SmugMug Specifics section on <a href="http://wiki.smugmug.net/display/API/OAuth">their OAuth page</a>), passing the request token ID as a query parameter (you need to extract that from the getRequestToken method&#8217;s response). At this URL the user will log in and grant the requested access to your application. Here is how I did it:
<pre class="brush:java">public class App {
    // base URL for the API calls
    private static final String URL_API =
            "http://api.smugmug.com/services/api/json/1.2.2/";
    // authorization URL
    private static final String URL_AUTHORIZE =
            "http://api.smugmug.com/services/oauth/authorize.mg";

    private static final String CONSUMER_SECRET = /* your API Key */;
    private static final String CONSUMER_KEY = /* your secret key */;

    public static void main( String[] args ) throws Exception {
        // Create a Jersey client
        Client client = Client.create();

        // Create a resource to be used to make SmugMug API calls
        WebResource resource = client.resource(URL_API).
                queryParam("method", "smugmug.auth.getRequestToken");

        // Set the OAuth parameters
        OAuthSecrets secrets = new OAuthSecrets().consumerSecret(CONSUMER_SECRET);
        OAuthParameters params = new OAuthParameters().consumerKey(CONSUMER_KEY).
                signatureMethod("HMAC-SHA1").version("1.0");
        // Create the OAuth client filter
        OAuthClientFilter filter =
                new OAuthClientFilter(client.getProviders(), params, secrets);
        // Add the filter to the resource
        resource.addFilter(filter);

        // make the request
        RequestTokenResponse response = resource.get(RequestTokenResponse.class);
        // check the status
        if (!"ok".equals(response.stat)) {
            System.out.println("getRequestToken failed with response: " +
                    response.toString());
            return;
        }

        // open the browser at the authorization URL to let user authorize
        Desktop.getDesktop().browse(new URI(URL_AUTHORIZE +
                "?oauth_token=" + response.auth.token.id));
    }
}</pre>
<p>The RequestTokenResponse class representing getRequestToken method&#8217;s response looks as follows:</p>
<pre class="brush:java">@XmlRootElement
public class RequestTokenResponse {
    public String stat;
    public String method;
    public @XmlElement(name="Auth") AuthElement auth;

    public static class AuthElement {
        public @XmlElement(name="Token") TokenElement token;

        @Override
        public String toString() {
            return "token=(" + (token == null ? "null" : token.toString()) + ")";
        }
    }

    public static class TokenElement {
        public String id;
        public @XmlElement(name="Secret") String secret;

        @Override
        public String toString() {
            return "id=" + id + " secret=" + secret;
        }
    }

    @Override
    public String toString() {
        return "stat=" + stat + " method=" + method + " auth=(" +
                (auth == null ? "null" : auth.toString()) + ")";
    }
}</pre>
</li>
<li>After the user authenticates and grants access for your application, the last step is to request an access token &#8211; that will then enable your application to make subsequent API calls. You can implement this by adding the following lines at the end of the main method from the previous bullet:
<pre class="brush:java">        // wait for the user to authenticate
        System.out.println("Once you authenticated with SmugMug and granted" +
                "permissions to this app, press Enter to continue.");
        System.in.read();

        // make an API call to request the access token
        resource = client.resource(URL_API).queryParam("method",
                "smugmug.auth.getAccessToken");
        // use the request token id and secret to create the request
        secrets.setTokenSecret(response.auth.token.secret);
        params.token(response.auth.token.id);
        resource.addFilter(filter);
        // make the request and print out the result
        System.out.println(resource.get(String.class));</pre>
</li>
<li>That&#8217;s it! Now your application can store the access token and use it to perform actions on behalf of the user.</li>
</ol>
]]></content:encoded>
			<wfw:commentRss>http://blog.alutam.com/2009/08/10/using-jersey-client-oauth-support-with-smugmug/feed/</wfw:commentRss>
		<slash:comments>11</slash:comments>
		</item>
	</channel>
</rss>

