0

I have a rest end point that takes the urls with the following 3 parameters as valid: regno, hostid, location regno, domid, location regno, provider

Anything other than these combinations are invalid. I have a validator method that checks this

if (!StringUtils.isEmpty(criteria.getRegno())) {
if ((!StringUtils.isEmpty(criteria.getHostid()) || !StringUtils.isEmpty(criteria.getDomId())) && !StringUtils.isEmpty(criteria.getLocation())) {
criteria.setSearchType(GET_HOST_SEARCH_TYPE);
} else if (!StringUtils.isEmpty(criteria.getProvider()) && (StringUtils.isEmpty(criteria.getLocation()) && StringUtils.isEmpty(criteria.getHostid) && StringUtils.isEmpty(criteria.getDomId()))) {
criteria.setSearchType(GET_PROVIDER_SEARCH_TYPE);
} else {
throw new BadRequestException("Either Provider, Location, Hostid or domid is missing");
}
} else {
throw new BadRequestException("Regno is missing");
}

I dont like the fact that I am using a lot of if else statements. If there is a better readable way of doing this please feel free to help.

Raskill
  • 175
  • 13

1 Answers1

1

You may try the following approach, it will reduce the need of if else drastically..

    public String detectSearchType(String url) throws BadRequestException{
        final String condition1 = "(?=.*location)(?=.*(?:hostid|domid))";
        final String condition2 = "(?=.*provider)(?!.*hostid)(?!.*domid)(?!.*location)";

        if(!url.contains("regno="))
            throw new BadRequestException("Regno is missing");
        else if(Pattern.compile(condition1).matcher(url).find())
            return "GET_HOST_SEARCH_TYPE";
        else if(Pattern.compile(condition2).matcher(url).find())
            return "GET_PROVIDER_SEARCH_TYPE";
        else 
            throw new BadRequestException("Either Provider, Location, Hostid or domid is missing");

    }

You need to pass the url strings to this method. such as the following:

detectSearchType("localhost/search?location=india&regno=12532&hostid=gdy-101");
detectSearchType("localhost/search?location=india&regno=12532&domid=gdy-101");
detectSearchType("localhost/search?regno=12532&provider=mrt");
detectSearchType("localhost/search?regno=12532&provider=mrt&host=abul");
detectSearchType("localhost/abc?regno=1&hostid=2");
Mustofa Rizwan
  • 10,215
  • 2
  • 28
  • 43