Skip to content

Commit

Permalink
Merge pull request #224 from ajkannan/handle-scheme
Browse files Browse the repository at this point in the history
Add scheme to user-provided host if necessary
  • Loading branch information
aozarov committed Oct 8, 2015
2 parents c6b7f27 + b8923f4 commit 5b1e341
Showing 1 changed file with 37 additions and 1 deletion.
Original file line number Diff line number Diff line change
Expand Up @@ -32,6 +32,7 @@
import com.google.api.services.datastore.client.DatastoreException;
import com.google.api.services.datastore.client.DatastoreFactory;
import com.google.api.services.datastore.client.DatastoreOptions.Builder;
import com.google.common.base.Preconditions;
import com.google.common.collect.ImmutableMap;
import com.google.gcloud.datastore.DatastoreOptions;
import com.google.gcloud.spi.DatastoreRpc.DatastoreRpcException.Reason;
Expand All @@ -40,6 +41,10 @@
import org.json.JSONObject;
import org.json.JSONTokener;

import java.net.InetAddress;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.UnknownHostException;
import java.util.HashMap;
import java.util.Map;

Expand All @@ -62,14 +67,45 @@ public class DefaultDatastoreRpc implements DatastoreRpc {
}

public DefaultDatastoreRpc(DatastoreOptions options) {
String normalizedHost = normalizeHost(options.host());
client = DatastoreFactory.get().create(
new Builder()
.dataset(options.projectId())
.host(options.host())
.host(normalizedHost)
.initializer(options.httpRequestInitializer())
.build());
}

private static String normalizeHost(String host) {
host = host.toLowerCase();
if (includesScheme(host)) {
Preconditions.checkArgument(!(host.startsWith("https://") && isLocalHost(host)),
"\"https\" is not supported for localhost. Use \"http\" instead.");
return host;
}
return "http://" + host;
}

private static boolean isLocalHost(String host) {
if (host != null) {
try {
String normalizedHost = host;
if (!includesScheme(normalizedHost)) {
normalizedHost = "http://" + normalizedHost;
}
InetAddress hostAddr = InetAddress.getByName(new URL(normalizedHost).getHost());
return hostAddr.isAnyLocalAddress() || hostAddr.isLoopbackAddress();
} catch (UnknownHostException | MalformedURLException e) {
// ignore
}
}
return false;
}

private static boolean includesScheme(String url) {
return url.startsWith("http://") || url.startsWith("https://");
}

private static DatastoreRpcException translate(DatastoreException exception) {
String message = exception.getMessage();
String reasonStr = "";
Expand Down

0 comments on commit 5b1e341

Please sign in to comment.