DZone
Thanks for visiting DZone today,
Edit Profile
  • Manage Email Subscriptions
  • How to Post to DZone
  • Article Submission Guidelines
Sign Out View Profile
  • Post an Article
  • Manage My Drafts
Over 2 million developers have joined DZone.
Log In / Join
Refcards Trend Reports Events Over 2 million developers have joined DZone. Join Today! Thanks for visiting DZone today,
Edit Profile Manage Email Subscriptions Moderation Admin Console How to Post to DZone Article Submission Guidelines
View Profile
Sign Out
Refcards
Trend Reports
Events
Zones
Culture and Methodologies Agile Career Development Methodologies Team Management
Data Engineering AI/ML Big Data Data Databases IoT
Software Design and Architecture Cloud Architecture Containers Integration Microservices Performance Security
Coding Frameworks Java JavaScript Languages Tools
Testing, Deployment, and Maintenance Deployment DevOps and CI/CD Maintenance Monitoring and Observability Testing, Tools, and Frameworks
Culture and Methodologies
Agile Career Development Methodologies Team Management
Data Engineering
AI/ML Big Data Data Databases IoT
Software Design and Architecture
Cloud Architecture Containers Integration Microservices Performance Security
Coding
Frameworks Java JavaScript Languages Tools
Testing, Deployment, and Maintenance
Deployment DevOps and CI/CD Maintenance Monitoring and Observability Testing, Tools, and Frameworks
  1. DZone
  2. Coding
  3. Java
  4. Extract Second- and Top-Level Domains from URLs with Java

Extract Second- and Top-Level Domains from URLs with Java

Kelvin Tan user avatar by
Kelvin Tan
·
Nov. 19, 12 · Interview
Like (0)
Save
Tweet
Share
11.60K Views

Join the DZone community and get the full member experience.

Join For Free

It turns out that extracting second- and top-level domains is not a simple task, the primary difficulty being that in addition to the usual suspects (.com .org .net etc), there are the country suffixes (.uk .it .de etc) which need to be accounted for.

Regex alone has no way of handling this. http://publicsuffix.org/list/ contains a somewhat authoritative list of TLD and ccTLD that we can use.

Here follows a Java class which parses this list, builds a regex from it, and extracts out the the TLD and second-level domain from a hostname. You'll need to download the effective_tld_names.dat from http://mxr.mozilla.org/mozilla-central/source/netwerk/dns/effective_tld_names.dat?raw=1 and place it in the same directory as the Java class.

In my next post, I'll build a Lucene Tokenizer out of this, so it can be used in Lucene and Solr.

package org.supermind.solr.analysis;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

public class SecondLDExtractor {
  private StringBuilder sb = new StringBuilder();
  private Pattern pattern;

  public void init() {
    try {
      ArrayList<String> terms = new ArrayList<String>();

      BufferedReader br = new BufferedReader(new InputStreamReader(getClass().getResourceAsStream("effective_tld_names.dat")));
      String s = null;
      while ((s = br.readLine()) != null) {
        s = s.trim();
        if (s.length() == 0 || s.startsWith("//") || s.startsWith("!")) continue;
        terms.add(s);
      }
      Collections.sort(terms, new StringLengthComparator());
      for(String t: terms) add(t);
      compile();
      br.close();
    } catch (IOException e) {
      throw new IllegalStateException(e);
    }
  }

  protected void add(String s) {
    s = s.replace(".", "\\.");
    s = "\\." + s;
    if (s.startsWith("*")) {
      s = s.replace("*", ".+");
      sb.append(s).append("|");
    } else {
      sb.append(s).append("|");
    }
  }

  public void compile() {
    if (sb.length() > 0) sb.deleteCharAt(sb.length() - 1);
    sb.insert(0, "[^.]+?(");
    sb.append(")$");
    pattern = Pattern.compile(sb.toString());
    sb = null;
  }

  public String extract2LD(String host) {
    Matcher m = pattern.matcher(host);
    if (m.find()) {
      return m.group(0);
    }
    return null;
  }

  public String extractTLD(String host) {
    Matcher m = pattern.matcher(host);
    if (m.find()) {
      return m.group(1);
    }
    return null;
  }

  public static class StringLengthComparator implements Comparator<String> {
    public int compare(String s1, String s2) {
      if (s1.length() > s2.length()) return -1;
      if (s1.length() < s2.length()) return 1;
      return 0;
    }
  }
}

Java (programming language) Extract

Published at DZone with permission of Kelvin Tan. See the original article here.

Opinions expressed by DZone contributors are their own.

Popular on DZone

  • What Java Version Are You Running? Let’s Take a Look Under the Hood of the JDK!
  • Distributed Stateful Edge Platforms
  • Best Practices for Writing Clean and Maintainable Code
  • How To Validate Three Common Document Types in Python

Comments

Partner Resources

X

ABOUT US

  • About DZone
  • Send feedback
  • Careers
  • Sitemap

ADVERTISE

  • Advertise with DZone

CONTRIBUTE ON DZONE

  • Article Submission Guidelines
  • Become a Contributor
  • Visit the Writers' Zone

LEGAL

  • Terms of Service
  • Privacy Policy

CONTACT US

  • 600 Park Offices Drive
  • Suite 300
  • Durham, NC 27709
  • support@dzone.com
  • +1 (919) 678-0300

Let's be friends: