<?xml version="1.0" encoding="utf-8"?>
<feed xmlns="http://www.w3.org/2005/Atom">

 <title>Jamie Perkins</title>
 <link href="/atom.xml" rel="self"/>
 <link href="/"/>
 <updated>2017-10-21T12:28:51+01:00</updated>
 <id></id>
 <author>
   <name>Jamie Perkins</name>
   <email></email>
 </author>

 
 <entry>
   <title>Coming Up In Kubernetes</title>
   <link href="/2016/05/31/coming-up-in-kubernetes/"/>
   <updated>2016-05-31T00:00:00+01:00</updated>
   <id>/2016/05/31/coming-up-in-kubernetes</id>
   <content type="html">&lt;h3&gt;Kubernetes 1.3&lt;/h3&gt;

&lt;p&gt;If you didn&amp;#39;t know, we are currently in the middle of migrating our infrastructure
from VMs on AWS to Kubernetes on VMs on AWS.
We are holding off for version 1.3 which is due to be released on June 24th. In the meantime
we are making all the preparations we can with testing on 1.2, planning our migration and writing all the configuration we can.&lt;/p&gt;

&lt;p&gt;I thought I&amp;#39;d write about 2 major additions the new version brings to Kubernetes.&lt;/p&gt;

&lt;h3&gt;PetSets&lt;/h3&gt;

&lt;p&gt;&lt;a href=&quot;https://github.com/kubernetes/kubernetes/issues/260&quot;&gt;Petsets&lt;/a&gt; solve a problem with stateful applications and services. You may know in Kubernetes the smallest unit of deployment is a &lt;a href=&quot;http://kubernetes.io/docs/user-guide/pods/&quot;&gt;Pod&lt;/a&gt;. Pods are ephemeral by design, akin to a running instance of a container image and nuking it when it stops. When the Pod dies, it is permanently gone too, replaced by a new instance with a fresh filesystem, new network identity and all the rest.&lt;/p&gt;

&lt;p&gt;This is generally fine except in the cases where an instance of your application wants to survive restarts and stops with it&amp;#39;s filesystem and identity intact. For example in the case of a database node.&lt;/p&gt;

&lt;p&gt;Petsets solve this problem by giving a unique and stable identity to a Pod. This is important for clustered services that need stable identities to refer to when bootstrapping a cluster or seeding additional nodes. The stable ID allows Pods to retrieve the data (volume) associated with a particular identity, meaning &lt;code&gt;db.node1&lt;/code&gt; still holds the same data between restarts.&lt;/p&gt;

&lt;h3&gt;Ubernetes (aka Kubernetes Cluster Federation)&lt;/h3&gt;

&lt;p&gt;This is basically what it says on the tin. Kubernetes as of version 1.2 officially only supports single master, multi slave deployments. This works fine but leaves a single point of failure on the master node, which handles cluster state changes and hosts the Kubernetes API.&lt;/p&gt;

&lt;p&gt;&lt;a href=&quot;https://github.com/kubernetes/kubernetes/blob/master/docs/proposals/federation.md&quot;&gt;Ubernetes&lt;/a&gt; aims to place a control plane on top individual Kubernetes clusters to support things like failover between clusters running in different availability zone. Hopefully, in practice this means the automatic and dynamic rescaling of services and applications in response to failure of a cluster and/or availability zone.&lt;/p&gt;

&lt;p&gt;Ubernetes actually goes a step further than that. It aims to support the use-case of multiple Kubernetes clusters hosted across different cloud providers (e.g. GCE and AWS) and optionally on-premise bare metal. This is nice, but not something we are likely to use being quite comfortable in &lt;a href=&quot;https://metabroadcast.com/blog/why-we-re-sticking-with-aws&quot;&gt;Amazon&amp;#39;s warm embrace&lt;/a&gt;.&lt;/p&gt;

&lt;p&gt;One more thing to mention is the changes to the script used to bootstrap a Kubernetes cluster. Titled &lt;code&gt;kube-up.sh&lt;/code&gt;, it handles deploying the master and minion nodes, their network configuration and so on. In the case of AWS this means picking the AMI, setting up a VPC, gateways, subnets and more. This is being reworked in v1.3 to support Ubernetes, which should remove the manual work that is needed to setup the same in v1.2.&lt;/p&gt;

&lt;h3&gt;That&amp;#39;s all&lt;/h3&gt;

&lt;p&gt;Minor disclaimer that anything I&amp;#39;ve written was parsed from the Github &lt;a href=&quot;https://github.com/kubernetes/kubernetes/issues&quot;&gt;issues and discussions&lt;/a&gt;. The general concepts of Petsets and Ubernetes are blockers to &lt;a href=&quot;https://github.com/kubernetes/kubernetes/wiki/Release-1.3&quot;&gt;the 1.3 release&lt;/a&gt; for the Kubernetes team. Their implementation and particular details may vary before release though, so do your own research on if they are right for you.&lt;/p&gt;

&lt;p&gt;We&amp;#39;re looking forward to lots of things from Kubernetes. Our playing around with v1.2 looked like it could remove a lot of the pain of dealing with heterogenous infrastructure and applications, each configured in different and special ways.&lt;/p&gt;

&lt;p&gt;&lt;small&gt;Originally posted on &lt;a href=&quot;https://metabroadcast.com/blog/coming-up-in-kubernetes&quot;&gt;Metabroadcast&amp;#39;s blog&lt;/a&gt;.&lt;/small&gt;&lt;/p&gt;
</content>
 </entry>
 
 <entry>
   <title>Java Socket Programming With Netty</title>
   <link href="/2016/02/17/java-socket-programming-with-netty/"/>
   <updated>2016-02-17T00:00:00+00:00</updated>
   <id>/2016/02/17/java-socket-programming-with-netty</id>
   <content type="html">&lt;p&gt;It’s (hopefully) quite infrequent that one needs to work with network sockets directly to chuck bytes around. Normally in an application you’ll use an existing application–level protocol like REST over HTTP to pass data around. The reasons for this include, but are not limited to; convenience, reliability, interoperability and sanity.&lt;/p&gt;

