Sunday, March 31, 2013

Programming Puzzle: The Clock Angle Problem



I came across an interesting programming puzzle the other day that I hadn’t seen before. It’s called the Clock Angle Problem. In a nutshell: Given a time of day, what is the smallest angle between the hands on an analog clock showing that time? What about the angle for the current time, whatever that time is? While there is an analytic solution, the problem provides a tidy little puzzle for programmers to solve programmatically.

So I did the obvious thing: coded up a solution and posted it to Github. The trick is to convert hours and seconds to the same units so you can find the difference. You can compute the difference in degrees (in this sample the values are also precomputed). You can also normalize their values first.

Let’s take this question a step further and ask: How would we unit test all of this? (again, test code is on Github) If we have a method for finding the angle given the current time, any unit test require separation of obtaining and parsing the current time from the actual clock angle algorithm. Once that’s done, a parameterized unit test fits the bill nicely for the algorithm and we can spot check some known values.

We can write another test for parsing the hour and minute from a Date. The trickiest part to test is obtaining the current Date, since time-based unit tests require a little special handling. We need to encapsulate the production of the current Date (say, in a DateProvider class, or in an overridable factory method on the Clock) in such a way that we can override it in the test to provide a constant Date for unit testing. Then the one-liner that provides the current Date can easily be unit tested: test that it is the same as a new Date() constructed in the unit test (within a certain tolerance, say 100ms).

We can still do more with this question. What if the hour and minute hands ticked for every millisecond and we wanted millisecond-level accuracy? Would rounding errors be a concern, and if so, how would we mitigate that? If the calculation was really expensive, how could we implement caching? (Hint: Not WeakHashMap) I’m not answering these questions here, but they are left as an exercise for the reader (or for myself for a future blog post).

Sunday, March 24, 2013

Pros and Cons of Google Web Toolkit, Part 2


Last time we talked about Google Web Toolkit (GWT) and reviewed the advantages. Here we’ll look at some of the disadvantages and see when you might not want to use it.


(Side Note: This blog post is just about my own personal experience. Recently Vaadin put out a very nice set of infographics about GWT which covers a more statistically significant view of the strengths and weaknesses of GWT since it surveyed many GWT developers.)


The primary disadvantage in my view is compile time. Granted: many people are building large applications with GWT and large applications take a long time to build no matter what language you’re using. But the fact remains that even small to medium sized projects take far longer to compile than you would expect for something of that scale.


GWT also has a lack of good UI components. Generally we need to write all of our widgets from scratch and spend a lot of time on styling, as opposed to choosing a full featured widget library and theming it. Granted: this is by design, GWT does not pretend that it is there to provide a strong set of UI components. But it would be nice to have more components built in than it does, since it already provides everything else for you to structure your entire application. Additionally, the widgets it does have generate a lot of (needless to say, non-semantic) markup, complicating your CSS. How many times have I worked with a UI designer who cursed the markup that GWT was generating!


One of the strengths I mentioned before is also a weakness: Coding in Java.
  • More Code: There is simply more code to write in Java than there would be in Javascript. Strong typing gives you compile time type checking at the expense of much more code where types are close but not the same and cannot be inherited. Additionally, programming for the web requires something much more like callback-oriented programming, and Java is not designed for that. Things that would be a one or two-liner in Javascript can take 5 or 10 lines in Java.
  • Unit Testing: GWT tantalizingly provides a  GWTTestCase for unit testing UI classes. However, any test that runs based on this class is going to be agonizingly slow - increasing the pain of build times and destroying the possibility of having fast unit tests.
  • Finally, the strength of making front end development accessible to back end developers actually comes at the expense of excluding the majority of front end developers in the world. Most front end developers will be fluent in JS/CSS/HTML but not GWT and Java.

The only other disadvantages I’ve noticed are miscellaneous but worth mentioning.
  • There is sometimes a difference between “compiled” mode and “dev” mode. This is very very rare (it happens to me maybe once per year), but when it does happen it is next to impossible to debug.
  • Can’t debug network traffic: If you are using GWT-RPC or GWT-Dispatch, the network traffic is encoded and impossible to manually inspect. While developing this is not a problem since you can set a debugging breakpoint just before objects get marshalled or unmarshalled. But in a production environment, it will be impossible to troubleshoot a problem by looking at the network traffic (say, to see what data the productionserver thinks it’s getting). This can be alleviated by using RequestBuilder and  overlay types to call JSON REST services, although this is more work.
  • Given that many services are allowing multiple application clients (like what happened with Twitter) and that growth of mobile devices is outpacing growth of desktop computers, there is a disadvantage to requiring one language or framework for a front end application to interact with your services. If you use GWT-RPC or GWT-Dispatch, you can’t easily write mobile apps for your service - and neither can anybody else. The client would have to be a GWT client capable of making GWT calls. Again, this can be alleviated by using RequestBuilder and  overlay types to call JSON REST services, although this is more work.


