2017-03-16 75 views
0

我休息終點與以下3個參數爲有效採取網址: REGNO,主機標識,位置 REGNO,domid,位置 REGNO,供應商休息搜索參數的驗證

比這些東西組合其他無效。 我有檢查此

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

我不喜歡的事實,我使用了很多的if else語句的驗證方法。如果有更好的可讀性,請隨時提供幫助。

+0

得到有效的完整的URL字符串的帶參數 –

+0

本地主機/搜索位置=印度&REGNO = 12532&主機標識= GDY-101的樣品? – Raskill

回答

1

你可以試試下面的辦法,這將減少的if else大幅..

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

    } 

您需要的URL字符串傳遞給該方法的需要。如以下內容:

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