&lt;p&gt;That said, should you find yourself in a position where you need better performance or more flexibility than an existing protocol, it’s useful to know where to start.&lt;/p&gt;

&lt;p&gt;For example, I used it recently in an &lt;a href=&quot;https://www.wikiwand.com/en/Internet_of_Things&quot;&gt;IoT&lt;/a&gt; project where it would have been time consuming and inefficient to deal with HTTP clients in embedded C++ code.&lt;/p&gt;

&lt;h3&gt;Netty&lt;/h3&gt;

&lt;p&gt;&lt;a href=&quot;http://netty.io/&quot;&gt;Netty&lt;/a&gt; is an NIO (non–blocking input/output) client–server framework for Java. It simplifies the process of writing servers and clients that talk to each other under the hood using your typical &lt;code&gt;DatagramSocket&lt;/code&gt;, &lt;code&gt;ServerSocket&lt;/code&gt; and &lt;code&gt;Socket&lt;/code&gt; classes. In this example I’ll show you how to write a very simple server that will accept connections over a TCP port, read and decode JSON and do something with it.&lt;/p&gt;

&lt;p&gt;In real life you’re probably more likely to use something binary like &lt;a href=&quot;https://thrift.apache.org/&quot;&gt;Thrift&lt;/a&gt;, &lt;a href=&quot;https://github.com/google/protobuf&quot;&gt;Protocol Buffers&lt;/a&gt; or &lt;a href=&quot;http://wiki.fasterxml.com/SmileFormat&quot;&gt;Smile&lt;/a&gt;, instead of JSON.&lt;/p&gt;

&lt;h3&gt;&lt;a id=&quot;getting_started_23&quot;&gt;&lt;/a&gt;Getting started&lt;/h3&gt;

&lt;p&gt;I am assuming you have imported Netty using the dependency manager of your choice and are ready to start typing code.&lt;/p&gt;

&lt;p&gt;&lt;noscript&gt;&lt;pre&gt;NioEventLoopGroup acceptorGroup = new NioEventLoopGroup(2); // 2 threads
NioEventLoopGroup handlerGroup = new NioEventLoopGroup(10); // 10 threads&lt;/pre&gt;&lt;/noscript&gt;&lt;script src=&quot;https://gist.github.com/JamieAP/fc88328a57003a819350.js&quot;&gt; &lt;/script&gt;&lt;/p&gt;

&lt;p&gt;First off we need instances of &lt;code&gt;NioEventLoopGroup&lt;/code&gt;. This class implements a multi-threaded &lt;a href=&quot;https://www.wikiwand.com/en/Event_loop&quot;&gt;Event Loop&lt;/a&gt;, that is, something that constantly and frequently polls IO abstractions for stuff to do like read data or start a new connection. There is also the &lt;code&gt;EpollEventLoopGroup&lt;/code&gt; available if you&amp;#39;re on Linux, which makes use of the more performant &lt;a href=&quot;https://www.wikiwand.com/en/Epoll&quot;&gt;Epoll&lt;/a&gt;.&lt;/p&gt;

&lt;p&gt;We need two of them, one to accept new connections and one to handle existing connections. If you’ve worked with an HTTP server you’ll know it typically uses the same thing.&lt;/p&gt;

&lt;h3&gt;&lt;a id=&quot;configuring_the_server_42&quot;&gt;&lt;/a&gt;Configuring the server&lt;/h3&gt;

&lt;p&gt;Next we must configure the server proper. Lets walk through.&lt;/p&gt;

&lt;p&gt;&lt;noscript&gt;&lt;pre&gt;ServerBootstrap b = new ServerBootstrap();
b.group(acceptorGroup, handlerGroup)
        .channel(NioServerSocketChannel.class)
        .childHandler(new MySocketInitialiser())
        .option(ChannelOption.SO&lt;em&gt;BACKLOG, 5)
        .childOption(ChannelOption.SO&lt;/em&gt;KEEPALIVE, true);&lt;/p&gt;

&lt;p&gt;b.localAddress(port).bind().sync();
LOG.info(&amp;quot;Started on port {}&amp;quot;, port);&lt;/pre&gt;&lt;/noscript&gt;&lt;script src=&quot;https://gist.github.com/JamieAP/ba4bcc0862e1dbac5369.js&quot;&gt; &lt;/script&gt;
&lt;code&gt;ServerBootstrap&lt;/code&gt; is a helper of sorts that lets you avoid configuring every single aspect of the highly complex &lt;code&gt;ServerChannel&lt;/code&gt; implementations. Basically does what it says on the tin, it bootstraps a server for us.&lt;/p&gt;

&lt;p&gt;It needs setting up with a few things, first we give it the event loops we created earlier which allows our server to accept and handle connections.&lt;/p&gt;

&lt;p&gt;Next is a call to &lt;code&gt;.channel()&lt;/code&gt; with a class. Netty will creates instances of this class and uses them to accept new connections. In this case that’s &lt;code&gt;NioServerSocketChannel&lt;/code&gt; which is an implementation of &lt;code&gt;ServerChannel&lt;/code&gt;.&lt;/p&gt;

&lt;p&gt;Then a call to &lt;code&gt;.childHandler()&lt;/code&gt; with an instance of &lt;code&gt;ChannelHandler&lt;/code&gt;. This is where interesting things will happen, it sets up the pipeline that accepted connections are handled through. Here I’m using a class called &lt;code&gt;MySocketInitialiser&lt;/code&gt;, my own creation, we’ll come back to this.&lt;/p&gt;

&lt;p&gt;Calls to &lt;code&gt;.option()&lt;/code&gt; let us set TCP options on the acceptor. In this case &lt;code&gt;SO_BACKLOG&lt;/code&gt; tells the server to refuse connections if it already has 5 queued up.&lt;/p&gt;

&lt;p&gt;Finally calls to &lt;code&gt;.childOption()&lt;/code&gt; let us set TCP options on the handlers. &lt;code&gt;SO_KEEPALIVE&lt;/code&gt; tells clients to keep their connections open with &lt;a href=&quot;https://www.wikiwand.com/en/Keepalive&quot;&gt;keepalive&lt;/a&gt; packets.&lt;/p&gt;

