4444import java .io .FileInputStream ;
4545import java .io .IOException ;
4646import java .io .InputStream ;
47+ import java .net .MalformedURLException ;
48+ import java .net .URI ;
49+ import java .net .URISyntaxException ;
50+ import java .net .URL ;
4751import java .nio .file .Path ;
4852import java .util .ArrayList ;
4953import java .util .Collections ;
5054import java .util .List ;
5155import java .util .UUID ;
5256import java .util .function .Function ;
5357
58+ import static io .opentdf .platform .sdk .TDF .logger ;
59+
5460/**
5561 * A builder class for creating instances of the SDK class.
5662 */
@@ -74,6 +80,40 @@ public static SDKBuilder newBuilder() {
7480 return builder ;
7581 }
7682
83+ static String normalizeAddress (String urlString , boolean usePlaintext ) {
84+ URL url ;
85+ try {
86+ url = new URL (urlString );
87+ } catch (MalformedURLException e ) {
88+ url = tryParseHostAndPort (urlString );
89+ }
90+ final int port = url .getPort () == -1 ? ("http" .equals (url .getProtocol ()) ? 80 : 443 ) : url .getPort ();
91+ final String protocol = usePlaintext && "http" .equals (url .getProtocol ()) ? "http" : "https" ;
92+
93+ try {
94+ var returnUrl = new URL (protocol , url .getHost (), port , "" ).toString ();
95+ TDF .logger .debug ("normalized url [{}] to [{}]" , urlString , returnUrl );
96+ return returnUrl ;
97+ } catch (MalformedURLException e ) {
98+ throw new SDKException ("error creating KAS address" , e );
99+ }
100+ }
101+
102+ private static URL tryParseHostAndPort (String urlString ) {
103+ URI uri ;
104+ try {
105+ uri = new URI (null , urlString , null , null , null ).parseServerAuthority ();
106+ } catch (URISyntaxException e ) {
107+ throw new SDKException ("error trying to parse host and port" , e );
108+ }
109+
110+ try {
111+ return new URL (uri .getPort () == 80 ? "http" : "https" , uri .getHost (), uri .getPort (), "" );
112+ } catch (MalformedURLException e ) {
113+ throw new SDKException ("error trying to create URL from host and port" , e );
114+ }
115+ }
116+
77117 public SDKBuilder sslFactory (SSLFactory sslFactory ) {
78118 this .sslFactory = sslFactory ;
79119 return this ;
@@ -237,6 +277,7 @@ ServicesAndInternals buildServices() {
237277 throw new SDKException ("Error generating DPoP key" , e );
238278 }
239279
280+ this .platformEndpoint = normalizeAddress (this .platformEndpoint , this .usePlainText );
240281 var authInterceptor = getAuthInterceptor (dpopKey );
241282 var kasClient = getKASClient (dpopKey , authInterceptor );
242283 var protocolClient = getProtocolClient (platformEndpoint , authInterceptor );
0 commit comments