So: when should you not use GWT?
  • You have front end developers who are already fluent in JS/CSS/HTML
  • You are planning on allowing third party development of applications for your services
  • You are planning on writing native mobile applications for your services
  • You don’t have enough money to buy extremely powerful build servers to compile your GWT code (Just Kidding! Or am I ?!?)

Sunday, March 17, 2013

Pros and Cons of Google Web Toolkit, Part I

I’ve been using Google Web Toolkit (GWT) off and on for the last 4 years (nonstop for the last 2), and was going over my experiences with a friend recently. GWT transpiles Java code into Javascript, allowing you to effectively write Java for the browser. There are some definite pros and cons to this approach, here are some of my own thoughts on the subject.

[EDIT This blog post is just about my own personal experience. Recently Vaadin put out a very nice set of infographics about GWT which covers a more statistically significant view of the strengths and weaknesses of GWT since it surveyed many GWT developers.]
 
In this post we’ll review the advantages. The advantage of GWT falls into two main categories: the fact that you’re using Java, and the capabilities of the framework itself. Let’s start with the first of these.

Because the front-end code is written in Java, you can leverage the ecosystem’s very mature IDEs such as Eclipse and Netbeans. You can use the same IDE to develop the front end and the back end, providing a seamless end-to-end development experience. The same is true for debugging - the debugger steps from front end to back end and you never have to leave your IDE. Other big advantages of using a mature IDE include refactoring support, functionality to find usages, and other code navigation.

You can leverage language features not available in Javascript directly, like a built in module system (Java’s packages). For large projects, it is easier to use modules to manage one million lines of Java than one million lines of Javascript. Support for unit testing in Java has been first class for many years with JUnit and TestNG. Javascript does have unit testing capability (say, with Jasmine), but I don’t have the impression that unit testing in Javascript is as widespread or easy as it is with Java.

Finally for the “you’re using Java” aspect: you can leverage Java developers. For a small software shop that doesn’t have the resources or needs for a pure front end development team, it makes a lot of sense to make use of the skills your developers already have. I have seen several workplaces where this was the case, and it has generally worked out pretty well, making efficient use of existing development resources.

The other advantage of GWT lies in the capabilities of the framework itself. GWT as a framework doesn’t do anything that you can’t do with the right combination of other Javascript libraries. But as an AJAX framework, GWT pulls together a cohesive set of functionality for building a RIA and gives it to you out of the box. For example: AJAX handling (actually multiple communication techniques: GWT-RPC, RequestFactory, and direct HTTP requests), history and place management, templating system with UI binder, form binding, and internationalization.

In conclusion, GWT is a mature and proven product, it is still being actively maintained and used, and it provides a lot of advantages to the software shop where it’s a good fit (say, a small team of Java developers who don’t have front end developers). As for whether or not GWT is always a good choice: As usual, it depends. In the next segment we’ll look at some of the disadvantages and see when you might not want to use it.

Sunday, March 10, 2013

Setting up HTTPS with CA certificates on Tomcat

There’s no doubt that every website needs to consider security. And serving critical portions of your site over HTTPS instead of HTTP is an important first step to securing your site.

There are any number of tutorials for setting up SSL on Tomcat. Many of us have generated our own keys and self-signed certificates at some point for side projects and personal development, that part is easy. But when you are ready to take your site public and a browser finds a self-signed certificate and it’s not from a certificate authority (CA), the browser will display all kinds of scary warnings about your site being unknown and potentially dangerous (which objectively it is at that point).

To resolve this, you need to get a certificate from an actual CA. They will verify your identity and send you a certificate that you can use with your site, and your site will become part of the CA’s - and hopefully the web’s - circle of trust.

Some CA’s that provide inexpensive certificates include Thawte, Digicert, and GeoTrust. To get a certificate from a CA, you generate a private key and use it to create a Certificate Signing Request (CSR). Send the CSR to the CA, and they will send you back a certificate that is registered with them that you can use on your site.