&lt;p&gt;We then start the server by telling it to bind to a port at the local address and call &lt;code&gt;.sync()&lt;/code&gt; to wait for the server to shutdown.&lt;/p&gt;

&lt;h3&gt;&lt;a id=&quot;setting_up_a_pipeline_87&quot;&gt;&lt;/a&gt;Setting up a pipeline&lt;/h3&gt;

&lt;p&gt;Back to &lt;code&gt;MySocketInitialiser&lt;/code&gt; to see where the magic happens.
&lt;noscript&gt;&lt;pre&gt;/**
 * Performs the initial set up of sockets as they connect to Netty.
 * Registers the pipeline of handlers that received messages are passed through
 */
public class MySocketInitialiser extends ChannelInitializer&amp;lt;SocketChannel&amp;gt; {&lt;/p&gt;
&lt;figure class=&quot;highlight&quot;&gt;&lt;pre&gt;&lt;code class=&quot;language-text&quot; data-lang=&quot;text&quot;&gt;@Override
public void initChannel(SocketChannel ch) throws Exception {
    ChannelPipeline pipeline = ch.pipeline();

    pipeline.addLast(LineBasedFrameDecoder.class.getName(),
            new LineBasedFrameDecoder(256));

    pipeline.addLast(StringDecoder.class.getName(),
            new StringDecoder(CharsetUtil.UTF_8));

    pipeline.addLast(JsonDecoder.class.getName(),
            new JsonDecoder&amp;amp;lt;&amp;amp;gt;(Person.class));

    pipeline.addLast(&amp;amp;quot;stdoutHandler&amp;amp;quot;,
            new ChannelInboundMessageHandlerAdapter&amp;amp;lt;Person&amp;amp;gt;() {
                @Override
                public void messageReceived(ChannelHandlerContext ctx, Person person) throws Exception {
                    System.out.println(
                            &amp;amp;quot;Your name is &amp;amp;quot; + person.getFirstName() + &amp;amp;quot; &amp;amp;quot; + person.getLastName() + &amp;amp;quot;!&amp;amp;quot;
                    );
                }
            }
    );
&lt;/code&gt;&lt;/pre&gt;&lt;/figure&gt;
&lt;p&gt;}&lt;/pre&gt;&lt;/noscript&gt;&lt;script src=&quot;https://gist.github.com/JamieAP/175d9cfc54dab8532d56.js&quot;&gt; &lt;/script&gt;
The &lt;code&gt;initChannel()&lt;/code&gt; method of this class is called by Netty whenever it receives a new connection. A &lt;code&gt;SocketChannel&lt;/code&gt; is simply the &lt;a href=&quot;http://netty.io/4.0/api/io/netty/channel/Channel.html&quot;&gt;channel&lt;/a&gt; abstraction over a TCP/IP socket.&lt;/p&gt;

&lt;p&gt;Each &lt;code&gt;SocketChannel&lt;/code&gt; has a &lt;a href=&quot;http://netty.io/4.0/api/io/netty/channel/ChannelPipeline.html&quot;&gt;pipeline&lt;/a&gt; associated with it. You can think of think of the pipeline as an ordered list of handlers with each feeding its output as the input to the next one. There are caveats to this but we can ignore them for now.&lt;/p&gt;

&lt;p&gt;In the example pipeline above we have in order the following:&lt;/p&gt;

&lt;ol&gt;
&lt;li&gt; A &lt;code&gt;LineBasedFrameDecoder&lt;/code&gt;, this delimits messages by detecting newlines bytes (i.e. \n or \r\n)&lt;/li&gt;
&lt;li&gt; A &lt;code&gt;StringDecoder&lt;/code&gt;, this decodes bytes into UTF-8 &lt;code&gt;String&lt;/code&gt;s or any other encoding of your choice&lt;/li&gt;
&lt;li&gt; A &lt;code&gt;JsonDecoder&lt;/code&gt;, this decodes &lt;code&gt;String&lt;/code&gt;s using &lt;a href=&quot;https://github.com/google/gson&quot;&gt;Gson&lt;/a&gt; into objects of type &lt;code&gt;Person&lt;/code&gt; or any other type of your choice&lt;/li&gt;
&lt;li&gt; An anonymous class that simply prints the name of our decoded &lt;code&gt;Person&lt;/code&gt; to standard output&lt;/li&gt;
&lt;/ol&gt;

&lt;p&gt;&lt;code&gt;JsonDecoder&lt;/code&gt; is not a part of Netty, its implementation is as follows:&lt;/p&gt;

&lt;p&gt;&lt;noscript&gt;&lt;pre&gt;public class JsonDecoder&amp;lt;T&amp;gt; extends MessageToMessageDecoder&amp;lt;String, T&amp;gt; {&lt;/p&gt;
&lt;figure class=&quot;highlight&quot;&gt;&lt;pre&gt;&lt;code class=&quot;language-text&quot; data-lang=&quot;text&quot;&gt;private static final Gson GSON = new GsonBuilder().create();

private final Class&amp;amp;lt;T&amp;amp;gt; clazz;

public JsonDecoder(Class&amp;amp;lt;T&amp;amp;gt; clazz, Class&amp;amp;lt;?&amp;amp;gt;... acceptedMsgTypes) {
    super(acceptedMsgTypes);
    this.clazz = checkNotNull(clazz);
}

@Override
public T decode(ChannelHandlerContext ctx, String msg) throws Exception {
    return GSON.fromJson(msg, clazz);
}
&lt;/code&gt;&lt;/pre&gt;&lt;/figure&gt;
&lt;p&gt;}&lt;/pre&gt;&lt;/noscript&gt;&lt;script src=&quot;https://gist.github.com/JamieAP/3c3dd2ece49bef05b137.js&quot;&gt; &lt;/script&gt;
That’s everything we need for our example Netty server to do stuff.&lt;/p&gt;

&lt;h3&gt;&lt;a id=&quot;seeing_it_in_action_162&quot;&gt;&lt;/a&gt;Seeing it in action&lt;/h3&gt;

&lt;p&gt;First we start up the server. How you do this will depend on the way your project is structured:&lt;/p&gt;

&lt;p&gt;&lt;noscript&gt;&lt;pre&gt;INFO  [2016-02-16 12:06:38,880] nettytest.SocketServer: Started on port 9000&lt;/pre&gt;&lt;/noscript&gt;&lt;script src=&quot;https://gist.github.com/JamieAP/d10ae69416dcca57db3d.js&quot;&gt; &lt;/script&gt;&lt;/p&gt;

&lt;p&gt;We can then use &lt;code&gt;telnet&lt;/code&gt; to open a socket to our server:&lt;/p&gt;

&lt;p&gt;&lt;noscript&gt;&lt;pre&gt;# jamie at eduD692.kent.ac.uk in ~ [12:08:52]
$ telnet localhost 9000
Trying ::1...
Connected to localhost.
Escape character is &amp;#39;^]&amp;#39;.
{&amp;quot;firstName&amp;quot;:&amp;quot;Jamie&amp;quot;, &amp;quot;lastName&amp;quot;:&amp;quot;Perkins&amp;quot;}&lt;/pre&gt;&lt;/noscript&gt;&lt;script src=&quot;https://gist.github.com/JamieAP/5beb7d505373122a8eef.js&quot;&gt; &lt;/script&gt;&lt;/p&gt;

&lt;p&gt;And then in standard out we’ll see:&lt;/p&gt;

&lt;p&gt;&lt;noscript&gt;&lt;pre&gt;Your name is Jamie Perkins!&lt;/pre&gt;&lt;/noscript&gt;&lt;script src=&quot;https://gist.github.com/JamieAP/db3e23b8a4622028bc59.js&quot;&gt; &lt;/script&gt;&lt;/p&gt;

&lt;h3&gt;&lt;a id=&quot;wrapping_up_185&quot;&gt;&lt;/a&gt;Wrapping up&lt;/h3&gt;

&lt;p&gt;There is a huge amount of detail I’ve glossed over for the sake of making this a very easy introduction and to get you off the ground quickly. The &lt;a href=&quot;http://netty.io/wiki/user-guide-for-4.x.html&quot;&gt;Netty user guide&lt;/a&gt; goes into more depth and is a good place to start when learning more. If you want to read about NIO in general the &lt;a href=&quot;https://docs.oracle.com/javase//8/docs/technotes/guides/io/index.html&quot;&gt;Oracle docs&lt;/a&gt; are also helpful.&lt;/p&gt;

&lt;p&gt;&lt;small&gt;Originally posted on &lt;a href=&quot;https://metabroadcast.com/blog/java-socket-programming-with-netty&quot;&gt;MetaBroadcast&amp;#39;s blog&lt;/a&gt;.&lt;/small&gt;&lt;/p&gt;
</content>
 </entry>
 
