<?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>Coffee to go</title>
	<atom:link href="http://waqassiddiqi.net/blog/feed/" rel="self" type="application/rss+xml" />
	<link>http://waqassiddiqi.net/blog</link>
	<description>var thisBlog = getGlobalContext().buildFromTemplate(PERSONAL &#124; PROGRAMMING &#124; RANDOM_THOUGHTS);</description>
	<lastBuildDate>Sun, 02 Dec 2012 05:56:55 +0000</lastBuildDate>
	<language>en</language>
	<sy:updatePeriod>hourly</sy:updatePeriod>
	<sy:updateFrequency>1</sy:updateFrequency>
	<generator>http://wordpress.org/?v=3.3.1</generator>
		<item>
		<title>android &#8211; Renaming output APK when building using ANT</title>
		<link>http://waqassiddiqi.net/blog/2012/12/02/android-renaming-output-apk-when-building-using-ant/</link>
		<comments>http://waqassiddiqi.net/blog/2012/12/02/android-renaming-output-apk-when-building-using-ant/#comments</comments>
		<pubDate>Sun, 02 Dec 2012 05:56:55 +0000</pubDate>
		<dc:creator>admin</dc:creator>
				<category><![CDATA[Uncategorized]]></category>
		<category><![CDATA[android]]></category>
		<category><![CDATA[ant]]></category>
		<category><![CDATA[java]]></category>
		<category><![CDATA[xml]]></category>

		<guid isPermaLink="false">http://waqassiddiqi.net/blog/?p=241</guid>
		<description><![CDATA[By default when using ant build file generated by Android to build release package, it names android_rules-release.apk to final output APK file. In order to change the name to a dynamic file name i.e. either provided as a property value on command line or specifying a property in .properties file, we can use additional ant [...]]]></description>
			<content:encoded><![CDATA[<p>By default when using ant build file generated by Android to build release package, it names android_rules-release.apk to final output APK file.<br />
In order to change the name to a dynamic file name i.e. either provided as a property value on command line or specifying a property in .properties file, we can use additional <strong>ant task</strong>, make it dependant on <strong>release</strong> task and then rename the output APK file using <strong>&lt;copy file /&gt;</strong> task.</p>
<p>For example:</p>
<pre class="brush: xml; title: ; notranslate">
&lt;target name=&quot;deploy&quot; depends=&quot;release&quot;&gt;
	&lt;copy file=&quot;${out.dir}/android_rules-release.apk&quot; tofile=&quot;${out.dir}/${appname}.apk&quot; overwrite=&quot;true&quot;/&gt;
&lt;/target&gt;
</pre>
<p>Now from command prompt run:<br />
<code><br />
ant deploy -Dappname=MyApp<br />
</code></p>
<p>And on successful build it will generate <strong>MyApp.APK</strong> in bin/ folder</p>

				<!-- Social Sharing Toolkit v2.0.4 | http://www.marijnrongen.com/wordpress-plugins/social_sharing_toolkit/ -->
				<div class="mr_social_sharing_wrapper"><span class="mr_social_sharing_top"><iframe src="https://www.facebook.com/plugins/like.php?locale=en_US&amp;href=http%3A%2F%2Fwaqassiddiqi.net%2Fblog%2F2012%2F12%2F02%2Fandroid-renaming-output-apk-when-building-using-ant%2F&amp;layout=standard&amp;show_faces=false&amp;width=51px&amp;height=24px" scrolling="no" frameborder="0" style="border:none; overflow:hidden; width:51px; height:24px;" allowTransparency="true"></iframe></span><span class="mr_social_sharing_top"><a href="http://twitter.com/share?url=http%3A%2F%2Fwaqassiddiqi.net%2Fblog%2F2012%2F12%2F02%2Fandroid-renaming-output-apk-when-building-using-ant%2F&amp;text=android+%E2%80%93+Renaming+output+APK+when+building+using+ANT&amp;via=waqas_siddiqi" target="_blank" class="mr_social_sharing_popup_link"><img src="http://waqassiddiqi.net/blog/wp-content/plugins/social-sharing-toolkit/images/buttons/twitter.png" alt="Share on Twitter" title="Share on Twitter"/></a></span><span class="mr_social_sharing_top"><g:plusone size="medium" count="false" href="http://waqassiddiqi.net/blog/2012/12/02/android-renaming-output-apk-when-building-using-ant/"></g:plusone></span><span class="mr_social_sharing_top"><script type="IN/Share" data-url="http://waqassiddiqi.net/blog/2012/12/02/android-renaming-output-apk-when-building-using-ant/"></script></span></div>]]></content:encoded>
			<wfw:commentRss>http://waqassiddiqi.net/blog/2012/12/02/android-renaming-output-apk-when-building-using-ant/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>MongoDB: Changing a field type from String to Array</title>
		<link>http://waqassiddiqi.net/blog/2012/10/28/mongodb-changing-a-field-type-from-string-to-array/</link>
		<comments>http://waqassiddiqi.net/blog/2012/10/28/mongodb-changing-a-field-type-from-string-to-array/#comments</comments>
		<pubDate>Sun, 28 Oct 2012 07:35:38 +0000</pubDate>
		<dc:creator>admin</dc:creator>
				<category><![CDATA[Uncategorized]]></category>
		<category><![CDATA[mongodb nosql]]></category>

		<guid isPermaLink="false">http://waqassiddiqi.net/blog/?p=224</guid>
		<description><![CDATA[In order to change the field&#8217;s data type, first retrieve the document using the correct $type value (the possible values of $type can be found here: http://www.mongodb.org/display/DOCS/Advanced+Queries#AdvancedQueries-%24type), cast the field to new data type and then save the document again. Below code snippet changes the String data type (notice $type : 2, where 2 indicates [...]]]></description>
			<content:encoded><![CDATA[<p>In order to change the field&#8217;s data type, first retrieve the document using the correct $type value (the possible values of $type can be found here: http://www.mongodb.org/display/DOCS/Advanced+Queries#AdvancedQueries-%24type), cast the field to new data type and then save the document again.</p>
<p>Below code snippet changes the String data type (notice $type : 2, where 2 indicates the category fields containing data of type String)  to an array of String:</p>
<pre class="brush: jscript; title: ; notranslate">
db.collection.find( { &quot;category&quot; : { $type : 2 } } ).forEach( function (x) {
    x.category = [ x.category];
    db.collection.save(x);
});
</pre>

				<!-- Social Sharing Toolkit v2.0.4 | http://www.marijnrongen.com/wordpress-plugins/social_sharing_toolkit/ -->
				<div class="mr_social_sharing_wrapper"><span class="mr_social_sharing_top"><iframe src="https://www.facebook.com/plugins/like.php?locale=en_US&amp;href=http%3A%2F%2Fwaqassiddiqi.net%2Fblog%2F2012%2F10%2F28%2Fmongodb-changing-a-field-type-from-string-to-array%2F&amp;layout=standard&amp;show_faces=false&amp;width=51px&amp;height=24px" scrolling="no" frameborder="0" style="border:none; overflow:hidden; width:51px; height:24px;" allowTransparency="true"></iframe></span><span class="mr_social_sharing_top"><a href="http://twitter.com/share?url=http%3A%2F%2Fwaqassiddiqi.net%2Fblog%2F2012%2F10%2F28%2Fmongodb-changing-a-field-type-from-string-to-array%2F&amp;text=MongoDB%3A+Changing+a+field+type+from+String+to+Array&amp;via=waqas_siddiqi" target="_blank" class="mr_social_sharing_popup_link"><img src="http://waqassiddiqi.net/blog/wp-content/plugins/social-sharing-toolkit/images/buttons/twitter.png" alt="Share on Twitter" title="Share on Twitter"/></a></span><span class="mr_social_sharing_top"><g:plusone size="medium" count="false" href="http://waqassiddiqi.net/blog/2012/10/28/mongodb-changing-a-field-type-from-string-to-array/"></g:plusone></span><span class="mr_social_sharing_top"><script type="IN/Share" data-url="http://waqassiddiqi.net/blog/2012/10/28/mongodb-changing-a-field-type-from-string-to-array/"></script></span></div>]]></content:encoded>
			<wfw:commentRss>http://waqassiddiqi.net/blog/2012/10/28/mongodb-changing-a-field-type-from-string-to-array/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Facebook android sdk, invalid_key &amp; key store alias</title>
		<link>http://waqassiddiqi.net/blog/2012/07/16/facebook-android-sdk-invalid_key-key-store-alias/</link>
		<comments>http://waqassiddiqi.net/blog/2012/07/16/facebook-android-sdk-invalid_key-key-store-alias/#comments</comments>
		<pubDate>Mon, 16 Jul 2012 06:29:36 +0000</pubDate>
		<dc:creator>admin</dc:creator>
				<category><![CDATA[Uncategorized]]></category>
		<category><![CDATA[android]]></category>
		<category><![CDATA[facebook-sdk]]></category>

		<guid isPermaLink="false">http://waqassiddiqi.net/blog/?p=217</guid>
		<description><![CDATA[If you are getting this error &#8216;invalid_key: Android key mismatch. Your key &#8220;xxxxxxxxxxxxxx&#8221; does not match the allowed keys specified in your application settings&#8217; then it clearly means that there is something wrong either with the key you generated or the key you have listed in facebook application page. Although, the error description is very [...]]]></description>
			<content:encoded><![CDATA[<p>If you are getting this error &#8216;invalid_key: Android key mismatch. Your key &#8220;xxxxxxxxxxxxxx&#8221; does not match the allowed keys specified in your application settings&#8217; then it clearly means that there is something wrong either with the key you generated or the key you have listed in facebook application page.</p>
<p>Although, the error description is very clear and straight forward but it took me some good amount of time to discover the actual cause. In my case, I was using wrong key store alias for generating the key, resulting in key mismatch when application is executed. So if you also have forgotten the key alias then there this command which returns details of a key in key store:<br />
<code><br />
C:\Users\Waqas>keytool -list -v -keystore c:\path-to-keystore\key.store<br />
</code><br />
enter the password if required and if all goes well you get&#8217;ll something like this:<br />
<code><br />
Keystore type: JKS<br />
Keystore provider: SUN</p>
<p>Your keystore contains 1 entry</p>
<p><strong>Alias name: sample-app</strong><br />
Creation date: May 13, 2012<br />
Entry type: PrivateKeyEntry<br />
Certificate chain length: 1<br />
Certificate[1]:<br />
Owner: CN=Waqas Hussain Siddiqui, C=PK<br />
Issuer: CN=Waqas Hussain Siddiqui, C=PK<br />
Serial number: 4faf9730<br />
Valid from: Sun May 13 16:12:48 PKT 2012 until: Tue May 06 16:12:48 PKT 2042<br />
Certificate fingerprints:<br />
         MD5:  00:00:00:00:00:00:00:76:52:27:42:D3:72:96:84<br />
         SHA1: BA:BA:EF:XX:XX:XX:8B:0A:94:1D:E7:XX:B5:72:AA:59:88:XX:F7:XX<br />
         Signature algorithm name: SHA1withRSA<br />
         Version: 3</p>
<p>*******************************************<br />
*******************************************<br />
</code></p>

				<!-- Social Sharing Toolkit v2.0.4 | http://www.marijnrongen.com/wordpress-plugins/social_sharing_toolkit/ -->
				<div class="mr_social_sharing_wrapper"><span class="mr_social_sharing_top"><iframe src="https://www.facebook.com/plugins/like.php?locale=en_US&amp;href=http%3A%2F%2Fwaqassiddiqi.net%2Fblog%2F2012%2F07%2F16%2Ffacebook-android-sdk-invalid_key-key-store-alias%2F&amp;layout=standard&amp;show_faces=false&amp;width=51px&amp;height=24px" scrolling="no" frameborder="0" style="border:none; overflow:hidden; width:51px; height:24px;" allowTransparency="true"></iframe></span><span class="mr_social_sharing_top"><a href="http://twitter.com/share?url=http%3A%2F%2Fwaqassiddiqi.net%2Fblog%2F2012%2F07%2F16%2Ffacebook-android-sdk-invalid_key-key-store-alias%2F&amp;text=Facebook+android+sdk%2C+invalid_key+%26+key+store+alias&amp;via=waqas_siddiqi" target="_blank" class="mr_social_sharing_popup_link"><img src="http://waqassiddiqi.net/blog/wp-content/plugins/social-sharing-toolkit/images/buttons/twitter.png" alt="Share on Twitter" title="Share on Twitter"/></a></span><span class="mr_social_sharing_top"><g:plusone size="medium" count="false" href="http://waqassiddiqi.net/blog/2012/07/16/facebook-android-sdk-invalid_key-key-store-alias/"></g:plusone></span><span class="mr_social_sharing_top"><script type="IN/Share" data-url="http://waqassiddiqi.net/blog/2012/07/16/facebook-android-sdk-invalid_key-key-store-alias/"></script></span></div>]]></content:encoded>
			<wfw:commentRss>http://waqassiddiqi.net/blog/2012/07/16/facebook-android-sdk-invalid_key-key-store-alias/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>node.js &amp; Error: listen EACCES</title>
		<link>http://waqassiddiqi.net/blog/2012/04/27/node-js-error-listen-eacces/</link>
		<comments>http://waqassiddiqi.net/blog/2012/04/27/node-js-error-listen-eacces/#comments</comments>
		<pubDate>Thu, 26 Apr 2012 19:31:24 +0000</pubDate>
		<dc:creator>admin</dc:creator>
				<category><![CDATA[Uncategorized]]></category>
		<category><![CDATA[node.js]]></category>

		<guid isPermaLink="false">http://waqassiddiqi.net/blog/?p=209</guid>
		<description><![CDATA[For one of my own &#8216;technology venture&#8217; I have recently started getting my hand dirty with node.js and mongodb- I followed a great step by step blog post (whose link has got been missing, sorry) about setting up node.js and mongodb on amazon ec2 server and luckily it went smooth and I was able to [...]]]></description>
			<content:encoded><![CDATA[<p>For one of my own &#8216;technology venture&#8217; I have recently started getting my hand dirty with node.js and mongodb- I followed a great step by step blog post (whose link has got been missing, sorry) about setting up node.js and mongodb on amazon ec2 server and luckily it went smooth and I was able to run node.js web server at port &#8217;80&#8242;-</p>
<p>But after couple of days when i resumed from where I stopped last time, did some changes in my webserver to make it more useful rather printing &#8216;Welcome&#8217; message, when I tried running following command</p>
<pre class="brush: jscript; title: ; notranslate">
node my_server.js
</pre>
<p>It always ended up with following exception:</p>
<pre class="brush: jscript; title: ; notranslate">
node.js:201
        throw e; // process.nextTick error, or 'error' event on first tick
              ^
Error: listen EACCES
    at errnoException (net.js:642:11)
    at Array.0 (net.js:728:28)
    at EventEmitter._tickCallback (node.js:192:40)
</pre>
<p>I banged my head quite a while, try changes bits here and there but nothing worked out- so i decided to google it and as always found a similar post and solution posted on StackOverflow- so basically it turned out that <strong>Error: listen EACCES</strong> occurs when user doesn&#8217;t have enough rights to start web server on certain ports- and obviously my ec2-user doesn&#8217;t have permission to start server on port &#8217;80&#8242;. So for solving this all i did was gave the appropiate rights to logged-in user and &#8230; happy ending&#8230;</p>

				<!-- Social Sharing Toolkit v2.0.4 | http://www.marijnrongen.com/wordpress-plugins/social_sharing_toolkit/ -->
				<div class="mr_social_sharing_wrapper"><span class="mr_social_sharing_top"><iframe src="https://www.facebook.com/plugins/like.php?locale=en_US&amp;href=http%3A%2F%2Fwaqassiddiqi.net%2Fblog%2F2012%2F04%2F27%2Fnode-js-error-listen-eacces%2F&amp;layout=standard&amp;show_faces=false&amp;width=51px&amp;height=24px" scrolling="no" frameborder="0" style="border:none; overflow:hidden; width:51px; height:24px;" allowTransparency="true"></iframe></span><span class="mr_social_sharing_top"><a href="http://twitter.com/share?url=http%3A%2F%2Fwaqassiddiqi.net%2Fblog%2F2012%2F04%2F27%2Fnode-js-error-listen-eacces%2F&amp;text=node.js+%26+Error%3A+listen+EACCES&amp;via=waqas_siddiqi" target="_blank" class="mr_social_sharing_popup_link"><img src="http://waqassiddiqi.net/blog/wp-content/plugins/social-sharing-toolkit/images/buttons/twitter.png" alt="Share on Twitter" title="Share on Twitter"/></a></span><span class="mr_social_sharing_top"><g:plusone size="medium" count="false" href="http://waqassiddiqi.net/blog/2012/04/27/node-js-error-listen-eacces/"></g:plusone></span><span class="mr_social_sharing_top"><script type="IN/Share" data-url="http://waqassiddiqi.net/blog/2012/04/27/node-js-error-listen-eacces/"></script></span></div>]]></content:encoded>
			<wfw:commentRss>http://waqassiddiqi.net/blog/2012/04/27/node-js-error-listen-eacces/feed/</wfw:commentRss>
		<slash:comments>4</slash:comments>
		</item>
		<item>
		<title>Getting (Reddit) authentication cookie and then using it &#8211; Apache HttpClient</title>
		<link>http://waqassiddiqi.net/blog/2012/02/29/getting-reddit-authentication-cookie-and-then-using-it-apache-httpclient/</link>
		<comments>http://waqassiddiqi.net/blog/2012/02/29/getting-reddit-authentication-cookie-and-then-using-it-apache-httpclient/#comments</comments>
		<pubDate>Wed, 29 Feb 2012 16:43:17 +0000</pubDate>
		<dc:creator>admin</dc:creator>
				<category><![CDATA[Uncategorized]]></category>

		<guid isPermaLink="false">http://waqassiddiqi.net/blog/?p=185</guid>
		<description><![CDATA[Recently I was working on Java application to scrap Reddit data using their api, although performing read-only operations (such as reading listing data) doesn&#8217;t require authentication but after reading a comment on StackOverflow I decided to use send authenticated request even if it isn&#8217;t necessary. Comment by the way says that for requests from robots/automatic [...]]]></description>
			<content:encoded><![CDATA[<p>Recently I was working on Java application to scrap Reddit data using their api, although performing read-only operations (such as reading listing data) doesn&#8217;t require authentication but after reading a comment on StackOverflow I decided to use send authenticated request even if it isn&#8217;t necessary. Comment by the way says that for requests from robots/automatic scrappers without a reddit_session id, reddit returns limited amount of data and some time data is inconsistent too.</p>
<p>Anyways to get started first step is to send HTTP POST request to http://www.reddit.com/api/login along with required parameters &#8216;user&#8217; and &#8216;passwd&#8217; for username and password. If username and password combination matches reddit server will return authentication cookie containing reddit_session along with other different stuff like domain, path etc&#8230;</p>
<p>Code here show how to make an HTTP POST request using Apache HttpClient, read and store cookie for further use:</p>
<pre class="brush: java; title: ; notranslate">
public class RedditClient {

    private List&lt;Cookie&gt; cookies = null;

    public boolean Login() throws ClientProtocolException, IOException {
		List&lt;NameValuePair&gt; loginParams = new ArrayList&lt;NameValuePair&gt;();
		loginParams.add(new BasicNameValuePair(&quot;api_type&quot;, &quot;json&quot;));

        //Set values of form fields
		loginParams.add(new BasicNameValuePair(&quot;user&quot;, userName));
		loginParams.add(new BasicNameValuePair(&quot;passwd&quot;, password));

		UrlEncodedFormEntity entity = new UrlEncodedFormEntity(loginParams, &quot;UTF-8&quot;);

		HttpPost httpPost = new HttpPost(&quot;https://ssl.reddit.com/api/login&quot;);
		httpPost.setEntity(entity);

		DefaultHttpClient httpClient = new DefaultHttpClient();

		HttpResponse httpResponse = httpClient.execute(httpPost);				

        //Save cookie in List of Cookies so we can use it later
		cookies = httpClient.getCookieStore().getCookies();						

		httpClient.getConnectionManager().shutdown();

		return false;
	}
}
</pre>
<p>Now in order to make a subsequent request which require authentication for example submitting a new post or posting a comment we have to pass attach this cookie with the request; Otherwise server will respond with an error.<br />
Below is how to make a subsequent request, in this case a request to retrieve top 100 post from funny category, along with cookie.</p>
<pre class="brush: java; title: ; notranslate">
public class RedditClient {
    ....
    public void readListing() {
         URI feedUrl = new URI(&quot;http://www.reddit.com/r/funny/top/?sort=top&amp;t=month&quot;);
         DefaultHttpClient httpClient = new DefaultHttpClient();

         HttpGet httpGet = new HttpGet(feedUrl);

         //Check if cookie list is not empty
         //attach it with current request
         if(this.cookies != null) {
             for(Cookie c : this.cookies)
	         httpClient.getCookieStore().addCookie(c);
         }

         HttpResponse response = httpClient.execute(httpGet);

         String strResponse = &quot;&quot;;

         BufferedReader rd = new BufferedReader(new InputStreamReader(response.getEntity().getContent()));
         String line = &quot;&quot;;
         while ((line = rd.readLine()) != null) {
	    strResponse += line;
         }

         httpClient.getConnectionManager().shutdown();
    }
}
</pre>
<p>In order to check if our request was treated as a trusted request look for the value of &#8216;modhash&#8217; in response it should be a long encrypted string, for unauthenticated requests it&#8217;s always empty.</p>
<pre class="brush: jscript; title: ; notranslate">
{&quot;kind&quot;: &quot;Listing&quot;, &quot;data&quot;: {&quot;modhash&quot;: &quot;bjxvddjbxaac5b494bc70000000000000000000000&quot;,........ }
</pre>
<p>And finally putting it all together:</p>
<pre class="brush: java; title: ; notranslate">
public class RedditClient {
    private List&lt;Cookie&gt; cookies = null;

    public boolean Login() throws ClientProtocolException, IOException {
		List&lt;NameValuePair&gt; loginParams = new ArrayList&lt;NameValuePair&gt;();
		loginParams.add(new BasicNameValuePair(&quot;api_type&quot;, &quot;json&quot;));

        //Set values of form fields
		loginParams.add(new BasicNameValuePair(&quot;user&quot;, userName));
		loginParams.add(new BasicNameValuePair(&quot;passwd&quot;, password));

		UrlEncodedFormEntity entity = new UrlEncodedFormEntity(loginParams, &quot;UTF-8&quot;);

		HttpPost httpPost = new HttpPost(&quot;https://ssl.reddit.com/api/login&quot;);
		httpPost.setEntity(entity);

		DefaultHttpClient httpClient = new DefaultHttpClient();

		HttpResponse httpResponse = httpClient.execute(httpPost);				

        //Save cookie in List of Cookies so we can use it later
		cookies = httpClient.getCookieStore().getCookies();						

		httpClient.getConnectionManager().shutdown();

		return false;
	}

    public void readListing() {
         URI feedUrl = new URI(&quot;http://www.reddit.com/r/funny/top/?sort=top&amp;t=month&quot;);
         DefaultHttpClient httpClient = new DefaultHttpClient();

         HttpGet httpGet = new HttpGet(feedUrl);

         //Check if cookie list is not empty
         //attach it with current request
         if(this.cookies != null) {
             for(Cookie c : this.cookies)
	         httpClient.getCookieStore().addCookie(c);
         }

         HttpResponse response = httpClient.execute(httpGet);

         String strResponse = &quot;&quot;;

         BufferedReader rd = new BufferedReader(new InputStreamReader(response.getEntity().getContent()));
         String line = &quot;&quot;;
         while ((line = rd.readLine()) != null) {
	    strResponse += line;
         }

         httpClient.getConnectionManager().shutdown();
    }
}
</pre>

				<!-- Social Sharing Toolkit v2.0.4 | http://www.marijnrongen.com/wordpress-plugins/social_sharing_toolkit/ -->
				<div class="mr_social_sharing_wrapper"><span class="mr_social_sharing_top"><iframe src="https://www.facebook.com/plugins/like.php?locale=en_US&amp;href=http%3A%2F%2Fwaqassiddiqi.net%2Fblog%2F2012%2F02%2F29%2Fgetting-reddit-authentication-cookie-and-then-using-it-apache-httpclient%2F&amp;layout=standard&amp;show_faces=false&amp;width=51px&amp;height=24px" scrolling="no" frameborder="0" style="border:none; overflow:hidden; width:51px; height:24px;" allowTransparency="true"></iframe></span><span class="mr_social_sharing_top"><a href="http://twitter.com/share?url=http%3A%2F%2Fwaqassiddiqi.net%2Fblog%2F2012%2F02%2F29%2Fgetting-reddit-authentication-cookie-and-then-using-it-apache-httpclient%2F&amp;text=Getting+%28Reddit%29+authentication+cookie+and+then+using+it+%E2%80%93+Apache+HttpClient&amp;via=waqas_siddiqi" target="_blank" class="mr_social_sharing_popup_link"><img src="http://waqassiddiqi.net/blog/wp-content/plugins/social-sharing-toolkit/images/buttons/twitter.png" alt="Share on Twitter" title="Share on Twitter"/></a></span><span class="mr_social_sharing_top"><g:plusone size="medium" count="false" href="http://waqassiddiqi.net/blog/2012/02/29/getting-reddit-authentication-cookie-and-then-using-it-apache-httpclient/"></g:plusone></span><span class="mr_social_sharing_top"><script type="IN/Share" data-url="http://waqassiddiqi.net/blog/2012/02/29/getting-reddit-authentication-cookie-and-then-using-it-apache-httpclient/"></script></span></div>]]></content:encoded>
			<wfw:commentRss>http://waqassiddiqi.net/blog/2012/02/29/getting-reddit-authentication-cookie-and-then-using-it-apache-httpclient/feed/</wfw:commentRss>
		<slash:comments>3</slash:comments>
		</item>
		<item>
		<title>Date formatting in JSON output &#8211; Spring 3 &amp; Jackson</title>
		<link>http://waqassiddiqi.net/blog/2012/02/10/date-formatting-in-json-output-spring-3-jackson/</link>
		<comments>http://waqassiddiqi.net/blog/2012/02/10/date-formatting-in-json-output-spring-3-jackson/#comments</comments>
		<pubDate>Fri, 10 Feb 2012 10:01:14 +0000</pubDate>
		<dc:creator>admin</dc:creator>
				<category><![CDATA[Uncategorized]]></category>
		<category><![CDATA[jackson]]></category>
		<category><![CDATA[java]]></category>
		<category><![CDATA[json]]></category>
		<category><![CDATA[spring]]></category>
		<category><![CDATA[spring-mvc]]></category>

		<guid isPermaLink="false">http://waqassiddiqi.net/blog/?p=143</guid>
		<description><![CDATA[Among the list of enhancements in Spring 3 the most I like is some excellent support of JSON/Ajax, very simplified configuration of Spring MVC using mvc namespace &#038; annotations. One of them is tag and @JsonSerialize annotation. The former is used to tell Spring what to use as sensible defaults based on entries in classpath, [...]]]></description>
			<content:encoded><![CDATA[<p>Among the list of enhancements in Spring 3 the most I like is some excellent support of JSON/Ajax, very simplified configuration of Spring MVC using <strong>mvc</strong> namespace &#038; annotations. </p>
<p>One of them is <strong><mvc:annotation-driven /></strong> tag and <strong><code>@JsonSerialize</code></strong> annotation. The former is used to tell Spring what to use as sensible defaults based on entries in classpath, so  if Jackson jars are in classpath, Jackson JSON Processor will be used to read/write JSON. </p>
<p>Whereas <strong><code>@JsonSerialize</code></strong> annotation can be used to override the default formatting strategy uses by Jackson during json serialization. This can be very handy when one is dealing with date time fields, lets take an example &#8211; I have a controller &#8216;subscription&#8217; with an action name &#8216;getSubscriber(String subcriberId)&#8217; and it returns an object of subscriber class as shown below:</p>
<pre class="brush: java; title: ; notranslate">
//Controller - SubscriptionController.java
@Controller
@RequestMapping(&quot;/subsciption&quot;)
public class SubscriptionController {

	@RequestMapping(value = &quot;/getSubcriber&quot;, method = RequestMethod.GET)
	public @ResponseBody
	Subscriber getSubscriber(@RequestParam String subscriberId) {
        return subscriberRepo.getSubscriber(subscriberId);
    }
}

//Subscriber POJO - Subscriber.java
public class Subscriber {
	private String subscriberId;
	private Date subscriptionExpiryDate;

	public Subscriber() { }

	public String getSubscriberId() {
		return this.subscriberId;
	}

	public void setSubscriberId(String subscriberId) {
		this.subscriberId = subscriberId;
	}

	public Date getSubscriptionExpiryDate() {
		return this.subscriptionExpiryDate;
	}

	public void setSubscriptionExpiryDate(Date subscriptionExpiryDate) {
		this.subscriptionExpiryDate = subscriptionExpiryDate;
	}
}
</pre>
<p>By default the serialized json output to this action will be:</p>
<pre class="brush: jscript; title: ; notranslate">{&quot;subscriberId&quot;:&quot;UFCC09211&quot;,&quot;subscriptionExpiryDate&quot;:1328866365808}</pre>
<p>Notice the value of <strong><code>subscriptionExpiryDate</code></strong> field &#8211; it doesn&#8217;t look like a date or time, also what if one wants date time in particular format like yyyy-mm-dd? This is where @JsonSerialize comes in a picture. In order to override the default date formatting one has to extend <code>JsonSerializer<T></code> class provided by Jackson and override the <code>serialize(Date value, JsonGenerator gen, SerializerProvider prov)</code> method.</p>
<p>For our example <code>CustomDateSerializer</code> class looks like this:</p>
<pre class="brush: java; title: ; notranslate">
public class CustomDateSerializer extends JsonSerializer&lt;Date&gt; {

	@Override
	public void serialize(Date value, JsonGenerator gen, SerializerProvider prov)
			throws IOException, JsonProcessingException {

		SimpleDateFormat formatter = new SimpleDateFormat(&quot;yyyy-MM-dd&quot;);
        String formattedDate = formatter.format(value);

        gen.writeString(formattedDate);
	}
}
</pre>
<p>and to tell Jackson to use this class to format date while serializing is to use the @JsonSerialize on get method of date field like this:</p>
<pre class="brush: java; title: ; notranslate">
@JsonSerialize(using = CustomDateSerializer.class)
public Date getSubscriptionExpiryDate() {
	return this.subscriptionExpiryDate;
}</pre>
<p>that&#8217;s it, the output date will now be in &#8216;yyyy-mm-dd&#8217; format:</p>
<pre class="brush: jscript; title: ; notranslate">{&quot;subscriberId&quot;:&quot;UFCC09211&quot;,&quot;subscriptionExpiryDate&quot;:&quot;2012-02-10&quot;}</pre>

				<!-- Social Sharing Toolkit v2.0.4 | http://www.marijnrongen.com/wordpress-plugins/social_sharing_toolkit/ -->
				<div class="mr_social_sharing_wrapper"><span class="mr_social_sharing_top"><iframe src="https://www.facebook.com/plugins/like.php?locale=en_US&amp;href=http%3A%2F%2Fwaqassiddiqi.net%2Fblog%2F2012%2F02%2F10%2Fdate-formatting-in-json-output-spring-3-jackson%2F&amp;layout=standard&amp;show_faces=false&amp;width=51px&amp;height=24px" scrolling="no" frameborder="0" style="border:none; overflow:hidden; width:51px; height:24px;" allowTransparency="true"></iframe></span><span class="mr_social_sharing_top"><a href="http://twitter.com/share?url=http%3A%2F%2Fwaqassiddiqi.net%2Fblog%2F2012%2F02%2F10%2Fdate-formatting-in-json-output-spring-3-jackson%2F&amp;text=Date+formatting+in+JSON+output+%E2%80%93+Spring+3+%26+Jackson&amp;via=waqas_siddiqi" target="_blank" class="mr_social_sharing_popup_link"><img src="http://waqassiddiqi.net/blog/wp-content/plugins/social-sharing-toolkit/images/buttons/twitter.png" alt="Share on Twitter" title="Share on Twitter"/></a></span><span class="mr_social_sharing_top"><g:plusone size="medium" count="false" href="http://waqassiddiqi.net/blog/2012/02/10/date-formatting-in-json-output-spring-3-jackson/"></g:plusone></span><span class="mr_social_sharing_top"><script type="IN/Share" data-url="http://waqassiddiqi.net/blog/2012/02/10/date-formatting-in-json-output-spring-3-jackson/"></script></span></div>]]></content:encoded>
			<wfw:commentRss>http://waqassiddiqi.net/blog/2012/02/10/date-formatting-in-json-output-spring-3-jackson/feed/</wfw:commentRss>
		<slash:comments>1</slash:comments>
		</item>
		<item>
		<title>Dynamic authentication success and failure url using Spring 3 MVC &amp; Security</title>
		<link>http://waqassiddiqi.net/blog/2012/01/28/dynamic-authentication-success-and-failure-url-using-spring-3-mvc-security/</link>
		<comments>http://waqassiddiqi.net/blog/2012/01/28/dynamic-authentication-success-and-failure-url-using-spring-3-mvc-security/#comments</comments>
		<pubDate>Sat, 28 Jan 2012 18:00:58 +0000</pubDate>
		<dc:creator>admin</dc:creator>
				<category><![CDATA[Uncategorized]]></category>
		<category><![CDATA[java]]></category>
		<category><![CDATA[spring]]></category>
		<category><![CDATA[spring-mvc]]></category>

		<guid isPermaLink="false">http://waqassiddiqi.net/blog/?p=86</guid>
		<description><![CDATA[If you have used spring&#8217;s form-login security before then following (part of) configuration will look familiar to you: What it says is: where the login page resides (login-page), after logging in redirect user to &#8220;/&#8221; (default-target-url) given that user wasn&#8217;t landed here while trying to access any page that required authentication and what page to [...]]]></description>
			<content:encoded><![CDATA[<p>If you have used spring&#8217;s form-login security before then following (part of) configuration will look familiar to you:</p>
<pre class="brush: xml; title: ; notranslate">&lt;security:form-login login-page=&quot;/login&quot;&lt;/pre&gt;
 authentication-failure-url=&quot;/login/failure&quot;
 default-target-url=&quot;/&quot;/&gt;</pre>
<p>What it says is: where the login page resides (<em><strong>login-page</strong></em>), after logging in redirect user to &#8220;/&#8221; (<em><strong>default-target-url</strong></em>) given that user wasn&#8217;t landed here while trying to access any page that required authentication and what page to serve in case of failed login attept (<em><strong>authentication-failure-url</strong></em>).</p>
<p>OK, it&#8217;s pretty straight forward but what if instead of using values specified in config one has to specify these values dynamically &#8211; with dynamically I mean on authentication failure instead of redirecting to &#8220;/login/failure&#8221; (value of authentication-failure-url), redirect to /signup or some other url depending on some checks/conditions?</p>
<p>Luckily for this spring has:</p>
<table style="width:100%;border-spacing:101px; border-collapse:collapse;">
<tr class="entry meta">
<td width="40%"><strong>Interface / Class</strong></td>
<td width="60%"><strong>Description</strong></td>
</tr>
<tr>
<td width="40%"><a href="http://static.springsource.org/spring-security/site/docs/3.0.x/apidocs/org/springframework/security/web/authentication/AuthenticationSuccessHandler.html">AuthenticationSuccessHandler</a></td>
<td width="60%">Strategy used to handle a successful user authentication.</td>
</tr>
<tr>
<td>&nbsp;</td>
<td>&nbsp;</td>
</tr>
<tr>
<td width="40%" valign="top"><a href="http://static.springsource.org/spring-security/site/docs/3.0.x/apidocs/org/springframework/security/web/authentication/SimpleUrlAuthenticationSuccessHandler.html#onAuthenticationSuccess(javax.servlet.http.HttpServletRequest, javax.servlet.http.HttpServletResponse, org.springframework.security.core.Authentication)">SimpleUrlAuthenticationSuccessHandler</a></td>
<td width="60%">Simple implementation of AuthenticationSuccessHandler interface which by default uses the default-target-url value to redirect to user on successful authentication</td>
</tr>
<tr>
<td>&nbsp;</td>
<td>&nbsp;</td>
</tr>
<tr>
<td width="40%" valign="top"><a href="http://static.springsource.org/spring-security/site/docs/3.0.x/apidocs/org/springframework/security/web/authentication/AuthenticationFailureHandler.html">AuthenticationFailureHandler</a></td>
<td width="60%">Strategy used to handle a failed user authentication.</td>
</tr>
<tr>
<td>&nbsp;</td>
<td>&nbsp;</td>
</tr>
<tr>
<td width="40%" valign="top"><a href="http://static.springsource.org/spring-security/site/docs/3.0.x/apidocs/org/springframework/security/web/authentication/SimpleUrlAuthenticationFailureHandler.html">SimpleUrlAuthenticationFailureHandler</a></td>
<td width="60%">Similarly, this class is simple implementation of AuthenticationFailureHandler interface and it by default redirect the user to value of authentication-failure-url</td>
</tr>
<tr>
<td>&nbsp;</td>
<td>&nbsp;</td>
</tr>
<tr>
<td width="40%" valign="top"><a href="http://static.springsource.org/spring-security/site/docs/3.0.x/apidocs/org/springframework/security/web/RedirectStrategy.html">RedirectStrategy</a></td>
<td width="60%">Encapsulate the redirection strategy</td>
</tr>
</table>
<p>If you haven&#8217;t noticed yet <code><strong>RedirectStrategy</strong></code> is the interface we are most interested in, since it&#8217;s the one that will be one incorporating the strategy of forward requests. So for this we simply need to write a custom class that implements <code><strong>RedirectStrategy</strong></code> and override <code><strong>sendRedirect(HttpServletRequest request, HttpServletResponse response, String url)</strong></code> method.</p>
<p>Let&#8217;s show you what I mean:</p>
<pre class="brush: java; title: ; notranslate">
//Custom redirection strategy for handling successful handling
public class CustomSuccessRedirection implements RedirectStrategy {

	@Override
	public void sendRedirect(HttpServletRequest request, HttpServletResponse response,
			String url) throws IOException {

		//redirect based on some condition
		if(someCondition) {
			response.sendRedirect(&quot;/home/a&quot;);
		} else {
			response.sendRedirect(&quot;/home/b&quot;);
		}
	}
}</pre>
<p>Similarly a strategy for failed authentication can also be written in the same way.</p>
<p>Now to override the default url redirection strategy we need to add following to config:</p>
<pre class="brush: xml; title: ; notranslate">
&lt;!-- Custom Redirection Strategy bean --&gt;
&lt;bean id=&quot;customSuccessRedirStrategy&quot; class=&quot;net.waqassiddiqi.spring.CustomSuccessRedirection&quot; /&gt;
&lt;bean id=&quot;customFailedRedirStrategy&quot; class=&quot;net.waqassiddiqi.spring.CustomFailedRedirection&quot; /&gt;

&lt;bean id=&quot;customRedirSuccessHandler&quot; class=&quot;org.springframework.security.web.authentication.SimpleUrlAuthenticationSuccessHandler&quot;&gt;
	&lt;property name=&quot;redirectStrategy&quot; ref=&quot;customSuccessRedirStrategy&quot; /&gt;
&lt;/bean&gt;

&lt;bean id=&quot;customRedirFailedHandler&quot; class=&quot;org.springframework.security.web.authentication.SimpleUrlAuthenticationFailureHandler&quot;&gt;
	&lt;property name=&quot;defaultFailureUrl&quot; value=&quot;/login/failure&quot; /&gt;
	&lt;property name=&quot;redirectStrategy&quot; ref=&quot;customFailedRedirStrategy&quot; /&gt;
&lt;/bean&gt;
</pre>
<p><br/><br />
<br/></p>

				<!-- Social Sharing Toolkit v2.0.4 | http://www.marijnrongen.com/wordpress-plugins/social_sharing_toolkit/ -->
				<div class="mr_social_sharing_wrapper"><span class="mr_social_sharing_top"><iframe src="https://www.facebook.com/plugins/like.php?locale=en_US&amp;href=http%3A%2F%2Fwaqassiddiqi.net%2Fblog%2F2012%2F01%2F28%2Fdynamic-authentication-success-and-failure-url-using-spring-3-mvc-security%2F&amp;layout=standard&amp;show_faces=false&amp;width=51px&amp;height=24px" scrolling="no" frameborder="0" style="border:none; overflow:hidden; width:51px; height:24px;" allowTransparency="true"></iframe></span><span class="mr_social_sharing_top"><a href="http://twitter.com/share?url=http%3A%2F%2Fwaqassiddiqi.net%2Fblog%2F2012%2F01%2F28%2Fdynamic-authentication-success-and-failure-url-using-spring-3-mvc-security%2F&amp;text=Dynamic+authentication+success+and+failure+url+using+Spring+3+MVC+%26+Security&amp;via=waqas_siddiqi" target="_blank" class="mr_social_sharing_popup_link"><img src="http://waqassiddiqi.net/blog/wp-content/plugins/social-sharing-toolkit/images/buttons/twitter.png" alt="Share on Twitter" title="Share on Twitter"/></a></span><span class="mr_social_sharing_top"><g:plusone size="medium" count="false" href="http://waqassiddiqi.net/blog/2012/01/28/dynamic-authentication-success-and-failure-url-using-spring-3-mvc-security/"></g:plusone></span><span class="mr_social_sharing_top"><script type="IN/Share" data-url="http://waqassiddiqi.net/blog/2012/01/28/dynamic-authentication-success-and-failure-url-using-spring-3-mvc-security/"></script></span></div>]]></content:encoded>
			<wfw:commentRss>http://waqassiddiqi.net/blog/2012/01/28/dynamic-authentication-success-and-failure-url-using-spring-3-mvc-security/feed/</wfw:commentRss>
		<slash:comments>1</slash:comments>
		</item>
		<item>
		<title>And java guys say c# is bad!</title>
		<link>http://waqassiddiqi.net/blog/2012/01/24/and-java-guys-say-c-is-bad/</link>
		<comments>http://waqassiddiqi.net/blog/2012/01/24/and-java-guys-say-c-is-bad/#comments</comments>
		<pubDate>Tue, 24 Jan 2012 12:46:43 +0000</pubDate>
		<dc:creator>admin</dc:creator>
				<category><![CDATA[Uncategorized]]></category>
		<category><![CDATA[c#]]></category>
		<category><![CDATA[java]]></category>

		<guid isPermaLink="false">http://waqassiddiqi.net/blog/?p=81</guid>
		<description><![CDATA[Its not like I don&#8217;t like or enjoy to work with Java, it&#8217;s just the fact that it takes more time as compare to C# to perform some trivial tasks; Like &#8216;calculating the time duration (in hours/minutes/seconds) between two date times&#8217; &#8211; doing this Java way (as pasted below, I really missed the days working [...]]]></description>
			<content:encoded><![CDATA[<p>Its not like I don&#8217;t like or enjoy to work with Java, it&#8217;s just the fact that it takes more time as compare to C# to perform some trivial tasks; Like &#8216;calculating the time duration (in hours/minutes/seconds) between two date times&#8217; &#8211; doing this Java way (as pasted below, I really missed the days working with C#)</p>
<pre class="brush: java; title: ; notranslate">
...
Calendar startDate = getStartDate();
Calendar endDate = getEndDate();

//Calculate time elapsed in HH:MM:SS
long totalMilliSec = endDate.getTimeInMillis() - startDate.getTimeInMillis();
int seconds = (int) (totalMilliSec / 1000) % 60;
int minutes =  ((int)(totalMilliSec / 1000) / 60) % 60;
int hours = (int)(totalMilliSec / 1000) / 3600;

System.out.format(&quot;%02d:%02d:%02d&quot;, hours, minutes, seconds);
....
Sample output will be something like: 24:01:34
....
</pre>
<p>For comparison find below the C# code which does exact the same:</p>
<pre class="brush: csharp; title: ; notranslate">
DateTime dtStart = getStartDate();
DateTime dtEnd = getEndDate();

TimeSpan ts = dtEnd.Subtract(dtStart);
Console.WriteLine(&quot;{0}:{1}:{2}&quot;, ts.Hours.ToString(&quot;D2&quot;),
      ts.Minutes.ToString(&quot;D2&quot;), ts.Seconds.ToString(&quot;D2&quot;));
.....
Sample output will be something like: 24:01:34
.....
</pre>
<p>Between, for java, there exists an easy to use library to work with date time &#8216;Joda Time&#8217;. One can say that it provide almost all the functionality C#&#8217;s DateTime provide. Here you can find more: http://joda-time.sourceforge.net/</p>

				<!-- Social Sharing Toolkit v2.0.4 | http://www.marijnrongen.com/wordpress-plugins/social_sharing_toolkit/ -->
				<div class="mr_social_sharing_wrapper"><span class="mr_social_sharing_top"><iframe src="https://www.facebook.com/plugins/like.php?locale=en_US&amp;href=http%3A%2F%2Fwaqassiddiqi.net%2Fblog%2F2012%2F01%2F24%2Fand-java-guys-say-c-is-bad%2F&amp;layout=standard&amp;show_faces=false&amp;width=51px&amp;height=24px" scrolling="no" frameborder="0" style="border:none; overflow:hidden; width:51px; height:24px;" allowTransparency="true"></iframe></span><span class="mr_social_sharing_top"><a href="http://twitter.com/share?url=http%3A%2F%2Fwaqassiddiqi.net%2Fblog%2F2012%2F01%2F24%2Fand-java-guys-say-c-is-bad%2F&amp;text=And+java+guys+say+c%23+is+bad%21&amp;via=waqas_siddiqi" target="_blank" class="mr_social_sharing_popup_link"><img src="http://waqassiddiqi.net/blog/wp-content/plugins/social-sharing-toolkit/images/buttons/twitter.png" alt="Share on Twitter" title="Share on Twitter"/></a></span><span class="mr_social_sharing_top"><g:plusone size="medium" count="false" href="http://waqassiddiqi.net/blog/2012/01/24/and-java-guys-say-c-is-bad/"></g:plusone></span><span class="mr_social_sharing_top"><script type="IN/Share" data-url="http://waqassiddiqi.net/blog/2012/01/24/and-java-guys-say-c-is-bad/"></script></span></div>]]></content:encoded>
			<wfw:commentRss>http://waqassiddiqi.net/blog/2012/01/24/and-java-guys-say-c-is-bad/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>java &#8211; ResultSet.getTimestamp() = Date + Time</title>
		<link>http://waqassiddiqi.net/blog/2012/01/20/java-resultset-gettimestamp-date-time/</link>
		<comments>http://waqassiddiqi.net/blog/2012/01/20/java-resultset-gettimestamp-date-time/#comments</comments>
		<pubDate>Fri, 20 Jan 2012 11:09:39 +0000</pubDate>
		<dc:creator>admin</dc:creator>
				<category><![CDATA[Uncategorized]]></category>
		<category><![CDATA[java]]></category>

		<guid isPermaLink="false">http://waqassiddiqi.net/blog/?p=76</guid>
		<description><![CDATA[Fall into this again, now not to forget this again I am posting it here. ResultSet.getDate() returns date without time i.e. If table column has date time value say 2011-01-01 12:05:01 then the output of ResultSet.getDate() will be 2011-01-01. And if in case complete date time value is required use ResultSet.getTimestamp() instead. The output will [...]]]></description>
			<content:encoded><![CDATA[<p>Fall into this again, now not to forget this again I am posting it here.</p>
<p><strong>ResultSet.getDate()</strong> returns date <strong>without</strong> time i.e. If table column has date time value say 2011-01-01 12:05:01 then the output of ResultSet.getDate() will be 2011-01-01.</p>
<p>And if in case complete date time value is required use <strong>ResultSet.getTimestamp()</strong> instead. The output will be complete date with time 2011-01-01 12:05:01</p>
<pre class="brush: java; title: ; notranslate">
ResultSet rs = ...;
rs.getDate(&quot;columnName&quot;); //value will be date without time
rs.getTimestamp(&quot;columnName&quot;); //value will be date *with* time
</pre>

				<!-- Social Sharing Toolkit v2.0.4 | http://www.marijnrongen.com/wordpress-plugins/social_sharing_toolkit/ -->
				<div class="mr_social_sharing_wrapper"><span class="mr_social_sharing_top"><iframe src="https://www.facebook.com/plugins/like.php?locale=en_US&amp;href=http%3A%2F%2Fwaqassiddiqi.net%2Fblog%2F2012%2F01%2F20%2Fjava-resultset-gettimestamp-date-time%2F&amp;layout=standard&amp;show_faces=false&amp;width=51px&amp;height=24px" scrolling="no" frameborder="0" style="border:none; overflow:hidden; width:51px; height:24px;" allowTransparency="true"></iframe></span><span class="mr_social_sharing_top"><a href="http://twitter.com/share?url=http%3A%2F%2Fwaqassiddiqi.net%2Fblog%2F2012%2F01%2F20%2Fjava-resultset-gettimestamp-date-time%2F&amp;text=java+%E2%80%93+ResultSet.getTimestamp%28%29+%3D+Date+%2B+Time&amp;via=waqas_siddiqi" target="_blank" class="mr_social_sharing_popup_link"><img src="http://waqassiddiqi.net/blog/wp-content/plugins/social-sharing-toolkit/images/buttons/twitter.png" alt="Share on Twitter" title="Share on Twitter"/></a></span><span class="mr_social_sharing_top"><g:plusone size="medium" count="false" href="http://waqassiddiqi.net/blog/2012/01/20/java-resultset-gettimestamp-date-time/"></g:plusone></span><span class="mr_social_sharing_top"><script type="IN/Share" data-url="http://waqassiddiqi.net/blog/2012/01/20/java-resultset-gettimestamp-date-time/"></script></span></div>]]></content:encoded>
			<wfw:commentRss>http://waqassiddiqi.net/blog/2012/01/20/java-resultset-gettimestamp-date-time/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Changing field name before serialized json output using flexjson &amp; java</title>
		<link>http://waqassiddiqi.net/blog/2012/01/16/changing-field-name-before-json-output-using-flexjson/</link>
		<comments>http://waqassiddiqi.net/blog/2012/01/16/changing-field-name-before-json-output-using-flexjson/#comments</comments>
		<pubDate>Mon, 16 Jan 2012 12:50:11 +0000</pubDate>
		<dc:creator>admin</dc:creator>
				<category><![CDATA[Uncategorized]]></category>
		<category><![CDATA[flexjson]]></category>
		<category><![CDATA[java]]></category>
		<category><![CDATA[json]]></category>

		<guid isPermaLink="false">http://waqassiddiqi.net/blog/?p=68</guid>
		<description><![CDATA[Today I was working on a Web API integration project when I ran into this problem. All data being sent and received from this Web API is in JSON format and for which we are flexjson, which works good for serializing and deserializing POJO to/from json. By default flexjson uses the POJO property names as [...]]]></description>
			<content:encoded><![CDATA[<p>Today I was working on a Web API integration project when I ran into this problem. All data being sent and received from this Web API is in JSON format and for which we are flexjson, which works good for serializing and deserializing POJO to/from json. </p>
<p>By default flexjson uses the POJO property names as the field name in serialized json output, so the output of this POJO:</p>
<pre class="brush: java; title: ; notranslate">
//Person.java
public class Person {
	String firstName;

    public String getName() { return firstName;}
    public void setName(String firstName) { this.firstName = firstName; }
}</pre>
<p>will be:</p>
<pre class="brush: jscript; title: ; notranslate">{&quot;firstName&quot;:&quot;Abdul Kareem&quot;}</pre>
<p>But what if I can&#8217;t change POJOs but still would like the serialized output to be something like this:</p>
<pre class="brush: jscript; title: ; notranslate">{&quot;first_name&quot;:&quot;Abdul Kareem&quot;}</pre>
<p>This was the problem which I ran into today, overriding the default flexjson behaviour and provide the field names manually. It wasn&#8217;t that difficult as I thought, few minutes into mailing list search led me to official flexjson tutorial page on sourceforge. There they have written about using Custom Transformer in great detail using example.</p>
<p>So in short, in order to play with field name&#8217;s during serialization flexjson has provided an abstract class AbstractTransformer, writting custom transformer is as easy as extending this class and overriding void transform(Object object) method.</p>
<p>Pasted below is the code of FieldNameTransformer class which I wrote for solving the problem I mentioned earlier. It allows user to specify the field name rather then using default POJO property names in json serialized output.</p>
<pre class="brush: java; title: ; notranslate">
public class FieldNameTransformer extends AbstractTransformer {
	private String transformedFieldName;

	public FieldNameTransformer(String transformedFieldName) {
		this.transformedFieldName = transformedFieldName;
	}

	/***
	 * Use this method to override the default functionality
	 * of handling field names and their values
	 */
	public void transform(Object object) {
		boolean setContext = false;

		TypeContext typeContext = getContext().peekTypeContext();

		//Write comma before starting to write field name if this
		//isn't first property that is being transformed
		if (!typeContext.isFirst())
			getContext().writeComma();

		typeContext.setFirst(false);

		getContext().writeName(getTransformedFieldName());
		getContext().writeQuoted((String) object);

		if (setContext) {
            getContext().writeCloseObject();
        }
	}

	/***
	 * TRUE tells the JSONContext that this class will be handling
	 * the writing of our property name by itself.
	 */
	@Override
    public Boolean isInline() {
        return Boolean.TRUE;
    }

	public String getTransformedFieldName() {
		return this.transformedFieldName;
	}
}</pre>
<p>And this is how to use it:</p>
<pre class="brush: java; title: ; notranslate">
Person person = new Person();
person.setFirstName(&quot;Abdul Kareem&quot;);

JSONSerializer serializer = new JSONSerializer().exclude(&quot;class&quot;)
                .transform(new StringTransformer(&quot;first_name&quot;), &quot;firstName&quot;);
String jsonString = serializer.serialize(person);</pre>
<p>And here is the desired output:</p>
<pre class="brush: jscript; title: ; notranslate">{&quot;first_name&quot;:&quot;Abdul Kareem&quot;}</pre>

				<!-- Social Sharing Toolkit v2.0.4 | http://www.marijnrongen.com/wordpress-plugins/social_sharing_toolkit/ -->
				<div class="mr_social_sharing_wrapper"><span class="mr_social_sharing_top"><iframe src="https://www.facebook.com/plugins/like.php?locale=en_US&amp;href=http%3A%2F%2Fwaqassiddiqi.net%2Fblog%2F2012%2F01%2F16%2Fchanging-field-name-before-json-output-using-flexjson%2F&amp;layout=standard&amp;show_faces=false&amp;width=51px&amp;height=24px" scrolling="no" frameborder="0" style="border:none; overflow:hidden; width:51px; height:24px;" allowTransparency="true"></iframe></span><span class="mr_social_sharing_top"><a href="http://twitter.com/share?url=http%3A%2F%2Fwaqassiddiqi.net%2Fblog%2F2012%2F01%2F16%2Fchanging-field-name-before-json-output-using-flexjson%2F&amp;text=Changing+field+name+before+serialized+json+output+using+flexjson+%26+java&amp;via=waqas_siddiqi" target="_blank" class="mr_social_sharing_popup_link"><img src="http://waqassiddiqi.net/blog/wp-content/plugins/social-sharing-toolkit/images/buttons/twitter.png" alt="Share on Twitter" title="Share on Twitter"/></a></span><span class="mr_social_sharing_top"><g:plusone size="medium" count="false" href="http://waqassiddiqi.net/blog/2012/01/16/changing-field-name-before-json-output-using-flexjson/"></g:plusone></span><span class="mr_social_sharing_top"><script type="IN/Share" data-url="http://waqassiddiqi.net/blog/2012/01/16/changing-field-name-before-json-output-using-flexjson/"></script></span></div>]]></content:encoded>
			<wfw:commentRss>http://waqassiddiqi.net/blog/2012/01/16/changing-field-name-before-json-output-using-flexjson/feed/</wfw:commentRss>
		<slash:comments>1</slash:comments>
		</item>
	</channel>
</rss>
