I have a need to get hostname in httpd url. So. I made it simple by using pattern and matcher class.
public class Util {
 public synchronized static String getHost(String domainURL) {
  String host = new String();
  Pattern pattern = Pattern.compile("(http://)+(\\w++-?\\w++)|(\\w++).?(\\w++.)++(\\w++)");
  Matcher match = pattern.matcher(domainURL);
  while (match.find()) {
   String dashContained = match.group(2);
   if (dashContained != null) {
    host = match.group(2);
   } else {
    host = match.group(3);
   }
  }
  return host;
 }
}
}
public class GettingHostTest {
 @Test
 public void getHost() {
  String url = "http://gmail.google.com"; // fulll domain
  String host = MonitorUtil.getHost(url);
  Assert.assertEndsWith("gmail", host);
 }
 @Test
 public void getHost1() {
  String url = "http://gmail1568h125.svr.google.com"; // sub domain
  String host = MonitorUtil.getHost(url);
  Assert.assertEndsWith("gmail1568h125", host);
 }
 @Test
 public void getHost2() throws Exception {
  String url = "http://alpha-gmail.google.com"; // dash contained domain
  String host = MonitorUtil.getHost(url);
  Assert.assertEndsWith("alpha-gmail", host);
 }
}
 
No comments:
Post a Comment