<?xml version="1.0" encoding="utf-8"?>
<feed xmlns="http://www.w3.org/2005/Atom" xmlns:creativeCommons="http://backend.userland.com/creativeCommonsRssModule" xmlns:thr="http://purl.org/syndication/thread/1.0">

<title type="html">codegremlins.com</title>
<link rel="self" href="http://codegremlins.com/feed.xml" type="application/atom+xml" />
<link rel="alternate" href="http://codegremlins.com/" type="text/html" />
<subtitle></subtitle>
<updated></updated>
<id>http://codegremlins.com/feed.xml</id>


	<entry>
		<title>Graceful restart without downtime with node.js</title>
		<link href="http://codegremlins.com/28/Graceful-restart-without-downtime-with-node-js"/>
		<id>http://codegremlins.com/28/Graceful-restart-without-downtime-with-node-js</id>

		<updated>2011-06-05T00:00:00Z</updated>
		<published>2011-06-05T00:00:00Z</published>



		<content type="html"><![CDATA[
<p>I recently started playing with node.js and one thing I like is that it enables (or at least makes easier) many interesting possibilities with regard to deployment and update methods (for example compared to Java/Jetty which I mostly use now).</p>

<p>One scenario I am interested in is restarting a node app without the users noticing any down time. Of course there is lots of information online about doing this by load balancing between several node processes.</p>

<p>But for our own reasons lets say we want to do this without load balancing. Assuming any session data is stored out of process (perhaps in Redis), the idea is to structure our node.js application like this:</p>

<ul>
<li>Perform any slow initialization (perhaps loading and compiling templates)</li>
<li>Send TERM signal to old node process</li>
<li>Start http server</li>
<li>listen for TERM signal and stop server from accepting further connections.</li>
</ul>

<p>This is so that while we are initializing, the original node process is still running and serving requests. On receiving SIGTERM the old process stops accepting new connections, but still completes serving any current requests before quiting. In the mean time the new node process is up and handling any new requests.</p>

<p>This is straightforward except perhaps step two. How do we know which process to send TERM signal to?
We could save the PID in a file and read if from there but it turns out there is a more fun way.</p>

<p>By using the <code>fuser</code> linux utility we can find out which process is listening on a specific port and send it a signal as well.
For example:</p>

<pre><code>fuser -n tcp 8000 -k -TERM
</code></pre>

<p>will find the process listening on port 8000 and send it the TERM signal. So using this, each time we start our node app we can send a TERM signal to the old version of the app which is listening for http connections and ask it to retire.</p>

<p>Here is some code:</p>

<pre><code>var exec = require('child_process').exec;

var server = null;
var signalReceived = false;

process.on('SIGTERM', function () {
  if (server != null) {
    server.close();
  }
  signalReceived = true;
});

exports.listen = function(_server, port, timeout) {
  port    = port || 8080;
  timeout = timeout || 5;
  server  = _server;

  exec('fuser -n tcp ' + port + ' -k -TERM', 
    function (error) {
      function attemptSocket(noretry) {
        if (signalReceived) {
          return;
        }

        try {
          server.listen(port);
        } catch (e) {
          console.log(e);
          if (e.code == 'EADDRINUSE' &amp;&amp; !noretry) {
            setTimeout(attemptSocket, timeout);
          }
        }
      }

      attemptSocket(error !== null);
    });
}
</code></pre>

<p>And here is how we would use it:</p>

<pre><code>var http = require("http");
var graceful = require('./graceful');

function onRequest(request, response) {
  console.log("Request received: " + request.path);
  response.writeHead(200, {"Content-Type": "text/html"});
  response.write("Hello World");
  response.end();
}


var server = http.createServer(onRequest);
graceful.listen(server, 8000);
</code></pre>

<p>One small problem with the above is with keep-alive connections. When a browser has a keep-alive connection open this will keep the old node process running (and possibly serving new requests from that connection) until the keep alive connection times out after a couple of minutes of inactivity.</p>		
	]]></content>
				
	</entry>

	<entry>
		<title>Going to town with annotations</title>
		<link href="http://codegremlins.com/22/Going-to-town-with-annotations"/>
		<id>http://codegremlins.com/22/Going-to-town-with-annotations</id>

		<updated>2010-07-17T00:00:00Z</updated>
		<published>2010-07-17T00:00:00Z</published>



		<content type="html"><![CDATA[
<p>Annotations are a very useful feature of the Java language but sometimes an overdose of a good thing can be bad for you. Let me explain:</p>

<p>In our first example from Spring MVC we are using an annotation to map a method to a url. Without annotations this mapping information would likely have to go into an external file, perhaps an xml file, so annotations are very helpful in this case, because the code is much more straightforward when we have the two together. This is a good use of annotations:</p>

<pre><code>@RequestMapping("/hello/kitty")
public String somePage(....) {
}
</code></pre>

<p>Going further and after a little googling I found <a href="http://wheelersoftware.com/articles/spring-bean-validation-framework.html">this example</a> of using annotations for validation, again in Spring:</p>

<pre><code>@NotBlank  
@Length(max = 80)  
private String name;  

@NotBlank  
@Email  
@Length(max = 80)  
private String email;  

@NotBlank  
@Length(max = 4000)  
private String text;  
</code></pre>

<p>Of course this can be a good thing, for example maybe you have a framework that uses the annotations to generate client-side Javascript validation code in addition to validating on the server side. But if that is not the case then we are starting to cross a line here, the line of using annotations to code things that could have been done perfectly well in plain Java code, and yet we are using annotations just because we can.</p>

<p>For comparison here is an imaginary piece of code of how this could look like in a universe where we are coding with pure servlets and without frameworks:</p>

<pre><code>Validator v = new Validator(httpRequest);
v.item("name").notBlank().maxLength(80);
v.item("email").notBlank().maxLength(80).email();
v.item("text").notBlank().maxLength(4000);

if (v.error()) {
    // failure
} else {
    // success
}
</code></pre>

<p>This looks like about the same amount of code. So purely in terms of writing more high level code we haven't gained anything by using annotations in this case.</p>

<p>Googling some more I found this example:</p>

<pre><code>public MovieRecommender(CustomerPreferenceDao customerPreferenceDao,
                        @Value("#{systemProperties['user.country']}"} String defaultLocale) {
    this.customerPreferenceDao = customerPreferenceDao;
    this.defaultLocale = defaultLocale;
}
</code></pre>

<p>Now we are passing actual code snippets as annotations. Perhaps there are legitimate uses of this but are we going a little overboard here? I mean what are we gaining for doing this instead of plainly writing:</p>

<pre><code>this.defaultLocale = System.getProperty("user.country")
</code></pre>

<p>So what is the moral of this story? People get excited about new language features and try to do imaginative things with them. But when designing a library/api/framework it is a good idea to ask yourself first: "Could this be easily done in plain Java code?" before designing a complex meta-programing system to do the same thing with annotations. </p>

<p>What are we losing when we are using annotations instead of plain Java code? Besides making our program dependent on more complicated frameworks, annotations (being metadata and not code) are less powerful than actual code when used for programming scenarios. So to compensate, frameworks must define more annotations in order to cover all combinations and different use cases but also sometimes you are stuck when you need to do something the framework designer has not predicted. </p>		
	]]></content>
				
	</entry>

	<entry>
		<title>My first netbook: Samsung N315</title>
		<link href="http://codegremlins.com/19/My-first-netbook-Samsung-N315"/>
		<id>http://codegremlins.com/19/My-first-netbook-Samsung-N315</id>

		<updated>2010-07-04T00:00:00Z</updated>
		<published>2010-07-04T00:00:00Z</published>



		<content type="html"><![CDATA[
<p>I recently bought my first netbook a Samsung N315, mainly so that I can have a computer with me when I am on holidays for web browsing, staying in touch with my projects and maybe doing some coding when I am feeling bored in the evenings.</p>

<p>The Samsung N315 has a nice look with rounded edges and a rubberized exterior. Specs are standard for current 10.1" netbooks:
1Gb ram, 1.66GHz n450 Atom cpu, 250Gb disk, wifi, bluetooth, 1024x600 display resolution, 3 USB ports, VGA out port, card reader, ethernet port and 1.3Mp webcam. It has a 'pebble' style keyboard which is comfortable enough to type on.</p>

<p><img src="http://img811.imageshack.us/img811/5042/n3152.jpg" alt="Sasmsung N315 Netbook"/></p>

<p>The machine came with Windows 7 Starter preinstalled, but this deficiency was easily remedied with the help of an Ubuntu 10.04 USB Startup Disk (actually more stick than "disk"). Installation was quick and without problems. Booting into Ubuntu takes roughly 25 seconds. I installed the <strong><a href="http://www.ubuntu.com/netbook">Ubuntu Netbook Edition</a></strong> but after trying the interface out I decided I prefer the normal Gnome interface (configurable via <code>System-&gt;Administration-&gt;Login Screen</code>). To save some vertical space the Gnome panels can be set to auto-hide.</p>

<p>All the hardware seems to be working great under Ubuntu as far as I can tell. I had some slight concerns before, having read that certain previous models had some problems with wireless under Ubuntu (requiring the windows driver with <code>ndiswrapper</code> to work), but everything worked out of the box for me, probably thanks to better support for netbook hardware in more recent kernels. The battery seems to last around 3 hours with moderate use (browsing the web, installing some programs, occasionally compiling something).</p>

<p>I only had two slight problems, one is that the special function keys are not working and the other is that I can't control the brightness of the display (not just with the function keys, but the gnome brightness applet does not seem to be working either). The display setting was too bright for my liking but although I haven't got the function keys working under Ubuntu yet, they do work before I boot into the OS (when I am in the BIOS settings for example). So I set the brightness to a level I find comfortable before I booted into Ubuntu. In order for the computer to preserve this setting between reboots, you must change <code>'Brightness Mode Control'</code> from <code>'Auto'</code> to <code>'User Control'</code> in the BIOS settings, otherwise the brightness level will be reset automatically on each reboot. But now that I lowered the brightness I had another problem, namely that the colors looked somewhat washed out. Usually on my desktop I would set a higher contrast level to compensate but I can't seem to find any way to control the contrast for the netbook display. Fortunately there is a utility called <code>xgamma</code> which does exactly what I need (gamma and contrast are not exactly the same thing, but it does what I needed), and by setting something like <code>xgamma -gamma 0.6</code> I got enough contrast and the colors now look crisp. To keep this setting between reboots you need to call xgamma each time you start X, one easy way to do this for people who don't want to tweak around too much is to simply add it to <code>Startup Applications</code>. </p>

<p>After some more googling I came across these scripts for fixing the above mentioned key and brightness problems, although by this time I got lazy so I haven't tried them out yet:</p>

<ul>
<li><a href="http://www.voria.org/forum/viewtopic.php?f=3&amp;t=296">http://www.voria.org/forum/viewtopic.php?f=3&amp;t=296</a></li>
<li><a href="https://launchpad.net/~voria/+archive/ppa?field.series_filter=lucid">https://launchpad.net/~voria/+archive/ppa?field.series_filter=lucid</a></li>
</ul>

<p>A lot has been said and written about the poor performance of netbooks, but I find that this netbook's performance is not bad for what I need it to do, and in any case it is not much worse than my 4 year old desktop (1Gb ram, Pentium D cpu), not to mention that it is much quieter (in fact it is completely silent, whereas my desktop on occasion sounds like something between a vacuum cleaner and a jetliner on takeoff). </p>

<p>For comparison GIMP starts in 6 seconds compared to 3 seconds on my desktop, but youtube videos seem smoother on the Samsung N315 than on my desktop. Also as a test I compiled one application I am currently working on: The application consists of 143 Java files and on my desktop the average build time is 5 seconds while on the netbook the average build time is 8 seconds (times are calculated loosely and unscientifically, basically I ran ant several times and after some initial fluctuation build times settled on the values given above). This may not be stellar performance, especially compared to the latest high end machines, but for me it is perfectly adequate and I find that netbooks have plenty of power for programming.</p>		
	]]></content>
				
	</entry>

	<entry>
		<title>wmd-editor: How to retrieve both markdown and html</title>
		<link href="http://codegremlins.com/11/wmd-editor-How-to-retrieve-both-markdown-and"/>
		<id>http://codegremlins.com/11/wmd-editor-How-to-retrieve-both-markdown-and</id>

		<updated>2010-06-16T00:00:00Z</updated>
		<published>2010-06-16T00:00:00Z</published>



		<content type="html"><![CDATA[
<p>You are using markdown with the wmd-editor in your application, perhaps after having discovered it thanks to <a href="http://stackoverflow.com">stackoverflow.com</a>. What do you post to the server, the markdown "source" or the rendered html? </p>

<p>You could post the html which saves you the trouble of generating the html again on the server side. But if you want to allow your users to edit the text in the future now you don't have the markdown source anymore. So then maybe it is better to post the markdown, which means you have to render it to html on your server using another server-side markdown library. However it can be that the markdown implementation for your language is not bug-free enough, or maybe just not 100% consistent with the official implementation. Or maybe you just feel that this step is redundant since you already have the html sitting ready and packed on the browser side.</p>

<p>So it looks that the better and simpler solution would be to post both markdown and html, but it seems wmd-editor only allows us to pick one, we can set either <code>output:"Markdown"</code> or <code>output:"HTML"</code>.</p>

<p>However if you don't mind using javascript (and since you are using wmd-editor the answer is that you don't mind), with the help of a little jquery we can easily send both, by simply using the markdown source from the editor textarea and the html from the <code>wmd-preview</code> area.</p>

<pre><code>var source = encodeURIComponent($('#wmd-input').attr('value'));    
var html   = encodeURIComponent($('#wmd-preview').html());    
var data   = 'Source=' + source + '&amp;Html=' + html;

$.post('/postArticle', data, function(result) {
    // Do things based on success or failure
});
</code></pre>

<p>For the above to work make sure the wmd-editor is set to <code>output:"Markdown"</code>. Also don't forget to sanitize the html on the server side.</p>		
	]]></content>
				
	</entry>

	<entry>
		<title>Faster development with eclipse and embedded jetty</title>
		<link href="http://codegremlins.com/10/Faster-development-with-eclipse-and-embedded"/>
		<id>http://codegremlins.com/10/Faster-development-with-eclipse-and-embedded</id>

		<updated>2009-08-11T00:00:00Z</updated>
		<published>2009-08-11T00:00:00Z</published>



		<content type="html"><![CDATA[
<p>These days I am working on some web applications, which I build with good old <strong>ant</strong>. Build time is less that 10 seconds which is pretty good. Yet even this is too slow when developing, if I had to wait 10 seconds (or 5 minutes if I were using <strong>maven</strong>) every time I made a change before I could test it, I would go nuts. </p>

<p>Instead I would like to make changes in eclipse and be able to instantly test the results in my browser, before my mind wanders off and I start playing tetris or barrage.  To achieve this I am using an embedded jetty server.</p>

<pre><code>public class EclipseMain {
    public static void main(String[] args) throws Exception {
        Server server = new Server();

        Context context = new Context(server, "/", Context.SESSIONS);

        // This allows me to have cookies that work over subdomains
        HashMap map = new HashMap();
        map.put("org.mortbay.jetty.servlet.SessionDomain", ".localhost.localhost");
        context.setInitParams(map);

        // I am using both http and https in my app and want to test both
        Connector connector = new SelectChannelConnector();
        connector.setPort(8080);

        SslSocketConnector sslConnector = new SslSocketConnector();
        sslConnector.setPort(8443);
        sslConnector.setKeystore("/path/to/my/keystore");
        sslConnector.setPassword("wouldntyouliketoknow");
        sslConnector.setKeyPassword("wouldntyouliketoknow");
        sslConnector.setTruststore("/path/to/my/keystore");
        sslConnector.setTrustPassword("wouldntyouliketoknow");  
        server.setConnectors(new Connector[] {connector, sslConnector});

        // enable persistent sessions, so we don't need to relogin after restart
        enablePersistentSessions(context, "/home/manuel/.jetty_test");

        // Using my own jurlmap library here
        context.addFilter(new FilterHolder(new GoblinDispatchFilter()), "/*", 
                          org.mortbay.jetty.Handler.REQUEST 
                          | org.mortbay.jetty.Handler.FORWARD);

        // Static files such as images, css
        context.setResourceBase("web"); 
        // Serve static files
        context.addServlet(DefaultServlet.class, "/"); 

        // Server is ready to start
        server.start();
    }

    public static void enablePersistentSessions(Context context, String folder) {
        File file = new File(folder);

        if (!file.exists()) {
            file.mkdirs();
        } else if (file.isFile()) {
            throw new RuntimeException("Session location not a folder: " + folder);
        }

        final HashSessionManager manager = new HashSessionManager();
        manager.setStoreDirectory(file);
        context.getSessionHandler().setSessionManager(manager);

        Runtime.getRuntime().addShutdownHook(new Thread() {
            public void run() {
                try {
                    manager.saveSessions();
                } catch (Exception ex) {
                    ex.printStackTrace();
                }
            }
        });
    }
}
</code></pre>

<p>If you are not using JSP then you just need to add these three libraries from the jetty distribution to your project classpath:</p>

<p><code>jetty-6.1.14.jar</code> <br />
<code>jetty-util-6.1.14.jar</code> <br />
<code>servlet-api-2.5-6.1.14.jar</code>  </p>

<p>With this setup it takes about two seconds between making changes and being able to test the results. Just edit your code and run <code>EclipseMain</code> as a normal application (in eclipse <code>Run As Java Application</code>). I have configured persistent sessions which means I don't even have to log back in to my app after every server restart, I just hit refresh and I am right back where I left. </p>		
	]]></content>
				
	</entry>

	<entry>
		<title>jurlmap - RESTful URLs for your Java app</title>
		<link href="http://codegremlins.com/9/jurlmap-RESTful-URLs-for-your-Java-app"/>
		<id>http://codegremlins.com/9/jurlmap-RESTful-URLs-for-your-Java-app</id>

		<updated>2009-08-03T00:00:00Z</updated>
		<published>2009-08-03T00:00:00Z</published>



		<content type="html"><![CDATA[
<p>If you are in the business of writing Web 2.0-ish applications then clean urls are an essential part of the package.</p>

<p>Bad => <code>/member.jsp?username=tastychicken&amp;view=blog&amp;sort=hot</code> <br />
Good => <code>/member/tastychicken/blog/hot</code>  </p>

<p>Here are some reasons why this matters:</p>

<ul>
<li><p>Your app looks more professional and by paying attention to details such as your urls you will give people the impression that your app is rock solid, well designed and in general that you know what you are doing. This assumes that the rest of your site looks as good as your urls.</p></li>
<li><p>It is easier for people to remember your urls and navigate to them manually. According to some research that I once stumbled upon on google but now totally forgot where and what it was about,  people spend as much as <strong>24%</strong> of their time on a search results page <strong>looking at the returned urls</strong>, and are more likely to click on clean and informative urls than messed up ones.</p></li>
<li><p>It likely matters for SEO.</p></li>
</ul>

<p>So if you are writing a site in java how do you go about implementing such urls for your app? There are several ways:</p>

<ul>
<li><p>You can do it the old fashion manual way, like it was done for centuries. <br />
You can create a filter in which you manually parse urls and forward to servlets or jsp pages for the action.
This becomes repetitive and unmaintainable very quickly.</p></li>
<li><p>You can use apache's mod_rewrite. <br />
And yet there are times when you would like to stay completely in java rather than having a part of your application (the url structure) stored in a completely separate and unrelated place. Plus maybe you don't want or can't run apache on your live setup for some reason.</p></li>
<li><p>You can use an existing library such as <a href="http://tuckey.org/urlrewrite/">UrlRewriteFilter</a> which implements in Java the functionality of apache mod_rewrite.  This is a very good and powerful tool, and yet, I still prefer something that is more directly tuned to the single goal or creating clean urls, which would avoid multiple lines of xml configuration per url mapping (for some sage advice regarding xml usage go <a href="http://www.bileblog.org/2007/03/xml-wiring-is-for-girls/">here</a>), and would give me even more help with handling parameters.</p></li>
</ul>

<p>To address this problem i wrote a small library called  <strong><a href="http://jurlmap.codegremlins.com">jurlmap</a></strong>. Some features of <a href="http://jurlmap.codegremlins.com">jurlmap</a> are:</p>

<ul>
<li>Simple pattern language for brevity and convenience</li>
<li>Direct binding of parameters to bean properties or method parameters</li>
<li>Configuration in plain java and annotations. No need for external configuration artifacts</li>
</ul>

<p>Here are some url pattern examples:</p>

<pre><code>protected void configure() {
    // In this pattern $ means a string, which when matched 
    // is bound to parameter `Username` and control forwarded to profile.jsp
    // Parameter will be accessible via request.getParameter()
    forward("/profile.jsp", "/profile/$Username");

    // Here % means integer pattern and * means until end of the pattern.
    // Binds integers to parameter ArticleId and forwards to article.jsp
    forward("/article.jsp", "/article/%ArticleId/*");

    // When matched will send a redirect back to browser and parameters
    // are appended to query string so in this case the target will
    // be `/servlets/profileservlet?Username=...`
    redirect("/servlets/profileservlet", "/member/$Username");


    // On match creates an instance of LoginPage and calls it's service method
    // LoginPage class implements com.pagegoblin.jurlmap.Page.
    // If it is annotated with a @Deploy(url) annotation
    // the we don't need to pass a url to the deploy method.
    // In this case parameters are bound to bean properties or fields 
    // of the newly created LoginPage instance.
    deploy(LoginPage.class);
}
</code></pre>

<p>Detailed info and more advanced use cases can be found in the <a href="http://jurlmap.codegremlins.com/manual">manual</a>.</p>

<ul>
<li><a href="http://jurlmap.codegremlins.com/"><b>jurlmap home</b></a>  </li>
<li><a href="http://jurlmap.codegremlins.com/download">Download</a>  </li>
</ul>

<p>Enjoy.</p>		
	]]></content>
				
	</entry>


</feed>
