4040import org .json .JSONObject ;
4141import org .json .JSONTokener ;
4242
43+ import java .net .InetAddress ;
44+ import java .net .MalformedURLException ;
45+ import java .net .URL ;
46+ import java .net .UnknownHostException ;
4347import java .util .HashMap ;
4448import java .util .Map ;
4549
@@ -62,14 +66,48 @@ public class DefaultDatastoreRpc implements DatastoreRpc {
6266 }
6367
6468 public DefaultDatastoreRpc (DatastoreOptions options ) {
69+ String normalizedHost = normalizeHost (options .host ());
6570 client = DatastoreFactory .get ().create (
6671 new Builder ()
6772 .dataset (options .projectId ())
68- .host (options . host () )
73+ .host (normalizedHost )
6974 .initializer (options .httpRequestInitializer ())
7075 .build ());
7176 }
7277
78+ private static String normalizeHost (String host ) {
79+ host = host .toLowerCase ();
80+ if (includesScheme (host )) {
81+ if (host .startsWith ("https://" ) && isLocalHost (host )) {
82+ throw new IllegalArgumentException (
83+ "\" https\" is not supported for localhost. Use \" http\" instead." );
84+ } else {
85+ return host ;
86+ }
87+ }
88+ return "http://" + host ;
89+ }
90+
91+ private static boolean isLocalHost (String host ) {
92+ if (host != null ) {
93+ try {
94+ String normalizedHost = host ;
95+ if (!includesScheme (normalizedHost )) {
96+ normalizedHost = "http://" + normalizedHost ;
97+ }
98+ InetAddress hostAddr = InetAddress .getByName (new URL (normalizedHost ).getHost ());
99+ return hostAddr .isAnyLocalAddress () || hostAddr .isLoopbackAddress ();
100+ } catch (UnknownHostException | MalformedURLException e ) {
101+ // ignore
102+ }
103+ }
104+ return false ;
105+ }
106+
107+ private static boolean includesScheme (String url ) {
108+ return url .startsWith ("http://" ) || url .startsWith ("https://" );
109+ }
110+
73111 private static DatastoreRpcException translate (DatastoreException exception ) {
74112 String message = exception .getMessage ();
75113 String reasonStr = "" ;
0 commit comments