Ok here are the steps to setting up HTTPS with CA certificates on Tomcat. If nothing else, take note of step 7 - it’s the hardest step to figure out if you don’t have these directions.

  1. You’ll need the password for your java keystore, or you’ll need to create a new java keystore. If you don’t know it you can always create a new keystore and point tomcat to that. A keystore is just a single file with keys and certificates inside it. Don’t be afraid to experiment, if you create a key in your keystore that you don’t want, you can just delete that key. And since a keystore is just a single file, you can always back it up, restore it, start over, etc. If you forget information about your keystore (such as its password), and tomcat was already configured with it, you can just review the keystore information in tomcat’s server.xml file to recover that information.
    1. list the contents of my keystore: keytool -storepass password -list -keystore keystore.jks
    2. you can always delete a key if you mess something up: keytool -storepass password -delete -alias tomcat -keystore keystore.jks
  2. Read up on the documentation to make sure you understand what goes where. You can start with the Tomcat documentation.
  3. Use openssl to generate a certificate signing request (CSR). This creates a .csr and a .key, the .csr is what you send to your CA and they will return a .crt that corresponds to your private key.
  4. Keep the .key file, and send the .csr to your CA. The CA accepts the CSR and sends back possibly multiple .crt files (a root certificate, possibly some intermediates, and the one for your site).
  5. Create a new keystore if you don’t have one already (see step 1). Creating a new keystore is easy with these handy notes. You can create a keystore with a single dummy key and delete that key later if you want.
  6. You can import all of the certs from the CA into your keystore using the java keytool. The command looks something like this: keytool -storepass password -import -trustcacerts -alias intermediate_cert_name -file intermediate_file.crt -keystore keystore.jks
  7. Here is the tricky part: You also need to import the private key (the .key file created at the same time as the .csr) into the keystore. This is the tricky part because the Java Keytool does not natively import the .key file, and you need to use two steps.
    1. Use openssl to convert the key along with the .crt for your site (the .crt for your site that you got from theCA) into a .p12 file (technically another keystore) that the java keytool can import. The command looks something like this: openssl pkcs12 -export -in www_mycoolsite_com.crt -inkey  mygeneratedkey.key -out www_mycoolsite_com.p12 -name "www_mycoolsite_com_private_key"
    2. Import the .p12 file as a keystore into your keystore. The command looks something like this: keytool  -storepass password -importkeystore -srckeystore www_give3_org.p12 -srcstoretype PKCS12 -destkeystore keystore.jks
  8. Configure tomcat’s server.xml to use the https connector, you will need to modify the port, keystore file location, and keystore password. There are plenty examples of how this is done  online.
  9. Finally, configure the app to serve the site on HTTPS. This is done in web.xml
  10. If the certificate is only good for “www.yourdomain.com” rather than “*.yourdomain.com”, you can test the certificate locally by editing your /etc/hosts file so the site corresponding to the site certificate actually goes to the local machine. Add a line like “127.0.0.1    www.yourdomain.com

And there you have it! Enjoy serving your site with HTTPS, and don’t neglect all the other aspects of security that need to be addresses for your public-facing site.


Sunday, March 3, 2013

Strong Type Weak Type


I was playing around with handlebars the other day, and I got to a point where the json object going into my handlebars template had a date (number) that I wanted to convert and format into a date string.

I quickly ran through a few thoughts: Can I execute javascript inside the handlebars template? Nope. Can I use a JSP Scriptlet? No this is on the browser. Do I need to define a new string field on my domain object on the server just so the json comes through in a way that I can display what I want in the UI? Ugh, besides requiring a change to my domain model and recompiling, that is mixing up my server side code with my display which is not what I want.

Waaaait a second...

Javascript objects are dynamically typed! I can just format the date and add the string as a new property to the object in javascript before passing the object to my handlebars template, and reference that new property from inside the template. Problem: solved.

Ok, this sounds like a trivial exercise for anybody who has ever coded in a dynamically typed language. It even sounds trivial to me. But even after having read some javascript books (including Javascript the Good Parts... a few times), and writing and practicing javascript on the side, years of programming in Java have oriented my brain to a certain way of thinking. That way of thinking at a fundamental level includes the idea of redefining a class and recompiling if I want to add an attribute to an object.

The new ways of dynamic typing DO come. But they do not come first. That is the experience of a strongly typed programmer moving into a weakly typed language.