<?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; java</title>
	<atom:link href="http://vivin.net/tag/java/feed/" rel="self" type="application/rss+xml" />
	<link>http://vivin.net</link>
	<description>random musings of just another computer nerd</description>
	<lastBuildDate>Tue, 17 Jan 2012 23:32:52 +0000</lastBuildDate>
	<language>en</language>
	<sy:updatePeriod>hourly</sy:updatePeriod>
	<sy:updateFrequency>1</sy:updateFrequency>
	<generator>http://wordpress.org/?v=3.3.1</generator>
		<item>
		<title>Implementing pinch-zoom and pan/drag in an Android view on the canvas</title>
		<link>http://vivin.net/2011/12/04/implementing-pinch-zoom-and-pandrag-in-an-android-view-on-the-canvas/?utm_source=rss&#038;utm_medium=rss&#038;utm_campaign=rss</link>
		<comments>http://vivin.net/2011/12/04/implementing-pinch-zoom-and-pandrag-in-an-android-view-on-the-canvas/#comments</comments>
		<pubDate>Sun, 04 Dec 2011 23:21:49 +0000</pubDate>
		<dc:creator>vivin</dc:creator>
				<category><![CDATA[Android]]></category>
		<category><![CDATA[Java]]></category>
		<category><![CDATA[Operating Systems]]></category>
		<category><![CDATA[Programming and Development]]></category>
		<category><![CDATA[Software]]></category>
		<category><![CDATA[android]]></category>
		<category><![CDATA[canvas]]></category>
		<category><![CDATA[drag]]></category>
		<category><![CDATA[dragging]]></category>
		<category><![CDATA[gestures]]></category>
		<category><![CDATA[java]]></category>
		<category><![CDATA[pan]]></category>
		<category><![CDATA[panning]]></category>
		<category><![CDATA[pinch-zoom]]></category>
		<category><![CDATA[view]]></category>
		<category><![CDATA[zoom]]></category>
		<category><![CDATA[zooming]]></category>

		<guid isPermaLink="false">http://vivin.net/?p=1806</guid>
		<description><![CDATA[I was trying to get pinch-zoom and panning working on an Android view today. Basically I was trying to implement the same behavior you see when you use Google Maps (for example). You can zoom in and pan around until the edge of the image, but no further. Also, if the image is fully zoomed [...]]]></description>
			<content:encoded><![CDATA[<p>I was trying to get pinch-zoom and panning working on an Android view today. Basically I was trying to implement the same behavior you see when you use Google Maps (for example). You can zoom in and pan around until the edge of the image, but no further. Also, if the image is fully zoomed out, you can&#8217;t pan the image. Implementing the pinch-zoom functionality was pretty easy. I found <a href="http://stackoverflow.com/questions/5216658/pinch-zoom-for-custom-view" title="Pinch Zoom on Android">an example on StackOverflow</a>. I then wanted to implement panning (or dragging) as well. However, I wasn&#8217;t able to easily find examples and tutorials for this functionality. I started with <a href="http://www.zdnet.com/blog/burnette/how-to-use-multi-touch-in-android-2-part-5-implementing-the-drag-gesture/1789?tag=content;siu-container" title="Drag">this example</a> that comes from the third edition of the <a href="http://pragprog.com/book/eband3/hello-android" title="Hello, Android!">Hello, Android!</a> book but I didn&#8217;t get too far. So I started playing around a little bit with the events and started writing some code from scratch (using the example from <i>Hello, Android!</i>) so that I could have a better idea of what was happening.</p>
<p>As I mentioned before, getting zoom to work was pretty easy. Implementing panning/dragging was the hard part. The major issues I encountered and subsequently fixed were the following:</p>
<ol>
<li>Panning continues indefinitely in all directions.</li>
<li>When you zoom and then pan, stop, and then start again, the view jerks to a new position instead of panning from the existing position.</li>
<li>Excessive panning towards the left and top can be constrained, but panning towards the right and bottom is not so easily constrained.</li>
</ol>
<p>Once I fixed all the problems, I figured that it would be nice to document it for future reference, and I also think it would be a useful resource for others who have the same problem. Now a little disclaimer before I go any further: I&#8217;m not an Android expert and I&#8217;m really not that great with graphics; I just started it learning to program for Android this semester for one of my Masters electives. So there might be a better way of doing all this, and if there is, please let me know! Also, if you want to skip all the explanations and just see the code, you can <a href = "http://vivin.net/2011/12/04/implementing-pinch-zoom-and-pandrag-in-an-android-view-on-the-canvas/8/">skip to the last page</a>.</p>
<p><span id="more-1806"></span></p>
<p>Let&#8217;s start with the simple stuff first, that is implementing pinch-zoom. To implement pinch-zoom, we make use of the <a href="http://developer.android.com/reference/android/view/ScaleGestureDetector.html" title="ScaleGestureDetector"><span class="code-snippet">ScaleGestureDetector</span></a> class. This class helps you detect the pinch-zoom event. Using it is pretty simple:</p>
<pre class="brush: java">
public class ZoomView extends View {

    private static float MIN_ZOOM = 1f;
    private static float MAX_ZOOM = 5f;

    private float scaleFactor = 1.f;
    private ScaleGestureDetector detector;

    public ZoomView(Context context) {
        super(context);
        detector = new ScaleGestureDetector(getContext(), new ScaleListener());
    }

    @Override
    public boolean onTouchEvent(MotionEvent event) {
        detector.onTouchEvent(event);
        return true;
    }

    @Override
    public void onDraw(Canvas canvas) {
        super.onDraw(canvas);

        canvas.save();
        canvas.scale(scaleFactor, scaleFactor);

        // ...
        // your canvas-drawing code
        // ...

        canvas.restore();
    }

    private class ScaleListener extends ScaleGestureDetector.SimpleOnScaleGestureListener {
        @Override
        public boolean onScale(ScaleGestureDetector detector) {
            scaleFactor *= detector.getScaleFactor();
            scaleFactor = Math.max(MIN_ZOOM, Math.min(scaleFactor, MAX_ZOOM));
            invalidate();
            return true;
        }
    }
}
</pre>
<p>Your view class has four private members: <span class="code-snippet">MIN_ZOOM</span>, <span class="code-snippet">MAX_ZOOM</span>, <span class="code-snippet">detector</span>, and <span class="code-snippet">scaleFactor</span>. The first two are static constants that define the maximum and minimum zoom allowed. The third is of type <span class="code-snippet">ScaleGestureDetector</span> and does all the heavy lifting as far as zooming is concerned. The fourth member holds the scaling factor i.e., a number that represents the amount of &#8220;zoom&#8221;.</p>
<p>Now what does this do?</p>
<p>In the constructor, you initialize the detector. The constructor to <span class="code-snippet">ScaleGestureDetector</span> takes two parameters: the current context, and a listener. Our listener is defined inside the class <span class="code-snippet">ScaleListener</span> which extends the abstract class <span class="code-snippet">ScaleGestureDetector.SimpleOnScaleGestureListener</span>. Inside the <span class="code-snippet">onScale</span> method, we get the current scale factor from the detector. We then check to see if it is greater or smaller than our upper and lower bounds. If so, we make sure that it we limit the value to be between those bounds. We then call <span class="code-snippet">invalidate()</span> which forces the canvas to redraw itself.</p>
<p>The actual scaling happens inside the <span class="code-snippet">onDraw</span> method. There, we save the canvas, set its scaling factor (which is the one we got from the detector), draw anything we need to draw, and then restore the canvas. What happens now is that anything you draw on the canvas is now scaled by the scaling factor. This is what gives you the &#8220;zoom&#8221; effect.</p>
<br /><a href="http://vivin.net/?p=1806#comments" title="Comments on &quot;Implementing pinch-zoom and pan/drag in an Android view on the canvas&quot;"><img src="http://vivin.net/wp-content/plugins/feed-comments-number/image.php?1806" alt="Comments" /></a><img src="http://vivin.net/?ak_action=api_record_view&#38;id=1806&#38;type=feed" alt="" />]]></content:encoded>
			<wfw:commentRss>http://vivin.net/2011/12/04/implementing-pinch-zoom-and-pandrag-in-an-android-view-on-the-canvas/feed/</wfw:commentRss>
		<slash:comments>4</slash:comments>
	
		<media:thumbnail url="http://vivin.net/wp-content/plugins/feed-comments-number/image.php?1806" />
		<media:content url="http://vivin.net/wp-content/plugins/feed-comments-number/image.php?1806" medium="image">
			<media:title type="html">Comments</media:title>
		</media:content>
		<media:content url="http://vivin.net/?ak_action=api_record_view&#38;id=1806&#38;type=feed" medium="image" />
	</item>
		<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>Fixing Maven 3.0.3&#8242;s dependency-resolution performance-regression</title>
		<link>http://vivin.net/2011/07/20/fixing-maven-3-0-3s-dependency-resolution-performance-regression/?utm_source=rss&#038;utm_medium=rss&#038;utm_campaign=rss</link>
		<comments>http://vivin.net/2011/07/20/fixing-maven-3-0-3s-dependency-resolution-performance-regression/#comments</comments>
		<pubDate>Wed, 20 Jul 2011 23:27:07 +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[aether]]></category>
		<category><![CDATA[continuous integration]]></category>
		<category><![CDATA[dependency resolution]]></category>
		<category><![CDATA[java]]></category>
		<category><![CDATA[maven]]></category>
		<category><![CDATA[maven 3]]></category>
		<category><![CDATA[performance regression]]></category>

		<guid isPermaLink="false">http://vivin.net/?p=1757</guid>
		<description><![CDATA[TL; DR; version: Maven 3.0.3 has a performance-regression while resolving dependencies. This is because it uses version 1.11 of aether. The problem has been fixed in version 1.12 of aether, but a version of maven with this library is not available. I built maven from source with the 1.12 version of aether, so use maven-3.0.3-with-aether-1.12.zip [...]]]></description>
			<content:encoded><![CDATA[<p><strong>TL; DR; version:</strong> Maven 3.0.3 has a performance-regression while resolving dependencies. This is because it uses version 1.11 of aether. The problem has been fixed in version 1.12 of aether, but a version of maven with this library is not available. I built maven from source with the 1.12 version of aether, so use <span style="font-family: courier new; font-weight: bold"><a href="http://vivin.net/pub/maven-3.0.3-with-aether-1.12.zip">maven-3.0.3-with-aether-1.12.zip</a></span> if you have the same problem.</p>
<p><strong>The whole story:</strong> At work we use Maven to build our project. Over the last few months, we started noticing a disparity in build times between different developers even though the hardware they were using was similar to each other (Core i7&#8242;s with 6 Gb RAM). Initially we suspected that it might have to do with SSD performance-degradation. Some of us were using SSD&#8217;s that didn&#8217;t support TRIM and others didn&#8217;t have TRIM enabled. I was one of the few with the former problem. I secure-erased my drive but still saw no performance benefits. I even got a new drive and even with that I didn&#8217;t see much of an improvement either. </p>
<p>We finally realized that the build-time disparity was related to the version of maven some developers were using. On maven 3.0b1, build times are much faster compared to 3.0.3. In 3.0.3 there is a performance regression when maven tries to build the dependency graph. For example, using 3.0b1 our project built in 3 minutes and 30 seconds, whereas using 3.0.3, the build times were upwards of 9 minutes. Long build-times take away from the amount of productive coding-time a developer has.</p>
<p>I was determined to find the reason for this performance regression and did some investigation by looking at the source for 3.0b1 and 3.0.3. In 3.0b1, maven uses its own code to resolve dependencies and build the dependency graph, whereas in 3.0.3 it uses the aether library. For more background information on the matter, take a look at <a href="http://maven.40175.n5.nabble.com/Maven-3-builds-take-much-longer-to-run-in-3-0-3-than-in-3-0b1-td4612863.html">this post</a> on the maven developer&#8217;s mailing list and <a href="https://jira.codehaus.org/browse/MNG-5125">this</a> JIRA issue.</p>
<p>Long story short, to get better build times, maven needs to use version 1.12 of aether. I downloaded the maven source and edited the <span style="font-family: courier new; font-weight: bold">pom.xml</span> file to use version 1.12 of aether. I then built maven from source and got a deployable version that uses the newer aether library. When I tested it out, the build times were comparable to 3.0b1.</p>
<p>I initially thought that version 3.0.4 of maven would include version 1.12 of aether. But it turns out that there were licensing changes and so the maven developers are discussing whether to include it. In the meantime, you can use <a href="http://vivin.net/pub/maven-3.0.3-with-aether-1.12.zip">this version</a> of maven that I built from source, which includes version 1.12 of aether. It&#8217;s a zip file and you can install it like you would normally install maven.</p>
<br /><a href="http://vivin.net/?p=1757#comments" title="Comments on &quot;Fixing Maven 3.0.3&#8242;s dependency-resolution performance-regression&quot;"><img src="http://vivin.net/wp-content/plugins/feed-comments-number/image.php?1757" alt="Comments" /></a><img src="http://vivin.net/?ak_action=api_record_view&#38;id=1757&#38;type=feed" alt="" />]]></content:encoded>
			<wfw:commentRss>http://vivin.net/2011/07/20/fixing-maven-3-0-3s-dependency-resolution-performance-regression/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
	
		<media:thumbnail url="http://vivin.net/wp-content/plugins/feed-comments-number/image.php?1757" />
		<media:content url="http://vivin.net/wp-content/plugins/feed-comments-number/image.php?1757" medium="image">
			<media:title type="html">Comments</media:title>
		</media:content>
		<media:content url="http://vivin.net/?ak_action=api_record_view&#38;id=1757&#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>13</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>Bytecode optimization in Java</title>
		<link>http://vivin.net/2011/01/21/bytecode-optimization-in-java/?utm_source=rss&#038;utm_medium=rss&#038;utm_campaign=rss</link>
		<comments>http://vivin.net/2011/01/21/bytecode-optimization-in-java/#comments</comments>
		<pubDate>Fri, 21 Jan 2011 17:54:36 +0000</pubDate>
		<dc:creator>vivin</dc:creator>
				<category><![CDATA[Assembly]]></category>
		<category><![CDATA[Computers]]></category>
		<category><![CDATA[Java]]></category>
		<category><![CDATA[assembly]]></category>
		<category><![CDATA[bytecode]]></category>
		<category><![CDATA[bytecode optimization]]></category>
		<category><![CDATA[getfield]]></category>
		<category><![CDATA[iload]]></category>
		<category><![CDATA[java]]></category>
		<category><![CDATA[optimization]]></category>

		<guid isPermaLink="false">http://vivin.net/?p=1644</guid>
		<description><![CDATA[I learnt something new about bytecode optimization today. In languages like C and C++, if you&#8217;re really concerned about efficiency, you can drop into assembly mode and write specific assembly code instead of relying on the compiler to convert your C/C++ code into assembly (compilers can optimize, but not as well as humans in all [...]]]></description>
			<content:encoded><![CDATA[<p>I learnt something new about bytecode optimization today. In languages like C and C++, if you&#8217;re really concerned about efficiency,  you can drop into assembly mode and write specific assembly code instead of relying on the compiler to convert your C/C++ code into assembly (compilers can optimize, but not as well as humans in all cases).</p>
<p>I saw a <a href="http://stackoverflow.com/questions/4761681/avoiding-getfield-opcode/">question</a> on Stackoverflow today that talked about the <i>getfield</i> opcode in the context of the <i>trim()</i> method in the <i>String</i> class. In the <i>trim()</i> method, you have the following comments:</p>
<pre class="brush: java">
int off = offset;      /* avoid getfield opcode */
char[] val = value;    /* avoid getfield opcode */
</pre>
<p>The author of the question wanted to know what these comments mean. This question seemed pretty interesting to me and so I went and did some research. I found out that <i>getfield</i> is an operation that lets you get access to the member variable/field of a class. This operation is fairly expensive as it involves indexing into the runtime constant pool. Performing this operation a few times does not really incur a performance hit. It is when you perform the operation multiple times, that performance becomes an issue. You can see this from the next few lines of code:</p>
<pre class="brush: java">
while ((st &lt; len) &amp;&amp; (val[off + st] &lt;= &#039; &#039;)) {
    st++;
}
while ((st &lt; len) &amp;&amp; (val[off + len - 1] &lt;= &#039; &#039;)) {
    len--;
}
</pre>
<p>Now if the author of the <i>trim()</i> method hadn&#8217;t assigned <i>offset</i> and <i>value</i> to local variables, a <i>getfield</i> operation would be performed every time the loop-condition is tested. This is obviously inefficient. Therefore, the author assigned the the values of <i>offset</i> and <i>val</i> into the local variables <i>off</i> and <i>val</i>. So now, instead of <i>getfield</i> you have <i>iload</i> (for <i>off</i> anyway), which performs much faster.</p>
<br /><a href="http://vivin.net/?p=1644#comments" title="Comments on &quot;Bytecode optimization in Java&quot;"><img src="http://vivin.net/wp-content/plugins/feed-comments-number/image.php?1644" alt="Comments" /></a><img src="http://vivin.net/?ak_action=api_record_view&#38;id=1644&#38;type=feed" alt="" />]]></content:encoded>
			<wfw:commentRss>http://vivin.net/2011/01/21/bytecode-optimization-in-java/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
	
		<media:thumbnail url="http://vivin.net/wp-content/plugins/feed-comments-number/image.php?1644" />
		<media:content url="http://vivin.net/wp-content/plugins/feed-comments-number/image.php?1644" medium="image">
			<media:title type="html">Comments</media:title>
		</media:content>
		<media:content url="http://vivin.net/?ak_action=api_record_view&#38;id=1644&#38;type=feed" medium="image" />
	</item>
		<item>
		<title>CherryBlossom</title>
		<link>http://vivin.net/2010/03/04/cherryblossom/?utm_source=rss&#038;utm_medium=rss&#038;utm_campaign=rss</link>
		<comments>http://vivin.net/2010/03/04/cherryblossom/#comments</comments>
		<pubDate>Fri, 05 Mar 2010 02:58:26 +0000</pubDate>
		<dc:creator>vivin</dc:creator>
				<category><![CDATA[Arts]]></category>
		<category><![CDATA[Haiku]]></category>
		<category><![CDATA[Perl]]></category>
		<category><![CDATA[Poetry]]></category>
		<category><![CDATA[Programming and Development]]></category>
		<category><![CDATA[brainf*ck]]></category>
		<category><![CDATA[brainfuck]]></category>
		<category><![CDATA[cherryblossom]]></category>
		<category><![CDATA[code]]></category>
		<category><![CDATA[development]]></category>
		<category><![CDATA[esoteric languages]]></category>
		<category><![CDATA[haiku]]></category>
		<category><![CDATA[interpreters]]></category>
		<category><![CDATA[java]]></category>
		<category><![CDATA[parsers]]></category>
		<category><![CDATA[perl]]></category>
		<category><![CDATA[poems]]></category>
		<category><![CDATA[poetry]]></category>
		<category><![CDATA[programming]]></category>
		<category><![CDATA[programming languages]]></category>
		<category><![CDATA[project]]></category>

		<guid isPermaLink="false">http://vivin.net/?p=1451</guid>
		<description><![CDATA[I&#8217;ve created a project page for the CherryBlossom programming language. You can check it out here. The interpreter is written in perl.]]></description>
			<content:encoded><![CDATA[<p>I&#8217;ve created a project page for the <em><strong>CherryBlossom</strong></em> programming language. You can check it out <a title = "CherryBlossom" href = "http://vivin.net/projects/cherryblossom" target="_self">here</a>. The interpreter is written in perl.</p>
<br /><a href="http://vivin.net/?p=1451#comments" title="Comments on &quot;CherryBlossom&quot;"><img src="http://vivin.net/wp-content/plugins/feed-comments-number/image.php?1451" alt="Comments" /></a><img src="http://vivin.net/?ak_action=api_record_view&#38;id=1451&#38;type=feed" alt="" />]]></content:encoded>
			<wfw:commentRss>http://vivin.net/2010/03/04/cherryblossom/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
	
		<media:thumbnail url="http://vivin.net/wp-content/plugins/feed-comments-number/image.php?1451" />
		<media:content url="http://vivin.net/wp-content/plugins/feed-comments-number/image.php?1451" medium="image">
			<media:title type="html">Comments</media:title>
		</media:content>
		<media:content url="http://vivin.net/?ak_action=api_record_view&#38;id=1451&#38;type=feed" medium="image" />
	</item>
		<item>
		<title>Introducing CherryBlossom</title>
		<link>http://vivin.net/2010/03/02/introducing-cherryblossom/?utm_source=rss&#038;utm_medium=rss&#038;utm_campaign=rss</link>
		<comments>http://vivin.net/2010/03/02/introducing-cherryblossom/#comments</comments>
		<pubDate>Wed, 03 Mar 2010 06:06:49 +0000</pubDate>
		<dc:creator>vivin</dc:creator>
				<category><![CDATA[Arts]]></category>
		<category><![CDATA[Haiku]]></category>
		<category><![CDATA[Perl]]></category>
		<category><![CDATA[Poetry]]></category>
		<category><![CDATA[Programming and Development]]></category>
		<category><![CDATA[brainf*ck]]></category>
		<category><![CDATA[brainfuck]]></category>
		<category><![CDATA[cherryblossom]]></category>
		<category><![CDATA[code]]></category>
		<category><![CDATA[development]]></category>
		<category><![CDATA[esoteric languages]]></category>
		<category><![CDATA[haiku]]></category>
		<category><![CDATA[interpreters]]></category>
		<category><![CDATA[java]]></category>
		<category><![CDATA[parsers]]></category>
		<category><![CDATA[perl]]></category>
		<category><![CDATA[poems]]></category>
		<category><![CDATA[poetry]]></category>
		<category><![CDATA[programming]]></category>
		<category><![CDATA[programming languages]]></category>
		<category><![CDATA[project]]></category>

		<guid isPermaLink="false">http://vivin.net/?p=1407</guid>
		<description><![CDATA[Over the past month, I&#8217;ve been working on a new project. It&#8217;s called CherryBlossom, and it&#8217;s a way to write programs using haikus. Strictly speaking, CherryBlossom is a brainfuck analog. I actually spent more time writing the obligatory &#8220;Hello World&#8221; program in CherryBlossom than I did writing the interpreter for the language. The idea behind [...]]]></description>
			<content:encoded><![CDATA[<p>Over the past month, I&#8217;ve been working on a new project. It&#8217;s called <strong><em><a href="http://vivin.net/projects/cherryblossom">CherryBlossom</a></em></strong>, and it&#8217;s a way to write programs using <a href="http://en.wikipedia.org/wiki/Haiku">haikus</a>. Strictly speaking, <strong><em>CherryBlossom</em></strong> is a brainfuck analog. I actually spent more time writing the obligatory &#8220;Hello World&#8221; program in CherryBlossom than I did writing the interpreter for the language. The idea behind <strong><em>CherryBlossom</em></strong> is simple. Brainfuck instructions are mapped to words that convey the essence of the Brainfuck instruction. Of course, this is a little subjective and also a little abstract. </p>
<p>Ultimately, it serves as a way to make program code not just functional, but beautiful and artistic. Thus, we introduce a new criteria to programming. Your code must not only be elegant algorithmically, but must also be poetic and artistic (also, since program code consists of haikus, you need to represent your code in sets of 3 lines with the first and last lines having 5 syllables, and the second line 7. That is, conforming to haiku rules). <strong><em>CherryBlossom</em></strong> serves to blend the programmer and the poet into one entity (hopefully with amazing results).</p>
<p>Here is an example of &#8220;Hello World!&#8221; in<strong> <em>CherryBlossom</em></strong>. I have opted to use a spruced up div tag instead of enclosing my beautiful poem in soulless <em>sourcecode</em> tags.<br />
<span id="more-1407"></span></p>
<div style = "margin-left:auto; margin-right:auto; text-align:center; background-image:url('/wordpress/wp-content/uploads/2010/03/cherryblossom25t.png'); background-repeat:no-repeat; width:350px; font-weight:bold; font-style:italic; font-size:12pt; font-family:times new roman;">
beautiful jasmine<br />
your lovely fragrance heals me<br />
every morning</p>
<p>remembering you,<br />
dreaming of your lovely smile,<br />
when will you come here?</p>
<p>floating butterflies<br />
sunshine and summer flowers<br />
a lovely morning</p>
<p>blossoming hillside<br />
on a fragrant summer day<br />
blooming, flowering.</p>
<p>I can remember<br />
my happy dreams of summer<br />
it was beautiful</p>
<p>flying doves, sunrays<br />
beauty flying in sunshine<br />
rain in the valley.</p>
<p>snow falls in moonlight,<br />
returns to the mountainside.<br />
lovely, beautiful.</p>
<p>view from mountaintop<br />
is a beautiful painting,<br />
in summer sunshine.</p>
<p>the fragrant flowers<br />
and the pretty butterflies<br />
spring by singing creek.</p>
<p>beautiful morning<br />
butterflies by riverside<br />
floating in sunshine.</p>
<p>such a lovely sight,<br />
the valley waterfall is<br />
in the spring sunshine.</p>
<p>sunrays and sunshine,<br />
the butterflies and flowers<br />
loving the new spring.</p>
<p>the pretty flowers<br />
are dreaming of a summer<br />
with the smiling sun.</p>
<p>music from heaven,<br />
is melodious and sweet,<br />
dreamy and happy.</p>
<p>the river is cold<br />
and misty in the moonlight,<br />
in the autumn chill.</p>
<p>winter riverside,<br />
lonely, icy, and chilly<br />
darkening evening</p>
<p>the lonely winter,<br />
barren riverside ahead<br />
a dreaming poet
</p></div>
<p>Trust me, this does print out &#8220;Hello World!&#8221;! You might think I&#8217;m crazy, but I&#8217;m not! Either tomorrow or day after, I&#8217;ll add a new page to the Projects menu and you&#8217;ll see how CherryBlossom works and you will also have access to the interpreter!</p>
<br /><a href="http://vivin.net/?p=1407#comments" title="Comments on &quot;Introducing CherryBlossom&quot;"><img src="http://vivin.net/wp-content/plugins/feed-comments-number/image.php?1407" alt="Comments" /></a><img src="http://vivin.net/?ak_action=api_record_view&#38;id=1407&#38;type=feed" alt="" />]]></content:encoded>
			<wfw:commentRss>http://vivin.net/2010/03/02/introducing-cherryblossom/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
	
		<media:thumbnail url="http://vivin.net/wp-content/plugins/feed-comments-number/image.php?1407" />
		<media:content url="http://vivin.net/wp-content/plugins/feed-comments-number/image.php?1407" medium="image">
			<media:title type="html">Comments</media:title>
		</media:content>
		<media:content url="http://vivin.net/?ak_action=api_record_view&#38;id=1407&#38;type=feed" medium="image" />
	</item>
		<item>
		<title>Maven project for Generic (n-ary) Tree in Java</title>
		<link>http://vivin.net/2010/03/02/maven-project-for-generic-n-ary-tree-in-java/?utm_source=rss&#038;utm_medium=rss&#038;utm_campaign=rss</link>
		<comments>http://vivin.net/2010/03/02/maven-project-for-generic-n-ary-tree-in-java/#comments</comments>
		<pubDate>Wed, 03 Mar 2010 04:49:48 +0000</pubDate>
		<dc:creator>vivin</dc:creator>
				<category><![CDATA[Java]]></category>
		<category><![CDATA[Programming and Development]]></category>
		<category><![CDATA[data structures]]></category>
		<category><![CDATA[generic trees]]></category>
		<category><![CDATA[java]]></category>
		<category><![CDATA[k-ary trees]]></category>
		<category><![CDATA[n-ary trees]]></category>
		<category><![CDATA[programming]]></category>
		<category><![CDATA[software engineering]]></category>
		<category><![CDATA[trees (data structure)]]></category>

		<guid isPermaLink="false">http://vivin.net/?p=1405</guid>
		<description><![CDATA[Guus was kind enough to make a maven project for the Generic Tree. He also fixed an error in my equals method for the GenericTreeNode (I intended to do Object.equals(Object obj) but was doing GenericTreeNode.equals(GenericTreeNode obj). Since it&#8217;s a maven project, you can easily create a jar out of it and add it as a [...]]]></description>
			<content:encoded><![CDATA[<p><a href="http://vivin.net/2010/01/30/generic-n-ary-tree-in-java/#comment-1461">Guus</a> was kind enough to make a maven project for the Generic Tree. He also fixed an error in my <em>equals</em> method for the GenericTreeNode (I intended to do <em>Object.equals(Object obj)</em> but was doing <em>GenericTreeNode.equals(GenericTreeNode obj)</em>. Since it&#8217;s a maven project, you can easily create a <em>jar</em> out of it and add it as a dependency to your project. You can download the project <a href="https://github.com/vivin/GenericTree">here</a>. Thanks Guus!</p>
<br /><a href="http://vivin.net/?p=1405#comments" title="Comments on &quot;Maven project for Generic (n-ary) Tree in Java&quot;"><img src="http://vivin.net/wp-content/plugins/feed-comments-number/image.php?1405" alt="Comments" /></a><img src="http://vivin.net/?ak_action=api_record_view&#38;id=1405&#38;type=feed" alt="" />]]></content:encoded>
			<wfw:commentRss>http://vivin.net/2010/03/02/maven-project-for-generic-n-ary-tree-in-java/feed/</wfw:commentRss>
		<slash:comments>3</slash:comments>
	
		<media:thumbnail url="http://vivin.net/wp-content/plugins/feed-comments-number/image.php?1405" />
		<media:content url="http://vivin.net/wp-content/plugins/feed-comments-number/image.php?1405" medium="image">
			<media:title type="html">Comments</media:title>
		</media:content>
		<media:content url="http://vivin.net/?ak_action=api_record_view&#38;id=1405&#38;type=feed" medium="image" />
	</item>
		<item>
		<title>Generic (n-ary) Tree in Java</title>
		<link>http://vivin.net/2010/01/30/generic-n-ary-tree-in-java/?utm_source=rss&#038;utm_medium=rss&#038;utm_campaign=rss</link>
		<comments>http://vivin.net/2010/01/30/generic-n-ary-tree-in-java/#comments</comments>
		<pubDate>Sat, 30 Jan 2010 22:05:13 +0000</pubDate>
		<dc:creator>vivin</dc:creator>
				<category><![CDATA[Java]]></category>
		<category><![CDATA[Programming and Development]]></category>
		<category><![CDATA[data structures]]></category>
		<category><![CDATA[generic trees]]></category>
		<category><![CDATA[java]]></category>
		<category><![CDATA[k-ary trees]]></category>
		<category><![CDATA[n-ary trees]]></category>
		<category><![CDATA[programming]]></category>
		<category><![CDATA[software engineering]]></category>
		<category><![CDATA[trees (data structure)]]></category>

		<guid isPermaLink="false">http://vivin.net/?p=1395</guid>
		<description><![CDATA[This project is available on github. Please download from there to make sure you have the latest version. Last week I was solving a problem at work that required the use of a Generic (n-ary) Tree. An n-ary tree is a tree where node can have between 0 and n children. There is a special [...]]]></description>
			<content:encoded><![CDATA[<p><strong>This project is available on <a href="https://github.com/vivin/GenericTree">github</a>. Please download from there to make sure you have the latest version.</strong></p>
<p>Last week I was solving a problem at work that required the use of a Generic (<em>n</em>-ary) Tree. An <em>n</em>-ary tree is a tree where node can have between 0 and <em>n</em> children. There is a special case of <em>n</em>-ary trees where each node can have <em>at most</em> <em>n</em> nodes (<em>k</em>-ary tree). This implementation focuses on the most general case, where any node can have between 0 and <em>n</em> children. Java doesn&#8217;t have a Tree or Tree Node data structure. I couldn&#8217;t find any third-party implementations either (like in commons-lang). So I decided to write my own.<br />
<span id="more-1395"></span><br />
First, we need to define the node of our tree. Our node has two attributes. One is the data, and another is a List which can contain references to the children of that node:</p>
<div id="attachment_1397" class="wp-caption aligncenter" style="width: 310px;  border: 1px solid #dddddd; background-color: #f3f3f3; padding-top: 4px; margin: 10px; text-align:center; display: block; margin-right: auto; margin-left: auto;"><a href="http://vivin.net/wp-content/uploads/2010/01/generictreestructure.png"><img class="size-medium wp-image-1397" title="Generic Tree Node Structure" src="http://vivin.net/wp-content/uploads/2010/01/generictreestructure-300x167.png" alt="Structure of a Generic Tree Node" width="300" height="167" /></a><p style=' padding: 0 4px 5px; margin: 0;'  class="wp-caption-text">Structure of a Generic Tree Node</p></div>
<p>The code for a Generic Tree Node looks like this:</p>
<p><strong>GenericTreeNode.java</strong></p>
<pre class="brush: java">
import java.util.ArrayList;
import java.util.List;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

public class GenericTreeNode&lt;T&gt; {

    public T data;
    public List&lt;GenericTreeNode&lt;T&gt;&gt; children;

    public GenericTreeNode() {
        super();
        children = new ArrayList&lt;GenericTreeNode&lt;T&gt;&gt;();
    }

    public GenericTreeNode(T data) {
        this();
        setData(data);
    }

    public List&lt;GenericTreeNode&lt;T&gt;&gt; getChildren() {
        return this.children;
    }

    public int getNumberOfChildren() {
        return getChildren().size();
    }

    public boolean hasChildren() {
        return (getNumberOfChildren() &gt; 0);
    }

    public void setChildren(List&lt;GenericTreeNode&lt;T&gt;&gt; children) {
        this.children = children;
    }

    public void addChild(GenericTreeNode&lt;T&gt; child) {
        children.add(child);
    }

    public void addChildAt(int index, GenericTreeNode&lt;T&gt; child) throws IndexOutOfBoundsException {
        children.add(index, child);
    }

    public void removeChildren() {
        this.children = new ArrayList&lt;GenericTreeNode&lt;T&gt;&gt;();
    }

    public void removeChildAt(int index) throws IndexOutOfBoundsException {
        children.remove(index);
    }

    public GenericTreeNode&lt;T&gt; getChildAt(int index) throws IndexOutOfBoundsException {
        return children.get(index);
    }

    public T getData() {
        return this.data;
    }

    public void setData(T data) {
        this.data = data;
    }

    public String toString() {
        return getData().toString();
    }

    public boolean equals(GenericTreeNode&lt;T&gt; node) {
        return node.getData().equals(getData());
    }

    public int hashCode() {
        return getData().hashCode();
    }

    public String toStringVerbose() {
        String stringRepresentation = getData().toString() + &quot;:[&quot;;

        for (GenericTreeNode&lt;T&gt; node : getChildren()) {
            stringRepresentation += node.getData().toString() + &quot;, &quot;;
        }

        //Pattern.DOTALL causes ^ and $ to match. Otherwise it won&#039;t. It&#039;s retarded.
        Pattern pattern = Pattern.compile(&quot;, $&quot;, Pattern.DOTALL);
        Matcher matcher = pattern.matcher(stringRepresentation);

        stringRepresentation = matcher.replaceFirst(&quot;&quot;);
        stringRepresentation += &quot;]&quot;;

        return stringRepresentation;
    }
}
</pre>
<br /><a href="http://vivin.net/?p=1395#comments" title="Comments on &quot;Generic (n-ary) Tree in Java&quot;"><img src="http://vivin.net/wp-content/plugins/feed-comments-number/image.php?1395" alt="Comments" /></a><img src="http://vivin.net/?ak_action=api_record_view&#38;id=1395&#38;type=feed" alt="" />]]></content:encoded>
			<wfw:commentRss>http://vivin.net/2010/01/30/generic-n-ary-tree-in-java/feed/</wfw:commentRss>
		<slash:comments>34</slash:comments>
	
		<media:thumbnail url="http://vivin.net/wp-content/uploads/2010/01/generictreestructure-150x150.png" />
		<media:content url="http://vivin.net/wp-content/uploads/2010/01/generictreestructure.png" medium="image">
			<media:title type="html">Generic Tree Node Structure</media:title>
			<media:description type="html">Structure of a Generic Tree Node</media:description>
			<media:thumbnail url="http://vivin.net/wp-content/uploads/2010/01/generictreestructure-150x150.png" />
		</media:content>
		<media:content url="http://vivin.net/wp-content/plugins/feed-comments-number/image.php?1395" medium="image">
			<media:title type="html">Comments</media:title>
		</media:content>
		<media:content url="http://vivin.net/?ak_action=api_record_view&#38;id=1395&#38;type=feed" medium="image" />
	</item>
	</channel>
</rss>

