001package org.consensusj.decentralizedid; 002 003import java.net.URI; 004import java.net.URISyntaxException; 005 006/** 007 * Representation of a W3C DID 008 * 009 * Based on java.net.URI with some inspiration from OkHttp.HttpUrl and use of Java 8-style `.of()` methods. 010 * 011 */ 012public class Did { 013 public static String DID_SCHEME = "did"; 014 protected final URI didUri; 015 016 private Did(String didString) throws URISyntaxException { 017 this(new URI(didString)); 018 } 019 020 protected Did(URI didUri) { 021 String scheme = didUri.getScheme(); 022 if (scheme != null && !scheme.equals(DID_SCHEME)) { 023 fail(didUri, "DID Scheme Required"); 024 } 025 this.didUri = didUri; 026 } 027 028 private static void fail(URI candidateUri, String reason) throws IllegalArgumentException { 029 throw new IllegalArgumentException(candidateUri.toString() + " is not a DID URI (" + reason + ")"); 030 } 031 032 /** 033 * 034 * @param uriString A string representing a DID URI 035 * @return a valid DID 036 * @throws URISyntaxException 037 * If the URI string constructed from the given components 038 * violates RFC 2396 039 */ 040 public static Did of(String uriString) throws URISyntaxException { 041 return new Did(uriString); 042 } 043 044 /** 045 * 046 * @param didUri a DID URI 047 * @return a valid DID 048 * 049 */ 050 public static Did of(URI didUri) { 051 return new Did(didUri); 052 } 053 054 /** 055 * Create a DID from a known good string 056 * 057 * Similar to `java.net.url#create` 058 * 059 * @param uriString 060 * @return a valid DID 061 * 062 * @throws NullPointerException 063 * If {@code str} is {@code null} 064 * 065 * @throws IllegalArgumentException 066 * If the given string violates RFC 2396 067 */ 068 public static Did create(String uriString) { 069 return new Did(URI.create(uriString)); 070 } 071 072 public URI toURI() { 073 return didUri; 074 } 075 076 public String toString() { 077 return didUri.toString(); 078 } 079}