简体   繁体   中英

Rest Search Parameters Validation

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.

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");

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM