Tag Archives: Spring

Tomcat, JNDI and Spring bean application configuration

While setting up a Continuous Integration environment recently i faced an issue related to application (REST API in this case) configuration not being deployment-environment independent. Namely as the code pushed to Git repository and picked up by Jenkins build server was later on automatically deployed across several server environments (DEV, INT, STAGING, PROD) it turned out that in each of those environments the API application (war archive deployed in Tomcat container) requires to be fed with a specific/different configuration (environment-specific settings).


This is how i managed to solve this issue:


1. I created the following Tomcat context entry in “conf/context.xml” file:

    <Resource name="config/Api"
        sso="sso.mycompany.com" />


2. Created the “CustomApiJNDIFactory” class:

public class CustomApiJNDIFactory implements ObjectFactory {

    public Object getObjectInstance(Object obj, Name name, Context nameCtx, Hashtable<?,?> environment) throws Exception {

        validateProperty(obj, "Invalid JNDI object reference");

        String scheme = null;
        String host = null;
        String port = null;
        String version = null;
        String sso = null;

        Reference ref = (Reference) obj;

        Enumeration props = ref.getAll();

        while (props.hasMoreElements()) {

            RefAddr addr = props.nextElement();
            String propName = addr.getType();
            String propValue = (String) addr.getContent();

            switch (propName) {
                case "scheme":
                    scheme = propValue;
                case "host":
                    host = propValue;
                case "port":
                    port = propValue;
                case "version":
                    version = propValue;
                case "sso":
                    sso = propValue;


        // validate properties
        validateProperty(scheme, "Invalid or empty scheme type");
        validateProperty(host, "Invalid or empty server host name");
        validateProperty(port, "Invalid or empty port number");
        validateProperty(version, "Invalid or empty API version number");
        validateProperty(sso, "Invalid or empty SSO server name");

        //create API Configuration Bean
        return new ApiConfigBean(scheme, host, port, version, sso);


     * Validate internal String properties
     * @param property the property
     * @param errorMessage the error message
     * @throws javax.naming.NamingException
    private void validateProperty(String property, String errorMessage) throws NamingException {

        if (property == null || property.trim().equals("")) {
            throw new NamingException(errorMessage);




3. Defined an jndi-lookup entry in my “spring-api-context.xml” file that will read Tomcat JNDI configuration entry and expose it as a Spring bean of name jndiApi:

<jee:jndi-lookup id="jndiApi" jndi-name="java:/comp/env/config/Api" expected-type="com.mycompany.model.ApiConfigBean" />


4. Created the “jndiApi” Spring bean backing pojo

public class ApiConfigBean {

    private String scheme;
    private String host;
    private String port;
    private String version;
    private String sso;

    public ApiConfigBean(String scheme, String host, String port, String version, String sso) {
        this.scheme = scheme;
        this.host = host;
        this.port = port;
        this.version = version;
        this.sso = sso;

    // getters and setters ommited.



5. and finally wired-in the bean to my classes where i needed to make use of the “externalized” configuration:

private ApiConfigBean apiConfigBean;

    public void foo() {

        String host = apiConfigBean.getHost();




That’s it! Have a wonderful day! 🙂

Spring localized exception handling in REST API

In today’s post i’ll share with you the way we’re handling Internationalization (i18n) and Localization (L10n) in our REST API which is based on Spring MVC (3.2.3.RELEASE).

Our front-end web client is an SPA (Single Page Application) built using AngularJS framework and occasionally it needs to handle Java exceptions messages thrown by the back-end. The way it has been implemented is that it intercepts JSON error responses, wraps them in a pre-defined web page template and displays to the user in a unified and nice way.

“Localization” of back-end related error messages happens …at the back-end level.


After this quick intro let’s get familiar with following two definitions:

  • Internationalization – process of designing software applications so that they can be adapted to various languages and regions without engineering changes.
  • Localization – process of adapting internationalized applications for a specific region or language by adding locale-specific components and translating text.

OK, this is how message bundles look like:

// messages.properties
exception.npe=Unrecognized error: We're sorry.

and the project view so you get a feel on how maven-managed multi-module project is structured (i use IntelliJ IDEA)



The ‘resourceBundle’ spring bean is located in ‘spring-locale-context.xml’

<bean id="resourceBundle"
      p:defaultEncoding="UTF-8" />


As you can see i’m using ‘ReloadableResourceBundleMessageSource‘ which i prefer over ‘ResourceBundleMessageSource‘ – here’s why (according to Spring framework spec.)

  • ResourceBundleMessageSource – MessageSource implementation that accesses resource bundles using specified basenames. This class relies on the underlying JDK’s ResourceBundle implementation, in combination with the JDK’s standard message parsing provided by MessageFormat. This MessageSource caches both the accessed ResourceBundle instances and the generated MessageFormats for each message. It also implements rendering of no-arg messages without MessageFormat, as supported by the AbstractMessageSource base class. The caching provided by this MessageSource is significantly faster than the built-in caching of the java.util.ResourceBundle class. Unfortunately, java.util.ResourceBundle caches loaded bundles forever: Reloading a bundle during VM execution is not possible. As this MessageSource relies on ResourceBundle, it faces the same limitation. Consider ReloadableResourceBundleMessageSource for an alternative that is capable of refreshing the underlying bundle files.
  • ReloadableResourceBundleMessageSource – Spring-specific MessageSource implementation that accesses resource bundles using specified basenames, participating in the Spring ApplicationContext‘s resource loading. In contrast to the JDK-based ResourceBundleMessageSource, this class uses Properties instances as its custom data structure for messages, loading them via a PropertiesPersister strategy from Spring Resource handles. This strategy is not only capable of reloading files based on timestamp changes, but also of loading properties files with a specific character encoding. It will detect XML property files as well. In contrast to ResourceBundleMessageSource, this class supports reloading of properties files through the "cacheSeconds" setting, and also through programmatically clearing the properties cache. Since application servers typically cache all files loaded from the classpath, it is necessary to store resources somewhere else (for example, in the “WEB-INF” directory of a web app). Otherwise changes of files in the classpath will not be reflected in the application. This MessageSource implementation is usually slightly faster than ResourceBundleMessageSource, which builds on ResourceBundle – in the default mode, i.e. when caching forever. With “cacheSeconds” set to 1, message lookup takes about twice as long – with the benefit that changes in individual properties files are detected with a maximum delay of 1 second. Higher “cacheSeconds” values usually do not make a significant difference.


Now, let’s make our resourceBundle accessible to exception handlers:

public class AbstractExceptionHandler {

    private ReloadableResourceBundleMessageSource resourceBundle;

    public ReloadableResourceBundleMessageSource getResourceBundle() {
        return resourceBundle;

    public void setResourceBundle(ReloadableResourceBundleMessageSource resourceBundle) {
        this.resourceBundle = resourceBundle;



Create an MVC REST Controller:

@RequestMapping(value = "/users")
public class UserController {

    private UserService service;

     * Handling GET request to retrieve all {@link User}'s
     * @return Collection<User> a collection of users
    @RequestMapping(method = RequestMethod.GET)
    public @ResponseBody
    Collection<User> getUsers() {
        return service.findAllUsers();



…and an exception handler that will intercept (NPE in this case) exceptions thrown by the controller:

public class BusinessExceptionHandler extends AbstractExceptionHandler {

    @ResponseStatus(value = HttpStatus.INTERNAL_SERVER_ERROR)
    @ResponseBody DefaultErrorMessage handleNullPointerException() {

        String error = getResourceBundle().getMessage("exception.npe", null, Locale.getDefault());

        return new DefaultErrorMessage("RS00230", "SYSTEM_ERROR", error);




As you can see above, I did two things:

  • fed the error string with exception.npe message that comes from the message bundle and used Locale.getDefault()
  • and defined a custom DefaultErrorMessage which basically is a POJO send over to the client as a JSON response which looks like this:
  "code" : "RS00230",
  "status" : "SYSTEM_ERROR",
  "errors" : [ "Unrecognized error: We're sorry." ]


Hope you find this brief example helpful. Cheers!




Disabling SSL Certificate Validation

Recently i came across two SSL-related exceptions when writing a testing Spring-based client application using RestTemplate. Because both of them are related to an untrusted connection when making HTTPS calls (as a result of self-signed SSL certificate configured in Tomcat), and both have one common solution, i thought i’ll share it with You.


Exceptions thrown:

  • java.security.cert.CertificateException: No name matching my.company.com found; nested exception is javax.net.ssl.SSLHandshakeException
  • sun.security.validator.ValidatorException: PKIX path building failed: sun.security.provider.certpath.SunCertPathBuilderException: unable to find valid certification path to requested target


  • disabling SSL certificate validation (unless you want to go the “hard way” of installing a correct/SSL Authority-signed certificate)
  • This is how i did it in Java:


import javax.net.ssl.*;
import java.security.cert.CertificateException;
import java.security.cert.X509Certificate;

public class SSLCertificateValidation {

    public static void disable() {
        try {
            SSLContext sslc = SSLContext.getInstance("TLS");
            TrustManager[] trustManagerArray = { new NullX509TrustManager() };
            sslc.init(null, trustManagerArray, null);
            HttpsURLConnection.setDefaultHostnameVerifier(new NullHostnameVerifier());
        } catch(Exception e) {

    private static class NullX509TrustManager implements X509TrustManager {
        public void checkClientTrusted(X509Certificate[] chain, String authType) throws CertificateException {
        public void checkServerTrusted(X509Certificate[] chain, String authType) throws CertificateException {
        public X509Certificate[] getAcceptedIssuers() {
            return new X509Certificate[0];

    private static class NullHostnameVerifier implements HostnameVerifier {
        public boolean verify(String hostname, SSLSession session) {
            return true;


The complete example is available as a Gist.


What you now have to do, is to invoke SSLCertificateValidation.disable() prior to making a HTTPS call using RestClient. Simple as that.