<?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/"
	
	xmlns:media="http://search.yahoo.com/mrss/"
	>

<channel>
	<title>Rough Book &#187; Web</title>
	<atom:link href="http://vivin.net/category/nerdy-stuff/computers-nerdy-stuff/programming-and-development-computers-nerdy-stuff/web-programming-and-development-computers-nerdy-stuff/feed/" rel="self" type="application/rss+xml" />
	<link>http://vivin.net</link>
	<description>random musings of just another computer nerd</description>
	<lastBuildDate>Wed, 02 May 2012 18:20:05 +0000</lastBuildDate>
	<language>en</language>
	<sy:updatePeriod>hourly</sy:updatePeriod>
	<sy:updateFrequency>1</sy:updateFrequency>
	<generator>http://wordpress.org/?v=3.3.2</generator>
		<item>
		<title>Setting the content type to text/plain for a JSON response from a Spring controller</title>
		<link>http://vivin.net/2011/11/07/setting-the-content-type-to-textplain-for-a-json-response-from-a-spring-controller/?utm_source=rss&#038;utm_medium=rss&#038;utm_campaign=rss</link>
		<comments>http://vivin.net/2011/11/07/setting-the-content-type-to-textplain-for-a-json-response-from-a-spring-controller/#comments</comments>
		<pubDate>Mon, 07 Nov 2011 20:30:19 +0000</pubDate>
		<dc:creator>vivin</dc:creator>
				<category><![CDATA[Computers]]></category>
		<category><![CDATA[Java]]></category>
		<category><![CDATA[Nerdy Stuff]]></category>
		<category><![CDATA[Software]]></category>
		<category><![CDATA[Web]]></category>
		<category><![CDATA[ajax]]></category>
		<category><![CDATA[ajax fie upload]]></category>
		<category><![CDATA[iframe]]></category>
		<category><![CDATA[java]]></category>
		<category><![CDATA[json]]></category>
		<category><![CDATA[jsonp]]></category>
		<category><![CDATA[spring]]></category>
		<category><![CDATA[spring 3]]></category>
		<category><![CDATA[spring mvc]]></category>

		<guid isPermaLink="false">http://vivin.net/?p=1779</guid>
		<description><![CDATA[I was using a jQuery plugin called a ajaxfileupload to upload a file through AJAX. Technically what the plugin does isn&#8217;t AJAX. It creates a hidden form and an iframe, and then submits the form using the iframe as the target. The iframe will then end up with the response from the server. This response [...]]]></description>
			<content:encoded><![CDATA[<p>I was using a jQuery plugin called a <a href="http://www.phpletter.com/Our-Projects/AjaxFileUpload/" title="ajaxfileupload">ajaxfileupload</a> to upload a file through AJAX. Technically what the plugin does isn&#8217;t AJAX. It creates a hidden form and an iframe, and then submits the form using the iframe as the target. The iframe will then end up with the response from the server. This response is then read-in by the plugin and handled appropriately. In my case I was using a controller action that would return JSON (using the <span class="code-snippet">.action</span> extension). The action uses Spring&#8217;s <span class="code-snippet">MappingJacksonJSONView</span> that returns JSON with a content type of <span class="code-snippet">application/json</span> (as it should). This works perfectly in Chrome, however in both Firefox and IE, the user is presented with a dialog box that asks them to download the JSON response. This is obviously not what I wanted. The reason this is happening is because the response is being directly submitted to the iframe (and therefore, the page). That is, it&#8217;s not coming through via the <span class="code-snippet">XMLHttpRequest</span> object. So IE and FF don&#8217;t know what to do with it and assume that it is something the user would want to download. The solution to this problem is to set the content-type to <span class="code-snippet">text/plain</span>. This wasn&#8217;t as straightforward as I thought it would be. </p>
<p>Initially I was going to call the <span class="code-snippet">render(&#8230;)</span> method of <span class="code-snippet">MappingJacksonJsonView</span> but that didn&#8217;t work because the content-type had already been set to <span class="code-snippet">application/json</span>. The solution I came up with was to duplicate some of the code (ugh) inside <span class="code-snippet">MappingJacksonJsonView</span> to get the JSON as a string and to then write that to the response:</p>
<pre class="brush: java">

@RequestMapping
public void processFileUpload(HttpServletResponse response, Model model, ...) {

    ...

    //Set the content-type and charset of the response
    response.setContentType(&quot;text/plain&quot;);
    response.setCharacterEncoding(&quot;UTF-8&quot;);

    //I need to use another OutputStream here; I cannot use the response&#039;s OutputStream because that will cause errors
    //later on when the JSP needs to render its content (recall that getOutputStream() can only be called exactly once
    //on a response). Therefore I&#039;m writing the data to a ByteArrayOutputStream and then writing the byte array from
    //the ByteArrayOutputStream to the response manually.

    ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
    ObjectMapper objectMapper = new ObjectMapper();
    JsonGenerator generator = objectMapper.getJsonFactory().createJsonGenerator(byteArrayOutputStream, JsonEncoding.UTF8);

    //Before I can convert the data into JSON, I will need to filter some attributes out of the model (namely BindingResult)
    Map&lt;String, Object&gt; result = new HashMap&lt;String, Object&gt;();

    for(Map.Entry&lt;String, Object&gt; entry : model.asMap().entrySet()) {
        if(!(entry.getValue() instanceof BindingResult)) {
            result.put(entry.getKey(), entry.getValue());
        }
    }

    objectMapper.writeValue(generator, result);
    response.getWriter().write(new String(byteArrayOutputStream.toByteArray(), &quot;UTF8&quot;));
}
</pre>
<p>This still seems a little hacky to me. A possible improvement is to annotate the action with <span class="code-snippet">@ResponseBody</span> and return the JSON as a string without involving the response at all. If anyone has a better solution, I&#8217;m all ears!</p>
<br /><a href="http://vivin.net/?p=1779#comments" title="Comments on &quot;Setting the content type to text/plain for a JSON response from a Spring controller&quot;"><img src="http://vivin.net/wp-content/plugins/feed-comments-number/image.php?1779" alt="Comments" /></a><img src="http://vivin.net/?ak_action=api_record_view&#38;id=1779&#38;type=feed" alt="" />]]></content:encoded>
			<wfw:commentRss>http://vivin.net/2011/11/07/setting-the-content-type-to-textplain-for-a-json-response-from-a-spring-controller/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
	
		<media:thumbnail url="http://vivin.net/wp-content/plugins/feed-comments-number/image.php?1779" />
		<media:content url="http://vivin.net/wp-content/plugins/feed-comments-number/image.php?1779" medium="image">
			<media:title type="html">Comments</media:title>
		</media:content>
		<media:content url="http://vivin.net/?ak_action=api_record_view&#38;id=1779&#38;type=feed" medium="image" />
	</item>
		<item>
		<title>Popularity Contest WordPress plugin breaks RSS feed</title>
		<link>http://vivin.net/2011/10/23/popularity-contest-wordpress-plugin-breaks-rss-feed/?utm_source=rss&#038;utm_medium=rss&#038;utm_campaign=rss</link>
		<comments>http://vivin.net/2011/10/23/popularity-contest-wordpress-plugin-breaks-rss-feed/#comments</comments>
		<pubDate>Sun, 23 Oct 2011 17:24:51 +0000</pubDate>
		<dc:creator>vivin</dc:creator>
				<category><![CDATA[PHP]]></category>
		<category><![CDATA[Programming and Development]]></category>
		<category><![CDATA[Web]]></category>
		<category><![CDATA[php]]></category>
		<category><![CDATA[rss]]></category>
		<category><![CDATA[wordpress]]></category>
		<category><![CDATA[xml]]></category>

		<guid isPermaLink="false">http://vivin.net/?p=1773</guid>
		<description><![CDATA[I&#8217;m using a somewhat old plugin (it hasn&#8217;t been updated since &#8217;09) called Popularity Contest to show the popularity of my posts. However, I noticed that it was breaking my RSS feed. This is due to the fact that the plugin doesn&#8217;t properly escape the ampersand character inside an image URL. Instead of &#38;#38; it [...]]]></description>
			<content:encoded><![CDATA[<p>I&#8217;m using a somewhat old plugin (it hasn&#8217;t been updated since &#8217;09) called <a href="http://wordpress.org/extend/plugins/popularity-contest/" title="Popularity Contest" target="_blank">Popularity Contest</a> to show the popularity of my posts. However, I noticed that it was breaking my RSS feed. This is due to the fact that the plugin doesn&#8217;t properly escape the ampersand character inside an image URL. Instead of &#38;#38; it uses just &#38;. You can fix this by changind line number 2272 to:</p>
<pre class="brush: php">
$str .= &#039;&lt;img src=&quot;&#039;.site_url(&#039;?ak_action=api_record_view&amp;#38;id=&#039;.$post-&gt;ID.&#039;&amp;#38;type=feed&#039;).&#039;&quot; alt=&quot;&quot; /&gt;&#039;;
</pre>
<br /><a href="http://vivin.net/?p=1773#comments" title="Comments on &quot;Popularity Contest WordPress plugin breaks RSS feed&quot;"><img src="http://vivin.net/wp-content/plugins/feed-comments-number/image.php?1773" alt="Comments" /></a><img src="http://vivin.net/?ak_action=api_record_view&#38;id=1773&#38;type=feed" alt="" />]]></content:encoded>
			<wfw:commentRss>http://vivin.net/2011/10/23/popularity-contest-wordpress-plugin-breaks-rss-feed/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
	
		<media:thumbnail url="http://vivin.net/wp-content/plugins/feed-comments-number/image.php?1773" />
		<media:content url="http://vivin.net/wp-content/plugins/feed-comments-number/image.php?1773" medium="image">
			<media:title type="html">Comments</media:title>
		</media:content>
		<media:content url="http://vivin.net/?ak_action=api_record_view&#38;id=1773&#38;type=feed" medium="image" />
	</item>
		<item>
		<title>Implementing JSONP in Spring MVC 3.0.x</title>
		<link>http://vivin.net/2011/07/01/implementing-jsonp-in-spring-mvc-3-0-x/?utm_source=rss&#038;utm_medium=rss&#038;utm_campaign=rss</link>
		<comments>http://vivin.net/2011/07/01/implementing-jsonp-in-spring-mvc-3-0-x/#comments</comments>
		<pubDate>Fri, 01 Jul 2011 16:33:22 +0000</pubDate>
		<dc:creator>vivin</dc:creator>
				<category><![CDATA[Computers]]></category>
		<category><![CDATA[Java]]></category>
		<category><![CDATA[Nerdy Stuff]]></category>
		<category><![CDATA[Programming and Development]]></category>
		<category><![CDATA[Software]]></category>
		<category><![CDATA[Web]]></category>
		<category><![CDATA[java]]></category>
		<category><![CDATA[json]]></category>
		<category><![CDATA[jsonp]]></category>
		<category><![CDATA[spring]]></category>
		<category><![CDATA[spring 3]]></category>
		<category><![CDATA[spring mvc]]></category>

		<guid isPermaLink="false">http://vivin.net/?p=1732</guid>
		<description><![CDATA[In Spring 3, it&#8217;s very easy to get a view to return JSON. However, there is no built-in mechanism to return JSONP. I was able to find a pretty good tutorial That uses Spring&#8217;s DelegatingFilterProxy. I implemented this solution and I got it to work, but I didn&#8217;t like the fact that I had to [...]]]></description>
			<content:encoded><![CDATA[<p>In Spring 3, it&#8217;s very easy to get a view to return JSON. However, there is no built-in mechanism to return <a href="http://en.wikipedia.org/wiki/JSONP">JSONP</a>. I was able to find a <a href="http://jpgmr.wordpress.com/2010/07/28/tutorial-implementing-a-servlet-filter-for-jsonp-callback-with-springs-delegatingfilterproxy/">pretty good tutorial</a> That uses Spring&#8217;s <span style="font-family: courier new; font-weight: bold">DelegatingFilterProxy</span>. I implemented this solution and I got it to work, but I didn&#8217;t like the fact that I had to create a separate filter and a bunch of other classes just for that. I also wanted to use a specific extension (<span style = "font-family: courier new; font-weight: bold">.jsonp</span>) for JSONP just to make it more explicit. Spring uses <span style="font-family: courier new; font-weight: bold">MappingJacksonJsonView</span> to return JSON. I figured that I could extend this view and have it return JSONP instead of JSON.<br />
<span id="more-1732"></span></p>
<p>Although I pulled my hair out for an hour or two (I was getting a 404 when hitting my controller with with a <span style="font-family: courier new; font-weight: bold">.jsonp</span> extension; I&#8217;ll explain why, later), the resulting solution is actually pretty simple. First, you need to extend <span style="font-family: courier new; font-weight: bold">MappingJacksonJsonView</span> to create your own view. Since <span style="font-family: courier new; font-weight: bold">MappingJacksonJsonView</span> already handles the creation of JSON, all we need to do is pad it with our callback. The way to do this is to override the <span style="font-family: courier new; font-weight: bold">MappingJacksonJsonView#render(Map<String, ?> model, HttpServletRequest request, HttpServletResponse response)</span> method (This method is actually defined in <span style="font-family: courier new; font-weight: bold">AbstractView</span>, a Spring-provided abstract class that you can override in your own view). The full source is below:</p>
<pre class="brush: java">
package net.vivin.mvc.spring.view.jsonp;

import org.springframework.web.servlet.view.json.MappingJacksonJsonView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.Map;

public class MappingJacksonJsonpView extends MappingJacksonJsonView {

	/**
	 * Default content type. Overridable as bean property.
	 */
	public static final String DEFAULT_CONTENT_TYPE = &quot;application/javascript&quot;;

    @Override
    public String getContentType() {
        return DEFAULT_CONTENT_TYPE;
    }

 	/**
	 * Prepares the view given the specified model, merging it with static
	 * attributes and a RequestContext attribute, if necessary.
	 * Delegates to renderMergedOutputModel for the actual rendering.
	 * @see #renderMergedOutputModel
	 */
    @Override
	public void render(Map&lt;String, ?&gt; model, HttpServletRequest request, HttpServletResponse response) throws Exception {

        if(&quot;GET&quot;.equals(request.getMethod().toUpperCase())) {
            @SuppressWarnings(&quot;unchecked&quot;)
            Map&lt;String, String[]&gt; params = request.getParameterMap();

            if(params.containsKey(&quot;callback&quot;)) {
                response.getOutputStream().write(new String(params.get(&quot;callback&quot;)[0] + &quot;(&quot;).getBytes());
                super.render(model, request, response);
                response.getOutputStream().write(new String(&quot;);&quot;).getBytes());
                response.setContentType(&quot;application/javascript&quot;);
            }

            else {
                super.render(model, request, response);
            }
        }

        else {
            super.render(model, request, response);
        }
    }
}
</pre>
<p>The <span style="font-family: courier new; font-weight: bold">DEFAULT_CONTENT_TYPE</span> public static property and the <span style="font-family: courier new; font-weight: bold">getContentType()</span> method are important. Spring uses this method (among other things) to find the best candidate view. I spent at least an hour trying to figure out why I was getting 404&#8242;s. It was because I hadn&#8217;t overridden the property and the accessor to return the correct content-type. Going back to the <span style="font-family: courier new; font-weight: bold">render</span> method itself, you can see that it&#8217;s pretty simple. First I make sure that the request method is <span style="font-family: courier new; font-weight: bold">GET</span>. Then I get the request parameter-map and check for the <span style="font-family: courier new; font-weight: bold">callback</span> parameter. If this parameter exists, I write out the name of the callback with an open parenthesis. Then I call the parent class&#8217;s <span style="font-family: courier new; font-weight: bold">render</span> method. This method belongs to <span style="font-family: courier new; font-weight: bold">MappingJacksonJsonView</span> and will write out JSON to the response. Finally, I write out a closing parenthesis and a semicolon to the response and set the content type to <span style="font-family: courier new; font-weight: bold">application/javascript</span>. So as you can see, I&#8217;ve converted JSON into JSONP.</p>
<p>The next thing you need to do is include an entry for your new view in the <span style="font-family: courier new; font-weight: bold">springmvc-servlet.xml</span> file. This part also took a little work. I wasn&#8217;t sure how to include my new view within the <span style="font-family: courier new; font-weight: bold">ContentNegotiatingViewResolver</span> bean. But <a href="http://www.rickherrick.com/?q=node/63">this post</a> proved to be remarkably helpful. The post actually talks about returning XML or JSON (based on the extension), but I was able to adapt it to return JSON or JSON. Here&#8217;s what it looks like:</p>
<pre class="brush: xml">
    &lt;bean class=&quot;org.springframework.web.servlet.view.ContentNegotiatingViewResolver&quot;&gt;
        &lt;property name=&quot;favorPathExtension&quot; value=&quot;true&quot;/&gt;
        &lt;property name=&quot;mediaTypes&quot;&gt;
            &lt;map&gt;
                &lt;entry key=&quot;json&quot; value=&quot;application/json&quot;/&gt;
                &lt;entry key=&quot;jsonp&quot; value=&quot;application/javascript&quot;/&gt;
            &lt;/map&gt;
        &lt;/property&gt;
        &lt;property name=&quot;defaultViews&quot;&gt;
            &lt;list&gt;
                &lt;bean class=&quot;org.springframework.web.servlet.view.json.MappingJacksonJsonView&quot;/&gt;
                &lt;bean class=&quot;net.vivin.mvc.spring.view.jsonp.MappingJacksonJsonpView&quot;/&gt;
            &lt;/list&gt;
        &lt;/property&gt;
    &lt;/bean&gt;
</pre>
<p>If you notice, the <span style="font-family: courier new; font-weight: bold">value</span> property for <span style="font-family: courier new; font-weight: bold">jsonp</span> has been set to <span style="font-family: courier new; font-weight: bold">application/javascript</span>. Spring uses this value and checks it against the view class to figure out the best candidate view. If you didn&#8217;t override the <span style="font-family: courier new; font-weight: bold">DEFAULT_CONTENT_TYPE</span> property and the associated getter, you would get a 404.</p>
<p>Finally, you need a <span style="font-family: courier new; font-weight: bold">url-pattern</span> entry under <span style="font-family: courier new; font-weight: bold">servlet-mapping</span> in your <span style="font-family: courier new; font-weight: bold">web.xml</span> file so that the new <span style="font-family: courier new; font-weight: bold">.jsonp</span> extension is recognized:</p>
<pre class="brush: xml">
    &lt;servlet-mapping&gt;
        &lt;servlet-name&gt;springmvc&lt;/servlet-name&gt;
        &lt;url-pattern&gt;*.json&lt;/url-pattern&gt;
        &lt;url-pattern&gt;*.jsonp&lt;/url-pattern&gt;
        ...
    &lt;/servlet-mapping&gt;
</pre>
<p>That&#8217;s pretty much it. With this code in place, you can hit your controller with <span style="font-family: courier new; font-weight: bold">http://my.domain.com/controllerName/actionName.jsonp?callback=myCallback</span> and you&#8217;ll get your data back as JSONP! I thought this solution was pretty simple and a little less invasive than creating a filter. Comments/suggestions/criticisms for improvement are welcome!</p>
<br /><a href="http://vivin.net/?p=1732#comments" title="Comments on &quot;Implementing JSONP in Spring MVC 3.0.x&quot;"><img src="http://vivin.net/wp-content/plugins/feed-comments-number/image.php?1732" alt="Comments" /></a><img src="http://vivin.net/?ak_action=api_record_view&#38;id=1732&#38;type=feed" alt="" />]]></content:encoded>
			<wfw:commentRss>http://vivin.net/2011/07/01/implementing-jsonp-in-spring-mvc-3-0-x/feed/</wfw:commentRss>
		<slash:comments>16</slash:comments>
	
		<media:thumbnail url="http://vivin.net/wp-content/plugins/feed-comments-number/image.php?1732" />
		<media:content url="http://vivin.net/wp-content/plugins/feed-comments-number/image.php?1732" medium="image">
			<media:title type="html">Comments</media:title>
		</media:content>
		<media:content url="http://vivin.net/?ak_action=api_record_view&#38;id=1732&#38;type=feed" medium="image" />
	</item>
		<item>
		<title>Integrating Regula with Spring 3.0.x MVC</title>
		<link>http://vivin.net/2011/02/21/integrating-regula-with-spring-3-0-x-mvc/?utm_source=rss&#038;utm_medium=rss&#038;utm_campaign=rss</link>
		<comments>http://vivin.net/2011/02/21/integrating-regula-with-spring-3-0-x-mvc/#comments</comments>
		<pubDate>Tue, 22 Feb 2011 01:50:20 +0000</pubDate>
		<dc:creator>vivin</dc:creator>
				<category><![CDATA[Computers]]></category>
		<category><![CDATA[Java]]></category>
		<category><![CDATA[Programming and Development]]></category>
		<category><![CDATA[Web]]></category>
		<category><![CDATA[annotation]]></category>
		<category><![CDATA[annotation-based form-validation]]></category>
		<category><![CDATA[annotation-based validation]]></category>
		<category><![CDATA[annotations]]></category>
		<category><![CDATA[bean-validation]]></category>
		<category><![CDATA[form-validation]]></category>
		<category><![CDATA[framework]]></category>
		<category><![CDATA[hibernate]]></category>
		<category><![CDATA[java]]></category>
		<category><![CDATA[javascript]]></category>
		<category><![CDATA[javascript form-validation]]></category>
		<category><![CDATA[library]]></category>
		<category><![CDATA[regula]]></category>
		<category><![CDATA[spring]]></category>
		<category><![CDATA[spring mvc]]></category>

		<guid isPermaLink="false">http://vivin.net/?p=1680</guid>
		<description><![CDATA[A little less than a year ago, I released Regula, an annotation-based form-validation written in Javascript. The source and documentation are available on GitHub. I started working on the integration on and off throughout most of last year. At the end of the year, I had a pretty good integration going, where you could annotate [...]]]></description>
			<content:encoded><![CDATA[<p>A little less than a year ago, I <a href="http://vivin.net/2011/03/30/regula-an-annotation-based-form-validator-written-in-javascript/">released</a> Regula, an annotation-based form-validation written in Javascript. The <a href="https://github.com/vivin/regula">source</a> and <a href="https://github.com/vivin/regula/wiki">documentation</a> are available on GitHub. I started working on the integration on and off throughout most of last year. At the end of the year, I had a pretty good integration going, where you could annotate fields with Hibernate Validator annotations, and the corresponding Regula validation-code would be generated on the client side. Of course, I wasn&#8217;t done yet because what I had was simply a demo project and I had to figure out a good way to distribute the whole thing; I was able to finish up the packaging and distribution today. With minimal setup, you should be able to get started with Regula and Spring. You don&#8217;t need to go through this post to figure out how to use the integration. This post is mostly about <i>how</i> I accomplished the integration (I don&#8217;t go into all the details; just the important bits). As far as actually using it, I will make a blog post about it later.</p>
<p>The <a href="https://github.com/vivin/regula-spring">source</a> for the integration is also hosted on GitHub. My approach towards translating validation constraints from the server-side to the client-side was two-fold: gather validation constraints from the object and represent it in a canonical form. Using the canonical form, generate Javascript code that uses Regula for validation. To do this, I created a service that examines a domain object and gathers all information regarding its properties and validation constraints. The service returns this information in a canonical form, that I then inserted into the model. On the client-side, I had a tag that used the canonical form and outputted Javascript that uses the Regula framework. Initially, I was calling the service explicitly from an action in the controller. Later, in an effort to make the integration less-invasive and more seamless, I used an aspect-oriented approach with interceptors. In fact, that&#8217;s where I&#8217;d like to start.<br />
<span id="more-1680"></span><br />
I created an annotation called <span style="font-family:courier">@ValidateClientSide</span> that marks a domain object as requiring client-side validation. Then, I created an interceptor called <span style="font-family:courier">ClientSideValidationInterceptor</span> that will call the validation service and gather validation information:</p>
<br /><a href="http://vivin.net/?p=1680#comments" title="Comments on &quot;Integrating Regula with Spring 3.0.x MVC&quot;"><img src="http://vivin.net/wp-content/plugins/feed-comments-number/image.php?1680" alt="Comments" /></a><img src="http://vivin.net/?ak_action=api_record_view&#38;id=1680&#38;type=feed" alt="" />]]></content:encoded>
			<wfw:commentRss>http://vivin.net/2011/02/21/integrating-regula-with-spring-3-0-x-mvc/feed/</wfw:commentRss>
		<slash:comments>1</slash:comments>
	
		<media:thumbnail url="http://vivin.net/wp-content/plugins/feed-comments-number/image.php?1680" />
		<media:content url="http://vivin.net/wp-content/plugins/feed-comments-number/image.php?1680" medium="image">
			<media:title type="html">Comments</media:title>
		</media:content>
		<media:content url="http://vivin.net/?ak_action=api_record_view&#38;id=1680&#38;type=feed" medium="image" />
	</item>
		<item>
		<title>Packaging and distributing taglibs in a JAR</title>
		<link>http://vivin.net/2011/02/21/packaging-and-distributing-taglibs-in-a-jar/?utm_source=rss&#038;utm_medium=rss&#038;utm_campaign=rss</link>
		<comments>http://vivin.net/2011/02/21/packaging-and-distributing-taglibs-in-a-jar/#comments</comments>
		<pubDate>Mon, 21 Feb 2011 21:23:35 +0000</pubDate>
		<dc:creator>vivin</dc:creator>
				<category><![CDATA[Computers]]></category>
		<category><![CDATA[Java]]></category>
		<category><![CDATA[Programming and Development]]></category>
		<category><![CDATA[Web]]></category>
		<category><![CDATA[custom taglibs]]></category>
		<category><![CDATA[custom tags]]></category>
		<category><![CDATA[distributing]]></category>
		<category><![CDATA[jar]]></category>
		<category><![CDATA[jstl]]></category>
		<category><![CDATA[maven]]></category>
		<category><![CDATA[packing]]></category>
		<category><![CDATA[taglibs]]></category>
		<category><![CDATA[tags]]></category>

		<guid isPermaLink="false">http://vivin.net/?p=1673</guid>
		<description><![CDATA[This is more of a &#8220;note to self&#8221; than a &#8220;how to&#8221;. If you&#8217;re trying to distribute tag files in a JAR, you need to put them under /META-INF/tags. You then need to create a TLD file that you also put under /META-INF/tags. If you have tags or functions that you created in Java, and [...]]]></description>
			<content:encoded><![CDATA[<p>This is more of a &#8220;note to self&#8221; than a &#8220;how to&#8221;.</p>
<p>If you&#8217;re trying to distribute tag files in a JAR, you need to put them under <span style="font-family:courier">/META-INF/tags</span>. You then need to create a TLD file that you also put under <span style="font-family:courier">/META-INF/tags</span>. If you have tags or functions that you created in Java, and want to distribute them alongside the tag files, you need to reference them in the TLD and package them in the same JAR (goes without saying).</p>
<p>If you want to do the same thing in maven, the location for the tag files and the tld file is different; you need to put them in <span style="font-family:courier">src/main/resources/META-INF/tags</span>. Then you can run <span style="font-family:courier">mvn package</span> and maven will create a JAR with your tags.<br />
<span id="more-1673"></span><br />
My directory structure in my maven project looks like this:</p>
<pre>
src
`-- main
    |-- java
    |   `-- net
    |       `-- vivin
    |           `-- regula
    |               `-- validation
    |                   `-- util
    |                       `-- TagStringUtils.java
    `-- resources
        `-- META-INF
            `-- tags
                |-- generate-validation.tag
                `-- regula-spring.tld
</pre>
<p>And my TLD file looks like this:</p>
<pre class="brush: xml">
&lt;taglib&gt;
 &lt;tlib-version&gt;1.0&lt;/tlib-version&gt;
 &lt;short-name&gt;regula-spring&lt;/short-name&gt;
 &lt;uri&gt;http://regula-spring&lt;/uri&gt;
 &lt;jsp-version&gt;2.0&lt;/jsp-version&gt;

 &lt;tag-file&gt;
   &lt;name&gt;generate-validation&lt;/name&gt;
   &lt;path&gt;/META-INF/tags/generate-validation.tag&lt;/path&gt;
 &lt;/tag-file&gt;

 &lt;function&gt;
   &lt;name&gt;matches&lt;/name&gt;
   &lt;function-class&gt;net.vivin.regula.validation.util.TagStringUtils&lt;/function-class&gt;
   &lt;function-signature&gt;boolean matches(java.lang.String, java.lang.String, java.lang.String)&lt;/function-signature&gt;
 &lt;/function&gt;

 &lt;function&gt;
   &lt;name&gt;replaceUsingRegex&lt;/name&gt;
   &lt;function-class&gt;net.vivin.regula.validation.util.TagStringUtils&lt;/function-class&gt;
   &lt;function-signature&gt;java.lang.String replaceUsingRegex(java.lang.String, java.lang.String, java.lang.String, java.lang.String)&lt;/function-signature&gt;
 &lt;/function&gt;
&lt;/taglib&gt;
</pre>
<br /><a href="http://vivin.net/?p=1673#comments" title="Comments on &quot;Packaging and distributing taglibs in a JAR&quot;"><img src="http://vivin.net/wp-content/plugins/feed-comments-number/image.php?1673" alt="Comments" /></a><img src="http://vivin.net/?ak_action=api_record_view&#38;id=1673&#38;type=feed" alt="" />]]></content:encoded>
			<wfw:commentRss>http://vivin.net/2011/02/21/packaging-and-distributing-taglibs-in-a-jar/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
	
		<media:thumbnail url="http://vivin.net/wp-content/plugins/feed-comments-number/image.php?1673" />
		<media:content url="http://vivin.net/wp-content/plugins/feed-comments-number/image.php?1673" medium="image">
			<media:title type="html">Comments</media:title>
		</media:content>
		<media:content url="http://vivin.net/?ak_action=api_record_view&#38;id=1673&#38;type=feed" medium="image" />
	</item>
		<item>
		<title>Regula: An annotation-based form-validator written in Javascript</title>
		<link>http://vivin.net/2010/03/30/regula-an-annotation-based-form-validator-written-in-javascript/?utm_source=rss&#038;utm_medium=rss&#038;utm_campaign=rss</link>
		<comments>http://vivin.net/2010/03/30/regula-an-annotation-based-form-validator-written-in-javascript/#comments</comments>
		<pubDate>Tue, 30 Mar 2010 15:16:27 +0000</pubDate>
		<dc:creator>vivin</dc:creator>
				<category><![CDATA[Programming and Development]]></category>
		<category><![CDATA[Projects]]></category>
		<category><![CDATA[Web]]></category>
		<category><![CDATA[annotation]]></category>
		<category><![CDATA[annotation-based form-validation]]></category>
		<category><![CDATA[annotation-based validation]]></category>
		<category><![CDATA[annotations]]></category>
		<category><![CDATA[bean-validation]]></category>
		<category><![CDATA[form-validation]]></category>
		<category><![CDATA[framework]]></category>
		<category><![CDATA[hibernate]]></category>
		<category><![CDATA[javascript]]></category>
		<category><![CDATA[javascript form-validation]]></category>
		<category><![CDATA[library]]></category>
		<category><![CDATA[regula]]></category>

		<guid isPermaLink="false">http://vivin.net/?p=1477</guid>
		<description><![CDATA[Regula is an annotation-based form-validation framework written in Javascript. There already exist a few frameworks that address form-validation in Javascript, but I have found them to be somewhat lacking. I have thought about writing one of my own for some time, but I honestly had no idea what form it would or should take. I [...]]]></description>
			<content:encoded><![CDATA[<p><strong><em>Regula</em></strong> is an annotation-based form-validation framework written in Javascript. There already exist a few frameworks that address form-validation in Javascript, but I have found them to be somewhat lacking. I have thought about writing one of my own for some time, but I honestly had no idea what form it would or should take. I knew that I wanted to make one that was easy to use, flexible, and easily extensible (custom validation rules). I finally got an idea as to the form my framework should take, when I was looking at <a href="http://www.hibernate.org/">Hibernate</a> <a href="http://docs.jboss.org/hibernate/stable/validator/reference/en/html_single/">bean-validation</a>. I like the fact that you can set constraints by using annotations like <em>@NotNull</em> or  <em>@NotEmpty</em>. That way, when you look at the bean, you are immediately aware of the constraints attached to it. I wanted to do something similar in HTML.<br />
<span id="more-1477"></span><br />
Enter HTML5. HTML5 supports and endorses <a href="http://dev.w3.org/html5/spec/dom.html#embedding-custom-non-visible-data">custom attributes</a> in HTML tags. Purists may scream &#8220;No!&#8221;, but I think it is a useful feature. However, like all features it has the potential for abuse. But that&#8217;s another topic entirely. Anyway, I started thinking &#8211; what if I could use a custom attribute to specify the constraints? Then I could use Javascript to identify those constraints and then enforce them during validation. What I was thinking of, was to do something like this:</p>
<pre class="brush: html">
&lt;input id = &quot;myInput&quot;
         type = &quot;text&quot;
         data-constraints = &#039;@NotEmpty @IsNumeric @Between(min=1, max=5)&#039;&gt;
</pre>
<p>That bit of code describes a text box which cannot be empty, and which expects a numeric value between 1 and 5. With this basic design in mind, I started working on my framework. It took me about a week of on-and-off work (maybe 3 days actual work) but I&#8217;ve come up with something that is, in my humble opinion, a flexible and easy to use framework. I plan to document the use of this library/framework more thoroughly, but this post should serve as a gentle introduction to the framework and its features.</p>
<p>In <em><strong>Regula</strong></em> (which, by the way, means &#8220;rule&#8221; in Latin) form elements (input elements or even the form elements) can have constraints attached to them in a similar fashion to the example I described earlier. There is a small difference, however:</p>
<pre class="brush: html">
&lt;input id = &quot;myInput&quot;
         class = &quot;regula-validation&quot;
         type = &quot;text&quot;
         data-constraints = &#039;@NotEmpty @IsNumeric @Between(min=1, max=5)&#039;&gt;
</pre>
<p>As you can see, I use a class name of <em>regula-validation</em> which tells the framework that this input element has constraints attached to it. The reason I did this was for efficiency reasons. It&#8217;s much more efficient to grab all elements that have a class name of <em>regula-validation</em> than walking the whole document tree to search for nodes that have a <em>data-constraints</em> attribute.</p>
<p>After you annotate the input elements with their constraints, you&#8217;re halfway there already! All you have to do after that is add a script tag for the framework:</p>
<pre class="brush: html">
  &lt;script type = &quot;text/javascript&quot; src=&quot;regula.js&quot;&gt;&lt;/script&gt;
</pre>
<p>And then add the necessary Javascript to validate the form (example uses jQuery):</p>
<pre class="brush: javascript">
jQuery(document).ready(function() {
    // must call this first. The best place would be in an
    // onload handler. This function looks for elements with
    // a class name of &quot;regula-validation&quot; and binds the
    // appropriate constraints to the elements
    regula.bind(); 

    jQuery(&quot;#myForm&quot;).submit(function() {
        // this functions performs the actual validation
        var validationResults = regula.validate();

        for(var index in validationResults) {
             var validationResult = validationResults[index];
             alert(validationResult.message);
        }
    });
});
</pre>
<p>That&#8217;s pretty much all there is to it. More advanced uses of the framework don&#8217;t deviate that much from this pattern. Compared to other form-validation frameworks (that I&#8217;ve seen), validation will not stop on the first failing element. The <em>validate</em> function runs through every input element and validates it against the constraints bound to that element, and returns an array of &#8220;validation results&#8221;. Each &#8220;validation result&#8221; element in the array has the following properties:</p>
<ul>
<li><em><strong>constraintName</strong></em> &#8211; the name of the failing constraint</li>
<li><em><strong>custom</strong></em> &#8211; a flag that says whether this is a custom constraint or not</li>
<li><em><strong>constraintParameters</strong></em> &#8211; An array of objects that represents the parameters passed to this constraint (defined in the HTML. For example <em>@Max(max=5)</em>, where you have a parameter who&#8217;s name is <em>max</em> and who&#8217;s value is <em>5</em>. There&#8217;s a little more to this, but like I said, this is supposed to be a gentle introduction <img src='http://vivin.net/wp-includes/images/smilies/icon_smile.gif' alt=':)' class='wp-smiley' /> )</li>
<li><em><strong>receivedParameters</strong></em> &#8211; A hash (organized such that the name of the parameter is the key, and the value is well, the value) of parameters that the validator function received (helpful when you have a custom validator).
<li><em><strong>failingElements</strong></em> &#8211; An array containing references to the actual input element or elements (in the case of form-specific constraints) that failed the constraint.</li>
<li><em><strong>message</strong></em> &#8211; The error message.</li>
</ul>
<br /><a href="http://vivin.net/?p=1477#comments" title="Comments on &quot;Regula: An annotation-based form-validator written in Javascript&quot;"><img src="http://vivin.net/wp-content/plugins/feed-comments-number/image.php?1477" alt="Comments" /></a><img src="http://vivin.net/?ak_action=api_record_view&#38;id=1477&#38;type=feed" alt="" />]]></content:encoded>
			<wfw:commentRss>http://vivin.net/2010/03/30/regula-an-annotation-based-form-validator-written-in-javascript/feed/</wfw:commentRss>
		<slash:comments>3</slash:comments>
	
		<media:thumbnail url="http://vivin.net/wp-content/plugins/feed-comments-number/image.php?1477" />
		<media:content url="http://vivin.net/wp-content/plugins/feed-comments-number/image.php?1477" medium="image">
			<media:title type="html">Comments</media:title>
		</media:content>
		<media:content url="http://vivin.net/?ak_action=api_record_view&#38;id=1477&#38;type=feed" medium="image" />
	</item>
		<item>
		<title>Akismet flagging everything as spam</title>
		<link>http://vivin.net/2010/03/29/akismet-flagging-everything-as-spam/?utm_source=rss&#038;utm_medium=rss&#038;utm_campaign=rss</link>
		<comments>http://vivin.net/2010/03/29/akismet-flagging-everything-as-spam/#comments</comments>
		<pubDate>Tue, 30 Mar 2010 02:19:18 +0000</pubDate>
		<dc:creator>vivin</dc:creator>
				<category><![CDATA[Nerdy Stuff]]></category>
		<category><![CDATA[Web]]></category>
		<category><![CDATA[akismet]]></category>
		<category><![CDATA[comments]]></category>
		<category><![CDATA[spam]]></category>
		<category><![CDATA[wordpress]]></category>

		<guid isPermaLink="false">http://vivin.net/?p=1469</guid>
		<description><![CDATA[If you&#8217;ve been commenting on posts and now seeing anything, it&#8217;s because Akismet as been flagging all comments as spam. I don&#8217;t know why. I think it started after I upgraded WordPress. I&#8217;ve turned it off for now. Oh well.]]></description>
			<content:encoded><![CDATA[<p>If you&#8217;ve been commenting on posts and now seeing anything, it&#8217;s because Akismet as been flagging all comments as spam. I don&#8217;t know why. I think it started after I upgraded WordPress. I&#8217;ve turned it off for now. Oh well.</p>
<br /><a href="http://vivin.net/?p=1469#comments" title="Comments on &quot;Akismet flagging everything as spam&quot;"><img src="http://vivin.net/wp-content/plugins/feed-comments-number/image.php?1469" alt="Comments" /></a><img src="http://vivin.net/?ak_action=api_record_view&#38;id=1469&#38;type=feed" alt="" />]]></content:encoded>
			<wfw:commentRss>http://vivin.net/2010/03/29/akismet-flagging-everything-as-spam/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
	
		<media:thumbnail url="http://vivin.net/wp-content/plugins/feed-comments-number/image.php?1469" />
		<media:content url="http://vivin.net/wp-content/plugins/feed-comments-number/image.php?1469" medium="image">
			<media:title type="html">Comments</media:title>
		</media:content>
		<media:content url="http://vivin.net/?ak_action=api_record_view&#38;id=1469&#38;type=feed" medium="image" />
	</item>
		<item>
		<title>JSTL, instanceof, and hasProperty</title>
		<link>http://vivin.net/2009/12/04/jstl-instanceof-and-hasproperty/?utm_source=rss&#038;utm_medium=rss&#038;utm_campaign=rss</link>
		<comments>http://vivin.net/2009/12/04/jstl-instanceof-and-hasproperty/#comments</comments>
		<pubDate>Sat, 05 Dec 2009 04:12:30 +0000</pubDate>
		<dc:creator>vivin</dc:creator>
				<category><![CDATA[Java]]></category>
		<category><![CDATA[Programming and Development]]></category>
		<category><![CDATA[Web]]></category>
		<category><![CDATA[custom tags]]></category>
		<category><![CDATA[development]]></category>
		<category><![CDATA[instanceof]]></category>
		<category><![CDATA[java]]></category>
		<category><![CDATA[jsp]]></category>
		<category><![CDATA[jstl]]></category>
		<category><![CDATA[programming]]></category>
		<category><![CDATA[reflection]]></category>
		<category><![CDATA[taglibs]]></category>
		<category><![CDATA[web development]]></category>

		<guid isPermaLink="false">http://vivin.net/?p=1233</guid>
		<description><![CDATA[I&#8217;ve been doing a little bit of JSTL over the past week, especially custom tags. I&#8217;ve written custom tags in Grails before, and there you use actual Groovy code. I guess this was how custom tags used to be written (in Java), but now you can can build your own custom tags using the standard [...]]]></description>
			<content:encoded><![CDATA[<p>I&#8217;ve been doing a little bit of <a href="http://java.sun.com/products/jsp/jstl/">JSTL</a> over the past week, especially custom tags. I&#8217;ve written custom tags in Grails before, and there you use actual Groovy code. I guess this was how custom tags used to be written (in Java), but now you can can build your own custom tags using the standard tag library. The standard tag library is still pretty useful when it comes to building custom tags. Since it&#8217;s not straight Java, it forces you think really hard about your logic. You don&#8217;t want to put any business or application logic in your tag, and you want to restrict everything to view or presentation logic. A side effect of it not being Java is that if you want to do anything extremely complicated, you&#8217;re probably better off writing the tag in Java (making sure that you don&#8217;t let any business logic creep in).</p>
<p>While writing my own custom tag, I noticed that although <em>instanceof</em> is a reserved word in the JSTL EL (expression language), it is not supported as an operator. The reason I wanted to use the <em>instanceof</em> operator is that I have an attribute that could either be a <em>List</em> or a <em>Map</em> and depending on the type, I wanted to do different things.</p>
<p>Another thing I was trying to do, was to inspect the incoming object to see if it had a certain property (reflection). JSTL uses reflection so that you can access the properties of an object via dot notation, if they follow the JavaBean naming-convention. However, there was no way for me to see if an object had a certain property. To solve both these problems, I wrote my own JSTL functions.<br />
<span id="more-1233"></span><br />
The first function I wrote was one that performed the <em>instanceof</em> operation. I created a class called <em>TagUtils</em> that contained static methods that returned primitive types (like boolean, String, or Integer). <em>instanceof</em> presents a special challenge because you can&#8217;t have the second parameter be dynamic. For example, assuming that you have an object named <em>acura</em> that&#8217;s an instance of the class <em>Car</em> and a String named <em>className</em> that holds the value &#8220;<em>Car</em>&#8220;, you can&#8217;t do <em><strong>acura</strong> instanceof <strong>className</strong></em>. You have to use reflection and create a <em>Class</em> object using the <em>forName</em> static method and then check to see if <em>acura</em> is an instance by using the <em>isInstance</em> method.</p>
<p>The second function I wrote is the <em>hasProperty</em> function which uses reflection to check whether the supplied object has a particular property. To be precise, I don&#8217;t explicitly check for the existence of the object directly. Rather, I check and see if there is a getter for that property. For example, if the property is called <em>firstName</em>, then there should be a getter called <em>getFirstName()</em>.</p>
<p>The code for the functions looks like this:</p>
<pre class="brush: java">
package util.tag;

public class TagUtils {

    //Checks to see if Object &#039;o&#039; is an instance of the class in the string &quot;className&quot;
    public static boolean instanceOf(Object o, String className) {
        boolean returnValue;

        try {
            returnValue = Class.forName(className).isInstance(o);
        }

        catch(ClassNotFoundException e) {
            returnValue = false;
        }

        return returnValue;
    }

    //Checks to see if Object &#039;o&#039; has a property specified in &quot;propertyName&quot;
    public static boolean hasProperty(Object o, String propertyName) {
        boolean methodFound = false;
        int i = 0;

        Class myClass = o.getClass();
        String methodName = &quot;get&quot; + propertyName.toUpperCase().charAt(0) + propertyName.substring(1);
        Method[] methods = myClass.getMethods();

        while(i &lt; methods.length &amp;&amp; !methodFound) {
            methodFound = methods[i].getName().compareTo(methodName) == 0;
            i++;
        }

        return methodFound;
    }
}
</pre>
<p><del datetime="2009-12-12T21:35:27+00:00">For the <em>hasProperty</em> function, you can see that I used the <em>getMethod</em> method. The second argument is an array of parameter types. Since the getter accepts no parameters, we pass in an empty array (of type <em>Class</em>).</del></p>
<p>Using exceptions in business logic is really bad, because it slows down the JVM. So the rendering will also become really slow if there are a lot of exceptions being thrown. To fix this problem, I used the <em>getMethods</em> method, which returns an array of <em>Method</em> objects. I then search the array to see if the getter I want, exists.</p>
<p>After you create your functions, you have to put them in a <em>tld</em> file. I created a one called <em>tagutils.tld</em> that I put in <em>WEB-INF</em>:</p>
<pre class="brush: xml">
&lt;?xml version=&quot;1.0&quot; encoding=&quot;UTF-8&quot;?&gt;
&lt;taglib xmlns=&quot;http://java.sun.com/xml/ns/javaee&quot; xmlns:xsi=&quot;http://www.w3.org/2001/XMLSchema-instance&quot;
    xsi:schemaLocation=&quot;http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-jsptaglibrary_2_1.xsd&quot;
    version=&quot;2.1&quot;&gt;
    &lt;tlib-version&gt;1.0&lt;/tlib-version&gt;
    &lt;short-name&gt;function&lt;/short-name&gt;
    &lt;uri&gt;http://tagutils&lt;/uri&gt;
    &lt;function&gt;
        &lt;name&gt;instanceOf&lt;/name&gt;
        &lt;function-class&gt;util.tag.TagUtils&lt;/function-class&gt;
        &lt;function-signature&gt;boolean instanceOf(java.lang.Object, java.lang.String)&lt;/function-signature&gt;
    &lt;/function&gt;
    &lt;function&gt;
        &lt;name&gt;hasProperty&lt;/name&gt;
        &lt;function-class&gt;util.tag.TagUtils&lt;/function-class&gt;
        &lt;function-signature&gt;boolean hasProperty(java.lang.Object, java.lang.String)&lt;/function-signature&gt;
    &lt;/function&gt;
&lt;/taglib&gt;
</pre>
<p>Once you create that file, you can use your new functions in your JSP files. To test the <em>hasProperty</em> function, I created a simple class called <em>Person</em>:</p>
<pre class="brush: java">
package domain;

public class Person {
    private String firstName;
    private String lastName;

    public Person(String firstName, String lastName) {
        this.firstName = firstName;
        this.lastName = lastName;
    }

    public void setFirstName(String firstName) {
        this.firstName = firstName;
    }

    public void setLastName(String lastName) {
        this.lastName = lastName;
    }

    public String getFirstName() {
        return firstName;
    }

    public String getLastName() {
        return lastName;
    }

    public String toString() {
        return firstName + &quot; &quot; + lastName;
    }
}
</pre>
<p>Now I put it all together:</p>
<pre class="brush: xhtml">
&lt;%@ taglib prefix=&quot;function&quot; uri=&quot;http://tagutils&quot;%&gt;
&lt;%@ taglib prefix=&quot;c&quot; uri=&quot;http://java.sun.com/jsp/jstl/core&quot; %&gt;

&lt;%@ page import=&quot;java.util.Map&quot; %&gt;
&lt;%@ page import=&quot;java.util.LinkedHashMap&quot; %&gt;
&lt;%@ page import=&quot;java.util.List&quot; %&gt;
&lt;%@ page import=&quot;java.util.ArrayList&quot; %&gt;
&lt;%@ page import=&quot;domain.Person&quot; %&gt;
&lt;%
    Map&lt;String, String&gt; myMap = new LinkedHashMap&lt;String, String&gt;();
    pageContext.setAttribute(&quot;myMap&quot;, myMap);

    List&lt;Person&gt; myList = new ArrayList&lt;Person&gt;();
    pageContext.setAttribute(&quot;myList&quot;, myList);

    pageContext.setAttribute(&quot;person&quot;, new Person(&quot;Holly&quot;, &quot;Hoo&quot;));
%&gt;

myMap is an instance of Map:
&lt;b&gt;
 &lt;c:choose&gt;
   &lt;c:when test=&quot;${function:instanceOf(myMap, &#039;java.util.Map&#039;)}&quot;&gt;true&lt;/c:when&gt;
   &lt;c:otherwise&gt;false&lt;/c:otherwise&gt;
  &lt;/c:choose&gt;
&lt;/b&gt;&lt;br/&gt;
myList is an instance of List:
&lt;b&gt;
 &lt;c:choose&gt;
  &lt;c:when test=&quot;${function:instanceOf(myList, &#039;java.util.List&#039;)}&quot;&gt;true&lt;/c:when&gt;
  &lt;c:otherwise&gt;false&lt;/c:otherwise&gt;
 &lt;/c:choose&gt;
&lt;/b&gt;&lt;br/&gt;&lt;br/&gt;

myMap is an instance of List:
&lt;b&gt;
 &lt;c:choose&gt;
  &lt;c:when test=&quot;${function:instanceOf(myMap, &#039;java.util.List&#039;)}&quot;&gt;true&lt;/c:when&gt;
  &lt;c:otherwise&gt;false&lt;/c:otherwise&gt;&lt;/c:choose&gt;
&lt;/b&gt;&lt;br/&gt;
myList is an instance of Map:
&lt;b&gt;
 &lt;c:choose&gt;
  &lt;c:when test=&quot;${function:instanceOf(myList, &#039;java.util.Map&#039;)}&quot;&gt;true&lt;/c:when&gt;
  &lt;c:otherwise&gt;false&lt;/c:otherwise&gt;
 &lt;/c:choose&gt;
&lt;/b&gt;&lt;br/&gt;&lt;br/&gt;

Person has a property called firstName:
&lt;b&gt;
 &lt;c:choose&gt;
  &lt;c:when test=&quot;${function:hasProperty(person, &#039;firstName&#039;)}&quot;&gt;true&lt;/c:when&gt;
  &lt;c:otherwise&gt;false&lt;/c:otherwise&gt;
 &lt;/c:choose&gt;
&lt;/b&gt;&lt;br/&gt;
Person has a property called lastName:
&lt;b&gt;
 &lt;c:choose&gt;
  &lt;c:when test=&quot;${function:hasProperty(person, &#039;lastName&#039;)}&quot;&gt;true&lt;/c:when&gt;
  &lt;c:otherwise&gt;false&lt;/c:otherwise&gt;
 &lt;/c:choose&gt;
&lt;/b&gt;&lt;br /&gt;
Person has a property called id:
&lt;b&gt;
 &lt;c:choose&gt;
  &lt;c:when test=&quot;${function:hasProperty(person, &#039;id&#039;)}&quot;&gt;true&lt;/c:when&gt;
  &lt;c:otherwise&gt;false&lt;/c:otherwise&gt;
 &lt;/c:choose&gt;
&lt;/b&gt;&lt;br /&gt;
</pre>
<p><em><strong>Note</strong>: I have used a scriptlet in the above example simple to demonstrate the usage of the functions. The use of scriptlets in JSP is bad practice since it probably means that you are putting your business logic in your JSP. The proper place for such code is in a Controller or a Service.</em></p>
<p>As you can see from the above example, the usage is pretty simple. If everything went well, the output should look something like this:</p>
<blockquote><p>
myMap is an instance of Map: <strong>true</strong><br />
myList is an instance of List: <strong>true</strong></p>
<p>myMap is an instance of List: <strong>false</strong><br />
myList is an instance of Map: <strong>false</strong></p>
<p>Person has a property called firstName: <strong>true</strong><br />
Person has a property called lastName: <strong>true</strong><br />
Person has a property called id: <strong>false</strong>
</p></blockquote>
<p><em><b>Note</b>: Using the JSP above, the <em>true</em> and <em>false</em> values will actually be on separate lines. I broke the code up in my example for readability. In my actual code, The whole logic expression is in one line.</em></p>
<p>One important thing to note is that when you use the <em>instanceOf</em> function, you have to provide the <strong>fully-qualified class-name</strong>. Otherwise, the method will return <em>false</em>.</p>
<p><strong>UPDATE</strong></p>
<p><strong>thetoolman</strong> suggested some improvements that uses <span style = "font-family: courier new; font-weight: bold">BeanInfo</span> instead of the reflection API:</p>
<pre class="brush: java">
public class TagUtils {

    public static boolean instanceOf(Object o, String className) {
        if (o == null || className == null) {
            return false;
        }

        try {
            return Class.forName(className, false, Thread.currentThread().getContextClassLoader()).isInstance(o);
        }

        catch (ClassNotFoundException e) {
            return false;
        }
    }

    public static boolean hasProperty(Object o, String propertyName) {
        if (o == null || propertyName == null) {
            return false;
        }

        BeanInfo beanInfo;
        try {
            beanInfo = java.beans.Introspector.getBeanInfo(o.getClass());
        }

        catch (IntrospectionException e) {
            return false;
        }

        for(final PropertyDescriptor pd : beanInfo.getPropertyDescriptors()) {

            if (propertyName.equals(pd.getName())) {
                return true;
            }
        }
        return false;
    }
}
</pre>
<h4>References</h4>
<ol>
<li><a href="http://stackoverflow.com/questions/1076315/jstl-check-if-property-doesnt-exist"> JSTL: check if property doesn&#8217;t exist (stackoverflow.com)</a></li>
<li><a href="http://mindprod.com/jgloss/instanceof.html">instanceof: Java Glossary (mindprod.com)</a></li>
<li><a href="http://java.sun.com/javase/6/docs/api/java/lang/Class.html">Class (Java Platform SE 6)</a></li>
</ol>
<br /><a href="http://vivin.net/?p=1233#comments" title="Comments on &quot;JSTL, instanceof, and hasProperty&quot;"><img src="http://vivin.net/wp-content/plugins/feed-comments-number/image.php?1233" alt="Comments" /></a><img src="http://vivin.net/?ak_action=api_record_view&#38;id=1233&#38;type=feed" alt="" />]]></content:encoded>
			<wfw:commentRss>http://vivin.net/2009/12/04/jstl-instanceof-and-hasproperty/feed/</wfw:commentRss>
		<slash:comments>6</slash:comments>
	
		<media:thumbnail url="http://vivin.net/wp-content/plugins/feed-comments-number/image.php?1233" />
		<media:content url="http://vivin.net/wp-content/plugins/feed-comments-number/image.php?1233" medium="image">
			<media:title type="html">Comments</media:title>
		</media:content>
		<media:content url="http://vivin.net/?ak_action=api_record_view&#38;id=1233&#38;type=feed" medium="image" />
	</item>
		<item>
		<title>Displaying images side-by-side in WordPress</title>
		<link>http://vivin.net/2009/11/05/displaying-images-side-by-side-in-wordpress/?utm_source=rss&#038;utm_medium=rss&#038;utm_campaign=rss</link>
		<comments>http://vivin.net/2009/11/05/displaying-images-side-by-side-in-wordpress/#comments</comments>
		<pubDate>Fri, 06 Nov 2009 02:11:30 +0000</pubDate>
		<dc:creator>vivin</dc:creator>
				<category><![CDATA[Computers]]></category>
		<category><![CDATA[Programming and Development]]></category>
		<category><![CDATA[Web]]></category>
		<category><![CDATA[css]]></category>
		<category><![CDATA[development]]></category>
		<category><![CDATA[html]]></category>
		<category><![CDATA[programming]]></category>
		<category><![CDATA[web development]]></category>
		<category><![CDATA[wordpress]]></category>

		<guid isPermaLink="false">http://vivin.net/?p=1109</guid>
		<description><![CDATA[I&#8217;ve been using WordPress for about two months now and I really like it. It takes away a lot of the pain from blogging. Recently I was writing a blog post and I was trying to get two images displayed side-by-side. This proved to be more difficult than I thought. There&#8217;s no immediately obvious way [...]]]></description>
			<content:encoded><![CDATA[<p>I&#8217;ve been using WordPress for about two months now and I really like it. It takes away a lot of the pain from blogging. Recently I was writing a blog post and I was trying to get two images displayed side-by-side. This proved to be more difficult than I thought. There&#8217;s no immediately obvious way in WordPress to display images side-by-side. I tried to use tables, but that didn&#8217;t work out. I also tried to use the gallery, but that displays all the images, and I just wanted to display two. I was able to get it working finally.<br />
<span id="more-1109"></span><br />
The method involves the <span style="font-family:courier new">inline-block display</span> property. You first insert images as you normally would, making sure that they have no alignment. An important point to note here is that you might want to adjust the size of your images if their combined width (plus any padding) exceeds the width of content area. Once you adjust the sizes of the images (if you need to), you wrap each image in a <span style="font-family:courier new">div</span> that has its <span style="font-family:courier new">display</span> property set to <span style="font-family:courier new">inline-block</span>. You also want to set the right margin to some non-zero value so that there&#8217;s a space between the images. The code looks like this:</p>
<pre class="brush: php">
&lt;div style=&quot;display: inline-block; margin-right: 5px&quot;&gt;
 [ ... wordpress generated code for first image ... ]
&lt;/div&gt;
&lt;div style=&quot;display: inline-block&quot;&gt;
 [ ... wordpress generated code for second image ... ]
&lt;/div&gt;
</pre>
<p>And the rendered content, like this:</p>
<div style="display: inline-block; margin-right: 5px;">
<div id="attachment_1112" class="wp-caption alignnone" style="width: 253px;  border: 1px solid #dddddd; background-color: #f3f3f3; padding-top: 4px; margin: 10px; text-align:center;"><a href="http://vivin.net/wp-content/uploads/2009/11/DSC05986.JPG"><img class="size-medium wp-image-1112  " title="Honey and Ham" src="http://vivin.net/wp-content/uploads/2009/11/DSC05986-300x225.jpg" alt="Honey and Ham" width="243" height="183" /></a><p style=' padding: 0 4px 5px; margin: 0;'  class="wp-caption-text">Honey and Ham</p></div>
</div>
<div style="display: inline-block;">
<div id="attachment_1113" class="wp-caption alignnone" style="width: 253px;  border: 1px solid #dddddd; background-color: #f3f3f3; padding-top: 4px; margin: 10px; text-align:center;"><a href="http://vivin.net/wp-content/uploads/2009/11/DSC05980.JPG"><img class="size-medium wp-image-1113  " title="Ham Jumping" src="http://vivin.net/wp-content/uploads/2009/11/DSC05980-300x225.jpg" alt="Ham Jumping" width="243" height="183" /></a><p style=' padding: 0 4px 5px; margin: 0;'  class="wp-caption-text">Ham Jumping</p></div>
</div>
<p>What if you wanted to center the content? That&#8217;s pretty simple too:</p>
<pre class="brush: php">
&lt;div style = &quot;text-align:center&quot;&gt;
 &lt;div style=&quot;display: inline-block; margin-right: 5px&quot;&gt;
   [ ... wordpress generated code for first image ... ]
 &lt;/div&gt;

 &lt;div style=&quot;display: inline-block&quot;&gt;
  [ ... wordpress generated code for second image ... ]
 &lt;/div&gt;
&lt;/div&gt;
</pre>
<p>The rendered content looks like this:</p>
<div style = "text-align:center">
<div style="display: inline-block; margin-right: 5px;">
<div id="attachment_1112" class="wp-caption alignnone" style="width: 253px;  border: 1px solid #dddddd; background-color: #f3f3f3; padding-top: 4px; margin: 10px; text-align:center;"><a href="http://vivin.net/wp-content/uploads/2009/11/DSC05986.JPG"><img class="size-medium wp-image-1112 " title="Honey and Ham" src="http://vivin.net/wp-content/uploads/2009/11/DSC05986-300x225.jpg" alt="Honey and Ham" width="243" height="183" /></a><p style=' padding: 0 4px 5px; margin: 0;'  class="wp-caption-text">Honey and Ham</p></div></div>
<div style="display: inline-block;">
<div id="attachment_1113" class="wp-caption alignnone" style="width: 253px;  border: 1px solid #dddddd; background-color: #f3f3f3; padding-top: 4px; margin: 10px; text-align:center;"><a href="http://vivin.net/wp-content/uploads/2009/11/DSC05980.JPG"><img class="size-medium wp-image-1113 " title="Ham Jumping" src="http://vivin.net/wp-content/uploads/2009/11/DSC05980-300x225.jpg" alt="Ham Jumping" width="243" height="183" /></a><p style=' padding: 0 4px 5px; margin: 0;'  class="wp-caption-text">Ham Jumping</p></div></div>
</div>
<p>The only problem with this solution is that it won&#8217;t work in <a href="http://en.wikipedia.org/wiki/Internet_Explorer">browsers that fail to implement standards correctly</a> (IE8 does though). But overall, a pretty simple method that should work in most browsers. Also, instead of having to type out the styles every time, you can easily add these to your stylesheet and then use them as you need them.</p>
<br /><a href="http://vivin.net/?p=1109#comments" title="Comments on &quot;Displaying images side-by-side in WordPress&quot;"><img src="http://vivin.net/wp-content/plugins/feed-comments-number/image.php?1109" alt="Comments" /></a><img src="http://vivin.net/?ak_action=api_record_view&#38;id=1109&#38;type=feed" alt="" />]]></content:encoded>
			<wfw:commentRss>http://vivin.net/2009/11/05/displaying-images-side-by-side-in-wordpress/feed/</wfw:commentRss>
		<slash:comments>72</slash:comments>
	
		<media:thumbnail url="http://vivin.net/wp-content/uploads/2009/11/DSC05986-150x150.jpg" />
		<media:content url="http://vivin.net/wp-content/uploads/2009/11/DSC05986.JPG" medium="image">
			<media:title type="html">Honey and Ham</media:title>
			<media:description type="html">Honey and Ham</media:description>
			<media:thumbnail url="http://vivin.net/wp-content/uploads/2009/11/DSC05986-150x150.jpg" />
		</media:content>
		<media:content url="http://vivin.net/wp-content/uploads/2009/11/DSC05980.JPG" medium="image">
			<media:title type="html">Ham Jumping</media:title>
			<media:description type="html">Ham Jumping</media:description>
			<media:thumbnail url="http://vivin.net/wp-content/uploads/2009/11/DSC05980-150x150.jpg" />
		</media:content>
		<media:content url="http://vivin.net/wp-content/uploads/2009/11/DSC05986.JPG" medium="image">
			<media:title type="html">Honey and Ham</media:title>
			<media:description type="html">Honey and Ham</media:description>
			<media:thumbnail url="http://vivin.net/wp-content/uploads/2009/11/DSC05986-150x150.jpg" />
		</media:content>
		<media:content url="http://vivin.net/wp-content/uploads/2009/11/DSC05980.JPG" medium="image">
			<media:title type="html">Ham Jumping</media:title>
			<media:description type="html">Ham Jumping</media:description>
			<media:thumbnail url="http://vivin.net/wp-content/uploads/2009/11/DSC05980-150x150.jpg" />
		</media:content>
		<media:content url="http://vivin.net/wp-content/plugins/feed-comments-number/image.php?1109" medium="image">
			<media:title type="html">Comments</media:title>
		</media:content>
		<media:content url="http://vivin.net/?ak_action=api_record_view&#38;id=1109&#38;type=feed" medium="image" />
	</item>
		<item>
		<title>The new vivin.net</title>
		<link>http://vivin.net/2009/09/04/the-new-vivin-net/?utm_source=rss&#038;utm_medium=rss&#038;utm_campaign=rss</link>
		<comments>http://vivin.net/2009/09/04/the-new-vivin-net/#comments</comments>
		<pubDate>Fri, 04 Sep 2009 07:08:04 +0000</pubDate>
		<dc:creator>vivin</dc:creator>
				<category><![CDATA[Programming and Development]]></category>
		<category><![CDATA[Web]]></category>
		<category><![CDATA[my website]]></category>
		<category><![CDATA[perl]]></category>
		<category><![CDATA[programming]]></category>
		<category><![CDATA[wordpress]]></category>

		<guid isPermaLink="false">http://vivin.net/?p=414</guid>
		<description><![CDATA[Well, I finally did it. I decided to migrate over to WordPress! For a long time I was thinking of rewriting my homegrown blogging-engine (that I initially designed over seven years ago). I never got around to doing it because it was just so much work! I know part of it has to do with [...]]]></description>
			<content:encoded><![CDATA[<p>Well, I finally did it. I decided to migrate over to <a title="Wordpress" href="http://wordpress.org" target="_blank">WordPress</a>! For a long time I was thinking of rewriting my homegrown blogging-engine (that I initially designed over seven years ago). I never got around to doing it because it was just so much work! I know part of it has to do with the &#8220;reinventing the wheel&#8221; syndrome. There is a certain pride that a developer has in coming up with his own solution for a problem. But then I realized that the problem has already been solved, but other people, with more resources than I, and in a much nicer way that I could ever do. I also realized that any new design would be a constant work in progress, and frankly, that just gets tiring after a while.</p>
<p>So, I made the decision to use WordPress. This meant that I would have to migrate all my old posts from my old database into WordPress&#8217;s database. Thanks to WordPress&#8217;s excellent database-schema documentation, this wasn&#8217;t hard at all. I wrote a Perl migration-script to move all my posts, comments, and tags into WordPress. I also had to make some changes to my .htaccess file (and write a redirect php page) to ensure that links in the old format would get translated into the new format. Everything seems to be working pretty well so far! I know there are a few rough edges to sand down (basically the old project pages, which aren&#8217;t visible now) but I don&#8217;t think it should be that difficult.</p>
<p>To my readers (the two or three of you!) if you spot anything out of the ordinary in my old posts (bad formatting, unparsed tags, broken links) please let me know so that I can fix it! Oh and another thing, since WordPress makes it so easy to add new posts, I think I will be writing a whole lot more!</p>
<br /><a href="http://vivin.net/?p=414#comments" title="Comments on &quot;The new vivin.net&quot;"><img src="http://vivin.net/wp-content/plugins/feed-comments-number/image.php?414" alt="Comments" /></a><img src="http://vivin.net/?ak_action=api_record_view&#38;id=414&#38;type=feed" alt="" />]]></content:encoded>
			<wfw:commentRss>http://vivin.net/2009/09/04/the-new-vivin-net/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
	
		<media:thumbnail url="http://vivin.net/wp-content/plugins/feed-comments-number/image.php?414" />
		<media:content url="http://vivin.net/wp-content/plugins/feed-comments-number/image.php?414" medium="image">
			<media:title type="html">Comments</media:title>
		</media:content>
		<media:content url="http://vivin.net/?ak_action=api_record_view&#38;id=414&#38;type=feed" medium="image" />
	</item>
	</channel>
</rss>

