<?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>Benny's Blog &#187; java</title>
	<atom:link href="http://blog.projectnibble.org/tag/java/feed/" rel="self" type="application/rss+xml" />
	<link>http://blog.projectnibble.org</link>
	<description>House Of Code</description>
	<lastBuildDate>Fri, 13 Aug 2010 15:06:14 +0000</lastBuildDate>
	<language>en</language>
	<sy:updatePeriod>hourly</sy:updatePeriod>
	<sy:updateFrequency>1</sy:updateFrequency>
	<generator>http://wordpress.org/?v=abc</generator>
		<item>
		<title>Java generic paged lazy List with JSF/JPA example implementation</title>
		<link>http://blog.projectnibble.org/2009/07/22/java-generic-paged-lazy-list-with-jsfjpa-example-implementation/</link>
		<comments>http://blog.projectnibble.org/2009/07/22/java-generic-paged-lazy-list-with-jsfjpa-example-implementation/#comments</comments>
		<pubDate>Wed, 22 Jul 2009 12:58:53 +0000</pubDate>
		<dc:creator>Benny Bottema</dc:creator>
				<category><![CDATA[JSF/Facelets]]></category>
		<category><![CDATA[Uncategorized]]></category>
		<category><![CDATA[java]]></category>
		<category><![CDATA[JPA]]></category>
		<category><![CDATA[JSF]]></category>
		<category><![CDATA[lazy loading]]></category>
		<category><![CDATA[paging]]></category>
		<category><![CDATA[programming]]></category>
		<category><![CDATA[richfaces]]></category>

		<guid isPermaLink="false">http://blog.projectnibble.org/?p=310</guid>
		<description><![CDATA[Here&#8217;s a list implementation I came up with to enable true paged data fetching completely transparent to any user. It works independent of persistence layers, such as JPA implementations etc. download PagedList Lazy loading with the PagedList Originally I made the PagedList because I needed paged data fetching using JMS queues for a JSF Rich [...]]]></description>
			<content:encoded><![CDATA[<p>Here&#8217;s a list implementation I came up with to enable true paged data fetching completely transparent to any user. It works independent of persistence layers, such as JPA implementations etc.</p>
<ul>
<li><a href="http://projectnibble.org/dump/blog/pagedlist/PagedList.rar">download PagedList</a></li>
</ul>
<p><span id="more-310"></span></p>
<h3>Lazy loading with the PagedList</h3>
<p>Originally I made the PagedList because I needed paged data fetching using JMS queues for a JSF Rich datatable and datascroller; a common problem in JSF but less commonly solved, even less documented and less still solved in an elegant way. Most people are able to solve this problem by using an <a href="https://www.hibernate.org/43.html">OpenSessionInView</a> antipattern (keeping Hibernate-oid session open until the view requests the lazy loaded data) but since I&#8217;m using JMS queue, this was not an option. I decided to circumvent the entire JSF to JMS queue integration by providing my data in a paging lazy list. It works beautifully.</p>
<pre  name="code" class="java">
public class PagedList&lt;Dto, QueryParameters&gt; extends AbstractList&lt;Dto&gt; {

    private final QueryParameters queryParameters;

    private final PagedDataProvider&lt;Dto, QueryParameters&gt; pagedDataProvider;

    private final Map&lt;Integer, List&lt;Dto&gt;&gt; fetchedPages;

    private final int dataSize;

    private final int pageSize;

    public PagedList(PagedDataProvider&lt;Dto, QueryParameters&gt; pagedDataProvider, QueryParameters queryParameters) {
        this.pagedDataProvider = pagedDataProvider;
        this.queryParameters = queryParameters;
        fetchedPages = new HashMap&lt;Integer, List&lt;Dto&gt;&gt;();
        dataSize = pagedDataProvider.getDataSize();
        pageSize = pagedDataProvider.getPageSize();
    }

    public Dto get(int index) {
        int pageNr = (int) Math.floor(index / pageSize);
        if (fetchedPages.get(pageNr) == null) {
            fetchedPages.put(pageNr, pagedDataProvider.provide(pageNr, queryParameters));
        }
        return fetchedPages.get(pageNr).get(index % pageSize);
    }

    public int size() {
        return dataSize;
    }
}
</pre>
<p>It is different from <a href="http://commons.apache.org/collections/apidocs/org/apache/commons/collections/list/LazyList.html">Apache&#8217;s LazyList</a> (and many other implementations) in that it relies on an external dataprovider to provide the dataset&#8217;s total size, pagesize and data provision itself. For example, using my lazy list version the <i>size()</i> method actually returns the total size of data potentially available, not just physically available in the list at the present. This way the list works completely transparent to its users. Also, there is no simple factory being passed in that creates dummy objects or something: actual remote data is being fecthed in pages by a data provider. Pages being fetched are independent of each other; when requesting page 5, page 1 through 4 are not need or fetched.</p>
<p>The PagedList works in combo with a <em>PagedDataProvider</em> interface that external dataproviders (some dao for example) could implement. So it has no dependencies whatsoever on some specific implementation. The paged data provider provides the total size of the dataset, the page size and pages of the dataset itself when needed.</p>
<h3>Example implementation for JSF and JPA dao</h3>
<p>Here&#8217;s an example implementation which ties a JSF Richfaces datatable to a JPA dao using a PagedList. I cut out the service layer, view handlers/controllers and whatnot for sake of simplicity.</p>
<pre  name="code" class="xhtml">
&lt;rich:dataTable id="searchResults" value="#{appleService.apples}" var="apple"&gt;
...
&lt;/rich:dataTable&gt;
</pre>
<pre  name="code" class="java">
/**
 * JPA dao which acts as paged data provider for the paged list.
 *
 * Relies on two JPA named queries specified on the Entity being fetched.
 *
 * @author Benny Bottema
 * @see PagedDataProvider
 */
public class AppleJPADao implements AppleDao, PagedDataProvider&lt;AppleDto, AppleQueryParameters&gt; {

    // entitymanager stuff omitted for example (real world: injected by Spring)

    private static final int PAGESIZE = 50;

    /**
     * @see AppleDao#getAllApples(String, String)
     */
    public List&lt;AppleDto&gt; getAllApples(String type, String quality) {
        // optional query parameters: can be null
        AppleQueryParameters params = new AppleQueryParameters();
        params.setAppleType(type);
        params.setAppleQuality(quality);
        return new PagedList&lt;AppleDto, AppleQueryParameters&gt;(this, params);
    }

    /**
     * @see PagedDataProvider#provide(int, Object)
     */
    public List&lt;AppleDto&gt; provide(int page, AppleQueryParameters queryCriteria) {
        Query query = entityManager.createNamedQuery("Apple.findAll");
        query.setParameter("appleType", queryCriteria.getAppleType());
        query.setParameter("appleQuality", queryCriteria.getAppleQuality());
        // JPA's paging mechanism
        query.setFirstResult(PAGESIZE * page);
        query.setMaxResults(PAGESIZE);
        return (List&lt;AppleDto>) query.getResultList();
    }

    /**
     * @see PagedDataProvider#getDataSize()
     */
    public int getDataSize() {
        Query countQuery = entityManager.createNamedQuery("Apple.count");
        return ((Long) countQuery.getSingleResult()).intValue();
    }

    /**
     * @see PagedDataProvider#provide()
     */
    public int getPageSize() {
        return PAGESIZE;
    }
}
</pre>
<h3>Known issues</h3>
<p>So far there is only one known issue, which is more of a problem with lazy loading in general: synchronizing the lazy loading list with the remote dataset to avoid becoming stale when changes happen to the dataset. Example: when the dataset changes, the size of the list is not being updated and the <i>get()</i> method may try to fetch wrong or even unavailable data throwing an exception. Since I&#8217;m using the paged list in a limited way, I&#8217;ve not yet encountered this problem. </p>
<p>One way would be to solve this problem for the Rich datable and datascroller specifically is to have a a4j poll component that listens for dataset changes on the server and refreshes the entire datatable as necessary. Just thinking out loud here&#8230;</p>
<p><a href="http://blog.projectnibble.org/2009/07/22/java-generic-paged-lazy-list-with-jsfjpa-example-implementation">trackback</a></p>
]]></content:encoded>
			<wfw:commentRss>http://blog.projectnibble.org/2009/07/22/java-generic-paged-lazy-list-with-jsfjpa-example-implementation/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>JSF is a diamond in the rough, you just need to make it shine</title>
		<link>http://blog.projectnibble.org/2009/05/24/jsf-is-a-diamond-in-the-rough-you-just-need-to-make-it-shine/</link>
		<comments>http://blog.projectnibble.org/2009/05/24/jsf-is-a-diamond-in-the-rough-you-just-need-to-make-it-shine/#comments</comments>
		<pubDate>Sun, 24 May 2009 13:30:53 +0000</pubDate>
		<dc:creator>Benny Bottema</dc:creator>
				<category><![CDATA[JSF/Facelets]]></category>
		<category><![CDATA[PrettyFaces]]></category>
		<category><![CDATA[a4j]]></category>
		<category><![CDATA[facelets]]></category>
		<category><![CDATA[java]]></category>
		<category><![CDATA[JSF]]></category>
		<category><![CDATA[richfaces]]></category>
		<category><![CDATA[seam]]></category>
		<category><![CDATA[tomahawk]]></category>

		<guid isPermaLink="false">http://blog.projectnibble.org/?p=108</guid>
		<description><![CDATA[[RE: JSF – Still pretty much a steaming pile of donkey turd] &#8211; I was replying to Wille Faler’s post about why JSF sucks, when the comment was getting too large, so I made it into a post on my own blog. JSF is hard to learn yes, but in my opinion it doesn&#8217;t suck [...]]]></description>
			<content:encoded><![CDATA[<div style="color:#999999">
<p>[RE: JSF – Still pretty much a steaming pile of donkey turd] &#8211; I was replying to <a href="http://faler.wordpress.com/2007/03/13/jsf-still-pretty-much-a-steaming-pile-of-donkey-turd/">Wille Faler’s post about why JSF sucks</a>, when the comment was getting too large, so I made it into a post on my own blog.</p>
</div>
<hr />
<p><b>JSF is hard to learn yes, but in my opinion it doesn&#8217;t suck as bad as Wille says. All the points Wille mentions can be solved by certain libraries or write-once reusable solutions (I&#8217;ve included my &#8216;magical&#8217; combination of frameworks on the bottom). JSF is a diamond in the rough, you just need to make it shine.</b></p>
<p><span id="more-108"></span></p>
<h3>The devil is in the details</h3>
<p>There are a couple of pitfalls you need to know about with JSF. It&#8217;s all really a matter of having read a good book about JSF that points them out, or having learned them the hard way. Luckily I&#8217;ve had some guidance by experienced colleagues of mine; I&#8217;m guessing that&#8217;s the missing factor in Wille&#8217;s situation.</p>
<p>Referring to the pitfalls you need to know about, I&#8217;m talking about the common beginner&#8217;s problems like using JSTL c:tags that cause havoc when combined with those of jsf and facelets. I&#8217;m talking about the Ajax4Jsf details as Wille mentioned: once you know what to use it&#8217;s easy. Those 48 attributes? most of them are inherited and never used and you can forget about them, and that&#8217;s the learning curve. Once you know the right ones, it&#8217;s using exactly those, over and over again. And things like how you can incorporate Spring security and stuff like that. Another pitfall that comes to mind is how action=&#8221;" work quirky with navigation rules when using the array notation (action=&#8221;controller['action']&#8220;). And ofcourse there&#8217;s the issue of <a href="http://blog.projectnibble.org/2008/07/26/parameterized-jsf-facelets-validators/">parameterized JSF validators</a>, which needs some understanding. All pitfalls that can baffle a beginner or intermediate.</p>
<p>The thing with JSF is there are a number of little things that are hard to solve, but once you&#8217;re past that it <i>does</i> make you much more productive. You just have to have a solid base to start from each project. The pitfalls learning curve is definitely a downside of JSF, but <a href="http://blogs.jsfcentral.com/jsf2group/entry/jsf_2_primer">JSF 2.0</a> is in the making to solve all these issues.</p>
<h3>Bad performance or beginner&#8217;s mistake?</h3>
<p>Then there is this performance issue Wille mentions, where I think he missed the target: JSF does not have to be slow at all. It really depends on how you treat your backing beans. JSF has the weird tendency to call setters/getters multiple times, which seems utterly pointless (it&#8217;s related to resolving valuebindings in nested components). I&#8217;ve made the mistake before to directly retrieve values from a controller/service in my views instead of a static model (backing bean): this is what makes things slow. JSF in itself isn&#8217;t that slow for a webapp: yes there are many redundant calls but we&#8217;re not dealing with a realtime simulation application, webapps do just fine. On a sidenote, it also depends on the implementation&#8230; JSF is a reference specification, while there are various implementations of the framework (IBM&#8217;s, Sun&#8217;s etc.)</p>
<h3>SEO friendly JSF?</h3>
<p>Ahh, but for the <a href="http://blog.projectnibble.org/2009/03/20/bookmarkable-and-seo-friendly-jsf/">JSF Search Engine Friendliness</a>. That&#8217;s solved too, somewhat. There&#8217;s is a framework called <a href="http://ocpsoft.com/prettyfaces/">PrettyFaces</a> which allows you to dynamically generate/interpret pretty GET urls with bean values. It&#8217;s a great framework that solves a common problem, but there still exists the problem that existing jsf/facelets/richfaces components are not generating SEO HTML code. That&#8217;s really the fault of the component makers, not JSF, though JSF definitely isn&#8217;t innocent with its POST obsession: PrettyFaces fixes at least that.</p>
<h3>Common sense: use frameworks to avoid most pitfalls</h3>
<p>Once you&#8217;ve got those kind of things down and use a good framework combo, JSF is straightforward. You won&#8217;t really need to know about the various phases and you can be very productive if you&#8217;ve set up the jsf/facelets components right. I&#8217;ve worked with JSF intensively for about a year now in various projects with various implementations and I hardly ever need to use phaselisteners and that sort of stuff. The rare cases where you do need them, you can define these things ones and reuse them in other projects. With this approach I&#8217;ve created a template project with some standard libraries, phaselisteners, security set up, facelets components etc. and I&#8217;m up and running in no time.</p>
<p>I haven&#8217;t sanitized or otherwise cleaned up the template project so I won&#8217;t put that up for the time being, but at least I can tell you what frameworks are in it by default. </p>
<ul>The magical combination that works for me and my colleagues: </p>
<li>JSF (MVC)</li>
<li>Facelets (Templating, use of XHTML)</li>
<li><a href="http://livedemo.exadel.com/richfaces-demo/richfaces/inputNumberSlider.jsf?c=inputNumberSlider&#038;tab=usage">Richfaces</a> (component suite)</li>
<li><a href="http://livedemo.exadel.com/richfaces-demo/richfaces/commandButton.jsf?c=commandButton&#038;tab=usage">Richfaces A4J</a> (Ajax support)</li>
<li><a href="http://myfaces.apache.org/tomahawk/index.html">Tomahawk</a> (only for <a href="http://myfaces.apache.org/tomahawk/extensionsFilter.html">file uploads with the Extensions Filter</a>)</li>
<li>PrettyFaces (for indexable GET urls)</li>
</ul>
<p>Now that I&#8217;ve mentioned these, you should check out <a href="http://www.jboss.com/products/seam/">JBoss Seam</a> as well, which basically is supposed to do everything the above libraries do combined, plus a couple of things more like solving the <a href="http://matthiaswessendorf.wordpress.com/2008/11/19/conversation-scope-and-jsf-or-your-favorite-web-framework/">conversational scope</a> issue. I haven&#8217;t worked with this framework myself though so I can&#8217;t speak from experience.</p>
<h3>Final note</h3>
<p>Although I agree JSF has some annoying pitfalls, shortcomings and a high learning curve, it&#8217;s been out there for enough time to pass for supplement frameworks to pop up from under the ground to solve most of these problems.</p>
<p>With the right combination, most classic counter arguments have become obsolete. Maybe it&#8217;s time for critics to take JSF as is: incomplete but ultimately making you more productive if combined with the right frameworks.</p>
<p><a href="http://blog.projectnibble.org/2009/05/24/jsf-is-a-diamond-in-the-rough-you-just-need-to-make-it-shine/trackback/">trackback</a></p>
]]></content:encoded>
			<wfw:commentRss>http://blog.projectnibble.org/2009/05/24/jsf-is-a-diamond-in-the-rough-you-just-need-to-make-it-shine/feed/</wfw:commentRss>
		<slash:comments>13</slash:comments>
		</item>
		<item>
		<title>Vesijama, the Very Simple Java Mail library</title>
		<link>http://blog.projectnibble.org/2009/04/27/vesijama-very-simple-java-mail/</link>
		<comments>http://blog.projectnibble.org/2009/04/27/vesijama-very-simple-java-mail/#comments</comments>
		<pubDate>Mon, 27 Apr 2009 20:26:23 +0000</pubDate>
		<dc:creator>Benny Bottema</dc:creator>
				<category><![CDATA[mailing]]></category>
		<category><![CDATA[open source]]></category>
		<category><![CDATA[java]]></category>
		<category><![CDATA[mail]]></category>
		<category><![CDATA[rfc]]></category>

		<guid isPermaLink="false">http://blog.projectnibble.org/?p=67</guid>
		<description><![CDATA[In Java, sending emails can be a pain unless you're using a third party library. Now, the easiest one yet just went open source. Enter Vesijama, the Very Simple Java Mail library.]]></description>
			<content:encoded><![CDATA[<p><strong>Here&#8217;s the story about why I wrote a mail API wrapper in Java and made it Open Source. It is called <a href="http://code.google.com/p/vesijama/">Vesijama, Very Simple Java Mail</a>.</strong></p>
<p><span id="more-67"></span></p>
<h2>Prologue</h2>
<p>So I was looking into sending some emails from my little Java webapp, right. I thought: <q>easy, java has built in mail support called <a href="http://java.sun.com/products/javamail/">JavaMail</a></q>. Well, I was in for an unpleasant surprise when I found out I was merely handed the sand grains to build my castle. I can&#8217;t just say to Java&#8217;s mailing library <q>Hey, here&#8217;s what I want to send, and here are the addresses I need it sent to</q>, no. I can say however <q>I want you to formulate a mixed multipart message with the following attributes and these addresses encoded into special objects and oh yeah, define some mimemessage bodyparts for these attachments and use the following headers and put everything in a very specific nested structure dot dot dot</q>.</p>
<p>You actually need to research the RFC for mail structures to do it properly! In case you&#8217;re interested (which you&#8217;re not), check out this <a href="http://www.lesnikowski.com/mail/rfc.aspx">page of useful email rfc&#8217;s</a>. The rfc&#8217;s <a href="http://www.lesnikowski.com/mail/Rfc/rfc822.txt">822</a>, <a href="http://www.lesnikowski.com/mail/Rfc/rfc2047.txt">2047</a> and <a href="http://www.lesnikowski.com/mail/Rfc/rfc2045.txt">2045</a> are referenced in Java&#8217;s <a href="http://java.sun.com/products/javamail/javadocs/javax/mail/internet/MimePart.html">MimePart</a> alone. That&#8217;s just stupid, I can&#8217;t think of anything else where the JDK is forcing developers to work on such a low level where you need to deal with rfc&#8217;s.</p>
<p>An example of the JavaMail madness can be found on a <a href="http://www.velocityreviews.com/forums/showthread.php?p=3850368">thread at velocityreviews.com</a>, where someone asks for a simple tutorial to learn how to simply send emails using JavaMail. Here&#8217;s the answer of one of the members:</p>
<blockquote style="font-size:8pt"><p>First, you need to read and understand the relevant RFCs governing Internet<br />
email, if you don&#8217;t already understand this. I&#8217;d recommend starting with:</p>
<p>RFC 2821 &#8211; Simple Mail Transfer (SMTP)<br />
RFC 2822 &#8211; Format of Internet Messages<br />
RFC 1939 &#8211; Post Office Protocol (POP3)<br />
RFC 2060 &#8211; Internet Mail Access Protocol (IMAP)</p>
<p>then moving on to MIME:</p>
<p>RFCs 2045 &#8211; 2049 &#8211; Multipurpose Internet Mail Extensions (MIME)</p>
<p>Once you understand this, you should be able to figure out JavaMail using<br />
the tutorial at http://java.sun.com/developer/onlineTraining/JavaMail/contents.html,<br />
(which is, incidentally, the first hit returned from a Google search on the<br />
term &#8220;javamail tutorial&#8221;), along with the JavaDoc that is shipped along<br />
with the JavaMail libraries. If you have any specific questions about how<br />
JavaMail is to be used, please post them to the news group and you&#8217;ll be<br />
pretty sure to get an answer.</p>
<p>Cheers!</p></blockquote>
<p>With all his good intentions, this guy doesn&#8217;t realize he&#8217;s completely scaring the mail novice away; people looking for a way to send emails shouldn&#8217;t be required to be RFC educated email engineers. I just now realize that maybe JavaMail wasn&#8217;t meant to be used by Joe sixpack, but rather by third-party library vendors. Also, realize that JavaMail is much more than just smtp client API. Still, when I began writing Vesijama there weren&#8217;t a whole lot of third-party options, let alone one as simple to use as Vesijama.</p>
<p>Don&#8217;t get me wrong though: it&#8217;s not that the JavaMail API is so bad, it&#8217;s great actually. It allows for very finegrained configuration for pop3, smtp and everything mail related. It&#8217;s just that you don&#8217;t want regular Java developers to deal with API on such a low level: it takes a lot of time getting it right and the risk of a faulty implementation is very high, as the result will often work in <i>some</i> email (web) clients and subtle mistakes with significant consequences will go unnoticed.</p>
<h2>Enter Vesijama, the Very Simple Java Mail library</h2>
<p>To spare other developers the same fate, I decided to write a proper wrapper around the JavaMail smtp API so no Java developer needs to be bothered by this stuff and just keep pluggin&#8217; on an abstract business logic level. You know, just send the damn mails.</p>
<p>It took me quite a while to get it right since email clients, especially web clients, are very sensitive to incorrect nested structures. I&#8217;m happy to say I&#8217;ve succesfully used this when I was working for a commercial company, which means it has been professionally tested with a broad range of email (web) clients.</p>
<p>Enter Vesijama. It´s been a while since I wrote this little framework, I´ve only recently had the time to properly prepare the code for an Open Source release. At the time of writing the library I didn&#8217;t know about <a href="http://static.springframework.org/spring/docs/2.0.x/reference/mail.html">Spring&#8217;s mailing facility</a> or <a href="http://commons.apache.org/email/userguide.html">Apache&#8217;s Commons Mail</a> libraries, but in hindsight I think there&#8217;s a place for Vesijama since in my completely biased opinion it is by far the easiest to use framework. Look it up over at <a href="http://code.google.com/p/vesijama/"><strong>Vesjiama at Google Code</strong></a>.</p>
<p>Here&#8217;s the one and only code example from the Vesijama project page:</p>
<pre  name="code" class="java">
final Email email = new Email();

email.setFromAddress("lollypop", "lolly.pop@somemail.com");
email.setSubject("hey");
email.addRecipient("C. Cane", "candycane@candyshop.org", RecipientType.TO);
email.addRecipient("C. Bo", "chocobo@candyshop.org", RecipientType.BCC);
email.setText("We should meet up! ;)");
email.setTextHTML("<img src='cid:wink1'><b>We should meet up!</b><img src='cid:wink2'>");

// embed images and include downloadable attachments
email.addEmbeddedImage("wink1", imageByteArray, "image/png");
email.addEmbeddedImage("wink2", imageDatesource);
email.addAttachment("invitation", pdfByteArray, "application/pdf");
email.addAttachment("dresscode", odfDatasource);

new Mailer("smtp.host.com", 25, "username", "password").sendMail(email);
</pre>
<p>Oh wow, is that it? Well, I just imagine masses of people gazing with open mouths thinking that, but that&#8217;ll never happen because nobody realizes how much effort went in the rfc research. And the very few lines that make up the mail structure don&#8217;t look very impressive either&#8230; the thing is it has to be just right; mail clients aren&#8217;t very forgiving. It often amazes me how many thousands of lines of rfc text results in miniscule implementations, but luckily in this case at least if you do it right, it works in all email clients that properly handle emails according the rfc&#8217;s.</p>
<p>Anyway, the library suited me and now it&#8217;s yours too. Enjoy.</p>
<p><a href="http://blog.projectnibble.org/2009/04/27/vesijama-very-simple-java-mail/trackback/">trackback</></p>
]]></content:encoded>
			<wfw:commentRss>http://blog.projectnibble.org/2009/04/27/vesijama-very-simple-java-mail/feed/</wfw:commentRss>
		<slash:comments>18</slash:comments>
		</item>
		<item>
		<title>Fix Eclipse @author under any account</title>
		<link>http://blog.projectnibble.org/2008/06/30/fix-eclipse-author-under-any-acount/</link>
		<comments>http://blog.projectnibble.org/2008/06/30/fix-eclipse-author-under-any-acount/#comments</comments>
		<pubDate>Mon, 30 Jun 2008 19:01:18 +0000</pubDate>
		<dc:creator>Benny Bottema</dc:creator>
				<category><![CDATA[eclipse]]></category>
		<category><![CDATA[java]]></category>
		<category><![CDATA[template]]></category>

		<guid isPermaLink="false">http://blogs.quintor.nl/bbottema/2008/06/30/fix-eclipse-author-under-any-acount/</guid>
		<description><![CDATA[Here&#8217;s a quick tip I found very useful in Windows, involving Eclipse template system and the @Author annotation. Say you are working under some kind of account, for example some assigned number combination which you use to log into Windows or something. Mine recently was AA170738. Now say you are editing Java classes in Eclipse [...]]]></description>
			<content:encoded><![CDATA[<p>Here&#8217;s a quick tip I found very useful in Windows, involving Eclipse template system and the @Author annotation.</p>
<p>Say you are working under some kind of account, for example some assigned number combination which you use to log into Windows or something. Mine recently was AA170738. Now say you are editing Java classes in Eclipse and generating comments with Eclipse. You might end up with something like this:</p>
<pre>/**
 * @author AA170738
 *
 */</pre>
<p>I Found this very annoying since it happened to me for every class I introduced and templates are supposed to save time. You could ofcourse turn it off entirely, <em>Preferences-&gt;Java-&gt;Editor-&gt;Templates-&gt;uncheck @author</em>, but I just wanted it fixed the right way.</p>
<p>Turns out Eclipse simply reads out the Java system property <strong>user.name</strong>. All we need to do then is boot Eclipse with an explicit system property. Like so&#8230;</p>
<p><em>eclipse.exe -vmargs -Duser.name=&#8221;John Doe&#8221;</em></p>
<p>Just change that in your shortcut and you&#8217;re set.</p>
<pre>/**
 * @author John Doe
 *
 */</pre>
<p><img src="http://images.slashdot.org/favicon.ico" alt="Slashdot" border="0" height="16" width="16" /> <a href="http://slashdot.org/slashdot-it.pl?op=basic&amp;url=http://blogs.quintor.nl/bbottema/2008/06/30/fix-eclipse-author-under-any-acount/">Slashdot It!</a>   /   <a href="http://blogs.quintor.nl/bbottema/2008/06/30/fix-eclipse-author-under-any-acount/trackback/">trackback</a></p>
<p><a href="http://technorati.com/faves?sub=addfavbtn&amp;add=http://blogs.quintor.nl/bbottema"><img src="http://static.technorati.com/pix/fave/btn-fave2.png" alt="Add to Technorati Favorites" /></a></p>
]]></content:encoded>
			<wfw:commentRss>http://blog.projectnibble.org/2008/06/30/fix-eclipse-author-under-any-acount/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>DWR in a Jiffy (quickstart tutorial)</title>
		<link>http://blog.projectnibble.org/2008/01/19/dwr-in-a-jiffy/</link>
		<comments>http://blog.projectnibble.org/2008/01/19/dwr-in-a-jiffy/#comments</comments>
		<pubDate>Sat, 19 Jan 2008 18:31:19 +0000</pubDate>
		<dc:creator>Benny Bottema</dc:creator>
				<category><![CDATA[dwr]]></category>
		<category><![CDATA[ajax]]></category>
		<category><![CDATA[java]]></category>

		<guid isPermaLink="false">http://blogs.quintor.nl/bbottema/2008/01/19/dwr-in-a-jiffy/</guid>
		<description><![CDATA[Direct Web Remoting, or DWR in short, is a technology that helps you ease the development of javascript based applications using a Java server. What it does is simply sit in between your javascript and your java classes and acts as marshaller for method calls from javascript to Java. In a nutshell: DWR provides Remote [...]]]></description>
			<content:encoded><![CDATA[<p><strong><a href="http://getahead.org/dwr">Direct Web Remoting</a>, or DWR in short</strong>, is a technology that helps you ease the development of javascript based applications using a Java server. What it does is simply sit in between your javascript and your java classes and acts as marshaller for method calls from javascript to Java. In a nutshell: DWR provides Remote Procedure Calls for javascript and is a great library for use in <a href="http://en.wikipedia.org/wiki/Ajax_(programming)" title="Wikipedia on Ajax">Ajax enabled webapplications</a>.</p>
<p>This isn&#8217;t yet another blogpost about what DWR exactly is or why it is so cool; the objective of my post today is to simply set up a quick example of how to work with it. A quick tutorial if you will.  I&#8217;m the kind of guy that likes many examples and diagrams and whatnot to take apart and learn from, so here&#8217;s my contribution to the &#8216;code by example&#8217; paradigm. If you want to know more about DWR before actually trying to use it, I suggest you check out the  <a href="http://getahead.org/dwr/">DWR homepage</a>.</p>
<p><span id="more-4"></span></p>
<h2>Setting the stage</h2>
<p>One of the cool things (two sentences and I already contradict myself :), is that it is so easy to setup, as you will soon see. To get DWR to expose the classes to javascript, you first need to add the dwr library and define the specific classes. Basically, this is a 3-step dance:</p>
<ol>
<li>Drop the dwr.jar you&#8217;ve downloaded from <a href="http://getahead.org/dwr/download">getahead</a> in the lib folder of your webapplication (ie. <em>\lib\dwr\dwr.jar</em>).</li>
<li>Add DWR to your <code>web.xml</code> as a servlet:
<pre><code class="prettyprint">&lt;servlet&gt;
	&lt;servlet-name&gt;dwr-invoker&lt;/servlet-name&gt;
	&lt;display-name&gt;DWR Servlet&lt;/display-name&gt;
	&lt;servlet-class&gt;uk.ltd.getahead.dwr.DWRServlet&lt;/servlet-class&gt;
	&lt;init-param&gt;
		&lt;param-name&gt;debug&lt;/param-name&gt;
		&lt;param-value&gt;true&lt;/param-value&gt;
	&lt;/init-param&gt;
	&lt;load-on-startup&gt;1&lt;/load-on-startup&gt;
&lt;/servlet&gt;

&lt;servlet-mapping&gt;
	&lt;servlet-name&gt;dwr-invoker&lt;/servlet-name&gt;
	&lt;url-pattern&gt;/dwr/*&lt;/url-pattern&gt;
&lt;/servlet-mapping&gt;</code></pre>
</li>
<li> Create a <em>dwr.xml</em>, which informs DWR about the classes you need exposed:
<pre><code class="prettyprint">&lt;dwr&gt;
	&lt;allow&gt;
		&lt;create creator="new" javascript="MyService"&gt;
			&lt;param name="class" value="org.foo.MyServiceClass"/&gt;
		&lt;/create&gt;
	&lt;/allow&gt;
&lt;/dwr&gt;</code></pre>
</li>
</ol>
<h2>Testing DWR</h2>
<p>To check if you&#8217;ve done everything right, you can open up the DWR testpage <em>http://localhost/dwr/</em> on which all exposed classes and methods should be visible. Remember, this works because you configured a DWR servlet that triggers on <em>/dwr/*</em>. If you click on any of the classes that are exposed, you&#8217;ll get a list of methods that are available to you javascript and are ready for testing right away. Note that this is all javascript already!</p>
<p>Specifying nothing but <em>/dwr/</em> results in this testpage. But If you want to use a specific java class in your own page to call methods on, you&#8217;d call <em>/dwr/TheService</em>. What happens is that the DWR library dynamically generates all the required javascript to communicate with the server through this servlet, runtime. Pretty cool huh?</p>
<h2>Using DWR on the client side</h2>
<p>To use the methods of the classes that are exposed through dwr.xml, you need to include a virtual javascript file with the name of such an exposed class. Since the classes are identified with the <em>javascript</em> attribute in dwr.xml, you&#8217;ll use that identifier when importing the javascript file. In addition to the scriptfile for your javaclass, you need at least <em>engine.js</em> as well.</p>
<pre><code class="prettyprint">&lt;script src="/dwr/interface/MyService.js" mce_src="/dwr/interface/MyService.js"&gt;&lt;/script&gt;
&lt;script src="/dwr/engine.js" mce_src="/dwr/engine.js"&gt;&lt;/script&gt;</code></pre>
<p>There are some other useful scripts you can include from DWR, such as <em>util.js</em>, which has a couple of nifty functions like <code>$()</code> (a shorthand version for <code>document.getElementById()</code>).</p>
<h2>About DWR callbacks</h2>
<p>To actually make use of the Java serviceclass, you simply call a method on the Myservice.js file. The catch here is that you need to provide a callback function as well. This is because of the fact that javascript runs asynchronously in the client and doesn&#8217;t wait for Java to come back with an answer. Instead, DWR relies on the callback method you defined that will handle the result in due time. Note that the function you call on the serviceclass.js has all the parameters as defined in the Java class, safe for the callback parameter and peripheral parameters such as <code>HttpSession</code> or <code>HttpRequest</code>.</p>
<p>The callback function can only have one parameter, <em>data</em>, which bares the result of the DWR servicecall.</p>
<p>Take a look:</p>
<pre><code class="prettyprint">// call function on DWR generated service.js
MyService.getInfo(arg1, arg2, parseResult);

// callback function that parses whatever result comes back
function parseResult(data) {
  // do stuff with result data
}</code></pre>
<p>On a side note, there are a couple of varying ways of calling a function on a serviceclass. For example, you can have the callback function as first or last argument, or not at all. You can also specify a time-out and some other options. For more details on check out the <a href="http://getahead.ltd.uk/dwr/browser/intro">DWR page on this usage subject</a>.</p>
<h2>Matching arguments types</h2>
<p>DWR already provides most common conversions such as Strings, Dates, Arrays (nested as well) and a host of other types, including stuff like Vector. If you&#8217;d like to use your own type for a parameter, you will need to create a javascript version with the same fields. Here&#8217;s an example:</p>
<pre><code class="prettyprint">// Java version:
public Person {
	private String name;
	private int age;
	private Date[] appointments;

	// getters and setters ...
}

// javascript version:
var person = {
	name:"Fred Bloggs",
	age:42,
	appointments:[ new Date(), new Date("1 Jan 2008") ]
};

MyService.setPerson(person);</code></pre>
<p>To make these conversions possible, you need to inform DWR about these &#8216;custom&#8217; classes. These so called &#8216;beans&#8217; allow DWR converters to marshal these classes from/to javascript.</p>
<p>More on DWR converters here:</p>
<ul>
<li><a href="http://getahead.ltd.uk/dwr/server/dwrxml/converters">http://getahead.ltd.uk/dwr/server/dwrxml/converters</a></li>
<li><a href="http://getahead.ltd.uk/dwr/server/dwrxml/converters">http://getahead.ltd.uk/dwr/server/dwrxml/converters/bean</a></li>
<li><a href="http://getahead.ltd.uk/dwr/server/dwrxml/converters/collection">http://getahead.ltd.uk/dwr/server/dwrxml/converters/collection</a></li>
</ul>
<p><img src="http://images.slashdot.org/favicon.ico" alt="Slashdot" border="0" height="16" width="16" /> <a href="http://slashdot.org/slashdot-it.pl?op=basic&amp;url=http://blogs.quintor.nl/bbottema/2008/01/19/dwr-in-a-jiffy/">Slashdot It!</a>   /   <a href="http://blogs.quintor.nl/bbottema/2008/01/19/dwr-in-a-jiffy/trackback/">trackback</a></p>
<p><a href="http://technorati.com/faves?sub=addfavbtn&amp;add=http://blogs.quintor.nl/bbottema"><img alt="Add to Technorati Favorites" src="http://static.technorati.com/pix/fave/btn-fave2.png" /></a></p>
]]></content:encoded>
			<wfw:commentRss>http://blog.projectnibble.org/2008/01/19/dwr-in-a-jiffy/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
	</channel>
</rss>
