001package org.gbif.dwc.terms;
002
003import java.net.URI;
004
005public class UnknownTerm implements Term {
006
007  private final URI uri;
008  private final String name;
009
010  public static UnknownTerm build(String qualifiedName){
011    return new UnknownTerm(URI.create(qualifiedName));
012  }
013
014  public static UnknownTerm build(String qualifiedName, String simpleName){
015    return new UnknownTerm(URI.create(qualifiedName), simpleName);
016  }
017
018  public UnknownTerm(URI uri, String name) {
019    if (uri == null || !uri.isAbsolute()) {
020      throw new IllegalArgumentException("The qualified name URI must be an absolute URI");
021    }
022    if (name == null || name.isEmpty()) {
023      throw new IllegalArgumentException("The simple name is required");
024    }
025    this.uri = uri;
026    this.name = name;
027  }
028
029  public UnknownTerm(URI uri) {
030    if (uri == null || !uri.isAbsolute()) {
031      throw new IllegalArgumentException("The qualified name URI is required and must be an absolute URI");
032    }
033
034    String name = null;
035    if (uri.getFragment() != null) {
036      name = uri.getFragment();
037
038    } else if (uri.getPath() != null) {
039      name = uri.getPath();
040      // remove trailing and ending slash if existing
041      if (name.endsWith("/")) {
042        name = name.substring(0, name.length()-1);
043      }
044      if (name.startsWith("/")) {
045        name = name.substring(1);
046      }
047      // only use last part of path
048      int pos = name.lastIndexOf("/");
049      if (pos > 0) {
050        name = name.substring(pos + 1);
051      }
052
053    } else {
054      throw new IllegalArgumentException("The qualified name URI must have a path or fragment to automatically derive a simple name");
055    }
056    if (name == null || name.isEmpty()) {
057      throw new IllegalArgumentException("The simple name is required");
058    }
059    this.uri = uri;
060    this.name = name;
061  }
062
063  @Override
064  public String qualifiedName() {
065    return uri.toString();
066  }
067
068  @Override
069  public String simpleName() {
070    return name;
071  }
072
073  @Override
074  public String toString() {
075    return uri.toString();
076  }
077
078  @Override
079  public boolean equals(Object o) {
080    if (this == o) return true;
081    if (!(o instanceof Term)) return false;
082
083    Term that = (Term) o;
084
085    return qualifiedName().equals(that.qualifiedName());
086  }
087
088  @Override
089  public int hashCode() {
090    return qualifiedName().hashCode();
091  }
092
093}