vendredi 23 février 2018

Property file based builder pattern in java

I have a property file which has the details of Elasticsearch hostname, port number, and the scheme.

The Elasticsearch RestCleint API provides constructors to instantiate a client object with the hostname and also with hostname, port number and scheme.

There are cases when an application is deployed to AWS it has only a URL which can be used as the hostname. The same application, when deployed in the different environment, will have all 3 properties.

Therefore, I have created a class which does some if else and tried to instantiate the RestClient basing on the availability. The code looks very ugly. I want to use a Builder kind of Pattern which handles this elegantly. But, I am unable to get an idea to implement it. I would like to request a help.

This is how my current implementation looks like.

public class ElasticSearchContext {

    private RestClient restClient;

    public RestClient getContext() throws Exception {

        if (PropertyFileReader.getInstance().containsKey("elasticsearchHostName")
                && PropertyFileReader.getInstance().containsKey("elasticsearchPortNumber")
                && PropertyFileReader.getInstance().containsKey("elasticsearchScheme")) {

            restClient = RestClient
                    .builder(new HttpHost(PropertyFileReader.getInstance().getProperty("elasticsearchHostName"),
                            Integer.parseInt(PropertyFileReader.getInstance().getProperty("elasticsearchPortNumber")),
                            PropertyFileReader.getInstance().getProperty("elasticsearchScheme")))
                    .build();

        } else if (PropertyFileReader.getInstance().containsKey("elasticsearchHostName")
                && !PropertyFileReader.getInstance().containsKey("elasticsearchPortNumber")
                || PropertyFileReader.getInstance().containsKey("elasticsearchScheme")) {
            restClient = RestClient
                    .builder(new HttpHost(PropertyFileReader.getInstance().getProperty("elasticsearchHostName")))
                    .build();
        } else {
            throw new Exception("Hostname is mandatory");
        }

        return restClient;

    }

}

This is how my properties look like.

elasticsearchHostName=localhost
elasticsearchPortNumber=9200
elasticsearchScheme=http

Aucun commentaire:

Enregistrer un commentaire