Skip to content

Commit 5b1e341

Browse files
committed
Merge pull request #224 from ajkannan/handle-scheme
Add scheme to user-provided host if necessary
2 parents c6b7f27 + b8923f4 commit 5b1e341

File tree

1 file changed

+37
-1
lines changed

1 file changed

+37
-1
lines changed

gcloud-java-datastore/src/main/java/com/google/gcloud/spi/DefaultDatastoreRpc.java

Lines changed: 37 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -32,6 +32,7 @@
3232
import com.google.api.services.datastore.client.DatastoreException;
3333
import com.google.api.services.datastore.client.DatastoreFactory;
3434
import com.google.api.services.datastore.client.DatastoreOptions.Builder;
35+
import com.google.common.base.Preconditions;
3536
import com.google.common.collect.ImmutableMap;
3637
import com.google.gcloud.datastore.DatastoreOptions;
3738
import com.google.gcloud.spi.DatastoreRpc.DatastoreRpcException.Reason;
@@ -40,6 +41,10 @@
4041
import org.json.JSONObject;
4142
import org.json.JSONTokener;
4243

44+
import java.net.InetAddress;
45+
import java.net.MalformedURLException;
46+
import java.net.URL;
47+
import java.net.UnknownHostException;
4348
import java.util.HashMap;
4449
import 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

Comments
 (0)