 <entry>
   <title>Spark Framework</title>
   <link href="/2015/12/26/spark/"/>
   <updated>2015-12-26T00:00:00+00:00</updated>
   <id>/2015/12/26/spark</id>
   <content type="html">&lt;p&gt;There&amp;#39;s a neat little framework I&amp;#39;ve used recently called &lt;a href=&quot;http://sparkjava.com/&quot;&gt;Spark&lt;/a&gt;. It is yet another
Java HTTP framework, but it&amp;#39;s a very small and simple one.&lt;/p&gt;

&lt;p&gt;I have written about &lt;a href=&quot;http://www.dropwizard.io/0.9.1/docs/&quot;&gt;Dropwizard&lt;/a&gt; in the &lt;a href=&quot;http://jamiep.net/2015/05/28/dropwizard/&quot;&gt;past&lt;/a&gt; which is
also a small (compared to say, &lt;a href=&quot;http://spring.io&quot;&gt;Spring&lt;/a&gt;) web framework, but Spark takes it to another level.&lt;/p&gt;

&lt;p&gt;Here is a code snippet taken from their site:&lt;/p&gt;

&lt;p&gt;&lt;noscript&gt;&lt;pre&gt;import static spark.Spark.*;&lt;/p&gt;

&lt;p&gt;public class HelloWorld {
    public static void main(String[] args) {
        get(&amp;quot;/hello&amp;quot;, (req, res) -&amp;gt; &amp;quot;Hello World&amp;quot;);
    }
}&lt;/pre&gt;&lt;/noscript&gt;&lt;script src=&quot;https://gist.github.com/JamieAP/c42aa3622cd31e4bcbd8.js&quot;&gt; &lt;/script&gt;&lt;/p&gt;

&lt;p&gt;That is &lt;em&gt;all&lt;/em&gt; (ignoring Maven config) that&amp;#39;s needed to start serving HTTP requests from the JVM.&lt;/p&gt;

&lt;p&gt;I&amp;#39;ve not had the opportunity to use Spark in anything resembling a production environment so I cannot vouch for its reliability there.
However I have used it for small projects and it&amp;#39;s been great doing zero setup before writing code that has an impact on the API&amp;#39;s output.&lt;/p&gt;

&lt;p&gt;Compare this to the equivalent endpoint using &lt;a href=&quot;http://expressjs.com/&quot;&gt;Express&lt;/a&gt;:&lt;/p&gt;

&lt;p&gt;&lt;noscript&gt;&lt;pre&gt;app.get(&amp;#39;/&amp;#39;, function (req, res) {
  res.send(&amp;#39;Hello World!&amp;#39;);
});&lt;/pre&gt;&lt;/noscript&gt;&lt;script src=&quot;https://gist.github.com/JamieAP/07cabfabe1248d9a2fd0.js&quot;&gt; &lt;/script&gt;&lt;/p&gt;

&lt;p&gt;Uncanny, right? The Java sure as shit wouldn&amp;#39;t have looked like that a few years ago...&lt;/p&gt;

&lt;p&gt;I know of a few JavaScripters who would like to learn Java but find its learning curve off-putting. Spark may offer a foot in the door by helping to lower that learning curve. It provides a natural application structure far more familiar to those who&amp;#39;ve used Express in the past than any other framework I&amp;#39;ve seen so far.&lt;/p&gt;

&lt;p&gt;They have easy to follow documentation on both &lt;a href=&quot;https://sparktutorials.github.io/2015/04/02/setting-up-a-spark-project-with-maven.html&quot;&gt;setting up&lt;/a&gt; &lt;a href=&quot;https://maven.apache.org/&quot;&gt;Maven&lt;/a&gt; and &lt;a href=&quot;http://sparkjava.com/documentation.html&quot;&gt;Spark&lt;/a&gt; itself, if you&amp;#39;re interested.&lt;/p&gt;

&lt;p&gt;Thanks for reading!&lt;/p&gt;
</content>
 </entry>
 
 <entry>
   <title>Dropwizard</title>
   <link href="/2015/05/28/dropwizard/"/>
   <updated>2015-05-28T00:00:00+01:00</updated>
   <id>/2015/05/28/dropwizard</id>
   <content type="html">&lt;p&gt;As you may know, we have many REST APIs running on the JVM. The majority of which use the &lt;a href=&quot;http://projects.spring.io/spring-framework/&quot;&gt;Spring MVC framework&lt;/a&gt;. We&amp;#39;ve very much a love/hate relationships with Spring (mostly hate).&lt;/p&gt;

&lt;p&gt;An entire series of posts could be written about things we don&amp;#39;t like about Spring, but to save time and sanity, I&amp;#39;ll summarise as: too much boilerplate and configuration around merely getting the framework to serve HTTP requests. XML config files and &lt;code&gt;ManagerServiceFactoryBeanImplFactory&lt;/code&gt; take time to understand and set up, leaving you less time to solve the problem that your application owes its existence to.  We use annotations in most places to configure our Spring apps, but it&amp;#39;s still a pain to have to deal with in general.&lt;/p&gt;

&lt;p&gt;We&amp;#39;ve now moved two of our projects onto &lt;a href=&quot;http://www.dropwizard.io&quot;&gt;Dropwizard&lt;/a&gt; and are so far extremely happy with what we&amp;#39;ve seen.&lt;/p&gt;

&lt;h3&gt;What is Dropwizard?&lt;/h3&gt;

&lt;p&gt;It&amp;#39;s a combination of things really as the Getting Started page will tell you. It provides &lt;a href=&quot;http://www.eclipse.org/jetty/&quot;&gt;Jetty&lt;/a&gt; for HTTP, &lt;a href=&quot;https://github.com/FasterXML/jackson&quot;&gt;Jackson&lt;/a&gt; for JSON, &lt;a href=&quot;https://jersey.java.net/&quot;&gt;Jersey&lt;/a&gt; for REST and so on. The power and convenience of Dropwizard comes from it&amp;#39;s hiding and pre-configuration of the above things right out of the box. To go from nothing to something serving API requests in Dropwizard doesn&amp;#39;t require you to write a line of code setting up a Jetty or configuring Jackson.&lt;/p&gt;

&lt;p&gt;Everything you need is exposed cleanly, everything you don&amp;#39;t is hidden away. This leaves you to start writing code to solve problems almost immediately. The two projects I mentioned above were already using Jetty and Jersey, and so their migrations were fairly trivial. We will be moving &lt;a href=&quot;https://github.com/atlasapi/atlas-deer&quot;&gt;Atlas Deer&lt;/a&gt; from Spring to Dropwizard sometime in the near future. I&amp;#39;ll report back on how that goes and with any useful tips for moving from one to the other.&lt;/p&gt;

&lt;h3&gt;Example!&lt;/h3&gt;

&lt;p&gt;&lt;noscript&gt;&lt;pre&gt;package com.metabroadcast.dropwizard.example;&lt;/p&gt;

&lt;p&gt;import io.dropwizard.Application;
import io.dropwizard.setup.Bootstrap;
import io.dropwizard.setup.Environment;&lt;/p&gt;

&lt;p&gt;public class ExampleApplication extends Application&amp;lt;ExampleConfiguration&amp;gt; {&lt;/p&gt;
&lt;figure class=&quot;highlight&quot;&gt;&lt;pre&gt;&lt;code class=&quot;language-text&quot; data-lang=&quot;text&quot;&gt;public static void main(String[] args) throws Exception {
    new ExampleApplication().run(args);
}

@Override
public void run(ExampleConfiguration conf, Environment env) throws Exception {
    env.jersey().register(HelloWorldResource.class);
}
&lt;/code&gt;&lt;/pre&gt;&lt;/figure&gt;
&lt;p&gt;}&lt;/pre&gt;&lt;/noscript&gt;&lt;script src=&quot;https://gist.github.com/mbst-jamie/b61c71774246ab1cf836.js&quot;&gt; &lt;/script&gt;&lt;/p&gt;

&lt;p&gt;The above code, plus a very simple &lt;a href=&quot;http://www.dropwizard.io/manual/core.html#configuration&quot;&gt;Configuration class and YAML&lt;/a&gt;, is all you need to start serving requests from an endpoint in Dropwizard. On top of that there is a &lt;a href=&quot;http://www.dropwizard.io/manual/index.html&quot;&gt;long list&lt;/a&gt; of built-in, out of the box features that most if not all applications of this type would like.&lt;/p&gt;

&lt;p&gt;An admin servlet is automatically configured and started, from which tasks and health checks can be easily built on top of. Other features include but are not limited to:&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;Logging&lt;/li&gt;
&lt;li&gt;Object lifecycle management&lt;/li&gt;
&lt;li&gt;Configuration validation&lt;/li&gt;
&lt;li&gt;JVM and resource metrics&lt;/li&gt;
&lt;li&gt;ASCII art printing at start up&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;All come for free and only require you to implement the bit you care about.&lt;/p&gt;

&lt;p&gt;I&amp;#39;ll save going into much more depth for after we&amp;#39;ve moved a Spring application onto Dropwizard, as I expect there will be far more to show. But so far, we would seriously recommend checking it out!&lt;/p&gt;

&lt;p&gt;&lt;small&gt;Originally posted on &lt;a href=&quot;https://metabroadcast.com/blog/dropwizard&quot;&gt;MetaBroadcast&amp;#39;s blog&lt;/a&gt;.&lt;/small&gt;&lt;/p&gt;
</content>
 </entry>
 
 <entry>
   <title>More Postgres - Full Text Search</title>
   <link href="/2015/05/14/more-postgres-full-text-search/"/>
   <updated>2015-05-14T00:00:00+01:00</updated>
   <id>/2015/05/14/more-postgres-full-text-search</id>
   <content type="html">&lt;p&gt;Hello! You may know from some of my previous posts that we use &lt;a href=&quot;http://www.postgresql.org/docs/9.4/static/textsearch.html&quot;&gt;Postgres Full Text Search&lt;/a&gt; to power search functionality on one of our services.&lt;/p&gt;

&lt;h3&gt;Materialised Views&lt;/h3&gt;

&lt;p&gt;We&amp;#39;ve changed the way we maintain and update the search index due to performance issues with the materialised view based approach we took the first time round. Previously we&amp;#39;d denormalise the &lt;code&gt;TSVECTOR&lt;/code&gt; columns that are stored on various tables in the DB into a materialised view. The materialised view would then be refreshed at regular intervals to keep it fresh.&lt;/p&gt;

&lt;p&gt;The benefits of this are that it requires very little SQL to set up and maintain, providing a workable solution at the start in a short amount of time. However as the DB grew in size and the materialised views grew in complexity and requirement we found the time taken to refresh was beyond acceptable.&lt;/p&gt;

&lt;p&gt;Of particular importance is the blocking nature of a materialised view refresh: nothing can read from the view while it is being regenerated. A &lt;a href=&quot;http://www.postgresql.org/docs/9.4/static/sql-refreshmaterializedview.html&quot;&gt;&lt;code&gt;CONCURRENTLY&lt;/code&gt;&lt;/a&gt; option was added in Postgres 9.4 that allows the view to be used while it regenerates. Unfortunately the resources required to compute the new index was still too much to be doing periodically while users are using the service.&lt;/p&gt;

&lt;h3&gt;Triggers&lt;/h3&gt;

&lt;p&gt;Ultimately we decided to turn our materialised view into a regular view, ensuring appropriate indices on the underlying tables for performance. This view is then queried as part of the initial data load and the result stored into a table that then acts as the search index. Triggers are assigned to the tables that underlie the view to update only the changed rows of the index on &lt;code&gt;UPDATE&lt;/code&gt; or &lt;code&gt;INSERT&lt;/code&gt;.&lt;/p&gt;

&lt;p&gt;The downside to this is a lot of Postgres UDFs (or stored procedures) that have to be maintained and tested. However this is outweighed by the benefits of an &amp;quot;instantly&amp;quot; updating view and a far more performant DB in general due to less background reindexing.&lt;/p&gt;

&lt;p&gt;From our experience using both approaches, we&amp;#39;d recommend strongly considering whether your use case is appropriate for materialised views. At first they seem a quick and simple way of computing and updating a result, but quickly become expensive and tricky to update without negatively affecting end-users.&lt;/p&gt;

&lt;p&gt;An example of such a trigger, featuring the wonderful syntax of PLPGSQL:&lt;/p&gt;

&lt;p&gt;&lt;noscript&gt;&lt;pre&gt;CREATE OR REPLACE FUNCTION update&lt;em&gt;scene&lt;/em&gt;search&lt;em&gt;text&lt;/em&gt;involvement()
  RETURNS TRIGGER AS
  $BODY$
  DECLARE
    update&lt;em&gt;scene&lt;/em&gt;id INTEGER;
  BEGIN
    CASE TG&lt;em&gt;OP
      WHEN &amp;#39;DELETE&amp;#39;
      THEN
        update&lt;/em&gt;scene&lt;em&gt;id := OLD.scene&lt;/em&gt;id;
    ELSE
      update&lt;em&gt;scene&lt;/em&gt;id := NEW.scene&lt;em&gt;id;
    END CASE;
    DELETE FROM scene&lt;/em&gt;search&lt;em&gt;text
    WHERE scene&lt;/em&gt;id = update&lt;em&gt;scene&lt;/em&gt;id;
    INSERT INTO scene&lt;em&gt;search&lt;/em&gt;text
      SELECT *
        FROM scene&lt;em&gt;search&lt;/em&gt;view
       WHERE scene&lt;em&gt;id = update&lt;/em&gt;scene_id;
    RETURN NULL;
  END; $BODY$
LANGUAGE plpgsql VOLATILE;&lt;/pre&gt;&lt;/noscript&gt;&lt;script src=&quot;https://gist.github.com/mbst-jamie/e5fa7ae788f0e6a59e06.js&quot;&gt; &lt;/script&gt;&lt;/p&gt;

&lt;p&gt;As you can see, this code will only update the rows that have the same &lt;code&gt;scene_id&lt;/code&gt; as the record that has changed.&lt;/p&gt;

&lt;p&gt;In general we&amp;#39;ve found Postgres&amp;#39; FTS capabilities to be quite sufficient for our use case. Hopefully these posts are helpful if you are trying to implement a search API using Postgres. Thanks for reading :)&lt;/p&gt;

&lt;p&gt;&lt;small&gt;Originally posted on &lt;a href=&quot;https://metabroadcast.com/blog/more-postgres-full-text-search&quot;&gt;MetaBroadcast&amp;#39;s blog&lt;/a&gt;.&lt;/small&gt;&lt;/p&gt;
</content>
 </entry>
 
 <entry>
   <title>Java 8 Method References</title>
   <link href="/2015/03/30/java-8-method-references/"/>
   <updated>2015-03-30T00:00:00+01:00</updated>
   <id>/2015/03/30/java-8-method-references</id>
   <content type="html">&lt;p&gt;The following is a fairly reasonable block of code that one might find in a project using Guava.&lt;/p&gt;

&lt;p&gt;&lt;noscript&gt;&lt;pre&gt;ImmutableList.copyOf(Iterables.limit(Iterables.filter(Iterables.transform(theIterable, new Function&amp;lt;Object, Object&amp;gt;() {
            @Override
            public Object apply(Object input) {
                return changeThing(input);
            }
        }), new Predicate&amp;lt;Object&amp;gt;() {
            @Override
            public boolean apply(Object input) {
                return testThing(input);
            }
        }), 5));&lt;/pre&gt;&lt;/noscript&gt;&lt;script src=&quot;https://gist.github.com/mbst-jamie/8e4eedebdf77995a1af3.js&quot;&gt; &lt;/script&gt;&lt;/p&gt;

&lt;p&gt;It&amp;#39;s fairly hard to tell just from glancing at this code what it is actually doing. First it&amp;#39;s transforming a group of Objects into different Objects, then it&amp;#39;s filtering them based on the result of some predicate and then taking the first 5 results. Finally it forces the Iterables.doSomething()s to be evaluated by copying the result into an ImmutableList.&lt;/p&gt;

&lt;p&gt;The main problem for this code&amp;#39;s readability is those pesky anonymous classes for the Predicate &lt;object&gt;and Function&lt;object, object=&quot;&quot;&gt;. The problem could be ameliorated by extracting them into constants or, if that&amp;#39;s not possible static factory methods. However that is just moving the problem elsewhere. There is one line of code in each of those anonymous classes that we actually care about.&lt;/p&gt;

&lt;p&gt;Lambdas and Stream can help things...&lt;/p&gt;

&lt;p&gt;&lt;noscript&gt;&lt;pre&gt;ImmutableList&amp;lt;Object&amp;gt; result = theIterable.stream()
                .map(s -&amp;gt; changeThing(s))
                .filter(s -&amp;gt; testThing(s))
                .limit(5)
                .collect(ImmutableCollectors.toList());&lt;/pre&gt;&lt;/noscript&gt;&lt;script src=&quot;https://gist.github.com/mbst-jamie/55b3c025d63ede096abb.js&quot;&gt; &lt;/script&gt;&lt;/p&gt;

&lt;p&gt;So that&amp;#39;s turned 10 lines of code into 5. However &lt;code&gt;s -&amp;gt; changeThing(s)&lt;/code&gt; this still feels like it could be less verbose, doesn&amp;#39;t it? Stream.map() and filter() expects a Function &lt;t, u=&quot;&quot;&gt;and a Predicate &lt;t&gt;to call respectively, which are both &lt;a href=&quot;https://docs.oracle.com/javase/8/docs/api/java/lang/FunctionalInterface.html&quot;&gt;@FunctionalInterfaces&lt;/a&gt; and expose a single method. In which case, why are we telling Java &lt;em&gt;how&lt;/em&gt; to use something if there is only one way to use it?&lt;/t&gt;&lt;/t,&gt;&lt;/p&gt;

&lt;h3&gt;Method References&lt;/h3&gt;

&lt;p&gt;&lt;noscript&gt;&lt;pre&gt;ImmutableList&amp;lt;Object&amp;gt; result = theIterable.stream()
                .map(this::changeThing)
                .filter(this::testThing)
                .limit(5)
                .collect(ImmutableCollectors.toList());&lt;/pre&gt;&lt;/noscript&gt;&lt;script src=&quot;https://gist.github.com/mbst-jamie/00dba9a956d9d1331eca.js&quot;&gt; &lt;/script&gt;&lt;/p&gt;

&lt;p&gt;Rather than telling the Stream how to use the method, we simply say there exists a method in this class called changeThing and testThing, go use them.&lt;/p&gt;

&lt;p&gt;Some more examples...&lt;/p&gt;

&lt;p&gt;&lt;noscript&gt;&lt;pre&gt;Iterables.transform(theIterable, this::changeThing);
Iterables.filter(theIterable, MyOtherClass::staticMethod);
Iterables.transform(theIterable, MyOtherClass::new);
Iterables.transform(theIterable, thingInstance::instanceMethod);
Multimaps.index(theIterable, keyMapper::getThing);&lt;/pre&gt;&lt;/noscript&gt;&lt;script src=&quot;https://gist.github.com/mbst-jamie/d52d0fc036bde16514a4.js&quot;&gt; &lt;/script&gt;&lt;/p&gt;

&lt;p&gt;This is useful because it means we don&amp;#39;t need to create an anonymous class just to invoke an existing method, we can simply reference it to use it as a lambda expression. In cases where you are using an existing project with Guava that has been upgraded to use Java 8 and you don&amp;#39;t want to mix Iterables and Stream this lets you take advantage of method references to make the code a little less verbose.&lt;/p&gt;

&lt;p&gt;&lt;small&gt;Originally posted on &lt;a href=&quot;https://metabroadcast.com/blog/java-8-method-references&quot;&gt;MetaBroadcast&amp;#39;s blog&lt;/a&gt;.&lt;/small&gt;&lt;/p&gt;
</content>
 </entry>
 
 <entry>
   <title>Hibernate and Postgres FTS</title>
   <link href="/2015/02/04/hibernate-and-postgres-fts/"/>
   <updated>2015-02-04T00:00:00+00:00</updated>
   <id>/2015/02/04/hibernate-and-postgres-fts</id>
   <content type="html">&lt;p&gt;Hello! We have a &lt;a href=&quot;http://www.postgresql.org/&quot;&gt;Postgres&lt;/a&gt; database that we&amp;#39;d like to search over. After much debate, we decided that &lt;a href=&quot;http://blog.lostpropertyhq.com/postgres-full-text-search-is-good-enough/&quot;&gt;Postgres&amp;#39;s full text search is good enough&lt;/a&gt;. Our initial thought was to use our existing &lt;a href=&quot;http://www.elasticsearch.org/&quot;&gt;ElasticSearch&lt;/a&gt; infrastructure and code — however as we are using Postgres — the built in searching &amp;#39;comes for free&amp;#39;.&lt;/p&gt;

&lt;p&gt;The above article will give you more than enough information to use Postgres FTS, what I wish to demonstrate is getting &lt;a href=&quot;http://hibernate.org/&quot;&gt;Hibernate&lt;/a&gt;, your friendly neighbourhood ORM, to play nicely with it.&lt;/p&gt;

&lt;p&gt;The methodology used here was inspired/learned from &lt;a href=&quot;http://java-talks.blogspot.co.uk/2014/04/use-postgresql-full-text-search-with-hql.html&quot;&gt;this article&lt;/a&gt;.&lt;/p&gt;

&lt;p&gt;&lt;noscript&gt;&lt;pre&gt;.put(&amp;quot;hibernate.dialect&amp;quot;, PgFullTextDialect.class.getCanonicalName())&lt;/pre&gt;&lt;/noscript&gt;&lt;script src=&quot;https://gist.github.com/mbst-jamie/d4ca27b9f2c4b51019ff.js&quot;&gt; &lt;/script&gt;&lt;/p&gt;

&lt;p&gt;So obviously Hibernate requires you to assert a dialect of SQL that is compatible with the database it must talk to. Here I am declaring it as &lt;code&gt;PgFullTextDialect&lt;/code&gt;, this is a custom dialect that I have defined as...&lt;/p&gt;

&lt;p&gt;&lt;noscript&gt;&lt;pre&gt;public class  PgFullTextDialect extends PostgreSQLDialect {&lt;/p&gt;
&lt;figure class=&quot;highlight&quot;&gt;&lt;pre&gt;&lt;code class=&quot;language-text&quot; data-lang=&quot;text&quot;&gt;public PgFullTextDialect() {
    registerFunction(&amp;amp;quot;fts&amp;amp;quot;, new PgFullTextFunction());
    registerFunction(&amp;amp;quot;ts_rank&amp;amp;quot;, new StandardSQLFunction(&amp;amp;quot;ts_rank&amp;amp;quot;, DoubleType.INSTANCE);
    registerFunction(&amp;amp;quot;to_tsquery&amp;amp;quot;, new StandardSQLFunction(&amp;amp;quot;to_tsquery&amp;amp;quot;, ObjectType.INSTANCE));
}
&lt;/code&gt;&lt;/pre&gt;&lt;/figure&gt;
&lt;p&gt;}&lt;/pre&gt;&lt;/noscript&gt;&lt;script src=&quot;https://gist.github.com/mbst-jamie/be000457d4df3a786056.js&quot;&gt; &lt;/script&gt;&lt;/p&gt;

&lt;p&gt;This is where we register additional functions on top of those defined in &lt;code&gt;PostgreSQLDialect&lt;/code&gt;, which doesn&amp;#39;t contain the full text functions. If you&amp;#39;ve used PG FTS before, you&amp;#39;ll know of &lt;code&gt;ts_rank&lt;/code&gt; which is used to get a relevance rank for a search result. You&amp;#39;ll also know &lt;code&gt;to_tsquery&lt;/code&gt; which turns a string of text (your query) into an object Postgres can use to search.&lt;/p&gt;

&lt;p&gt;The one you probably don&amp;#39;t recognise is &lt;code&gt;fts&lt;/code&gt;, which is infact not a PG function at all but the name I have assigned to the special Postgres syntax of &lt;code&gt;@@&lt;/code&gt;, used to compare a text vector to a query vector. Hibernate needs to be made aware of this syntax and requires us to declare a new function type, rather than just the name and return type like we did for the previous two. This is defined as...&lt;/p&gt;

&lt;p&gt;&lt;noscript&gt;&lt;pre&gt;public class PgFullTextFunction implements SQLFunction {&lt;/p&gt;
&lt;figure class=&quot;highlight&quot;&gt;&lt;pre&gt;&lt;code class=&quot;language-text&quot; data-lang=&quot;text&quot;&gt;/* Column name of TSVECTOR field in PgSQL table */
public static final String FTS_VECTOR_FIELD = &amp;amp;quot;search_text&amp;amp;quot;;

@Override
public Type getReturnType(Type columnType, Mapping mapping)
        throws QueryException {
    return new BooleanType();
}

@Override
public boolean hasArguments() {
    return true;
}

@Override
public boolean hasParenthesesIfNoArguments() {
    return false;
}

@SuppressWarnings(&amp;amp;quot;rawtypes&amp;amp;quot;)
@Override
public String render(Type type, List args, SessionFactoryImplementor factory) throws QueryException {
    String searchString = (String) args.get(0);
    return FTS_VECTOR_FIELD + &amp;amp;quot; @@ to_tsquery(&amp;amp;quot; + searchString + &amp;amp;quot;)&amp;amp;quot;;
}
&lt;/code&gt;&lt;/pre&gt;&lt;/figure&gt;
&lt;p&gt;}&lt;/pre&gt;&lt;/noscript&gt;&lt;script src=&quot;https://gist.github.com/mbst-jamie/e74b2b8ee0133e5a4069.js&quot;&gt; &lt;/script&gt;&lt;/p&gt;

&lt;p&gt;Here we have implemented the interface &lt;code&gt;SQLFunction&lt;/code&gt;. Like before we declare the return type of the function, we also implement two methods that indicate how Hibernate should handle the method. Crucially however we implement a method that is capable of rendering the function, that is, generating a valid SQL statement given some input. This is where the special syntax &lt;code&gt;@@&lt;/code&gt; is made available to Hibernate.&lt;/p&gt;

&lt;p&gt;Finally, using the JPA &lt;code&gt;CriteriaBuilder&lt;/code&gt;, we can make an FTS query by asserting that the function &lt;code&gt;fts&lt;/code&gt; returns true given a &lt;code&gt;searchString&lt;/code&gt;. Note that in this example the field to be search against is hardcoded and therefore is not specified here.&lt;/p&gt;

&lt;p&gt;&lt;noscript&gt;&lt;pre&gt;@Override public Predicate apply(Root&amp;lt;?&amp;gt; root, CriteriaBuilder cb, String searchString) {
        return cb.isTrue(
                cb.function(
                        &amp;quot;fts&amp;quot;,
                        Boolean.class,
                        cb.literal(searchString)
                )
        );
    }&lt;/pre&gt;&lt;/noscript&gt;&lt;script src=&quot;https://gist.github.com/mbst-jamie/7c332b876f5fa6203d04.js&quot;&gt; &lt;/script&gt;&lt;/p&gt;

&lt;p&gt;Hopefully this has been helpful if you are using JPA and Hibernate with Postgres for the purposes of full text searching. Thanks for reading!&lt;/p&gt;

&lt;p&gt;&lt;small&gt;Originally posted on &lt;a href=&quot;https://metabroadcast.com/blog/hibernate-and-postgres-fts&quot;&gt;MetaBroadcast&amp;#39;s blog&lt;/a&gt;.&lt;/small&gt;&lt;/p&gt;
</content>
 </entry>
 

</feed>
