<?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</title>
	<atom:link href="http://blog.alutam.com/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>Fri, 04 May 2012 12:03:17 +0000</lastBuildDate>
	<language>en</language>
	<sy:updatePeriod>hourly</sy:updatePeriod>
	<sy:updateFrequency>1</sy:updateFrequency>
	<generator>http://wordpress.org/?v=3.3.1</generator>

   <image>
    <title>Martin&#039;s Weekend Coding</title>
    <url>http://0.gravatar.com/avatar/fe13f36272d010f4b3c09e477a620991.png?s=48</url>
    <link>http://blog.alutam.com</link>
   </image><!-- Gravatar Favicon by Patrick http://patrick.bloggles.info/ -->
		<item>
		<title>Proxy Client on Top of JAX-RS 2.0 Client API</title>
		<link>http://blog.alutam.com/2012/05/04/proxy-client-on-top-of-jax-rs-2-0-client-api/#utm_source=feed&#038;utm_medium=feed&#038;utm_campaign=feed</link>
		<comments>http://blog.alutam.com/2012/05/04/proxy-client-on-top-of-jax-rs-2-0-client-api/#comments</comments>
		<pubDate>Fri, 04 May 2012 12:01:02 +0000</pubDate>
		<dc:creator>Martin</dc:creator>
				<category><![CDATA[Java]]></category>
		<category><![CDATA[REST]]></category>
		<category><![CDATA[client]]></category>
		<category><![CDATA[JAX-RS]]></category>
		<category><![CDATA[Jersey]]></category>

		<guid isPermaLink="false">http://blog.alutam.com/?p=227</guid>
		<description><![CDATA[Several JAX-RS 1.x implementations are providing proxy client API as one of the ways to access web services. The basic idea is you can attach the standard JAX-RS annotations to an interface, and then implement that interface by a resource class on the server side while reusing the same interface on the client side by [...]]]></description>
			<content:encoded><![CDATA[<p>Several JAX-RS 1.x implementations are providing proxy client API as one of the ways to access web services. The basic idea is you can attach the standard JAX-RS annotations to an interface, and then implement that interface by a resource class on the server side while reusing the same interface on the client side by dynamically generating an implementation of that using <a href="http://docs.oracle.com/javase/6/docs/api/java/lang/reflect/Proxy.html">java.lang.reflect.Proxy</a> calling the right low-level client API methods.</p>
<p>Jersey 1.x client API (and now JAX-RS 2.0 client API) leverages the fact REST (and HTTP) defines the standard set of operations, so unlike for JAX-WS type of web services, which are verb-centric, for RESTful web services the interface is uniform and thus there is no need for generating client proxies. The standard client API is static (has fixed set of operations &#8211; get, put, post, delete, &#8230;). Proxy client API may be seen as evil, as it creates tighter coupling between services and clients. However, some people do find it useful and it provides better opportunities for reusing JAX-RS concepts between services and clients, including name-bound interceptors, for example.</p>
<p>Few weeks back I quickly &#8220;hacked&#8221; a proxy client factory for Jersey as part of Jersey 2.0 and made some small incremental improvements since then. It is based purely on the current draft of the standard JAX-RS 2.0 client API, so should be usable with any JAX-RS 2.0 implementation, not just Jersey. Currently it lives in the <a href="http://java.net/projects/jersey/sources/code/show/incubator/proxy-client">&#8220;incubator&#8221; subfolder</a> of Jersey 2.0 workspace, so if you want to give it a try, you have to check it out and build it yourself. The project includes a test that illustrates the usage, and also a simple example.</p>
<h3>Building the Proxy-Client Project</h3>
<p>To build it, first clone the Jersey repository, build Jersey, then switch to the proxy-client folder and build the proxy-client project. The following shell commands do that (assuming you have git and mvn installed):</p>
<pre class="brush:bash">git clone ssh://[your-java.net-user-id]@git.java.net/jersey~code jersey
cd jersey
mvn install
cd incubator/proxy-client
mvn install</pre>
<h3>Using/Playing with the Proxy-Client</h3>
<p>The project has just one class &#8211; WebResourceFactory. Here is how it can be used:</p>
<p>Let&#8217;s say you want to access a web resource available at a URI that could be represented by the following URI template: </p>
<pre>http://acme.com/rest/books/{book-id}</pre>
<p>Let&#8217;s assume this resource can produce and consume application/json and application/xml and supports GET, PUT and DELETE operations. There is also a parent resource &#8211; <code>http://acme.com/rest/books/</code> which accepts GET (returns a list of books) and POST (creates a new book). Here is one example of how you can model it using the interfaces with JAX-RS annotations and then access these resources using those interfaces and WebResourceFactory class:</p>
<p>Interface representing the &#8220;books&#8221; resource:</p>
<pre class="brush:java">@Path("books")
public interface BooksResource {
    @GET
    @Produces({MediaType.APPLICATION_XML, MediaType.APPLICATION_JSON})
    List&lt;Book&gt; getBooks();

    @POST
    @Consumes({MediaType.APPLICATION_XML, MediaType.APPLICATION_JSON})
    Response createBook(Book book);

    @Path("{bookid}")
    BookResource getBookResource(@PathParam("bookid") String bookId);
}</pre>
<p>Interface representing &#8220;books/{bookid}&#8221; subresource:</p>
<pre class="brush:java">public interface BookResource {
    @GET
    @Produces({MediaType.APPLICATION_XML, MediaType.APPLICATION_JSON})
    Book get();

    @PUT
    @Consumes({MediaType.APPLICATION_XML, MediaType.APPLICATION_JSON})
    @Produces({MediaType.APPLICATION_XML, MediaType.APPLICATION_JSON})
    Book update(Book book);

    @DELETE
    void delete();
}</pre>
<p>Accessing it from your application:</p>
<pre class="brush:java">// create a new JAX-RS 2.0 target pointing to the root of the web api
Target t = ClientFactory.newClient().target("http://acme.com/rest/");

// create a new client proxy for the BooksResource
BooksResource booksRsc = WebResourceFactory(BooksResource.class, t);

// get list of books
List&lt;Book&gt; books = booksRsc.getBooks();

// get book resource by ID
BookResource bookRsc = booksRsc.getBookResource(bookId);
// get book object
Book myBook = bookRsc.get();
// delete book
bookRsc.delete();</pre>
<p>I hope you got the idea. As you can see, the proxy factory can handle path parameters and can automatically create proxies for sub-resources. It can also handle other kinds of parameters such as header parameters, query parameters, form parameters and cookie parameters.</p>
<p>Give it a try and let us know what you think.</p>
]]></content:encoded>
			<wfw:commentRss>http://blog.alutam.com/2012/05/04/proxy-client-on-top-of-jax-rs-2-0-client-api/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Optimizing MacOS X Lion for SSD</title>
		<link>http://blog.alutam.com/2012/04/01/optimizing-macos-x-lion-for-ssd/#utm_source=feed&#038;utm_medium=feed&#038;utm_campaign=feed</link>
		<comments>http://blog.alutam.com/2012/04/01/optimizing-macos-x-lion-for-ssd/#comments</comments>
		<pubDate>Sun, 01 Apr 2012 12:09:23 +0000</pubDate>
		<dc:creator>Martin</dc:creator>
				<category><![CDATA[Mac]]></category>
		<category><![CDATA[lion]]></category>
		<category><![CDATA[mac]]></category>
		<category><![CDATA[osx]]></category>
		<category><![CDATA[ssd]]></category>

		<guid isPermaLink="false">http://blog.alutam.com/?p=154</guid>
		<description><![CDATA[Approx. 18 months back I bought my first SSD (120GB OCZ Vertex 2) for my (then) new iMac. I am using it as the primary disk, while I kept the original 1TB HDD as the secondary one. So far I&#8217;ve been very happy with it and thanks to applying some tweaks the drive seems still [...]]]></description>
			<content:encoded><![CDATA[<style type="text/css">
pre.shell {
  background: #eaeaea;
  font-family: Consolas, Monaco, monospace;
  font-size: 0.9em;
  padding: 1px 3px;
  color: #4d4d4d;
  margin-bottom: 9px
}
</style>
<p>Approx. 18 months back I bought my first SSD (120GB OCZ Vertex 2) for my (then) new iMac. I am using it as the primary disk, while I kept the original 1TB HDD as the secondary one. So far I&#8217;ve been very happy with it and thanks to applying some tweaks the drive seems still healthy as new. Recently I bought another SSD &#8211; this time a 240GB Vertext 3 for my MacBook &#8211; that one I am using as the only drive in the laptop. And as I found out, with the new features in Lion, some additional tweaks need to be applied &#8211; especially in case of a laptop. So, I&#8217;ve decided to write this blog &#8211; for my own benefit (to keep track of what I did in case I have to re-apply it in the future) as well as for the benefit of others who may run into this blog entry. Here I am providing the list of things I found on various web sites or came up with myself to minimize the risk the SSD wears out too soon. Some of them you may already be aware of. So, here is a list of content in case you want to skip to particular sections:</p>
<blockquote><p>
DISCLAIMER: Applying any of these tweakss is at your own risk. Make sure you back up your computer before trying any of these.
</p></blockquote>
<p><a href="#no-benchmarks#utm_source=feed&amp;utm_medium=feed&amp;utm_campaign=feed">Don&#8217;t run benchmarks on your new SSD</a><br />
<a href="#trim-enabler#utm_source=feed&amp;utm_medium=feed&amp;utm_campaign=feed">Use Trim Enabler</a><br />
<a href="#time-machine#utm_source=feed&amp;utm_medium=feed&amp;utm_campaign=feed">Turn off local Time Machine snapshots <small style="color: #808080">[laptops only]</small></a><br />
<a href="#hibernation#utm_source=feed&amp;utm_medium=feed&amp;utm_campaign=feed">Turn off hibernation <small style="color: #808080">[laptops only]</small></a><br />
<a href="#noatime#utm_source=feed&amp;utm_medium=feed&amp;utm_campaign=feed">Set noatime flag</a><br />
<a href="#move-home#utm_source=feed&amp;utm_medium=feed&amp;utm_campaign=feed">Move user home directories to HDD <small style="color: #808080">[SSD+HDD only]</small></a><br />
<a href="#ramdisk#utm_source=feed&amp;utm_medium=feed&amp;utm_campaign=feed">Use RAM disk or HDD for temporary files</a><br />
<a href="#no_sms#utm_source=feed&amp;utm_medium=feed&amp;utm_campaign=feed">Turn off sudden motion sensor <small style="color: #808080">[SSD+HDD only]</small></a><br />
<a href="#no_hdd_sleep#utm_source=feed&amp;utm_medium=feed&amp;utm_campaign=feed">Turn off hard drive sleep <small style="color: #808080">[SSD+HDD only]</small></a><br />
<a href="#references#utm_source=feed&amp;utm_medium=feed&amp;utm_campaign=feed">References/Other tweaks</a></p>
<p>I&#8217;ll try keeping this list up to date. Let me know if any other tweaks work well for you.<br />
<!--------------------------------------------------><br />
<h3><a name="no-benchmarks">Don&#8217;t run benchmarks on your new SSD</a></h3>
<p>Some people, right after they buy a new SSD, want to enjoy the speed and are eager to find out how much faster exactly their new SSD is than the old HDD. So they get this cool idea of running some extensive benchmarks to see the amazing performance numbers. Benchmarks usually write a lot of data to the disk (to test the write speed), wearing it out. So it is the best way how you can ruin your SSD even before you start using it. Don&#8217;t do it.<br />
<!--------------------------------------------------><br />
<h3><a name="trim-enabler">Use Trim Enabler</a></h3>
<p>TRIM support is essential for keeping the SSD healthy. Unfortunately, MacOS supports TRIM only for Apple-supplied SSD&#8217;s. If you bought a 3rd party one like I did, you have to tweak the system to be able to turn on the TRIM support. Trim Enabler is a simple utility that does this for you. You can read more <a href="http://osxdaily.com/2012/01/03/enable-trim-all-ssd-mac-os-x-lion/">here</a> or go to the <a href="http://www.groths.org/?page_id=322">TrimEnabler web site</a> directly.<br />
<!--------------------------------------------------><br />
<h3><a name="time-machine">Turn off local Time Machine snapshots <small style="color: #808080">[laptops only]</small></a></h3>
<p>If you are using the SSD in a laptop, and you turned the Time Machine backups on, you should know that OS X Lion does local snapshots at times when your Time Machine disk is not available. This is quite common &#8211; you are typically connecting your external TM disk only once in a while or you are using Time Capsule at home but take your laptop to the office every day for 8+ hours. You can confirm if the local TM backups are on by opening Time Machine Preferences:<br />
<img src="/img/time-machine-preferences.png" alt="Time Machine Preferences pane showing local backups are enabled" /></p>
<p>There is no GUI switch to turn these local backups off, but it can easily be done on the command line. Just start Terminal.app and execute the following command:</p>
<p><code>sudo tmutil disablelocal</code></p>
<p>Once you do this, the TM Preferences panel will immediately reflect it &#8211; the text will change from &#8220;Time Machine keeps local snapshots as space permits, and:&#8221; to &#8220;Time Machine keeps:&#8221;. To turn it back on, you can simply run the following in the Terminal:</p>
<p><code>sudo tmutil enablelocal</code></p>
<p>Also note, this feature gets turned on automatically whenever you turn off and on the Time Machine &#8211; so don&#8217;t forget to turn the local backups back off again whenever you do that.</p>
<p>I found out about how to turn off the local backups from this article: <a href="http://osxdaily.com/2011/09/28/disable-time-machine-local-backups-in-mac-os-x-lion/">http://osxdaily.com/2011/09/28/disable-time-machine-local-backups-in-mac-os-x-lion/</a><br />
<!--------------------------------------------------><br />
<h3><a name="hibernation">Turn off hibernation <small style="color: #808080">[laptops only]</small></a></h3>
<p>Another feature of Mac OS turned on by default on laptops is, that it saves all the memory to disk when entering sleep mode. This is to ensure your laptop does not lose your work if it runs out of battery while &#8220;sleeping&#8221;. The more RAM you have, the more gigabytes it writes to the disk every time you close the lid/put it to sleep. I typically do this at least twice a day &#8211; when leaving the office and when going to sleep in the evening. If you are in a similar situation and you have 8GB of RAM, that means your MacBook writes 16 to 24 GB of hibernation data to your SSD every day. Here is how you can turn this off &#8211; it will not only make your SSD&#8217;s life longer, but also significantly speed up the time it takes for your laptop to enter the sleep mode:</p>
<p><code>sudo pmset -a hibernatemode 0</code></p>
<p>I found it in this article: <a href="http://news.metaparadigma.de/osx86-enable-and-disable-hibernation-57/">http://news.metaparadigma.de/osx86-enable-and-disable-hibernation-57/</a>. Reading the man pages for pmset sheds some more light on the factory defaults and meaning of the hibernatemode values:</p>
<blockquote><p>
We do not recommend modifying hibernation settings. Any changes you make are not supported. If you choose to do so anyway, we recommend using one of these three settings. For your sake and mine, please don&#8217;t use anything other 0, 3, or 25.</p>
<p><u>hibernatemode = 0</u> (binary 0000) by default on supported desktops. The system will not back memory up to persistent storage. The system must wake from the contents of memory; the system will lose context on power loss. This is, historically, plain old sleep.</p>
<p><u>hibernatemode = 3</u> (binary 0011) by default on supported portables. The system will store a copy of memory to persistent storage (the disk), and will power memory during sleep. The system will wake from memory, unless a power loss forces it to restore from disk image.</p>
<p><u>hibernatemode = 25</u> (binary 0001 1001) is only settable via pmset. The system will store a copy of memory to persistent storage (the disk), and will remove power to memory. The system will restore from disk image. If you want &#8220;hibernation&#8221; &#8211; slower sleeps, slower wakes, and better battery life, you should use this setting.
</p></blockquote>
<p>Once you turn off hibernation, you can also remove the sleep image file that will free up several GB of disk space (depending on how much RAM you have):</p>
<p><code>sudo rm /var/vm/sleepimage</code><br />
<!--------------------------------------------------><br />
<h3><a name="noatime">Set noatime flag</a></h3>
<p>MacOS (like other unix-based systems) by default records last access time for every file. I.e. every time you read a file, a write is made on the filesystem to record this action. There is no point in doing it and no side effects if you disable that by mounting the root filesystem with noatime flag set. To do that create a file named for example &#8220;com.nullvision.noatime.plist&#8221; (you can pick any other name you wish) in the directory /Library/LaunchDaemons with the following content:</p>
<pre class="brush:xml">&lt;?xml version="1.0" encoding="UTF-8"?&gt;
&lt;!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN"
        "http://www.apple.com/DTDs/PropertyList-1.0.dtd"&gt;
<plist version="1.0">
    <dict>
        <key>Label</key>
        <string>com.nullvision.noatime</string>
        <key>ProgramArguments</key>
        <array>
            <string>mount</string>
            <string>-vuwo</string>
            <string>noatime</string>
            <string>/</string>
        </array>
        <key>RunAtLoad</key>
        &lt;true/&gt;
    </dict>
</plist></pre>
<p>And execute the following command in Terminal:</p>
<p><code>sudo chown root:wheel /Library/LaunchDaemons/com.nullvision.noatime.plist</code></p>
<p>Restart the machine.</p>
<p>You can verify that it worked by executing the following in Terminal:</p>
<p><code>mount | grep " / "</code></p>
<p>You should get the following output (i.e. see noatime in the list in parentheses):</p>
<p><code>/dev/disk0s2 on / (hfs, local, journaled, noatime)</code></p>
<p>This tweak was taken from blogs.nullvision.com, which seems to not be available anymore, but I found a mirror of the old content here: <a href="http://www.icyte.com/saved/blogs.nullvision.com/441781">http://www.icyte.com/saved/blogs.nullvision.com/441781</a><br />
And the same trick (inspired by the same blog) is here: <a href="http://blog.philippklaus.de/2011/04/ssd-optimizations-on-mac-os-x/">http://blog.philippklaus.de/2011/04/ssd-optimizations-on-mac-os-x/</a><br />
<!--------------------------------------------------><br />
<h3><a name="move-home">Move user home directories to HDD <small style="color: #808080">[SSD+HDD only]</small></a></h3>
<p>This tweak is only useful if you have both SSD as well as HDD in your Mac. I&#8217;m using this in my iMac. I moved all the content of /Users folder to the HDD and created a symbolic link from the SSD to it (so that I don&#8217;t have to change the home folder location in the user settings, as I read some applications don&#8217;t like it and may not work correctly). To do that execute the following commands in Terminal:</p>
<pre class="shell">sudo ditto /Users /Volumes/your_hdd_name/Users
sudo mv /Users /Users.bak
sudo ln -s /Volumes/your_hdd_name/Users /Users</pre>
<p>Now, check if your home folders are showing up correctly in Finder. If so, restart your computer.</p>
<p>Finally, delete the back-up of your Users folder on the SSD by typing the following into the Terminal:</p>
<p><code>sudo rm -rf /Users.bak</code><br />
<!--------------------------------------------------><br />
<h3><a name="ramdisk">Use RAM disk or HDD for temporary files</a></h3>
<p>If you have enough RAM, you can dedicate (typically around 256 to 512 MB) of RAM to a RAM disk. RAM disk is a virtual disk that only resides in memory, so is suitable for storing data that need to live only until you shut down your computer. Temporary files are ideal for this. You can create a RAM disk during the boot time and redirect all the temporary files there. To do that, create a file named &#8220;MoveTempFoldersToRamDisk.sh&#8221; in your home directory and put the following content in:<br />
<script src="https://gist.github.com/931579.js?file=MoveTemporaryFoldersToRamdisk_MacOSX.sh"></script>Now, run the following in the Terminal:</p>
<pre class="shell">chmod 755 ~/MoveTempFoldersToRamDisk.sh
~/MoveTempFoldersToRamDisk.sh</pre>
<p>This creates two RAM disks on startup &#8211; one 256MB large for /private/tmp (command &#8220;RAMDisk /private/tmp 256&#8243; in the middle of the above script) and another one 64MB large for /var/run. You can now delete ~/MoveTempFoldersToRamDisk.sh from your computer.<br />
For the changes to take effect, you have to restart.</p>
<p>If you decide to undo this tweak in the future, you can do it simply by deleting /System/Library/StartupItems/RamFS directory from your Mac. E.g. by executing the following command in the Terminal:</p>
<p><code>sudo rm -rf /System/Library/StartupItems/RamFS</code></p>
<p>Again, restart is needed for this to take effect.</p>
<p>There are some small drawbacks to applying this tweak:</p>
<ul>
<li>After applying it it takes a few seconds (2-3 on my machine) to shut down</li>
<li>It lowers the size of RAM usable for applications</li>
</ul>
<p>If you are bothered by the above and have HDD in your Mac as well, you can consider moving the temporary files to HDD instead of the RAM disk. The steps are similar to moving the user home directories. E.g. to move /private/tmp, execute the following in the Terminal:</p>
<pre class="shell">sudo ditto /private/tmp /Volumes/your_hdd_name/private/tmp
sudo rm -rf /private/tmp
sudo ln -s /Volumes/your_hdd_name/private/tmp /private/tmp</pre>
<p>&nbsp;<br />
RAM disk portion of this tweak taken from here: <a href="http://blog.philippklaus.de/2011/04/ssd-optimizations-on-mac-os-x/">http://blog.philippklaus.de/2011/04/ssd-optimizations-on-mac-os-x/</a><br />
Originally suggested by blogs.nullvision.com (mirror at <a href="http://www.icyte.com/saved/blogs.nullvision.com/441781">http://www.icyte.com/saved/blogs.nullvision.com/441781</a>)<br />
<!--------------------------------------------------><br />
<h3><a name="no_sms">Turn off sudden motion sensor <small style="color: #808080">[no HDD only]</small></a></h3>
<p>If SSD is the only drive in your Mac, there is no point in using the <a href="http://en.wikipedia.org/wiki/Sudden_Motion_Sensor">Sudden Motion Sensor</a>. You can switch it off by executing the following in the Terminal:</p>
<p><code>sudo pmset -a sms 0</code></p>
<p>Taken from <a href="http://poller.se/2010/08/optimizing-mac-os-x-for-ssd-drives/">http://poller.se/2010/08/optimizing-mac-os-x-for-ssd-drives/</a><br />
<!--------------------------------------------------><br />
<h3><a name="no_hdd_sleep">Turn off hard drive sleep <small style="color: #808080">[no HDD only]</small></a></h3>
<p>Some websites mention SSD may freeze when the hard drive sleep feature is on, so it is recommended to turn it off. However, you probably don&#8217;t want to do this if you also have a HDD in your Mac. To switch the hard drive sleep off, go to System Preferences-&gt;Energy Saver and uncheck &#8220;Put the hard disk(s) to sleep when possible&#8221;.<br />
<img src="/img/energy-saver.png" alt="Energy Saver preferences pane screeshot" /></p>
<p>&nbsp;<br />
Taken from <a href="http://poller.se/2010/08/optimizing-mac-os-x-for-ssd-drives/">http://poller.se/2010/08/optimizing-mac-os-x-for-ssd-drives/</a><br />
<!--------------------------------------------------><br />
<h3><a name="references">References/Other tweaks</a></h3>
<p>The tweaks that I presented are the tweaks that I thought are worth applying. None of them really limits any features. There are other tweaks, which I did not want to apply as I would be giving up on some functionality (such as disabling the Spotlight) or I was not comfortable with (e.g. disabling the swap files). You can find these and more on the following web sites:<br />
<a href="http://poller.se/2010/08/optimizing-mac-os-x-for-ssd-drives/">http://poller.se/2010/08/optimizing-mac-os-x-for-ssd-drives/</a><br />
<a href="http://blog.philippklaus.de/2011/04/ssd-optimizations-on-mac-os-x/">http://blog.philippklaus.de/2011/04/ssd-optimizations-on-mac-os-x/</a><br />
<a href="http://www.ocztechnologyforum.com/forum/showthread.php?62354">http://www.ocztechnologyforum.com/forum/showthread.php?62354</a></p>
]]></content:encoded>
			<wfw:commentRss>http://blog.alutam.com/2012/04/01/optimizing-macos-x-lion-for-ssd/feed/</wfw:commentRss>
		<slash:comments>16</slash:comments>
		</item>
		<item>
		<title>New Library for Reading and Writing Zip Files in Java</title>
		<link>http://blog.alutam.com/2012/03/31/new-library-for-reading-and-writing-zip-files-in-java/#utm_source=feed&#038;utm_medium=feed&#038;utm_campaign=feed</link>
		<comments>http://blog.alutam.com/2012/03/31/new-library-for-reading-and-writing-zip-files-in-java/#comments</comments>
		<pubDate>Sat, 31 Mar 2012 17:09:51 +0000</pubDate>
		<dc:creator>Martin</dc:creator>
				<category><![CDATA[Java]]></category>
		<category><![CDATA[Password]]></category>
		<category><![CDATA[ZIP]]></category>

		<guid isPermaLink="false">http://blog.alutam.com/?p=149</guid>
		<description><![CDATA[More than two years ago I posted this blog entry, where I showed a little utility for reading password-protected zip files in Java. Since then it seems it helped a lot of people and many asked if I could provide something for the other direction &#8211; i.e. writing encrypted files. Finally I&#8217;ve decided to add [...]]]></description>
			<content:encoded><![CDATA[<p>More than two years ago I posted <a title="this blog entry" href="http://blog.alutam.com/2009/10/31/reading-password-protected-zip-files-in-java/#utm_source=feed&amp;utm_medium=feed&amp;utm_campaign=feed">this blog entry</a>, where I showed a little utility for reading password-protected zip files in Java. Since then it seems it helped a lot of people and many asked if I could provide something for the other direction &#8211; i.e. writing encrypted files. Finally I&#8217;ve decided to add that as well as improve the original class for reading and recently I published a small open source project which provides both the ZipDecryptInputStream (for reading) as well as ZipEncryptOutputStream (for writing). The project is named ziputils and is available here: <a title="https://bitbucket.org/matulic/ziputils/overview" href="https://bitbucket.org/matulic/ziputils/overview">https://bitbucket.org/matulic/ziputils/overview</a>.</p>
<p>The usage is very simple. ZipDecryptInputStream can be used in the same way as outlined in my <a title="Reading Password-Protected ZIP Files in Java" href="http://blog.alutam.com/2009/10/31/reading-password-protected-zip-files-in-java/#utm_source=feed&amp;utm_medium=feed&amp;utm_campaign=feed">old blog entry</a>. ZipEncryptOutputStream which I added can be used in a very similar way:</p>
<pre class="brush:java">import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.zip.ZipEntry;
import java.util.zip.ZipOutputStream;

// usage: java Main zip-file-name password filename1 [filename2 [filename3 [...]]]
public class Main {
    public static void main(String[] args) throws IOException {
        // create a stream that will encrypt the resulting zip file
        // using the password provided in the second command line argument
        ZipEncryptOutputStream zeos = new ZipEncryptOutputStream(new FileOutputStream(args[0]), args[1]);
        // create the standard zip output stream, initialize it with our encrypting stream
        ZipOutputStream zos = new ZipOutputStream(zeos);

        // write the zip file
        for (int i = 2; i &lt; args.length; i++) {
            ZipEntry ze = new ZipEntry(args[i]);
            zos.putNextEntry(ze);
            InputStream is = new FileInputStream(args[i]);
            int b;
            while ((b = is.read()) != -1) {
                zos.write(b);
            }
            zos.closeEntry();
        }
        zos.close();
    }
}</pre>
<p>You can find more about how to use the classes in the <a title="project javadoc" href="http://matulic.bitbucket.org/apidocs/ziputils-1.0/index.html">project javadoc</a>. To download the ziputils jar, go to the <a title="ziputils downloads" href="https://bitbucket.org/matulic/ziputils/downloads">project downloads page</a>. Enjoy!</p>
]]></content:encoded>
			<wfw:commentRss>http://blog.alutam.com/2012/03/31/new-library-for-reading-and-writing-zip-files-in-java/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>ooomailer 1.0 &#8211; More Flexible Out-of-office Replies</title>
		<link>http://blog.alutam.com/2011/10/02/ooomailer-1-0-more-flexible-out-of-office-replies/#utm_source=feed&#038;utm_medium=feed&#038;utm_campaign=feed</link>
		<comments>http://blog.alutam.com/2011/10/02/ooomailer-1-0-more-flexible-out-of-office-replies/#comments</comments>
		<pubDate>Sun, 02 Oct 2011 03:15:06 +0000</pubDate>
		<dc:creator>Martin</dc:creator>
				<category><![CDATA[Java]]></category>
		<category><![CDATA[auto-replies]]></category>
		<category><![CDATA[ooomailer]]></category>

		<guid isPermaLink="false">http://blog.alutam.com/?p=139</guid>
		<description><![CDATA[In my day job I have to deal with a huge amount of e-mails each day &#8211; most of them are not urgent, but some are. When I go for vacation or on a business trip, I need to let people know I am not available and won&#8217;t respond until I get back (and provide [...]]]></description>
			<content:encoded><![CDATA[<p>In my day job I have to deal with a huge amount of e-mails each day &#8211; most of them are not urgent, but some are. When I go for vacation or on a business trip, I need to let people know I am not available and won&#8217;t respond until I get back (and provide an alternate contact for urgent matters). These days pretty much every mail server has a &#8220;vacation message&#8221; feature, that allows you to do exactly that &#8211; supports sending automated responses to all e-mails coming to your inbox, letting others know you won&#8217;t be able to read the message before a given date. However the implementation of that feature varies from server to server.</p>
<p>I have several e-mail accounts on several mail servers and I found myself in a situation when I needed more flexibility in the way I set up my vacation message. Being involved in several open source projects and subscribed to many open mailing lists, I needed to make sure I don&#8217;t spam those lists or users of those lists (who may not know me) with my vacation auto-replies. Even people I do want to notify don&#8217;t need to get my auto-reply to every message that reaches me &#8211; notification once in several days is good enough. And I needed to customize the vacation message for internal recipients (e.g. providing links to internal resources) and have it slightly more detailed than the auto-replies that go to external people.</p>
<p>So, a couple of months back, the weekend before my summer vacation I sat down and implemented a simple utility that provides me with this flexibility. Since then I used it several times, fixed a few issues, and <a href="http://blogs.oracle.com/alexismp">Alexis</a> (a colleague of mine) contributed some more improvements. At this point I am pretty confident the tool works smoothly, so decided to release version 1.0. Give it a try if you are in a similar situation &#8211; the tool and the source code are available at <a href="http://hg.alutam.com/ooomailer" title="http://hg.alutam.com/ooomailer">http://hg.alutam.com/ooomailer</a>.</p>
]]></content:encoded>
			<wfw:commentRss>http://blog.alutam.com/2011/10/02/ooomailer-1-0-more-flexible-out-of-office-replies/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<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>Reading Password-Protected ZIP Files in Java</title>
		<link>http://blog.alutam.com/2009/10/31/reading-password-protected-zip-files-in-java/#utm_source=feed&#038;utm_medium=feed&#038;utm_campaign=feed</link>
		<comments>http://blog.alutam.com/2009/10/31/reading-password-protected-zip-files-in-java/#comments</comments>
		<pubDate>Sat, 31 Oct 2009 12:13:34 +0000</pubDate>
		<dc:creator>Martin</dc:creator>
				<category><![CDATA[Java]]></category>
		<category><![CDATA[Password]]></category>
		<category><![CDATA[ZIP]]></category>

		<guid isPermaLink="false">http://blog.alutam.com/?p=102</guid>
		<description><![CDATA[On a recent &#8220;fun&#8221; project, I needed my application to be able to access password-protected zip files of a particular format. It was one of these features I thought will take me no time to implement. Anyway, to my surprise, neither JDK supports password-protected ZIP files, nor I was able to find a suitable Java [...]]]></description>
			<content:encoded><![CDATA[<p>On a recent &#8220;fun&#8221; project, I needed my application to be able to access password-protected zip files of a particular format. It was one of these features I thought will take me no time to implement. Anyway, to my surprise, neither JDK supports password-protected ZIP files, nor I was able to find a suitable Java open source library I could use for that purpose. So, I ended up writing the utility class on my own. I wrote an implementation of <code>java.io.InputStream</code> that filters the ZIP file data and turns a password-protected ZIP into an unprotected one on the fly &#8211; so the stream can be nicely chained with <code>java.util.zip.ZipInputStream</code>. Although the class is specifically targeted at the particular type of ZIP files I had to deal with (see the limitations below), maybe other people have to deal with the same type of files, or this class can provide a good start for others to turn it into a utility that would work with any type of ZIP (maybe I will do it myself some day &#8211; for now I don&#8217;t have time).<br />
To implement this class I used the <a href="http://www.pkware.com/documents/casestudies/APPNOTE.TXT">ZIP File Format Specification</a> as the source of information. I also used the <a href="http://www.7-zip.org/">7-zip project</a> (C++) as a reference during the debugging to verify my understanding of the ZIP spec. and the CRC algorithm.<br />
So, here is the class:</p>
<pre class="brush:java">import java.io.IOException;
import java.io.InputStream;

public class ZipDecryptInputStream extends InputStream {
    private static final int[] CRC_TABLE = new int[256];
    // compute the table
    // (could also have it pre-computed - see http://snippets.dzone.com/tag/crc32)
    static {
        for (int i = 0; i &lt; 256; i++) {
            int r = i;
            for (int j = 0; j &lt; 8; j++) {
                if ((r &amp; 1) == 1) {
                    r = (r &gt;&gt;&gt; 1) ^ 0xedb88320;
                } else {
                    r &gt;&gt;&gt;= 1;
                }
            }
            CRC_TABLE[i] = r;
        }
    }

    private static final int DECRYPT_HEADER_SIZE = 12;
    private static final int[] LFH_SIGNATURE = {0x50, 0x4b, 0x03, 0x04};

    private final InputStream delegate;
    private final String password;
    private final int keys[] = new int[3];

    private State state = State.SIGNATURE;
    private int skipBytes;
    private int compressedSize;
    private int value;
    private int valuePos;
    private int valueInc;

    public ZipDecryptInputStream(InputStream stream, String password) {
        this.delegate = stream;
        this.password = password;
    }

    @Override
    public int read() throws IOException {
        int result = delegate.read();
        if (skipBytes == 0) {
            switch (state) {
                case SIGNATURE:
                    if (result != LFH_SIGNATURE[valuePos]) {
                        state = State.TAIL;
                    } else {
                        valuePos++;
                        if (valuePos &gt;= LFH_SIGNATURE.length) {
                            skipBytes = 2;
                            state = State.FLAGS;
                        }
                    }
                    break;
                case FLAGS:
                    if ((result &amp; 1) == 0) {
                        throw new IllegalStateException("ZIP not password protected.");
                    }
                    if ((result &amp; 64) == 64) {
                        throw new IllegalStateException("Strong encryption used.");
                    }
                    if ((result &amp; 8) == 8) {
                        throw new IllegalStateException("Unsupported ZIP format.");
                    }
                    result -= 1;
                    compressedSize = 0;
                    valuePos = 0;
                    valueInc = DECRYPT_HEADER_SIZE;
                    state = State.COMPRESSED_SIZE;
                    skipBytes = 11;
                    break;
                case COMPRESSED_SIZE:
                    compressedSize += result &lt;&lt; (8 * valuePos);
                    result -= valueInc;
                    if (result &lt; 0) {
                        valueInc = 1;
                        result += 256;
                    } else {
                        valueInc = 0;
                    }
                    valuePos++;
                    if (valuePos &gt; 3) {
                        valuePos = 0;
                        value = 0;
                        state = State.FN_LENGTH;
                        skipBytes = 4;
                    }
                    break;
                case FN_LENGTH:
                case EF_LENGTH:
                    value += result &lt;&lt; 8 * valuePos;
                    if (valuePos == 1) {
                        valuePos = 0;
                        if (state == State.FN_LENGTH) {
                            state = State.EF_LENGTH;
                        } else {
                            state = State.HEADER;
                            skipBytes = value;
                        }
                    } else {
                        valuePos = 1;
                    }
                    break;
                case HEADER:
                    initKeys(password);
                    for (int i = 0; i &lt; DECRYPT_HEADER_SIZE; i++) {
                        updateKeys((byte) (result ^ decryptByte()));
                        result = delegate.read();
                    }
                    compressedSize -= DECRYPT_HEADER_SIZE;
                    state = State.DATA;
                    // intentionally no break
                case DATA:
                    result = (result ^ decryptByte()) &amp; 0xff;
                    updateKeys((byte) result);
                    compressedSize--;
                    if (compressedSize == 0) {
                        valuePos = 0;
                        state = State.SIGNATURE;
                    }
                    break;
                case TAIL:
                    // do nothing
            }
        } else {
            skipBytes--;
        }
        return result;
    }

    @Override
    public void close() throws IOException {
        delegate.close();
        super.close();
    }

    private void initKeys(String password) {
        keys[0] = 305419896;
        keys[1] = 591751049;
        keys[2] = 878082192;
        for (int i = 0; i &lt; password.length(); i++) {
            updateKeys((byte) (password.charAt(i) &amp; 0xff));
        }
    }

    private void updateKeys(byte charAt) {
        keys[0] = crc32(keys[0], charAt);
        keys[1] += keys[0] &amp; 0xff;
        keys[1] = keys[1] * 134775813 + 1;
        keys[2] = crc32(keys[2], (byte) (keys[1] &gt;&gt; 24));
    }

    private byte decryptByte() {
        int temp = keys[2] | 2;
        return (byte) ((temp * (temp ^ 1)) &gt;&gt;&gt; 8);
    }

    private int crc32(int oldCrc, byte charAt) {
        return ((oldCrc &gt;&gt;&gt; 8) ^ CRC_TABLE[(oldCrc ^ charAt) &amp; 0xff]);
    }

    private static enum State {
        SIGNATURE, FLAGS, COMPRESSED_SIZE, FN_LENGTH, EF_LENGTH, HEADER, DATA, TAIL
    }
}</pre>
<p>These are the limitations:</p>
<ul>
<li>Only the &#8220;Traditional PKWARE Encryption&#8221; is supported (spec. section VII)</li>
<li>Files that have the &#8220;compressed length&#8221; information at the end of the data section (rather than at the beginning) are not supported (see &#8220;general purpose bit flag&#8221;, bit 3 in section V, subsection J in the spec.)</li>
</ul>
<p>And this is how you can use it in your code:</p>
<pre class="brush:java">import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.zip.ZipEntry;
import java.util.zip.ZipInputStream;

// usage: java Main [filename] [password]
public class Main {
    public static void main(String[] args) throws IOException {
        // password-protected zip file I need to read
        FileInputStream fis = new FileInputStream(args[0]);
        // wrap it in the decrypt stream
        ZipDecryptInputStream zdis = new ZipDecryptInputStream(fis, args[1]);
        // wrap the decrypt stream by the ZIP input stream
        ZipInputStream zis = new ZipInputStream(zdis);

        // read all the zip entries and save them as files
        ZipEntry ze;
        while ((ze = zis.getNextEntry()) != null) {
            FileOutputStream fos = new FileOutputStream(ze.getName());
            int b;
            while ((b = zis.read()) != -1) {
                fos.write(b);
            }
            fos.close();
            zis.closeEntry();
        }
        zis.close();
    }
}</pre>
]]></content:encoded>
			<wfw:commentRss>http://blog.alutam.com/2009/10/31/reading-password-protected-zip-files-in-java/feed/</wfw:commentRss>
		<slash:comments>56</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>JavaFX Password Field</title>
		<link>http://blog.alutam.com/2009/09/12/javafx-password-field/#utm_source=feed&#038;utm_medium=feed&#038;utm_campaign=feed</link>
		<comments>http://blog.alutam.com/2009/09/12/javafx-password-field/#comments</comments>
		<pubDate>Sat, 12 Sep 2009 11:33:02 +0000</pubDate>
		<dc:creator>Martin</dc:creator>
				<category><![CDATA[JavaFX]]></category>
		<category><![CDATA[Password]]></category>
		<category><![CDATA[TextBox]]></category>

		<guid isPermaLink="false">http://blog.alutam.com/?p=76</guid>
		<description><![CDATA[As I mentioned in My First Experience with JavaFX blog, there is no password field in JavaFX, so I had to google for some workarounds. Although I found a few, none of them worked flawlessly, so last night I decided to spend some time trying to come up with a password field that would really [...]]]></description>
			<content:encoded><![CDATA[<p>As I mentioned in <a href="http://blog.alutam.com/2009/08/21/my-first-experience-with-javafx/#utm_source=feed&amp;utm_medium=feed&amp;utm_campaign=feed">My First Experience with JavaFX</a> blog, there is no password field in JavaFX, so I had to google for some workarounds. Although I found a few, none of them worked flawlessly, so last night I decided to spend some time trying to come up with a password field that would really work as expected. And, I think I managed to come up with an elegant and simple solution. No hacking in form of covering the text area with additional components or adding effects that blur the text box (including the caret and component borders). It looks and behaves exactly as you would expect of a password field. Click on the following picture to try it out:<br />
<script type="text/javascript">// <![CDATA[
function showApplet() { 
    document.getElementById("Applet").innerHTML = "<iframe alt=PasswordBoxDemo scrolling=no frameborder=0 src='/apps/javafx/PasswordBoxDemo/PasswordBoxDemo.html' height=100 width=300 ></iframe>"; 
}
// ]]&gt;</script></p>
<div id="Applet" style="border: 1px solid; text-align: left;"><a href="##utm_source=feed&amp;utm_medium=feed&amp;utm_campaign=feed"><img onclick="showApplet();" src="/img/pbdemo.png" alt="" /></a></div>
<p>Or click the following button for standalone mode:<br />
<a href="/apps/javafx/PasswordBoxDemo/PasswordBoxDemo.jnlp#utm_source=feed&amp;utm_medium=feed&amp;utm_campaign=feed"><img src="/img/jws-launch-button.jpg" alt="" /></a><br />
And here is how it is implemented:</p>
<div class="codebox">
<pre class="brush:jfx">import javafx.scene.control.TextBox;
import javafx.util.Math;

/** * @author Martin Matula */
public class PasswordBox extends TextBox {
    public-read var password = "";

    override function replaceSelection(arg) {
        var pos1 = Math.min(dot, mark);
        var pos2 = Math.max(dot, mark);
        password = "{password.substring(0, pos1)}{arg}{password.substring(pos2)}";
        super.replaceSelection(getStars(arg.length()));
    }

    override function deleteNextChar() {
        if ((mark == dot) and (dot &lt; password.length())) {
            password = "{password.substring(0, dot)}{password.substring(dot + 1)}";
        }
        super.deleteNextChar();
    }

    override function deletePreviousChar() {
        if ((mark == dot) and (dot &gt; 0)) {
            password = "{password.substring(0, dot - 1)}{password.substring(dot)}";
        }
        super.deletePreviousChar();
    }

    function getStars(len: Integer): String {
        var result: String = "";
        for (i in [1..len]) {
            result = "{result}*";
        }
        result;
    }
}</pre>
</div>
<p>Quite simple, isn&#8217;t it? Here is how it is used in the Main class:</p>
<div class="codebox">
<pre class="brush:jfx">import javafx.stage.Stage;
import javafx.scene.Scene;
import javafx.scene.text.Text;

var password: PasswordBox;

var stage: Stage = Stage {
    title: "PasswordBox Demo"
    width: 200
    height: 100
    scene: Scene {
        content: [
            password = PasswordBox {
                translateX: 10
                translateY: 10
                columns: 20
            },
            Text {
                x: 10
                y: 50
                content: bind password.password
            }
        ]
    }
}</pre>
</div>
<p>I guess there is still a room for improving the API &#8211; the real password is stored in the <code>password</code> property, while the <code>text</code> property became useless and should never be set by a client. If you want to populate the field with a remembered password, you need to do it by calling <code>replaceSelection("password")</code> on the password field after it&#8217;s initialization (rather than setting the <code>text</code> or the <code>password</code> properties). Anyway, I wanted to keep the code simple so that you can easily see the basic idea behind it.</p>
]]></content:encoded>
			<wfw:commentRss>http://blog.alutam.com/2009/09/12/javafx-password-field/feed/</wfw:commentRss>
		<slash:comments>12</slash:comments>
		</item>
		<item>
		<title>More Struggling with JavaFX</title>
		<link>http://blog.alutam.com/2009/09/09/more-struggling-with-javafx/#utm_source=feed&#038;utm_medium=feed&#038;utm_campaign=feed</link>
		<comments>http://blog.alutam.com/2009/09/09/more-struggling-with-javafx/#comments</comments>
		<pubDate>Wed, 09 Sep 2009 21:09:21 +0000</pubDate>
		<dc:creator>Martin</dc:creator>
				<category><![CDATA[JavaFX]]></category>

		<guid isPermaLink="false">http://blog.alutam.com/?p=59</guid>
		<description><![CDATA[In my first blog on JavaFX I mentioned polishing the details takes a lot of time and I thought it is due to the lack of experience. As I am spending more time trying to develop a real-life desktop application, I am becoming more doubtful about this. Too often I have to spend too much [...]]]></description>
			<content:encoded><![CDATA[<p>In my first blog on JavaFX I mentioned polishing the details takes a lot of time and I thought it is due to the lack of experience. As I am spending more time trying to develop a real-life desktop application, I am becoming more doubtful about this. Too often I have to spend too much time trying to make the UI behave the way I want and sometimes I just have to give up and change my mind about the desired design to avoid wasting even more time. It is hard to provide concrete examples and ask for help as my application&#8217;s UI is quite complex. But recently I could isolate a simple case that I can use to demonstrate what I am talking about.<br />
Look at the following simple code:</p>
<pre class="brush:jfx">import javafx.stage.Stage;
import javafx.scene.Scene;
import javafx.scene.layout.VBox;
import javafx.scene.paint.Color;
import javafx.scene.shape.Rectangle;

var rec1: Rectangle;
var stage: Stage = Stage {
    title: "Rectangles"
    width: 200
    height: 200
    scene: Scene {
        content: [
            VBox {
                spacing: 0
                content: [
                    rec1 = Rectangle {
                        fill: Color.BLACK
                        width: bind stage.scene.width
                        height: 50
                    }
                    Rectangle {
                        fill: Color.GRAY
                        width: bind stage.scene.width
                        height: bind stage.scene.height - rec1.height
                    }
                ]
            }
        ]
    }
}</pre>
<p>It creates a window containing two rectangles that fully cover the scene:<br />
<img src="/img/rectangles1.png" alt="Rectangles screenshot" /><br />
All works great at this point.<br />
Now, let&#8217;s see what happens when I set the stroke to Color.BLACK:</p>
<pre class="brush:jfx; first-line:22; highlight:24;">                    Rectangle {
                        fill: Color.GRAY
                        stroke: Color.BLACK
                        width: bind stage.scene.width
                        height: bind stage.scene.height - rec1.height
                    }</pre>
<p>Running this I am getting the following result:<br />
<img src="/img/rectangles2.png" alt="Rectangles screenshot" /><br />
As you can see, besides the fact that the rectangle now has the black border, it also jumped both horizontally and vertically and uncovered a strip of white background color. Going back and forth trying to find a workaround can be time consuming &#8211; I did not find a good way of debugging this kind of issues. Now imagine the same thing happens when the UI contains many more nested components. Trying to figure out which one causes the problem and how to tweak things to get the desired result may be endless.<br />
Anyway, I am still not giving up! Has anyone found an efficient way of debugging and resolving this type of issues quickly?</p>
]]></content:encoded>
			<wfw:commentRss>http://blog.alutam.com/2009/09/09/more-struggling-with-javafx/feed/</wfw:commentRss>
		<slash:comments>4</slash:comments>
		</item>
	</channel>
</rss>

