Simple Guava ForwardingCache I use when developing value loaders

Guava caches are great, but developing with them can be troublesome.

One solution is wrapping the underlying cache using a simple implementation of the ForwardingCache class:

Instead of using a Cache directly from a CacheBuilder, you can wrap it with this class and toggle debug mode.

Note: if you’re using a LoadingCache, you’ll want to derive from the ForwardingLoadingCache instead and override the get(K key) and getAll(Iterable<? extends K> keys) methods as well.

Helpful utility for searching a Java exception chain for a particular exception type

Sometimes I want to search a chain of exceptions (caught->cause1->cause2…) for an exception of a particular type. This isn’t a difficult problem, but having a simple utility makes it easier:

It’s pretty easy to use:

How to silence ANTLR4’s error messages

By default a org.antlr.v4.runtime.Parser instance, as a subclass of org.antlr.v4.runtime.Recognizer, will have a org.antlr.v4.runtime.ConsoleErrorListener attached to it. Error messages will be piped through this listener and out to System.err, where they will be lost forever.

You can silence this output by calling removeErrorListeners() before parsing, and if you want to capture the error messages for parsing and display, you can add a custom BaseErrorListener implementation.

Here’s a simple one that keeps every error in a List:

You would add it to a Parser using the addErrorListener method.

Here’s a complete example:

Suppressing Tomcat error messages for all applications on a host

Sometimes I write web applications for Tomcat where I don’t want to report any errors beyond the HTTP status code. The quickest method for disabling those messages is configuring a Valve on the host section of the server.xml configuration file.

If you subclass the org.apache.catalina.valves.ErrorReportValve class (it’s in your Tomcat’s lib/catalina.jar) and override the report method like this:

The client still receives the HTTP status code and anything already buffered, but it hides all of the automatically generated Tomcat error information.

To install it, just JAR up the class and put it in your Tomcat’s lib folder, then add the errorReportValveClass attribute to your Tomcat’s server.xml file.