Monitoring with Metrics
Metrics is a minimal library for various server monitoring metrics, and easy reporting. Supported metrics include rate meters; instant gauges; counters; histograms; timers. Furthermore, various reporting formatting is included. See their Getting started page for more details.
It’s available on Maven Central, so the following Gradle config will include the latest 3.1.0 version.
The simplified tests in the code below will output this report.
Some metrics examples:
Identity Map Collector Helpers
When generating a Map, the basis is very often a list of unique elements (i.e. a Set), and often the original elements take part in the new Map, either as keys or values. When the original elements are keys, we might be talking about a cache, where the key is the pointer and the value is the result of some expensive operation. E.g. the key is a filename and the value is the bytes of the file loaded into memory for fast serving. Conversely, when the original elements are values of the new map, we’re often dealing with a look-up table, e.g. from an ID to its User object, or as in the previous article from a short-form string to a specific class reference.
Streams iterating over collections, and lambda functions take some of the dull boilerplate out of creating these kind of maps. However, some of the helper classes, like Collectors, come with rather long method names. To take away even these parts, here are a few helper methods for the identity maps. They come in two forms: One which returns a Collector which can be used in the collect() method of the Stream. Typically, this is useful if other operations, like filtering, is also used. The other helper methods operate directly on the Collection, and take only the mapping function for keys or values. See the full file for further examples and documentation below.
The full code listing, with examples and documentation. This code is under GPL3.
Object construction through reflection
In the last post I ranted about dependency injection framework magic, but even custom magic can cause problems. When objects are constructed and invoked through reflection, the execution flow is no longer apparent in the code. Yet, it still has its place in certain applications, typically mapping external input to object instances, be it language parsing or lexing, or DB output to object mapping. But how to best balance between the abstract world of reflected classes and concrete type-safe code?
The key lies in simplicity, and imposing certain constrains. Dynamically resolving classes and recursive reflective construction of a full object a hierarchy is probably not a good idea. Furthermore, as discussed previously, Java 8 method references now makes it cleaner to pass in factory methods, and avoid the Factory Factory Factory trap.
The following snippet shows the reflective construction of an object, given a few constraints: First off, the name of the input token can be mapped to typed classes. In this example that is done with a generated String to Class map, based on the concrete class references we’re dealing with. They have to be available at compile time, and at the time of writing the code. The advantage is that we avoid the Class.forName() look-up, and the package hierarchy confusion and possible mismatch of tokens and classes. If this is too strict, we can modify the map, e.g. by allowing for case-insensitive matching (by converting both map key and look-up to the same case). Or if there is not a literal mapping, an enum could define the relationship. Either way, the idea is that the code make it clear which classes we plan to deal with, in strongly typed manner.
The next assumption in this example is that the class to be created has only one constructor method, and that it is public. Or if that is not feasible, the constructor to be used could be marked with an Annotation. Just don’t go full-on Guice, and you’ll be fine.
Finally, we assume that the relevant constructor takes zero or more parameters, and if it does have parameters that they can themselves we represented and created from a single String object. These parameter objects are initialized in a helper method, discussed below.
The construction of the parameter classes also contains several assumptions and restrictions. As with the first order classes, we limit ourselves to a pre-defined set of classes. This make it possible to define which constructor or factory methods should be used. In this example, the constructor which takes a single String is used, except for the Password class, where a factory method is used, again taking a single String.
That is all it takes to construct objects through reflection, including its parameter types. The examples above maintain some type-safety, and also restricts the supported types. Finally, some error handling and messaging is in place, and more could be added to make it very clear which classes and input is allowed.
The full code listing below shows the example classes to be constructed and test code to verify them.
WebSocket Chat example with the SimpleFramework API
As mentioned in the previous post, the SimpleFramework API and server is a minimal alternative in the world of Java application servers like Glassfish, Tomcat. Hosted on GitHub under an Apache v2.0 license, they offer an embeddable HTTP, Servlet and WebSocket capable stack and API. They claim their performance is better than other Java based web servers.
The Dependency Injection Framework Trap
Whether they live up to their name, and is truly easy and simple to use is somewhat debatable, though. They favour Spring for dependency injection, which means part of the code is specified in XML, and is “magically” coupled during runtime. There might be benefits to that, but the downside is that it becomes difficult to read and debug. In fact, their demo application will not start for whatever reason, and all that is offered in terms of output is an InvalidArgumentException without further details deep down from the Spring code.
Don’t get me wrong, the Google Guice framework is not much better. It might specify its module coupling in Java code instead of XML, however, when it comes to following the code and debugging, it is just as obscure. Implementations tend to be hidden behind layers of interfaces. As for the promise of easily re-wireable code, they both fall short. When it comes down to it, a refactoring will typically involve changes in both class content and class relationships, so a dependency injection framework is more likely to get in the way than help.
Finally, when it comes to testability, dependency injection is of course crucial. Being able to inject mocks or other testing objects keeps unit tests small. However, a wiring framework is not needed to describe the class relationships. In fact, my personal experience is that Guice based code is more cumbersome to use in test related code. It takes considerable effort to track down which classes to include in a unit test, and which to leave out, and then to create a test module of it all. At least Spring leaves the class constructors intact and simple.
Making it work
So, with that rant out of the way, what does it take to make the Simple Framework WebSocket Chat Demo work? My solution was to simply shortcut the 114 line XML Spring configuration, and write the same class relations in Java. The following 20 lines achieves the same as the XML.
Furthermore, it’s worth noting that the SimpleFramework is structured in multiple Maven projects, with dependencies between each other, as seen below the code snippet. It highlights another potential problem with the project. A lot of the server code required to make the Chat demo run is in another demo package. It suggest quite a lot of custom code has to be written to use the server API.
The GitHub Maven packages and dependencies at the time of writing:
simple (core code)
simple-test (unit tests) -> “simple”
simple-demo (common demo code) -> “simple”
simple-demo-chat -> “simple”, “simple-demo”
simple-demo-graph -> “simple”, “simple-demo”
simple-demo-rest -> “simple”, “simple-demo”, “simple-demo-chat”
It is not entirely clear whether the last demo example, “simple-demo-rest”, depends on the “simple-chat” project as the XML suggests, or whether the duplicate ChatRoom class was intended to be used. It might be that the XML was copied, but not updated - highlighting the previous point about hard to maintain and read dependency injection code.
Focusing only on the “simple-demo-chat” example then, this would be what it could look like in the Eclipse Package Explorer, with each directory created as a separate Java project.
Finally, here’s the full main-file hack to make the chat example work. Notice the required helper classes from demo packages.
A failed attempt at a WebSocket server
Following the post about the small HTTP server using the the com.sun.net.httpserver API, I thought I’d try to make it work with WebSockets. I’ll save the suspense; it wont work. And I’m not the first to have failed at it, but it’s always more fun to search for the solution afterwards..
The problem is that the httpserver package is not designed for the persistent bi-directional connection used by the WebSocket protocol. The only part which will work is the handshake, which transmits a HTTP like request and response. However, as soon as that response is sent, the connection is closed, and thus the WebSocket object in the browser client will close.
There is a WebSocket API in Java EE, however it will require an application server like Glassfish or Tomcat to run. Another option is the SimpleFramework server, which also includes a WebSocket implementation. More about that in a later post.
The only part of the code worth mentioning here is the handshake response from the server. It sets the correct headers and encodes the server accept key according to the specification. Connecting to this server will therefore result in a valid websocket object on the client, as long as handle() method on the server does not return.
Hello World with JavaFx
JavaFx is a comprehensive platform and set of APIs to develop desktop, web and even mobile applications. Although intended to replace the Swing GUI API, it can get significantly more complex, with FXML for XML based object specification; CSS styling; and special IDE tool chains.
Since JDK 8, it is supposedly included in the main install, however, on Debian I had to install it separately:
The Oracle documentation and tutorial is detailed and well written, so I will not go into further detail here. The following is a simple Hello World app.
Terminal and ncurses Java libraries
There’s a few Java libraries for creating terminal and ncurses like applications. They abstract away the ANSI escape codes and low level control like tput. I’ve briefly looked at three of them: Lanterna, Charva and JCurses. They all come with basic terminal control, and some widgets and window managing to create terminal based GUI applications.
JCurses seems to be the oldest, and possibly unmaintained. It requires ncurses to be installed, and also a native library. It is available through the Maven Central repository, however, make sure to set up the path for access to the libjcurses.so (in the tar-ball from SourceForge, or within the .jar from Maven). Documentation is sparse, but it seems it’s possible to interface with the terminal with little code.
Charva is also ncurses based and requires a native lib. One of it’s selling points is that it can act as a drop-in replacement for java.awt UIs. It seems unlikely that that will work well for all but the simplest UIs, however, at least it offers an easy transition path.
Finally, Lanterna seems to be the best maintained, and clearly documented project of the three. It is unique in that is handles all terminal details itself, and does not require external libraries. It is compatible with Linux, Windows, Cygwin, OS X terminals. Furthermore, if launched from an X or similar GUI based environment instead of a terminal, it will create its own GUI window into which it will render the terminal. Neat.
The drawback with Lanterna is its rather verbose and involved API. For “serious” apps, maybe that’s OK, but for simple positioning of the cursor, it can get a bit too much. The follow renders a text label with a border:
Lanterna is available through Maven Central, so the following gradle.build lines will do.
Here’s the full test example, including a main-method to easily run it stand-alone from the terminal.
A simple HTTP server
The unofficial com.sun packages which is still part of the main JDK, include a few convenience classes for running a HTTP server. However, since these are not part of the official API, there’s typically a warning in the IDEs not to use them. The annotation @SuppressWarnings(“restriction”) can also be used to ignore this warning. Besides that, they will work fine.
Here’s what it takes to start the server on a given port, and serve static files from a specific directory tree:
The second argument to the create() method, which is currently 0, is the number of queued incoming queries. Setting a higher number here will allow the server to handle more parallel incoming requests, however potentially at the expense of overall throughput.
The start() is non-blocking, so a typically server application would have to go into an internal loop.
As for the handler, it listens to requests where the path of the URI starts with the specified string, in this case “/static”. It can then use the request URI to map this to hard-coded files, or files with the same name as in this example:
Finally, to test the running server, here’s two unit tests. The first downloads a file which exists, and prints its lines. The second requests a file which does not exist. Notice that the 404 return code passed from sendResponseHeaders() in the handler, is enough to make the openStream() call throw a FileNotFoundException on the client side.
Here’s the main class:
And here’s the Handler for static files: