3232import com .google .api .services .datastore .client .DatastoreException ;
3333import com .google .api .services .datastore .client .DatastoreFactory ;
3434import com .google .api .services .datastore .client .DatastoreOptions .Builder ;
35+ import com .google .common .base .Preconditions ;
3536import com .google .common .collect .ImmutableMap ;
3637import com .google .gcloud .datastore .DatastoreOptions ;
3738import com .google .gcloud .spi .DatastoreRpc .DatastoreRpcException .Reason ;
4041import org .json .JSONObject ;
4142import org .json .JSONTokener ;
4243
44+ import java .net .InetAddress ;
45+ import java .net .MalformedURLException ;
46+ import java .net .URL ;
47+ import java .net .UnknownHostException ;
4348import java .util .HashMap ;
4449import java .util .Map ;
4550
@@ -62,14 +67,45 @@ public class DefaultDatastoreRpc implements DatastoreRpc {
6267 }
6368
6469 public DefaultDatastoreRpc (DatastoreOptions options ) {
70+ String normalizedHost = normalizeHost (options .host ());
6571 client = DatastoreFactory .get ().create (
6672 new Builder ()
6773 .dataset (options .projectId ())
68- .host (options . host () )
74+ .host (normalizedHost )
6975 .initializer (options .httpRequestInitializer ())
7076 .build ());
7177 }
7278
79+ private static String normalizeHost (String host ) {
80+ host = host .toLowerCase ();
81+ if (includesScheme (host )) {
82+ Preconditions .checkArgument (!(host .startsWith ("https://" ) && isLocalHost (host )),
83+ "\" https\" is not supported for localhost. Use \" http\" instead." );
84+ return host ;
85+ }
86+ return "http://" + host ;
87+ }
88+
89+ private static boolean isLocalHost (String host ) {
90+ if (host != null ) {
91+ try {
92+ String normalizedHost = host ;
93+ if (!includesScheme (normalizedHost )) {
94+ normalizedHost = "http://" + normalizedHost ;
95+ }
96+ InetAddress hostAddr = InetAddress .getByName (new URL (normalizedHost ).getHost ());
97+ return hostAddr .isAnyLocalAddress () || hostAddr .isLoopbackAddress ();
98+ } catch (UnknownHostException | MalformedURLException e ) {
99+ // ignore
100+ }
101+ }
102+ return false ;
103+ }
104+
105+ private static boolean includesScheme (String url ) {
106+ return url .startsWith ("http://" ) || url .startsWith ("https://" );
107+ }
108+
73109 private static DatastoreRpcException translate (DatastoreException exception ) {
74110 String message = exception .getMessage ();
75111 String reasonStr = "" ;
0 commit comments