() {
@@ -92,7 +92,9 @@ public static TableId of(String dataset, String table) {
@Override
public boolean equals(Object obj) {
- return obj instanceof TableId && Objects.equals(toPb(), ((TableId) obj).toPb());
+ return obj == this
+ || obj instanceof TableId
+ && Objects.equals(toPb(), ((TableId) obj).toPb());
}
@Override
diff --git a/gcloud-java-bigquery/src/main/java/com/google/gcloud/bigquery/TableInfo.java b/gcloud-java-bigquery/src/main/java/com/google/cloud/bigquery/TableInfo.java
similarity index 94%
rename from gcloud-java-bigquery/src/main/java/com/google/gcloud/bigquery/TableInfo.java
rename to gcloud-java-bigquery/src/main/java/com/google/cloud/bigquery/TableInfo.java
index de331350e978..c27b0dfdf1e5 100644
--- a/gcloud-java-bigquery/src/main/java/com/google/gcloud/bigquery/TableInfo.java
+++ b/gcloud-java-bigquery/src/main/java/com/google/cloud/bigquery/TableInfo.java
@@ -14,7 +14,7 @@
* limitations under the License.
*/
-package com.google.gcloud.bigquery;
+package com.google.cloud.bigquery;
import static com.google.common.base.MoreObjects.firstNonNull;
import static com.google.common.base.Preconditions.checkNotNull;
@@ -52,10 +52,10 @@ public Table apply(TableInfo tableInfo) {
}
};
- private static final long serialVersionUID = -7679032506430816205L;
+ private static final long serialVersionUID = 609769795097719407L;
private final String etag;
- private final String id;
+ private final String generatedId;
private final String selfLink;
private final TableId tableId;
private final String friendlyName;
@@ -90,7 +90,7 @@ public abstract static class Builder {
*/
public abstract Builder friendlyName(String friendlyName);
- abstract Builder id(String id);
+ abstract Builder generatedId(String generatedId);
abstract Builder lastModifiedTime(Long lastModifiedTime);
@@ -117,7 +117,7 @@ public abstract static class Builder {
static class BuilderImpl extends Builder {
private String etag;
- private String id;
+ private String generatedId;
private String selfLink;
private TableId tableId;
private String friendlyName;
@@ -131,7 +131,7 @@ static class BuilderImpl extends Builder {
BuilderImpl(TableInfo tableInfo) {
this.etag = tableInfo.etag;
- this.id = tableInfo.id;
+ this.generatedId = tableInfo.generatedId;
this.selfLink = tableInfo.selfLink;
this.tableId = tableInfo.tableId;
this.friendlyName = tableInfo.friendlyName;
@@ -152,7 +152,7 @@ static class BuilderImpl extends Builder {
this.friendlyName = tablePb.getFriendlyName();
this.creationTime = tablePb.getCreationTime();
this.etag = tablePb.getEtag();
- this.id = tablePb.getId();
+ this.generatedId = tablePb.getId();
this.selfLink = tablePb.getSelfLink();
this.definition = TableDefinition.fromPb(tablePb);
}
@@ -188,8 +188,8 @@ public Builder friendlyName(String friendlyName) {
}
@Override
- Builder id(String id) {
- this.id = id;
+ Builder generatedId(String generatedId) {
+ this.generatedId = generatedId;
return this;
}
@@ -226,7 +226,7 @@ public TableInfo build() {
TableInfo(BuilderImpl builder) {
this.tableId = checkNotNull(builder.tableId);
this.etag = builder.etag;
- this.id = builder.id;
+ this.generatedId = builder.generatedId;
this.selfLink = builder.selfLink;
this.friendlyName = builder.friendlyName;
this.description = builder.description;
@@ -244,10 +244,10 @@ public String etag() {
}
/**
- * Returns an opaque id for the table.
+ * Returns the service-generated id for the table.
*/
- public String id() {
- return id;
+ public String generatedId() {
+ return generatedId;
}
/**
@@ -321,7 +321,7 @@ public String toString() {
return MoreObjects.toStringHelper(this)
.add("tableId", tableId)
.add("etag", etag)
- .add("id", id)
+ .add("generatedId", generatedId)
.add("selfLink", selfLink)
.add("friendlyName", friendlyName)
.add("description", description)
@@ -339,7 +339,8 @@ public int hashCode() {
@Override
public boolean equals(Object obj) {
- return obj != null
+ return obj == this
+ || obj != null
&& obj.getClass().equals(TableInfo.class)
&& Objects.equals(toPb(), ((TableInfo) obj).toPb());
}
@@ -379,7 +380,7 @@ Table toPb() {
tablePb.setEtag(etag);
tablePb.setExpirationTime(expirationTime);
tablePb.setFriendlyName(friendlyName);
- tablePb.setId(id);
+ tablePb.setId(generatedId);
tablePb.setSelfLink(selfLink);
return tablePb;
}
diff --git a/gcloud-java-bigquery/src/main/java/com/google/gcloud/bigquery/UserDefinedFunction.java b/gcloud-java-bigquery/src/main/java/com/google/cloud/bigquery/UserDefinedFunction.java
similarity index 99%
rename from gcloud-java-bigquery/src/main/java/com/google/gcloud/bigquery/UserDefinedFunction.java
rename to gcloud-java-bigquery/src/main/java/com/google/cloud/bigquery/UserDefinedFunction.java
index 2135e0ddc941..09fa2563c59f 100644
--- a/gcloud-java-bigquery/src/main/java/com/google/gcloud/bigquery/UserDefinedFunction.java
+++ b/gcloud-java-bigquery/src/main/java/com/google/cloud/bigquery/UserDefinedFunction.java
@@ -1,4 +1,4 @@
-package com.google.gcloud.bigquery;
+package com.google.cloud.bigquery;
import com.google.api.services.bigquery.model.UserDefinedFunctionResource;
import com.google.common.base.Function;
diff --git a/gcloud-java-bigquery/src/main/java/com/google/gcloud/bigquery/ViewDefinition.java b/gcloud-java-bigquery/src/main/java/com/google/cloud/bigquery/ViewDefinition.java
similarity index 95%
rename from gcloud-java-bigquery/src/main/java/com/google/gcloud/bigquery/ViewDefinition.java
rename to gcloud-java-bigquery/src/main/java/com/google/cloud/bigquery/ViewDefinition.java
index 796dd411b4a1..1d3a97ba616d 100644
--- a/gcloud-java-bigquery/src/main/java/com/google/gcloud/bigquery/ViewDefinition.java
+++ b/gcloud-java-bigquery/src/main/java/com/google/cloud/bigquery/ViewDefinition.java
@@ -14,7 +14,7 @@
* limitations under the License.
*/
-package com.google.gcloud.bigquery;
+package com.google.cloud.bigquery;
import static com.google.common.base.Preconditions.checkNotNull;
@@ -33,7 +33,7 @@
*
* @see Views
*/
-public final class ViewDefinition extends TableDefinition {
+public class ViewDefinition extends TableDefinition {
private static final long serialVersionUID = -8789311196910794545L;
@@ -146,12 +146,15 @@ ToStringHelper toStringHelper() {
}
@Override
- public boolean equals(Object obj) {
- return obj instanceof ViewDefinition && baseEquals((ViewDefinition) obj);
+ public final boolean equals(Object obj) {
+ return obj == this
+ || obj != null
+ && obj.getClass().equals(ViewDefinition.class)
+ && baseEquals((ViewDefinition) obj);
}
@Override
- public int hashCode() {
+ public final int hashCode() {
return Objects.hash(baseHashCode(), query, userDefinedFunctions);
}
diff --git a/gcloud-java-bigquery/src/main/java/com/google/gcloud/bigquery/WriteChannelConfiguration.java b/gcloud-java-bigquery/src/main/java/com/google/cloud/bigquery/WriteChannelConfiguration.java
similarity index 96%
rename from gcloud-java-bigquery/src/main/java/com/google/gcloud/bigquery/WriteChannelConfiguration.java
rename to gcloud-java-bigquery/src/main/java/com/google/cloud/bigquery/WriteChannelConfiguration.java
index 6cc44ce7d5d6..898063e7e0ed 100644
--- a/gcloud-java-bigquery/src/main/java/com/google/gcloud/bigquery/WriteChannelConfiguration.java
+++ b/gcloud-java-bigquery/src/main/java/com/google/cloud/bigquery/WriteChannelConfiguration.java
@@ -14,15 +14,15 @@
* limitations under the License.
*/
-package com.google.gcloud.bigquery;
+package com.google.cloud.bigquery;
import static com.google.common.base.Preconditions.checkNotNull;
import com.google.api.services.bigquery.model.JobConfigurationLoad;
+import com.google.cloud.bigquery.JobInfo.CreateDisposition;
+import com.google.cloud.bigquery.JobInfo.WriteDisposition;
import com.google.common.base.MoreObjects;
import com.google.common.collect.ImmutableList;
-import com.google.gcloud.bigquery.JobInfo.CreateDisposition;
-import com.google.gcloud.bigquery.JobInfo.WriteDisposition;
import java.io.Serializable;
import java.util.List;
@@ -30,10 +30,10 @@
/**
* Google BigQuery Configuration for a load operation. A load configuration can be used to load data
- * into a table with a {@link com.google.gcloud.WriteChannel}
+ * into a table with a {@link com.google.cloud.WriteChannel}
* ({@link BigQuery#writer(WriteChannelConfiguration)}).
*/
-public class WriteChannelConfiguration implements LoadConfiguration, Serializable {
+public final class WriteChannelConfiguration implements LoadConfiguration, Serializable {
private static final long serialVersionUID = 470267591917413578L;
@@ -241,7 +241,8 @@ public String toString() {
@Override
public boolean equals(Object obj) {
- return obj instanceof WriteChannelConfiguration
+ return obj == this
+ || obj instanceof WriteChannelConfiguration
&& Objects.equals(toPb(), ((WriteChannelConfiguration) obj).toPb());
}
diff --git a/gcloud-java-bigquery/src/main/java/com/google/gcloud/bigquery/package-info.java b/gcloud-java-bigquery/src/main/java/com/google/cloud/bigquery/package-info.java
similarity index 92%
rename from gcloud-java-bigquery/src/main/java/com/google/gcloud/bigquery/package-info.java
rename to gcloud-java-bigquery/src/main/java/com/google/cloud/bigquery/package-info.java
index db5e956e0a12..a701b82c1c2c 100644
--- a/gcloud-java-bigquery/src/main/java/com/google/gcloud/bigquery/package-info.java
+++ b/gcloud-java-bigquery/src/main/java/com/google/cloud/bigquery/package-info.java
@@ -19,7 +19,7 @@
*
* A simple usage example showing how to create a table if it does not exist and load data into
* it. For the complete source code see
- *
+ *
* CreateTableAndLoadData.java.
*
{@code
* BigQuery bigquery = BigQueryOptions.defaultInstance().service();
@@ -44,4 +44,4 @@
*
* @see Google Cloud BigQuery
*/
-package com.google.gcloud.bigquery;
+package com.google.cloud.bigquery;
diff --git a/gcloud-java-bigquery/src/main/java/com/google/gcloud/bigquery/spi/BigQueryRpc.java b/gcloud-java-bigquery/src/main/java/com/google/cloud/bigquery/spi/BigQueryRpc.java
similarity index 98%
rename from gcloud-java-bigquery/src/main/java/com/google/gcloud/bigquery/spi/BigQueryRpc.java
rename to gcloud-java-bigquery/src/main/java/com/google/cloud/bigquery/spi/BigQueryRpc.java
index d0b740e9e390..e221079cdd03 100644
--- a/gcloud-java-bigquery/src/main/java/com/google/gcloud/bigquery/spi/BigQueryRpc.java
+++ b/gcloud-java-bigquery/src/main/java/com/google/cloud/bigquery/spi/BigQueryRpc.java
@@ -14,7 +14,7 @@
* limitations under the License.
*/
-package com.google.gcloud.bigquery.spi;
+package com.google.cloud.bigquery.spi;
import com.google.api.services.bigquery.model.Dataset;
import com.google.api.services.bigquery.model.GetQueryResultsResponse;
@@ -26,7 +26,7 @@
import com.google.api.services.bigquery.model.TableDataInsertAllRequest;
import com.google.api.services.bigquery.model.TableDataInsertAllResponse;
import com.google.api.services.bigquery.model.TableRow;
-import com.google.gcloud.bigquery.BigQueryException;
+import com.google.cloud.bigquery.BigQueryException;
import java.util.Map;
diff --git a/gcloud-java-bigquery/src/main/java/com/google/gcloud/bigquery/spi/BigQueryRpcFactory.java b/gcloud-java-bigquery/src/main/java/com/google/cloud/bigquery/spi/BigQueryRpcFactory.java
similarity index 85%
rename from gcloud-java-bigquery/src/main/java/com/google/gcloud/bigquery/spi/BigQueryRpcFactory.java
rename to gcloud-java-bigquery/src/main/java/com/google/cloud/bigquery/spi/BigQueryRpcFactory.java
index 1323ec0624f4..8c9fb2413a41 100644
--- a/gcloud-java-bigquery/src/main/java/com/google/gcloud/bigquery/spi/BigQueryRpcFactory.java
+++ b/gcloud-java-bigquery/src/main/java/com/google/cloud/bigquery/spi/BigQueryRpcFactory.java
@@ -14,10 +14,10 @@
* limitations under the License.
*/
-package com.google.gcloud.bigquery.spi;
+package com.google.cloud.bigquery.spi;
-import com.google.gcloud.bigquery.BigQueryOptions;
-import com.google.gcloud.spi.ServiceRpcFactory;
+import com.google.cloud.bigquery.BigQueryOptions;
+import com.google.cloud.spi.ServiceRpcFactory;
/**
* An interface for BigQuery RPC factory.
diff --git a/gcloud-java-bigquery/src/main/java/com/google/gcloud/bigquery/spi/DefaultBigQueryRpc.java b/gcloud-java-bigquery/src/main/java/com/google/cloud/bigquery/spi/DefaultBigQueryRpc.java
similarity index 95%
rename from gcloud-java-bigquery/src/main/java/com/google/gcloud/bigquery/spi/DefaultBigQueryRpc.java
rename to gcloud-java-bigquery/src/main/java/com/google/cloud/bigquery/spi/DefaultBigQueryRpc.java
index 71712bda7806..2f02f55c68e7 100644
--- a/gcloud-java-bigquery/src/main/java/com/google/gcloud/bigquery/spi/DefaultBigQueryRpc.java
+++ b/gcloud-java-bigquery/src/main/java/com/google/cloud/bigquery/spi/DefaultBigQueryRpc.java
@@ -12,17 +12,17 @@
* the License.
*/
-package com.google.gcloud.bigquery.spi;
+package com.google.cloud.bigquery.spi;
-import static com.google.gcloud.bigquery.spi.BigQueryRpc.Option.ALL_DATASETS;
-import static com.google.gcloud.bigquery.spi.BigQueryRpc.Option.ALL_USERS;
-import static com.google.gcloud.bigquery.spi.BigQueryRpc.Option.DELETE_CONTENTS;
-import static com.google.gcloud.bigquery.spi.BigQueryRpc.Option.FIELDS;
-import static com.google.gcloud.bigquery.spi.BigQueryRpc.Option.MAX_RESULTS;
-import static com.google.gcloud.bigquery.spi.BigQueryRpc.Option.PAGE_TOKEN;
-import static com.google.gcloud.bigquery.spi.BigQueryRpc.Option.START_INDEX;
-import static com.google.gcloud.bigquery.spi.BigQueryRpc.Option.STATE_FILTER;
-import static com.google.gcloud.bigquery.spi.BigQueryRpc.Option.TIMEOUT;
+import static com.google.cloud.bigquery.spi.BigQueryRpc.Option.ALL_DATASETS;
+import static com.google.cloud.bigquery.spi.BigQueryRpc.Option.ALL_USERS;
+import static com.google.cloud.bigquery.spi.BigQueryRpc.Option.DELETE_CONTENTS;
+import static com.google.cloud.bigquery.spi.BigQueryRpc.Option.FIELDS;
+import static com.google.cloud.bigquery.spi.BigQueryRpc.Option.MAX_RESULTS;
+import static com.google.cloud.bigquery.spi.BigQueryRpc.Option.PAGE_TOKEN;
+import static com.google.cloud.bigquery.spi.BigQueryRpc.Option.START_INDEX;
+import static com.google.cloud.bigquery.spi.BigQueryRpc.Option.STATE_FILTER;
+import static com.google.cloud.bigquery.spi.BigQueryRpc.Option.TIMEOUT;
import static java.net.HttpURLConnection.HTTP_CREATED;
import static java.net.HttpURLConnection.HTTP_NOT_FOUND;
import static java.net.HttpURLConnection.HTTP_OK;
@@ -56,13 +56,12 @@
import com.google.api.services.bigquery.model.TableList;
import com.google.api.services.bigquery.model.TableReference;
import com.google.api.services.bigquery.model.TableRow;
+import com.google.cloud.bigquery.BigQueryException;
+import com.google.cloud.bigquery.BigQueryOptions;
import com.google.common.base.Function;
import com.google.common.collect.ImmutableList;
import com.google.common.collect.Iterables;
-import com.google.gcloud.bigquery.BigQueryException;
-import com.google.gcloud.bigquery.BigQueryOptions;
-
import java.io.IOException;
import java.math.BigInteger;
import java.util.List;
diff --git a/gcloud-java-bigquery/src/main/java/com/google/gcloud/bigquery/testing/RemoteBigQueryHelper.java b/gcloud-java-bigquery/src/main/java/com/google/cloud/bigquery/testing/RemoteBigQueryHelper.java
similarity index 94%
rename from gcloud-java-bigquery/src/main/java/com/google/gcloud/bigquery/testing/RemoteBigQueryHelper.java
rename to gcloud-java-bigquery/src/main/java/com/google/cloud/bigquery/testing/RemoteBigQueryHelper.java
index 491e822d683c..d844ad56235a 100644
--- a/gcloud-java-bigquery/src/main/java/com/google/gcloud/bigquery/testing/RemoteBigQueryHelper.java
+++ b/gcloud-java-bigquery/src/main/java/com/google/cloud/bigquery/testing/RemoteBigQueryHelper.java
@@ -14,13 +14,13 @@
* limitations under the License.
*/
-package com.google.gcloud.bigquery.testing;
+package com.google.cloud.bigquery.testing;
-import com.google.gcloud.AuthCredentials;
-import com.google.gcloud.RetryParams;
-import com.google.gcloud.bigquery.BigQuery;
-import com.google.gcloud.bigquery.BigQueryException;
-import com.google.gcloud.bigquery.BigQueryOptions;
+import com.google.cloud.AuthCredentials;
+import com.google.cloud.RetryParams;
+import com.google.cloud.bigquery.BigQuery;
+import com.google.cloud.bigquery.BigQueryException;
+import com.google.cloud.bigquery.BigQueryOptions;
import java.io.IOException;
import java.io.InputStream;
diff --git a/gcloud-java-bigquery/src/main/java/com/google/gcloud/bigquery/testing/package-info.java b/gcloud-java-bigquery/src/main/java/com/google/cloud/bigquery/testing/package-info.java
similarity index 96%
rename from gcloud-java-bigquery/src/main/java/com/google/gcloud/bigquery/testing/package-info.java
rename to gcloud-java-bigquery/src/main/java/com/google/cloud/bigquery/testing/package-info.java
index 9ca792ecd77d..be00683c9ce8 100644
--- a/gcloud-java-bigquery/src/main/java/com/google/gcloud/bigquery/testing/package-info.java
+++ b/gcloud-java-bigquery/src/main/java/com/google/cloud/bigquery/testing/package-info.java
@@ -35,4 +35,4 @@
* @see
* gcloud-java tools for testing
*/
-package com.google.gcloud.bigquery.testing;
+package com.google.cloud.bigquery.testing;
diff --git a/gcloud-java-bigquery/src/test/java/com/google/gcloud/bigquery/AclTest.java b/gcloud-java-bigquery/src/test/java/com/google/cloud/bigquery/AclTest.java
similarity index 88%
rename from gcloud-java-bigquery/src/test/java/com/google/gcloud/bigquery/AclTest.java
rename to gcloud-java-bigquery/src/test/java/com/google/cloud/bigquery/AclTest.java
index 438526b95b6e..51b5e1ad496e 100644
--- a/gcloud-java-bigquery/src/test/java/com/google/gcloud/bigquery/AclTest.java
+++ b/gcloud-java-bigquery/src/test/java/com/google/cloud/bigquery/AclTest.java
@@ -14,18 +14,18 @@
* limitations under the License.
*/
-package com.google.gcloud.bigquery;
+package com.google.cloud.bigquery;
import static org.junit.Assert.assertEquals;
import com.google.api.services.bigquery.model.Dataset;
-import com.google.gcloud.bigquery.Acl.Domain;
-import com.google.gcloud.bigquery.Acl.Entity;
-import com.google.gcloud.bigquery.Acl.Entity.Type;
-import com.google.gcloud.bigquery.Acl.Group;
-import com.google.gcloud.bigquery.Acl.Role;
-import com.google.gcloud.bigquery.Acl.User;
-import com.google.gcloud.bigquery.Acl.View;
+import com.google.cloud.bigquery.Acl.Domain;
+import com.google.cloud.bigquery.Acl.Entity;
+import com.google.cloud.bigquery.Acl.Entity.Type;
+import com.google.cloud.bigquery.Acl.Group;
+import com.google.cloud.bigquery.Acl.Role;
+import com.google.cloud.bigquery.Acl.User;
+import com.google.cloud.bigquery.Acl.View;
import org.junit.Test;
diff --git a/gcloud-java-bigquery/src/test/java/com/google/gcloud/bigquery/BigQueryErrorTest.java b/gcloud-java-bigquery/src/test/java/com/google/cloud/bigquery/BigQueryErrorTest.java
similarity index 97%
rename from gcloud-java-bigquery/src/test/java/com/google/gcloud/bigquery/BigQueryErrorTest.java
rename to gcloud-java-bigquery/src/test/java/com/google/cloud/bigquery/BigQueryErrorTest.java
index c8de039e233f..1d30bb87815e 100644
--- a/gcloud-java-bigquery/src/test/java/com/google/gcloud/bigquery/BigQueryErrorTest.java
+++ b/gcloud-java-bigquery/src/test/java/com/google/cloud/bigquery/BigQueryErrorTest.java
@@ -1,4 +1,4 @@
-package com.google.gcloud.bigquery;
+package com.google.cloud.bigquery;
import static org.junit.Assert.assertEquals;
diff --git a/gcloud-java-bigquery/src/test/java/com/google/gcloud/bigquery/BigQueryExceptionTest.java b/gcloud-java-bigquery/src/test/java/com/google/cloud/bigquery/BigQueryExceptionTest.java
similarity index 96%
rename from gcloud-java-bigquery/src/test/java/com/google/gcloud/bigquery/BigQueryExceptionTest.java
rename to gcloud-java-bigquery/src/test/java/com/google/cloud/bigquery/BigQueryExceptionTest.java
index 66e5289424e2..b0a32cd7f0c7 100644
--- a/gcloud-java-bigquery/src/test/java/com/google/gcloud/bigquery/BigQueryExceptionTest.java
+++ b/gcloud-java-bigquery/src/test/java/com/google/cloud/bigquery/BigQueryExceptionTest.java
@@ -14,7 +14,7 @@
* limitations under the License.
*/
-package com.google.gcloud.bigquery;
+package com.google.cloud.bigquery;
import static org.easymock.EasyMock.createMock;
import static org.easymock.EasyMock.expect;
@@ -25,8 +25,8 @@
import static org.junit.Assert.assertNull;
import static org.junit.Assert.assertTrue;
-import com.google.gcloud.BaseServiceException;
-import com.google.gcloud.RetryHelper.RetryHelperException;
+import com.google.cloud.BaseServiceException;
+import com.google.cloud.RetryHelper.RetryHelperException;
import org.junit.Test;
diff --git a/gcloud-java-bigquery/src/test/java/com/google/gcloud/bigquery/BigQueryImplTest.java b/gcloud-java-bigquery/src/test/java/com/google/cloud/bigquery/BigQueryImplTest.java
similarity index 96%
rename from gcloud-java-bigquery/src/test/java/com/google/gcloud/bigquery/BigQueryImplTest.java
rename to gcloud-java-bigquery/src/test/java/com/google/cloud/bigquery/BigQueryImplTest.java
index 305745e72da9..4a29697a73dc 100644
--- a/gcloud-java-bigquery/src/test/java/com/google/gcloud/bigquery/BigQueryImplTest.java
+++ b/gcloud-java-bigquery/src/test/java/com/google/cloud/bigquery/BigQueryImplTest.java
@@ -14,7 +14,7 @@
* limitations under the License.
*/
-package com.google.gcloud.bigquery;
+package com.google.cloud.bigquery;
import static org.easymock.EasyMock.capture;
import static org.easymock.EasyMock.eq;
@@ -31,18 +31,18 @@
import com.google.api.services.bigquery.model.TableDataInsertAllRequest;
import com.google.api.services.bigquery.model.TableDataInsertAllResponse;
import com.google.api.services.bigquery.model.TableRow;
+import com.google.cloud.Page;
+import com.google.cloud.RetryParams;
+import com.google.cloud.WriteChannel;
+import com.google.cloud.bigquery.InsertAllRequest.RowToInsert;
+import com.google.cloud.bigquery.spi.BigQueryRpc;
+import com.google.cloud.bigquery.spi.BigQueryRpc.Tuple;
+import com.google.cloud.bigquery.spi.BigQueryRpcFactory;
import com.google.common.base.Function;
import com.google.common.collect.ImmutableList;
import com.google.common.collect.ImmutableMap;
import com.google.common.collect.Iterables;
import com.google.common.collect.Lists;
-import com.google.gcloud.Page;
-import com.google.gcloud.RetryParams;
-import com.google.gcloud.WriteChannel;
-import com.google.gcloud.bigquery.InsertAllRequest.RowToInsert;
-import com.google.gcloud.bigquery.spi.BigQueryRpc;
-import com.google.gcloud.bigquery.spi.BigQueryRpc.Tuple;
-import com.google.gcloud.bigquery.spi.BigQueryRpcFactory;
import org.easymock.Capture;
import org.easymock.EasyMock;
@@ -148,12 +148,12 @@ public class BigQueryImplTest {
private static final TableRow TABLE_ROW =
new TableRow().setF(ImmutableList.of(BOOLEAN_FIELD, INTEGER_FIELD));
private static final QueryRequest QUERY_REQUEST = QueryRequest.builder("SQL")
- .maxResults(42L)
+ .pageSize(42L)
.useQueryCache(false)
.defaultDataset(DatasetId.of(DATASET))
.build();
private static final QueryRequest QUERY_REQUEST_WITH_PROJECT = QueryRequest.builder("SQL")
- .maxResults(42L)
+ .pageSize(42L)
.useQueryCache(false)
.defaultDataset(DatasetId.of(PROJECT, DATASET))
.build();
@@ -169,9 +169,9 @@ public class BigQueryImplTest {
private static final BigQuery.DatasetListOption DATASET_LIST_ALL =
BigQuery.DatasetListOption.all();
private static final BigQuery.DatasetListOption DATASET_LIST_PAGE_TOKEN =
- BigQuery.DatasetListOption.startPageToken("cursor");
- private static final BigQuery.DatasetListOption DATASET_LIST_MAX_RESULTS =
- BigQuery.DatasetListOption.maxResults(42L);
+ BigQuery.DatasetListOption.pageToken("cursor");
+ private static final BigQuery.DatasetListOption DATASET_LIST_PAGE_SIZE =
+ BigQuery.DatasetListOption.pageSize(42L);
private static final Map DATASET_LIST_OPTIONS = ImmutableMap.of(
BigQueryRpc.Option.ALL_DATASETS, true,
BigQueryRpc.Option.PAGE_TOKEN, "cursor",
@@ -188,19 +188,19 @@ public class BigQueryImplTest {
BigQuery.TableOption.fields(BigQuery.TableField.SCHEMA, BigQuery.TableField.ETAG);
// Table list options
- private static final BigQuery.TableListOption TABLE_LIST_MAX_RESULTS =
- BigQuery.TableListOption.maxResults(42L);
+ private static final BigQuery.TableListOption TABLE_LIST_PAGE_SIZE =
+ BigQuery.TableListOption.pageSize(42L);
private static final BigQuery.TableListOption TABLE_LIST_PAGE_TOKEN =
- BigQuery.TableListOption.startPageToken("cursor");
+ BigQuery.TableListOption.pageToken("cursor");
private static final Map TABLE_LIST_OPTIONS = ImmutableMap.of(
BigQueryRpc.Option.MAX_RESULTS, 42L,
BigQueryRpc.Option.PAGE_TOKEN, "cursor");
// TableData list options
- private static final BigQuery.TableDataListOption TABLE_DATA_LIST_MAX_RESULTS =
- BigQuery.TableDataListOption.maxResults(42L);
+ private static final BigQuery.TableDataListOption TABLE_DATA_LIST_PAGE_SIZE =
+ BigQuery.TableDataListOption.pageSize(42L);
private static final BigQuery.TableDataListOption TABLE_DATA_LIST_PAGE_TOKEN =
- BigQuery.TableDataListOption.startPageToken("cursor");
+ BigQuery.TableDataListOption.pageToken("cursor");
private static final BigQuery.TableDataListOption TABLE_DATA_LIST_START_INDEX =
BigQuery.TableDataListOption.startIndex(0L);
private static final Map TABLE_DATA_LIST_OPTIONS = ImmutableMap.of(
@@ -220,9 +220,9 @@ public class BigQueryImplTest {
private static final BigQuery.JobListOption JOB_LIST_STATE_FILTER =
BigQuery.JobListOption.stateFilter(JobStatus.State.DONE, JobStatus.State.PENDING);
private static final BigQuery.JobListOption JOB_LIST_PAGE_TOKEN =
- BigQuery.JobListOption.startPageToken("cursor");
- private static final BigQuery.JobListOption JOB_LIST_MAX_RESULTS =
- BigQuery.JobListOption.maxResults(42L);
+ BigQuery.JobListOption.pageToken("cursor");
+ private static final BigQuery.JobListOption JOB_LIST_PAGE_SIZE =
+ BigQuery.JobListOption.pageSize(42L);
private static final Map JOB_LIST_OPTIONS = ImmutableMap.of(
BigQueryRpc.Option.ALL_USERS, true,
BigQueryRpc.Option.STATE_FILTER, ImmutableList.of("done", "pending"),
@@ -235,9 +235,9 @@ public class BigQueryImplTest {
private static final BigQuery.QueryResultsOption QUERY_RESULTS_OPTION_INDEX =
BigQuery.QueryResultsOption.startIndex(1024L);
private static final BigQuery.QueryResultsOption QUERY_RESULTS_OPTION_PAGE_TOKEN =
- BigQuery.QueryResultsOption.startPageToken("cursor");
- private static final BigQuery.QueryResultsOption QUERY_RESULTS_OPTION_MAX_RESULTS =
- BigQuery.QueryResultsOption.maxResults(0L);
+ BigQuery.QueryResultsOption.pageToken("cursor");
+ private static final BigQuery.QueryResultsOption QUERY_RESULTS_OPTION_PAGE_SIZE =
+ BigQuery.QueryResultsOption.pageSize(0L);
private static final Map QUERY_RESULTS_OPTIONS = ImmutableMap.of(
BigQueryRpc.Option.TIMEOUT, 42L,
BigQueryRpc.Option.START_INDEX, 1024L,
@@ -388,7 +388,7 @@ public void testListDatasetsWithOptions() {
EasyMock.expect(bigqueryRpcMock.listDatasets(DATASET_LIST_OPTIONS)).andReturn(result);
EasyMock.replay(bigqueryRpcMock);
Page page = bigquery.listDatasets(DATASET_LIST_ALL, DATASET_LIST_PAGE_TOKEN,
- DATASET_LIST_MAX_RESULTS);
+ DATASET_LIST_PAGE_SIZE);
assertEquals(cursor, page.nextPageCursor());
assertArrayEquals(datasetList.toArray(), Iterables.toArray(page.values(), DatasetInfo.class));
}
@@ -560,7 +560,7 @@ public void testListTablesWithOptions() {
Tuple.of(cursor, Iterables.transform(tableList, TableInfo.TO_PB_FUNCTION));
EasyMock.expect(bigqueryRpcMock.listTables(DATASET, TABLE_LIST_OPTIONS)).andReturn(result);
EasyMock.replay(bigqueryRpcMock);
- Page page = bigquery.listTables(DATASET, TABLE_LIST_MAX_RESULTS, TABLE_LIST_PAGE_TOKEN);
+ Page page = bigquery.listTables(DATASET, TABLE_LIST_PAGE_SIZE, TABLE_LIST_PAGE_TOKEN);
assertEquals(cursor, page.nextPageCursor());
assertArrayEquals(tableList.toArray(), Iterables.toArray(page.values(), Table.class));
}
@@ -733,7 +733,7 @@ public void testListTableDataWithOptions() {
EasyMock.replay(bigqueryRpcMock);
bigquery = options.service();
Page> page = bigquery.listTableData(DATASET, TABLE,
- TABLE_DATA_LIST_MAX_RESULTS, TABLE_DATA_LIST_PAGE_TOKEN, TABLE_DATA_LIST_START_INDEX);
+ TABLE_DATA_LIST_PAGE_SIZE, TABLE_DATA_LIST_PAGE_TOKEN, TABLE_DATA_LIST_START_INDEX);
assertEquals(cursor, page.nextPageCursor());
assertArrayEquals(tableData.toArray(), Iterables.toArray(page.values(), List.class));
}
@@ -859,7 +859,7 @@ public com.google.api.services.bigquery.model.Job apply(Job job) {
EasyMock.expect(bigqueryRpcMock.listJobs(JOB_LIST_OPTIONS)).andReturn(result);
EasyMock.replay(bigqueryRpcMock);
Page page = bigquery.listJobs(JOB_LIST_ALL_USERS, JOB_LIST_STATE_FILTER,
- JOB_LIST_PAGE_TOKEN, JOB_LIST_MAX_RESULTS);
+ JOB_LIST_PAGE_TOKEN, JOB_LIST_PAGE_SIZE);
assertEquals(cursor, page.nextPageCursor());
assertArrayEquals(jobList.toArray(), Iterables.toArray(page.values(), Job.class));
}
@@ -886,12 +886,14 @@ public com.google.api.services.bigquery.model.Job apply(Job job) {
assertEquals(cursor, page.nextPageCursor());
assertArrayEquals(jobList.toArray(), Iterables.toArray(page.values(), Job.class));
String selector = (String) capturedOptions.getValue().get(JOB_OPTION_FIELDS.rpcOption());
- assertTrue(selector.contains("etag,jobs("));
+ assertTrue(selector.contains("nextPageToken,jobs("));
assertTrue(selector.contains("configuration"));
assertTrue(selector.contains("jobReference"));
assertTrue(selector.contains("statistics"));
- assertTrue(selector.contains("state,errorResult),nextPageToken"));
- assertEquals(80, selector.length());
+ assertTrue(selector.contains("state"));
+ assertTrue(selector.contains("errorResult"));
+ assertTrue(selector.contains(")"));
+ assertEquals(75, selector.length());
}
@Test
@@ -1012,7 +1014,7 @@ public void testGetQueryResultsWithOptions() {
EasyMock.replay(bigqueryRpcMock);
bigquery = options.service();
QueryResponse response = bigquery.getQueryResults(queryJob, QUERY_RESULTS_OPTION_TIME,
- QUERY_RESULTS_OPTION_INDEX, QUERY_RESULTS_OPTION_MAX_RESULTS,
+ QUERY_RESULTS_OPTION_INDEX, QUERY_RESULTS_OPTION_PAGE_SIZE,
QUERY_RESULTS_OPTION_PAGE_TOKEN);
assertEquals(queryJob, response.jobId());
assertEquals(true, response.jobCompleted());
diff --git a/gcloud-java-bigquery/src/test/java/com/google/gcloud/bigquery/CopyJobConfigurationTest.java b/gcloud-java-bigquery/src/test/java/com/google/cloud/bigquery/CopyJobConfigurationTest.java
similarity index 97%
rename from gcloud-java-bigquery/src/test/java/com/google/gcloud/bigquery/CopyJobConfigurationTest.java
rename to gcloud-java-bigquery/src/test/java/com/google/cloud/bigquery/CopyJobConfigurationTest.java
index 3f3f6f0fd15c..7d676a9b1505 100644
--- a/gcloud-java-bigquery/src/test/java/com/google/gcloud/bigquery/CopyJobConfigurationTest.java
+++ b/gcloud-java-bigquery/src/test/java/com/google/cloud/bigquery/CopyJobConfigurationTest.java
@@ -14,15 +14,15 @@
* limitations under the License.
*/
-package com.google.gcloud.bigquery;
+package com.google.cloud.bigquery;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertNotNull;
import static org.junit.Assert.assertNull;
+import com.google.cloud.bigquery.JobInfo.CreateDisposition;
+import com.google.cloud.bigquery.JobInfo.WriteDisposition;
import com.google.common.collect.ImmutableList;
-import com.google.gcloud.bigquery.JobInfo.CreateDisposition;
-import com.google.gcloud.bigquery.JobInfo.WriteDisposition;
import org.junit.Test;
diff --git a/gcloud-java-bigquery/src/test/java/com/google/gcloud/bigquery/CsvOptionsTest.java b/gcloud-java-bigquery/src/test/java/com/google/cloud/bigquery/CsvOptionsTest.java
similarity index 98%
rename from gcloud-java-bigquery/src/test/java/com/google/gcloud/bigquery/CsvOptionsTest.java
rename to gcloud-java-bigquery/src/test/java/com/google/cloud/bigquery/CsvOptionsTest.java
index 371202174431..df56a5ae096e 100644
--- a/gcloud-java-bigquery/src/test/java/com/google/gcloud/bigquery/CsvOptionsTest.java
+++ b/gcloud-java-bigquery/src/test/java/com/google/cloud/bigquery/CsvOptionsTest.java
@@ -14,7 +14,7 @@
* limitations under the License.
*/
-package com.google.gcloud.bigquery;
+package com.google.cloud.bigquery;
import static org.junit.Assert.assertEquals;
diff --git a/gcloud-java-bigquery/src/test/java/com/google/gcloud/bigquery/DatasetIdTest.java b/gcloud-java-bigquery/src/test/java/com/google/cloud/bigquery/DatasetIdTest.java
similarity index 98%
rename from gcloud-java-bigquery/src/test/java/com/google/gcloud/bigquery/DatasetIdTest.java
rename to gcloud-java-bigquery/src/test/java/com/google/cloud/bigquery/DatasetIdTest.java
index ec645d71c96f..5cf627a42e38 100644
--- a/gcloud-java-bigquery/src/test/java/com/google/gcloud/bigquery/DatasetIdTest.java
+++ b/gcloud-java-bigquery/src/test/java/com/google/cloud/bigquery/DatasetIdTest.java
@@ -14,7 +14,7 @@
* limitations under the License.
*/
-package com.google.gcloud.bigquery;
+package com.google.cloud.bigquery;
import static org.junit.Assert.assertEquals;
diff --git a/gcloud-java-bigquery/src/test/java/com/google/gcloud/bigquery/DatasetInfoTest.java b/gcloud-java-bigquery/src/test/java/com/google/cloud/bigquery/DatasetInfoTest.java
similarity index 94%
rename from gcloud-java-bigquery/src/test/java/com/google/gcloud/bigquery/DatasetInfoTest.java
rename to gcloud-java-bigquery/src/test/java/com/google/cloud/bigquery/DatasetInfoTest.java
index 20875c0fc853..6e9c961f207f 100644
--- a/gcloud-java-bigquery/src/test/java/com/google/gcloud/bigquery/DatasetInfoTest.java
+++ b/gcloud-java-bigquery/src/test/java/com/google/cloud/bigquery/DatasetInfoTest.java
@@ -14,7 +14,7 @@
* limitations under the License.
*/
-package com.google.gcloud.bigquery;
+package com.google.cloud.bigquery;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertNull;
@@ -38,7 +38,7 @@ public class DatasetInfoTest {
private static final String DESCRIPTION = "description";
private static final String ETAG = "0xFF00";
private static final String FRIENDLY_NAME = "friendlyDataset";
- private static final String ID = "P/D:1";
+ private static final String GENERATED_ID = "P/D:1";
private static final Long LAST_MODIFIED = CREATION_TIME + 50;
private static final String LOCATION = "";
private static final String SELF_LINK = "http://bigquery/p/d";
@@ -51,7 +51,7 @@ public class DatasetInfoTest {
.description(DESCRIPTION)
.etag(ETAG)
.friendlyName(FRIENDLY_NAME)
- .id(ID)
+ .generatedId(GENERATED_ID)
.lastModified(LAST_MODIFIED)
.location(LOCATION)
.selfLink(SELF_LINK)
@@ -90,7 +90,7 @@ public void testBuilder() {
assertEquals(DESCRIPTION, DATASET_INFO.description());
assertEquals(ETAG, DATASET_INFO.etag());
assertEquals(FRIENDLY_NAME, DATASET_INFO.friendlyName());
- assertEquals(ID, DATASET_INFO.id());
+ assertEquals(GENERATED_ID, DATASET_INFO.generatedId());
assertEquals(LAST_MODIFIED, DATASET_INFO.lastModified());
assertEquals(LOCATION, DATASET_INFO.location());
assertEquals(SELF_LINK, DATASET_INFO.selfLink());
@@ -101,7 +101,7 @@ public void testBuilder() {
assertEquals(DESCRIPTION, DATASET_INFO_COMPLETE.description());
assertEquals(ETAG, DATASET_INFO_COMPLETE.etag());
assertEquals(FRIENDLY_NAME, DATASET_INFO_COMPLETE.friendlyName());
- assertEquals(ID, DATASET_INFO_COMPLETE.id());
+ assertEquals(GENERATED_ID, DATASET_INFO_COMPLETE.generatedId());
assertEquals(LAST_MODIFIED, DATASET_INFO_COMPLETE.lastModified());
assertEquals(LOCATION, DATASET_INFO_COMPLETE.location());
assertEquals(SELF_LINK, DATASET_INFO_COMPLETE.selfLink());
@@ -125,7 +125,7 @@ private void compareDatasets(DatasetInfo expected, DatasetInfo value) {
assertEquals(expected.description(), value.description());
assertEquals(expected.etag(), value.etag());
assertEquals(expected.friendlyName(), value.friendlyName());
- assertEquals(expected.id(), value.id());
+ assertEquals(expected.generatedId(), value.generatedId());
assertEquals(expected.location(), value.location());
assertEquals(expected.selfLink(), value.selfLink());
assertEquals(expected.acl(), value.acl());
diff --git a/gcloud-java-bigquery/src/test/java/com/google/gcloud/bigquery/DatasetTest.java b/gcloud-java-bigquery/src/test/java/com/google/cloud/bigquery/DatasetTest.java
similarity index 97%
rename from gcloud-java-bigquery/src/test/java/com/google/gcloud/bigquery/DatasetTest.java
rename to gcloud-java-bigquery/src/test/java/com/google/cloud/bigquery/DatasetTest.java
index 373291021b23..7693e9900131 100644
--- a/gcloud-java-bigquery/src/test/java/com/google/gcloud/bigquery/DatasetTest.java
+++ b/gcloud-java-bigquery/src/test/java/com/google/cloud/bigquery/DatasetTest.java
@@ -14,7 +14,7 @@
* limitations under the License.
*/
-package com.google.gcloud.bigquery;
+package com.google.cloud.bigquery;
import static org.easymock.EasyMock.createMock;
import static org.easymock.EasyMock.createStrictMock;
@@ -30,10 +30,10 @@
import static org.junit.Assert.assertSame;
import static org.junit.Assert.assertTrue;
+import com.google.cloud.Page;
+import com.google.cloud.PageImpl;
import com.google.common.collect.ImmutableList;
import com.google.common.collect.Iterables;
-import com.google.gcloud.Page;
-import com.google.gcloud.PageImpl;
import org.junit.After;
import org.junit.Test;
@@ -51,7 +51,7 @@ public class DatasetTest {
private static final String DESCRIPTION = "description";
private static final String ETAG = "0xFF00";
private static final String FRIENDLY_NAME = "friendlyDataset";
- private static final String ID = "P/D:1";
+ private static final String GENERATED_ID = "P/D:1";
private static final Long LAST_MODIFIED = CREATION_TIME + 50;
private static final String LOCATION = "";
private static final String SELF_LINK = "http://bigquery/p/d";
@@ -102,7 +102,7 @@ public void testBuilder() {
.description(DESCRIPTION)
.etag(ETAG)
.friendlyName(FRIENDLY_NAME)
- .id(ID)
+ .generatedId(GENERATED_ID)
.lastModified(LAST_MODIFIED)
.location(LOCATION)
.selfLink(SELF_LINK)
@@ -114,7 +114,7 @@ public void testBuilder() {
assertEquals(DESCRIPTION, builtDataset.description());
assertEquals(ETAG, builtDataset.etag());
assertEquals(FRIENDLY_NAME, builtDataset.friendlyName());
- assertEquals(ID, builtDataset.id());
+ assertEquals(GENERATED_ID, builtDataset.generatedId());
assertEquals(LAST_MODIFIED, builtDataset.lastModified());
assertEquals(LOCATION, builtDataset.location());
assertEquals(SELF_LINK, builtDataset.selfLink());
@@ -260,11 +260,11 @@ public void testListWithOptions() throws Exception {
new Table(serviceMockReturnsOptions, new Table.BuilderImpl(TABLE_INFO3)));
PageImpl expectedPage = new PageImpl<>(null, "c", tableResults);
expect(bigquery.options()).andReturn(mockOptions);
- expect(bigquery.listTables(DATASET_INFO.datasetId(), BigQuery.TableListOption.maxResults(10L)))
+ expect(bigquery.listTables(DATASET_INFO.datasetId(), BigQuery.TableListOption.pageSize(10L)))
.andReturn(expectedPage);
replay(bigquery);
initializeDataset();
- Page tablePage = dataset.list(BigQuery.TableListOption.maxResults(10L));
+ Page tablePage = dataset.list(BigQuery.TableListOption.pageSize(10L));
assertArrayEquals(tableResults.toArray(), Iterables.toArray(tablePage.values(), Table.class));
assertEquals(expectedPage.nextPageCursor(), tablePage.nextPageCursor());
}
@@ -362,7 +362,7 @@ private void compareDatasetInfo(DatasetInfo expected, DatasetInfo value) {
assertEquals(expected.description(), value.description());
assertEquals(expected.etag(), value.etag());
assertEquals(expected.friendlyName(), value.friendlyName());
- assertEquals(expected.id(), value.id());
+ assertEquals(expected.generatedId(), value.generatedId());
assertEquals(expected.location(), value.location());
assertEquals(expected.selfLink(), value.selfLink());
assertEquals(expected.acl(), value.acl());
diff --git a/gcloud-java-bigquery/src/test/java/com/google/gcloud/bigquery/ExternalTableDefinitionTest.java b/gcloud-java-bigquery/src/test/java/com/google/cloud/bigquery/ExternalTableDefinitionTest.java
similarity index 99%
rename from gcloud-java-bigquery/src/test/java/com/google/gcloud/bigquery/ExternalTableDefinitionTest.java
rename to gcloud-java-bigquery/src/test/java/com/google/cloud/bigquery/ExternalTableDefinitionTest.java
index 247032dff890..e3e1c01b9403 100644
--- a/gcloud-java-bigquery/src/test/java/com/google/gcloud/bigquery/ExternalTableDefinitionTest.java
+++ b/gcloud-java-bigquery/src/test/java/com/google/cloud/bigquery/ExternalTableDefinitionTest.java
@@ -14,7 +14,7 @@
* limitations under the License.
*/
-package com.google.gcloud.bigquery;
+package com.google.cloud.bigquery;
import static org.junit.Assert.assertEquals;
diff --git a/gcloud-java-bigquery/src/test/java/com/google/gcloud/bigquery/ExtractJobConfigurationTest.java b/gcloud-java-bigquery/src/test/java/com/google/cloud/bigquery/ExtractJobConfigurationTest.java
similarity index 99%
rename from gcloud-java-bigquery/src/test/java/com/google/gcloud/bigquery/ExtractJobConfigurationTest.java
rename to gcloud-java-bigquery/src/test/java/com/google/cloud/bigquery/ExtractJobConfigurationTest.java
index 7ac67f41b1f8..62d5274e491d 100644
--- a/gcloud-java-bigquery/src/test/java/com/google/gcloud/bigquery/ExtractJobConfigurationTest.java
+++ b/gcloud-java-bigquery/src/test/java/com/google/cloud/bigquery/ExtractJobConfigurationTest.java
@@ -14,7 +14,7 @@
* limitations under the License.
*/
-package com.google.gcloud.bigquery;
+package com.google.cloud.bigquery;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertNotNull;
diff --git a/gcloud-java-bigquery/src/test/java/com/google/gcloud/bigquery/FieldTest.java b/gcloud-java-bigquery/src/test/java/com/google/cloud/bigquery/FieldTest.java
similarity index 99%
rename from gcloud-java-bigquery/src/test/java/com/google/gcloud/bigquery/FieldTest.java
rename to gcloud-java-bigquery/src/test/java/com/google/cloud/bigquery/FieldTest.java
index 5f039eaed206..8e044d889313 100644
--- a/gcloud-java-bigquery/src/test/java/com/google/gcloud/bigquery/FieldTest.java
+++ b/gcloud-java-bigquery/src/test/java/com/google/cloud/bigquery/FieldTest.java
@@ -14,7 +14,7 @@
* limitations under the License.
*/
-package com.google.gcloud.bigquery;
+package com.google.cloud.bigquery;
import static org.junit.Assert.assertEquals;
diff --git a/gcloud-java-bigquery/src/test/java/com/google/gcloud/bigquery/FieldValueTest.java b/gcloud-java-bigquery/src/test/java/com/google/cloud/bigquery/FieldValueTest.java
similarity index 99%
rename from gcloud-java-bigquery/src/test/java/com/google/gcloud/bigquery/FieldValueTest.java
rename to gcloud-java-bigquery/src/test/java/com/google/cloud/bigquery/FieldValueTest.java
index d6d879dbd58f..82086768b8ce 100644
--- a/gcloud-java-bigquery/src/test/java/com/google/gcloud/bigquery/FieldValueTest.java
+++ b/gcloud-java-bigquery/src/test/java/com/google/cloud/bigquery/FieldValueTest.java
@@ -14,7 +14,7 @@
* limitations under the License.
*/
-package com.google.gcloud.bigquery;
+package com.google.cloud.bigquery;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertFalse;
diff --git a/gcloud-java-bigquery/src/test/java/com/google/gcloud/bigquery/FormatOptionsTest.java b/gcloud-java-bigquery/src/test/java/com/google/cloud/bigquery/FormatOptionsTest.java
similarity index 98%
rename from gcloud-java-bigquery/src/test/java/com/google/gcloud/bigquery/FormatOptionsTest.java
rename to gcloud-java-bigquery/src/test/java/com/google/cloud/bigquery/FormatOptionsTest.java
index df939143156b..7406d8a7a283 100644
--- a/gcloud-java-bigquery/src/test/java/com/google/gcloud/bigquery/FormatOptionsTest.java
+++ b/gcloud-java-bigquery/src/test/java/com/google/cloud/bigquery/FormatOptionsTest.java
@@ -14,7 +14,7 @@
* limitations under the License.
*/
-package com.google.gcloud.bigquery;
+package com.google.cloud.bigquery;
import static org.junit.Assert.assertEquals;
diff --git a/gcloud-java-bigquery/src/test/java/com/google/gcloud/bigquery/InsertAllRequestTest.java b/gcloud-java-bigquery/src/test/java/com/google/cloud/bigquery/InsertAllRequestTest.java
similarity index 99%
rename from gcloud-java-bigquery/src/test/java/com/google/gcloud/bigquery/InsertAllRequestTest.java
rename to gcloud-java-bigquery/src/test/java/com/google/cloud/bigquery/InsertAllRequestTest.java
index 0866f0b9349e..607b6c4145a8 100644
--- a/gcloud-java-bigquery/src/test/java/com/google/gcloud/bigquery/InsertAllRequestTest.java
+++ b/gcloud-java-bigquery/src/test/java/com/google/cloud/bigquery/InsertAllRequestTest.java
@@ -14,7 +14,7 @@
* limitations under the License.
*/
-package com.google.gcloud.bigquery;
+package com.google.cloud.bigquery;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertFalse;
diff --git a/gcloud-java-bigquery/src/test/java/com/google/gcloud/bigquery/InsertAllResponseTest.java b/gcloud-java-bigquery/src/test/java/com/google/cloud/bigquery/InsertAllResponseTest.java
similarity index 98%
rename from gcloud-java-bigquery/src/test/java/com/google/gcloud/bigquery/InsertAllResponseTest.java
rename to gcloud-java-bigquery/src/test/java/com/google/cloud/bigquery/InsertAllResponseTest.java
index b2eb0458f27f..dc30620200bc 100644
--- a/gcloud-java-bigquery/src/test/java/com/google/gcloud/bigquery/InsertAllResponseTest.java
+++ b/gcloud-java-bigquery/src/test/java/com/google/cloud/bigquery/InsertAllResponseTest.java
@@ -14,7 +14,7 @@
* limitations under the License.
*/
-package com.google.gcloud.bigquery;
+package com.google.cloud.bigquery;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertFalse;
diff --git a/gcloud-java-bigquery/src/test/java/com/google/gcloud/bigquery/JobIdTest.java b/gcloud-java-bigquery/src/test/java/com/google/cloud/bigquery/JobIdTest.java
similarity index 97%
rename from gcloud-java-bigquery/src/test/java/com/google/gcloud/bigquery/JobIdTest.java
rename to gcloud-java-bigquery/src/test/java/com/google/cloud/bigquery/JobIdTest.java
index 740830f07544..68caf62413c9 100644
--- a/gcloud-java-bigquery/src/test/java/com/google/gcloud/bigquery/JobIdTest.java
+++ b/gcloud-java-bigquery/src/test/java/com/google/cloud/bigquery/JobIdTest.java
@@ -14,7 +14,7 @@
* limitations under the License.
*/
-package com.google.gcloud.bigquery;
+package com.google.cloud.bigquery;
import static org.junit.Assert.assertEquals;
diff --git a/gcloud-java-bigquery/src/test/java/com/google/gcloud/bigquery/JobInfoTest.java b/gcloud-java-bigquery/src/test/java/com/google/cloud/bigquery/JobInfoTest.java
similarity index 94%
rename from gcloud-java-bigquery/src/test/java/com/google/gcloud/bigquery/JobInfoTest.java
rename to gcloud-java-bigquery/src/test/java/com/google/cloud/bigquery/JobInfoTest.java
index 260088470aff..d7fde0957a2f 100644
--- a/gcloud-java-bigquery/src/test/java/com/google/gcloud/bigquery/JobInfoTest.java
+++ b/gcloud-java-bigquery/src/test/java/com/google/cloud/bigquery/JobInfoTest.java
@@ -14,20 +14,21 @@
* limitations under the License.
*/
-package com.google.gcloud.bigquery;
+package com.google.cloud.bigquery;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertNotNull;
import static org.junit.Assert.assertNull;
import static org.junit.Assert.assertTrue;
+import com.google.cloud.bigquery.JobInfo.CreateDisposition;
+import com.google.cloud.bigquery.JobInfo.WriteDisposition;
+import com.google.cloud.bigquery.JobStatistics.CopyStatistics;
+import com.google.cloud.bigquery.JobStatistics.ExtractStatistics;
+import com.google.cloud.bigquery.JobStatistics.LoadStatistics;
+import com.google.cloud.bigquery.JobStatistics.QueryStatistics;
import com.google.common.collect.ImmutableList;
import com.google.common.collect.ImmutableMap;
-import com.google.gcloud.bigquery.JobInfo.CreateDisposition;
-import com.google.gcloud.bigquery.JobInfo.WriteDisposition;
-import com.google.gcloud.bigquery.JobStatistics.ExtractStatistics;
-import com.google.gcloud.bigquery.JobStatistics.LoadStatistics;
-import com.google.gcloud.bigquery.JobStatistics.QueryStatistics;
import org.junit.Test;
@@ -37,12 +38,12 @@
public class JobInfoTest {
private static final String ETAG = "etag";
- private static final String ID = "id";
+ private static final String GENERATED_ID = "id";
private static final String SELF_LINK = "selfLink";
private static final String EMAIL = "email";
private static final JobId JOB_ID = JobId.of("job");
private static final JobStatus JOB_STATUS = new JobStatus(JobStatus.State.DONE);
- private static final JobStatistics COPY_JOB_STATISTICS = JobStatistics.builder()
+ private static final CopyStatistics COPY_JOB_STATISTICS = CopyStatistics.builder()
.creationTime(1L)
.endTime(3L)
.startTime(2L)
@@ -163,7 +164,7 @@ public class JobInfoTest {
.statistics(COPY_JOB_STATISTICS)
.jobId(JOB_ID)
.etag(ETAG)
- .id(ID)
+ .generatedId(GENERATED_ID)
.selfLink(SELF_LINK)
.userEmail(EMAIL)
.status(JOB_STATUS)
@@ -173,7 +174,7 @@ public class JobInfoTest {
.statistics(EXTRACT_JOB_STATISTICS)
.jobId(JOB_ID)
.etag(ETAG)
- .id(ID)
+ .generatedId(GENERATED_ID)
.selfLink(SELF_LINK)
.userEmail(EMAIL)
.status(JOB_STATUS)
@@ -183,7 +184,7 @@ public class JobInfoTest {
.statistics(LOAD_JOB_STATISTICS)
.jobId(JOB_ID)
.etag(ETAG)
- .id(ID)
+ .generatedId(GENERATED_ID)
.selfLink(SELF_LINK)
.userEmail(EMAIL)
.status(JOB_STATUS)
@@ -193,7 +194,7 @@ public class JobInfoTest {
.statistics(QUERY_JOB_STATISTICS)
.jobId(JOB_ID)
.etag(ETAG)
- .id(ID)
+ .generatedId(GENERATED_ID)
.selfLink(SELF_LINK)
.userEmail(EMAIL)
.status(JOB_STATUS)
@@ -266,7 +267,7 @@ public void testToBuilderIncomplete() {
@Test
public void testBuilder() {
assertEquals(ETAG, COPY_JOB.etag());
- assertEquals(ID, COPY_JOB.id());
+ assertEquals(GENERATED_ID, COPY_JOB.generatedId());
assertEquals(SELF_LINK, COPY_JOB.selfLink());
assertEquals(EMAIL, COPY_JOB.userEmail());
assertEquals(JOB_ID, COPY_JOB.jobId());
@@ -275,7 +276,7 @@ public void testBuilder() {
assertEquals(COPY_JOB_STATISTICS, COPY_JOB.statistics());
assertEquals(ETAG, EXTRACT_JOB.etag());
- assertEquals(ID, EXTRACT_JOB.id());
+ assertEquals(GENERATED_ID, EXTRACT_JOB.generatedId());
assertEquals(SELF_LINK, EXTRACT_JOB.selfLink());
assertEquals(EMAIL, EXTRACT_JOB.userEmail());
assertEquals(JOB_ID, EXTRACT_JOB.jobId());
@@ -284,7 +285,7 @@ public void testBuilder() {
assertEquals(EXTRACT_JOB_STATISTICS, EXTRACT_JOB.statistics());
assertEquals(ETAG, LOAD_JOB.etag());
- assertEquals(ID, LOAD_JOB.id());
+ assertEquals(GENERATED_ID, LOAD_JOB.generatedId());
assertEquals(SELF_LINK, LOAD_JOB.selfLink());
assertEquals(EMAIL, LOAD_JOB.userEmail());
assertEquals(JOB_ID, LOAD_JOB.jobId());
@@ -293,7 +294,7 @@ public void testBuilder() {
assertEquals(LOAD_JOB_STATISTICS, LOAD_JOB.statistics());
assertEquals(ETAG, QUERY_JOB.etag());
- assertEquals(ID, QUERY_JOB.id());
+ assertEquals(GENERATED_ID, QUERY_JOB.generatedId());
assertEquals(SELF_LINK, QUERY_JOB.selfLink());
assertEquals(EMAIL, QUERY_JOB.userEmail());
assertEquals(JOB_ID, QUERY_JOB.jobId());
@@ -359,7 +360,7 @@ private void compareJobInfo(JobInfo expected, JobInfo value) {
assertEquals(expected.hashCode(), value.hashCode());
assertEquals(expected.toString(), value.toString());
assertEquals(expected.etag(), value.etag());
- assertEquals(expected.id(), value.id());
+ assertEquals(expected.generatedId(), value.generatedId());
assertEquals(expected.jobId(), value.jobId());
assertEquals(expected.selfLink(), value.selfLink());
assertEquals(expected.status(), value.status());
diff --git a/gcloud-java-bigquery/src/test/java/com/google/gcloud/bigquery/JobStatisticsTest.java b/gcloud-java-bigquery/src/test/java/com/google/cloud/bigquery/JobStatisticsTest.java
similarity index 92%
rename from gcloud-java-bigquery/src/test/java/com/google/gcloud/bigquery/JobStatisticsTest.java
rename to gcloud-java-bigquery/src/test/java/com/google/cloud/bigquery/JobStatisticsTest.java
index 1ec67d034754..c4c8c5ae6f4b 100644
--- a/gcloud-java-bigquery/src/test/java/com/google/gcloud/bigquery/JobStatisticsTest.java
+++ b/gcloud-java-bigquery/src/test/java/com/google/cloud/bigquery/JobStatisticsTest.java
@@ -14,15 +14,16 @@
* limitations under the License.
*/
-package com.google.gcloud.bigquery;
+package com.google.cloud.bigquery;
import static org.junit.Assert.assertEquals;
import com.google.common.collect.ImmutableList;
-import com.google.gcloud.bigquery.JobStatistics.ExtractStatistics;
-import com.google.gcloud.bigquery.JobStatistics.LoadStatistics;
-import com.google.gcloud.bigquery.JobStatistics.QueryStatistics;
-import com.google.gcloud.bigquery.QueryStage.QueryStep;
+import com.google.cloud.bigquery.JobStatistics.CopyStatistics;
+import com.google.cloud.bigquery.JobStatistics.ExtractStatistics;
+import com.google.cloud.bigquery.JobStatistics.LoadStatistics;
+import com.google.cloud.bigquery.JobStatistics.QueryStatistics;
+import com.google.cloud.bigquery.QueryStage.QueryStep;
import org.junit.Test;
@@ -42,6 +43,11 @@ public class JobStatisticsTest {
private static final Long CREATION_TIME = 10L;
private static final Long END_TIME = 20L;
private static final Long START_TIME = 15L;
+ private static final CopyStatistics COPY_STATISTICS = CopyStatistics.builder()
+ .creationTime(CREATION_TIME)
+ .endTime(END_TIME)
+ .startTime(START_TIME)
+ .build();
private static final ExtractStatistics EXTRACT_STATISTICS = ExtractStatistics.builder()
.creationTime(CREATION_TIME)
.endTime(END_TIME)
@@ -71,7 +77,7 @@ public class JobStatisticsTest {
private static final QueryStage QUERY_STAGE = QueryStage.builder()
.computeRatioAvg(1.1)
.computeRatioMax(2.2)
- .id(42L)
+ .generatedId(42L)
.name("stage")
.readRatioAvg(3.3)
.readRatioMax(4.4)
@@ -101,17 +107,12 @@ public class JobStatisticsTest {
.billingTier(BILLING_TIER)
.cacheHit(CACHE_HIT)
.build();
- private static final JobStatistics STATISTICS = JobStatistics.builder()
- .creationTime(CREATION_TIME)
- .endTime(END_TIME)
- .startTime(START_TIME)
- .build();
@Test
public void testBuilder() {
- assertEquals(CREATION_TIME, STATISTICS.creationTime());
- assertEquals(START_TIME, STATISTICS.startTime());
- assertEquals(END_TIME, STATISTICS.endTime());
+ assertEquals(CREATION_TIME, COPY_STATISTICS.creationTime());
+ assertEquals(START_TIME, COPY_STATISTICS.startTime());
+ assertEquals(END_TIME, COPY_STATISTICS.endTime());
assertEquals(CREATION_TIME, EXTRACT_STATISTICS.creationTime());
assertEquals(START_TIME, EXTRACT_STATISTICS.startTime());
@@ -160,7 +161,7 @@ public void testToPbAndFromPb() {
ExtractStatistics.fromPb(EXTRACT_STATISTICS.toPb()));
compareLoadStatistics(LOAD_STATISTICS, LoadStatistics.fromPb(LOAD_STATISTICS.toPb()));
compareQueryStatistics(QUERY_STATISTICS, QueryStatistics.fromPb(QUERY_STATISTICS.toPb()));
- compareStatistics(STATISTICS, JobStatistics.fromPb(STATISTICS.toPb()));
+ compareStatistics(COPY_STATISTICS, JobStatistics.fromPb(COPY_STATISTICS.toPb()));
compareLoadStatistics(LOAD_STATISTICS_INCOMPLETE,
LoadStatistics.fromPb(LOAD_STATISTICS_INCOMPLETE.toPb()));
diff --git a/gcloud-java-bigquery/src/test/java/com/google/gcloud/bigquery/JobStatusTest.java b/gcloud-java-bigquery/src/test/java/com/google/cloud/bigquery/JobStatusTest.java
similarity index 98%
rename from gcloud-java-bigquery/src/test/java/com/google/gcloud/bigquery/JobStatusTest.java
rename to gcloud-java-bigquery/src/test/java/com/google/cloud/bigquery/JobStatusTest.java
index c44386a3e72c..78a4345a339b 100644
--- a/gcloud-java-bigquery/src/test/java/com/google/gcloud/bigquery/JobStatusTest.java
+++ b/gcloud-java-bigquery/src/test/java/com/google/cloud/bigquery/JobStatusTest.java
@@ -14,7 +14,7 @@
* limitations under the License.
*/
-package com.google.gcloud.bigquery;
+package com.google.cloud.bigquery;
import static org.junit.Assert.assertEquals;
diff --git a/gcloud-java-bigquery/src/test/java/com/google/gcloud/bigquery/JobTest.java b/gcloud-java-bigquery/src/test/java/com/google/cloud/bigquery/JobTest.java
similarity index 95%
rename from gcloud-java-bigquery/src/test/java/com/google/gcloud/bigquery/JobTest.java
rename to gcloud-java-bigquery/src/test/java/com/google/cloud/bigquery/JobTest.java
index db51706fff5a..44e5e201e95c 100644
--- a/gcloud-java-bigquery/src/test/java/com/google/gcloud/bigquery/JobTest.java
+++ b/gcloud-java-bigquery/src/test/java/com/google/cloud/bigquery/JobTest.java
@@ -14,7 +14,7 @@
* limitations under the License.
*/
-package com.google.gcloud.bigquery;
+package com.google.cloud.bigquery;
import static org.easymock.EasyMock.createMock;
import static org.easymock.EasyMock.createStrictMock;
@@ -27,6 +27,8 @@
import static org.junit.Assert.assertSame;
import static org.junit.Assert.assertTrue;
+import com.google.cloud.bigquery.JobStatistics.CopyStatistics;
+
import org.junit.After;
import org.junit.Test;
@@ -36,11 +38,11 @@ public class JobTest {
private static final TableId TABLE_ID1 = TableId.of("dataset", "table1");
private static final TableId TABLE_ID2 = TableId.of("dataset", "table2");
private static final String ETAG = "etag";
- private static final String ID = "id";
+ private static final String GENERATED_ID = "id";
private static final String SELF_LINK = "selfLink";
private static final String EMAIL = "email";
private static final JobStatus JOB_STATUS = new JobStatus(JobStatus.State.DONE);
- private static final JobStatistics COPY_JOB_STATISTICS = JobStatistics.builder()
+ private static final JobStatistics COPY_JOB_STATISTICS = CopyStatistics.builder()
.creationTime(1L)
.endTime(3L)
.startTime(2L)
@@ -52,7 +54,7 @@ public class JobTest {
.statistics(COPY_JOB_STATISTICS)
.jobId(JOB_ID)
.etag(ETAG)
- .id(ID)
+ .generatedId(GENERATED_ID)
.selfLink(SELF_LINK)
.userEmail(EMAIL)
.status(JOB_STATUS)
@@ -89,13 +91,13 @@ public void testBuilder() {
.statistics(COPY_JOB_STATISTICS)
.jobId(JOB_ID)
.etag(ETAG)
- .id(ID)
+ .generatedId(GENERATED_ID)
.selfLink(SELF_LINK)
.userEmail(EMAIL)
.status(JOB_STATUS)
.build();
assertEquals(ETAG, builtJob.etag());
- assertEquals(ID, builtJob.id());
+ assertEquals(GENERATED_ID, builtJob.generatedId());
assertEquals(SELF_LINK, builtJob.selfLink());
assertEquals(EMAIL, builtJob.userEmail());
assertEquals(JOB_ID, builtJob.jobId());
@@ -172,7 +174,7 @@ public void testIsDone_NotExists() throws Exception {
expect(bigquery.getJob(JOB_INFO.jobId(), expectedOptions)).andReturn(null);
replay(bigquery);
initializeJob();
- assertFalse(job.isDone());
+ assertTrue(job.isDone());
}
@Test
@@ -247,7 +249,7 @@ private void compareJobInfo(JobInfo expected, JobInfo value) {
assertEquals(expected.hashCode(), value.hashCode());
assertEquals(expected.toString(), value.toString());
assertEquals(expected.etag(), value.etag());
- assertEquals(expected.id(), value.id());
+ assertEquals(expected.generatedId(), value.generatedId());
assertEquals(expected.jobId(), value.jobId());
assertEquals(expected.selfLink(), value.selfLink());
assertEquals(expected.status(), value.status());
diff --git a/gcloud-java-bigquery/src/test/java/com/google/gcloud/bigquery/LoadJobConfigurationTest.java b/gcloud-java-bigquery/src/test/java/com/google/cloud/bigquery/LoadJobConfigurationTest.java
similarity index 97%
rename from gcloud-java-bigquery/src/test/java/com/google/gcloud/bigquery/LoadJobConfigurationTest.java
rename to gcloud-java-bigquery/src/test/java/com/google/cloud/bigquery/LoadJobConfigurationTest.java
index 88ae6a4fc1b8..9980f85426d8 100644
--- a/gcloud-java-bigquery/src/test/java/com/google/gcloud/bigquery/LoadJobConfigurationTest.java
+++ b/gcloud-java-bigquery/src/test/java/com/google/cloud/bigquery/LoadJobConfigurationTest.java
@@ -14,13 +14,13 @@
* limitations under the License.
*/
-package com.google.gcloud.bigquery;
+package com.google.cloud.bigquery;
import static org.junit.Assert.assertEquals;
+import com.google.cloud.bigquery.JobInfo.CreateDisposition;
+import com.google.cloud.bigquery.JobInfo.WriteDisposition;
import com.google.common.collect.ImmutableList;
-import com.google.gcloud.bigquery.JobInfo.CreateDisposition;
-import com.google.gcloud.bigquery.JobInfo.WriteDisposition;
import org.junit.Test;
diff --git a/gcloud-java-bigquery/src/test/java/com/google/cloud/bigquery/OptionTest.java b/gcloud-java-bigquery/src/test/java/com/google/cloud/bigquery/OptionTest.java
new file mode 100644
index 000000000000..2e40d63ff80c
--- /dev/null
+++ b/gcloud-java-bigquery/src/test/java/com/google/cloud/bigquery/OptionTest.java
@@ -0,0 +1,65 @@
+/*
+ * Copyright 2015 Google Inc. All Rights Reserved.
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+package com.google.cloud.bigquery;
+
+import static org.junit.Assert.assertEquals;
+import static org.junit.Assert.assertNotEquals;
+import static org.junit.Assert.assertNull;
+
+import com.google.cloud.bigquery.spi.BigQueryRpc;
+
+import org.junit.Rule;
+import org.junit.Test;
+import org.junit.rules.ExpectedException;
+
+public class OptionTest {
+
+ private static final BigQueryRpc.Option RPC_OPTION = BigQueryRpc.Option.PAGE_TOKEN;
+ private static final BigQueryRpc.Option ANOTHER_RPC_OPTION = BigQueryRpc.Option.FIELDS;
+ private static final String VALUE = "some value";
+ private static final String OTHER_VALUE = "another value";
+ private static final Option OPTION = new Option(RPC_OPTION, VALUE) {};
+ private static final Option OPTION_EQUALS = new Option(RPC_OPTION, VALUE) {};
+ private static final Option OPTION_NOT_EQUALS1 = new Option(RPC_OPTION, OTHER_VALUE) {};
+ private static final Option OPTION_NOT_EQUALS2 = new Option(ANOTHER_RPC_OPTION, VALUE) {};
+
+ @Rule
+ public ExpectedException thrown = ExpectedException.none();
+
+ @Test
+ public void testEquals() {
+ assertEquals(OPTION, OPTION_EQUALS);
+ assertNotEquals(OPTION, OPTION_NOT_EQUALS1);
+ assertNotEquals(OPTION, OPTION_NOT_EQUALS2);
+ }
+
+ @Test
+ public void testHashCode() {
+ assertEquals(OPTION.hashCode(), OPTION_EQUALS.hashCode());
+ }
+
+ @Test
+ public void testConstructor() {
+ assertEquals(RPC_OPTION, OPTION.rpcOption());
+ assertEquals(VALUE, OPTION.value());
+ Option option = new Option(RPC_OPTION, null) {};
+ assertEquals(RPC_OPTION, option.rpcOption());
+ assertNull(option.value());
+ thrown.expect(NullPointerException.class);
+ new Option(null, VALUE) {};
+ }
+}
diff --git a/gcloud-java-bigquery/src/test/java/com/google/gcloud/bigquery/QueryJobConfigurationTest.java b/gcloud-java-bigquery/src/test/java/com/google/cloud/bigquery/QueryJobConfigurationTest.java
similarity index 97%
rename from gcloud-java-bigquery/src/test/java/com/google/gcloud/bigquery/QueryJobConfigurationTest.java
rename to gcloud-java-bigquery/src/test/java/com/google/cloud/bigquery/QueryJobConfigurationTest.java
index 1ef270ee69cf..914a6db4d5eb 100644
--- a/gcloud-java-bigquery/src/test/java/com/google/gcloud/bigquery/QueryJobConfigurationTest.java
+++ b/gcloud-java-bigquery/src/test/java/com/google/cloud/bigquery/QueryJobConfigurationTest.java
@@ -14,18 +14,18 @@
* limitations under the License.
*/
-package com.google.gcloud.bigquery;
+package com.google.cloud.bigquery;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertNotNull;
import static org.junit.Assert.assertNull;
import static org.junit.Assert.assertTrue;
+import com.google.cloud.bigquery.JobInfo.CreateDisposition;
+import com.google.cloud.bigquery.JobInfo.WriteDisposition;
+import com.google.cloud.bigquery.QueryJobConfiguration.Priority;
import com.google.common.collect.ImmutableList;
import com.google.common.collect.ImmutableMap;
-import com.google.gcloud.bigquery.JobInfo.CreateDisposition;
-import com.google.gcloud.bigquery.JobInfo.WriteDisposition;
-import com.google.gcloud.bigquery.QueryJobConfiguration.Priority;
import org.junit.Test;
diff --git a/gcloud-java-bigquery/src/test/java/com/google/gcloud/bigquery/QueryRequestTest.java b/gcloud-java-bigquery/src/test/java/com/google/cloud/bigquery/QueryRequestTest.java
similarity index 92%
rename from gcloud-java-bigquery/src/test/java/com/google/gcloud/bigquery/QueryRequestTest.java
rename to gcloud-java-bigquery/src/test/java/com/google/cloud/bigquery/QueryRequestTest.java
index 370b4d614cbf..f3682aa78457 100644
--- a/gcloud-java-bigquery/src/test/java/com/google/gcloud/bigquery/QueryRequestTest.java
+++ b/gcloud-java-bigquery/src/test/java/com/google/cloud/bigquery/QueryRequestTest.java
@@ -14,7 +14,7 @@
* limitations under the License.
*/
-package com.google.gcloud.bigquery;
+package com.google.cloud.bigquery;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertNull;
@@ -29,13 +29,13 @@ public class QueryRequestTest {
private static final DatasetId DATASET_ID = DatasetId.of("dataset");
private static final Boolean USE_QUERY_CACHE = true;
private static final Boolean DRY_RUN = false;
- private static final Long MAX_RESULTS = 42L;
+ private static final Long PAGE_SIZE = 42L;
private static final Long MAX_WAIT_TIME = 42000L;
private static final QueryRequest QUERY_REQUEST = QueryRequest.builder(QUERY)
.useQueryCache(USE_QUERY_CACHE)
.defaultDataset(DATASET_ID)
.dryRun(DRY_RUN)
- .maxResults(MAX_RESULTS)
+ .pageSize(PAGE_SIZE)
.maxWaitTime(MAX_WAIT_TIME)
.build();
@@ -65,7 +65,7 @@ public void testBuilder() {
assertEquals(USE_QUERY_CACHE, QUERY_REQUEST.useQueryCache());
assertEquals(DATASET_ID, QUERY_REQUEST.defaultDataset());
assertEquals(DRY_RUN, QUERY_REQUEST.dryRun());
- assertEquals(MAX_RESULTS, QUERY_REQUEST.maxResults());
+ assertEquals(PAGE_SIZE, QUERY_REQUEST.pageSize());
assertEquals(MAX_WAIT_TIME, QUERY_REQUEST.maxWaitTime());
thrown.expect(NullPointerException.class);
QueryRequest.builder(null);
@@ -78,7 +78,7 @@ public void testOf() {
assertNull(request.useQueryCache());
assertNull(request.defaultDataset());
assertNull(request.dryRun());
- assertNull(request.maxResults());
+ assertNull(request.pageSize());
assertNull(request.maxWaitTime());
thrown.expect(NullPointerException.class);
QueryRequest.of(null);
@@ -102,7 +102,7 @@ private void compareQueryRequest(QueryRequest expected, QueryRequest value) {
assertEquals(expected.useQueryCache(), value.useQueryCache());
assertEquals(expected.defaultDataset(), value.defaultDataset());
assertEquals(expected.dryRun(), value.dryRun());
- assertEquals(expected.maxResults(), value.maxResults());
+ assertEquals(expected.pageSize(), value.pageSize());
assertEquals(expected.maxWaitTime(), value.maxWaitTime());
}
}
diff --git a/gcloud-java-bigquery/src/test/java/com/google/gcloud/bigquery/QueryResponseTest.java b/gcloud-java-bigquery/src/test/java/com/google/cloud/bigquery/QueryResponseTest.java
similarity index 99%
rename from gcloud-java-bigquery/src/test/java/com/google/gcloud/bigquery/QueryResponseTest.java
rename to gcloud-java-bigquery/src/test/java/com/google/cloud/bigquery/QueryResponseTest.java
index 08e885c8b3aa..8eae6a9e03e3 100644
--- a/gcloud-java-bigquery/src/test/java/com/google/gcloud/bigquery/QueryResponseTest.java
+++ b/gcloud-java-bigquery/src/test/java/com/google/cloud/bigquery/QueryResponseTest.java
@@ -14,7 +14,7 @@
* limitations under the License.
*/
-package com.google.gcloud.bigquery;
+package com.google.cloud.bigquery;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertFalse;
diff --git a/gcloud-java-bigquery/src/test/java/com/google/gcloud/bigquery/QueryResultTest.java b/gcloud-java-bigquery/src/test/java/com/google/cloud/bigquery/QueryResultTest.java
similarity index 98%
rename from gcloud-java-bigquery/src/test/java/com/google/gcloud/bigquery/QueryResultTest.java
rename to gcloud-java-bigquery/src/test/java/com/google/cloud/bigquery/QueryResultTest.java
index b6810ed93143..db4df54bfc0c 100644
--- a/gcloud-java-bigquery/src/test/java/com/google/gcloud/bigquery/QueryResultTest.java
+++ b/gcloud-java-bigquery/src/test/java/com/google/cloud/bigquery/QueryResultTest.java
@@ -14,7 +14,7 @@
* limitations under the License.
*/
-package com.google.gcloud.bigquery;
+package com.google.cloud.bigquery;
import static org.junit.Assert.assertEquals;
diff --git a/gcloud-java-bigquery/src/test/java/com/google/gcloud/bigquery/QueryStageTest.java b/gcloud-java-bigquery/src/test/java/com/google/cloud/bigquery/QueryStageTest.java
similarity index 95%
rename from gcloud-java-bigquery/src/test/java/com/google/gcloud/bigquery/QueryStageTest.java
rename to gcloud-java-bigquery/src/test/java/com/google/cloud/bigquery/QueryStageTest.java
index 99a7c8096454..670143190cf5 100644
--- a/gcloud-java-bigquery/src/test/java/com/google/gcloud/bigquery/QueryStageTest.java
+++ b/gcloud-java-bigquery/src/test/java/com/google/cloud/bigquery/QueryStageTest.java
@@ -14,13 +14,13 @@
* limitations under the License.
*/
-package com.google.gcloud.bigquery;
+package com.google.cloud.bigquery;
import static org.junit.Assert.assertEquals;
import com.google.api.services.bigquery.model.ExplainQueryStep;
+import com.google.cloud.bigquery.QueryStage.QueryStep;
import com.google.common.collect.ImmutableList;
-import com.google.gcloud.bigquery.QueryStage.QueryStep;
import org.junit.Test;
@@ -48,7 +48,7 @@ public class QueryStageTest {
private static final QueryStage QUERY_STAGE = QueryStage.builder()
.computeRatioAvg(COMPUTE_RATIO_AVG)
.computeRatioMax(COMPUTE_RATIO_MAX)
- .id(ID)
+ .generatedId(ID)
.name(NAME)
.readRatioAvg(READ_RATIO_AVG)
.readRatioMax(READ_RATIO_MAX)
@@ -73,7 +73,7 @@ public void testQueryStepConstructor() {
public void testBuilder() {
assertEquals(COMPUTE_RATIO_AVG, QUERY_STAGE.computeRatioAvg(), 0);
assertEquals(COMPUTE_RATIO_MAX, QUERY_STAGE.computeRatioMax(), 0);
- assertEquals(ID, QUERY_STAGE.id());
+ assertEquals(ID, QUERY_STAGE.generatedId());
assertEquals(NAME, QUERY_STAGE.name());
assertEquals(READ_RATIO_AVG, QUERY_STAGE.readRatioAvg(), 0);
assertEquals(READ_RATIO_MAX, QUERY_STAGE.readRatioMax(), 0);
@@ -108,7 +108,7 @@ private void compareQueryStage(QueryStage expected, QueryStage value) {
assertEquals(expected, value);
assertEquals(expected.computeRatioAvg(), value.computeRatioAvg(), 0);
assertEquals(expected.computeRatioMax(), value.computeRatioMax(), 0);
- assertEquals(expected.id(), value.id());
+ assertEquals(expected.generatedId(), value.generatedId());
assertEquals(expected.name(), value.name());
assertEquals(expected.readRatioAvg(), value.readRatioAvg(), 0);
assertEquals(expected.readRatioMax(), value.readRatioMax(), 0);
diff --git a/gcloud-java-bigquery/src/test/java/com/google/gcloud/bigquery/SchemaTest.java b/gcloud-java-bigquery/src/test/java/com/google/cloud/bigquery/SchemaTest.java
similarity index 98%
rename from gcloud-java-bigquery/src/test/java/com/google/gcloud/bigquery/SchemaTest.java
rename to gcloud-java-bigquery/src/test/java/com/google/cloud/bigquery/SchemaTest.java
index d24268d2e7cd..312b7e674991 100644
--- a/gcloud-java-bigquery/src/test/java/com/google/gcloud/bigquery/SchemaTest.java
+++ b/gcloud-java-bigquery/src/test/java/com/google/cloud/bigquery/SchemaTest.java
@@ -14,7 +14,7 @@
* limitations under the License.
*/
-package com.google.gcloud.bigquery;
+package com.google.cloud.bigquery;
import static org.junit.Assert.assertEquals;
diff --git a/gcloud-java-bigquery/src/test/java/com/google/gcloud/bigquery/SerializationTest.java b/gcloud-java-bigquery/src/test/java/com/google/cloud/bigquery/SerializationTest.java
similarity index 78%
rename from gcloud-java-bigquery/src/test/java/com/google/gcloud/bigquery/SerializationTest.java
rename to gcloud-java-bigquery/src/test/java/com/google/cloud/bigquery/SerializationTest.java
index d877bff2138c..30b1b9e067ec 100644
--- a/gcloud-java-bigquery/src/test/java/com/google/gcloud/bigquery/SerializationTest.java
+++ b/gcloud-java-bigquery/src/test/java/com/google/cloud/bigquery/SerializationTest.java
@@ -14,32 +14,21 @@
* limitations under the License.
*/
-package com.google.gcloud.bigquery;
-
-import static org.junit.Assert.assertEquals;
-import static org.junit.Assert.assertNotSame;
+package com.google.cloud.bigquery;
+import com.google.cloud.AuthCredentials;
+import com.google.cloud.BaseSerializationTest;
+import com.google.cloud.Restorable;
+import com.google.cloud.bigquery.StandardTableDefinition.StreamingBuffer;
import com.google.common.collect.ImmutableList;
import com.google.common.collect.ImmutableMap;
-import com.google.gcloud.AuthCredentials;
-import com.google.gcloud.RestorableState;
-import com.google.gcloud.RetryParams;
-import com.google.gcloud.WriteChannel;
-import com.google.gcloud.bigquery.StandardTableDefinition.StreamingBuffer;
-
-import org.junit.Test;
-import java.io.ByteArrayInputStream;
-import java.io.ByteArrayOutputStream;
-import java.io.IOException;
-import java.io.ObjectInputStream;
-import java.io.ObjectOutputStream;
import java.io.Serializable;
import java.nio.charset.StandardCharsets;
import java.util.List;
import java.util.Map;
-public class SerializationTest {
+public class SerializationTest extends BaseSerializationTest {
private static final Acl DOMAIN_ACCESS =
Acl.of(new Acl.Domain("domain"), Acl.Role.WRITER);
@@ -55,7 +44,7 @@ public class SerializationTest {
private static final String DESCRIPTION = "Description";
private static final String ETAG = "0xFF00";
private static final String FRIENDLY_NAME = "friendlyDataset";
- private static final String ID = "P/D:1";
+ private static final String GENERATED_ID = "P/D:1";
private static final Long LAST_MODIFIED = CREATION_TIME + 50;
private static final String LOCATION = "";
private static final String SELF_LINK = "http://bigquery/p/d";
@@ -67,7 +56,7 @@ public class SerializationTest {
.description(DESCRIPTION)
.etag(ETAG)
.friendlyName(FRIENDLY_NAME)
- .id(ID)
+ .generatedId(GENERATED_ID)
.lastModified(LAST_MODIFIED)
.location(LOCATION)
.selfLink(SELF_LINK)
@@ -117,27 +106,28 @@ public class SerializationTest {
.creationTime(CREATION_TIME)
.description(DESCRIPTION)
.etag(ETAG)
- .id(ID)
+ .generatedId(GENERATED_ID)
.build();
private static final TableDefinition VIEW_DEFINITION = ViewDefinition.of("QUERY");
private static final TableInfo VIEW_INFO = TableInfo.builder(TABLE_ID, VIEW_DEFINITION)
.creationTime(CREATION_TIME)
.description(DESCRIPTION)
.etag(ETAG)
- .id(ID)
+ .generatedId(GENERATED_ID)
.build();
private static final TableInfo EXTERNAL_TABLE_INFO =
TableInfo.builder(TABLE_ID, EXTERNAL_TABLE_DEFINITION)
.creationTime(CREATION_TIME)
.description(DESCRIPTION)
.etag(ETAG)
- .id(ID)
+ .generatedId(GENERATED_ID)
+ .build();
+ private static final JobStatistics.CopyStatistics COPY_STATISTICS =
+ JobStatistics.CopyStatistics.builder()
+ .creationTime(1L)
+ .endTime(3L)
+ .startTime(2L)
.build();
- private static final JobStatistics JOB_STATISTICS = JobStatistics.builder()
- .creationTime(1L)
- .endTime(3L)
- .startTime(2L)
- .build();
private static final JobStatistics.ExtractStatistics EXTRACT_STATISTICS =
JobStatistics.ExtractStatistics.builder()
.creationTime(1L)
@@ -207,7 +197,7 @@ public class SerializationTest {
.useQueryCache(true)
.defaultDataset(DATASET_ID)
.dryRun(false)
- .maxResults(42L)
+ .pageSize(42L)
.maxWaitTime(10L)
.build();
private static final QueryResult QUERY_RESULT = QueryResult.builder()
@@ -230,75 +220,40 @@ public class SerializationTest {
new Dataset(BIGQUERY, new DatasetInfo.BuilderImpl(DATASET_INFO));
private static final Table TABLE = new Table(BIGQUERY, new TableInfo.BuilderImpl(TABLE_INFO));
private static final Job JOB = new Job(BIGQUERY, new JobInfo.BuilderImpl(JOB_INFO));
+ private static final BigQueryException BIG_QUERY_EXCEPTION =
+ new BigQueryException(42, "message", BIGQUERY_ERROR);
- @Test
- public void testServiceOptions() throws Exception {
+ @Override
+ protected Serializable[] serializableObjects() {
BigQueryOptions options = BigQueryOptions.builder()
.projectId("p1")
.authCredentials(AuthCredentials.createForAppEngine())
.build();
- BigQueryOptions serializedCopy = serializeAndDeserialize(options);
- assertEquals(options, serializedCopy);
-
- options = options.toBuilder()
+ BigQueryOptions otherOptions = options.toBuilder()
.projectId("p2")
- .retryParams(RetryParams.defaultInstance())
.authCredentials(null)
.build();
- serializedCopy = serializeAndDeserialize(options);
- assertEquals(options, serializedCopy);
- }
-
- @Test
- public void testModelAndRequests() throws Exception {
- Serializable[] objects = {DOMAIN_ACCESS, GROUP_ACCESS, USER_ACCESS, VIEW_ACCESS, DATASET_ID,
+ return new Serializable[]{DOMAIN_ACCESS, GROUP_ACCESS, USER_ACCESS, VIEW_ACCESS, DATASET_ID,
DATASET_INFO, TABLE_ID, CSV_OPTIONS, STREAMING_BUFFER, TABLE_DEFINITION,
EXTERNAL_TABLE_DEFINITION, VIEW_DEFINITION, TABLE_SCHEMA, TABLE_INFO, VIEW_INFO,
- EXTERNAL_TABLE_INFO, INLINE_FUNCTION, URI_FUNCTION, JOB_STATISTICS, EXTRACT_STATISTICS,
+ EXTERNAL_TABLE_INFO, INLINE_FUNCTION, URI_FUNCTION, COPY_STATISTICS, EXTRACT_STATISTICS,
LOAD_STATISTICS, QUERY_STATISTICS, BIGQUERY_ERROR, JOB_STATUS, JOB_ID,
COPY_JOB_CONFIGURATION, EXTRACT_JOB_CONFIGURATION, LOAD_CONFIGURATION,
LOAD_JOB_CONFIGURATION, QUERY_JOB_CONFIGURATION, JOB_INFO, INSERT_ALL_REQUEST,
- INSERT_ALL_RESPONSE, FIELD_VALUE, QUERY_REQUEST, QUERY_RESPONSE,
+ INSERT_ALL_RESPONSE, FIELD_VALUE, QUERY_REQUEST, QUERY_RESPONSE, BIG_QUERY_EXCEPTION,
BigQuery.DatasetOption.fields(), BigQuery.DatasetDeleteOption.deleteContents(),
BigQuery.DatasetListOption.all(), BigQuery.TableOption.fields(),
- BigQuery.TableListOption.maxResults(42L), BigQuery.JobOption.fields(),
- BigQuery.JobListOption.allUsers(), DATASET, TABLE, JOB};
- for (Serializable obj : objects) {
- Object copy = serializeAndDeserialize(obj);
- assertEquals(obj, obj);
- assertEquals(obj, copy);
- assertNotSame(obj, copy);
- assertEquals(copy, copy);
- }
+ BigQuery.TableListOption.pageSize(42L), BigQuery.JobOption.fields(),
+ BigQuery.JobListOption.allUsers(), DATASET, TABLE, JOB, options, otherOptions};
}
- @Test
- public void testWriteChannelState() throws IOException, ClassNotFoundException {
- BigQueryOptions options = BigQueryOptions.builder()
- .projectId("p2")
- .retryParams(RetryParams.defaultInstance())
- .build();
+ @Override
+ protected Restorable>[] restorableObjects() {
+ BigQueryOptions options = BigQueryOptions.builder().projectId("p2").build();
// avoid closing when you don't want partial writes upon failure
@SuppressWarnings("resource")
TableDataWriteChannel writer =
new TableDataWriteChannel(options, LOAD_CONFIGURATION, "upload-id");
- RestorableState state = writer.capture();
- RestorableState deserializedState = serializeAndDeserialize(state);
- assertEquals(state, deserializedState);
- assertEquals(state.hashCode(), deserializedState.hashCode());
- assertEquals(state.toString(), deserializedState.toString());
- }
-
- @SuppressWarnings("unchecked")
- private T serializeAndDeserialize(T obj)
- throws IOException, ClassNotFoundException {
- ByteArrayOutputStream bytes = new ByteArrayOutputStream();
- try (ObjectOutputStream output = new ObjectOutputStream(bytes)) {
- output.writeObject(obj);
- }
- try (ObjectInputStream input =
- new ObjectInputStream(new ByteArrayInputStream(bytes.toByteArray()))) {
- return (T) input.readObject();
- }
+ return new Restorable>[]{writer};
}
}
diff --git a/gcloud-java-bigquery/src/test/java/com/google/gcloud/bigquery/TableDataWriteChannelTest.java b/gcloud-java-bigquery/src/test/java/com/google/cloud/bigquery/TableDataWriteChannelTest.java
similarity index 97%
rename from gcloud-java-bigquery/src/test/java/com/google/gcloud/bigquery/TableDataWriteChannelTest.java
rename to gcloud-java-bigquery/src/test/java/com/google/cloud/bigquery/TableDataWriteChannelTest.java
index 4c1be470ff57..646d82603950 100644
--- a/gcloud-java-bigquery/src/test/java/com/google/gcloud/bigquery/TableDataWriteChannelTest.java
+++ b/gcloud-java-bigquery/src/test/java/com/google/cloud/bigquery/TableDataWriteChannelTest.java
@@ -14,7 +14,7 @@
* limitations under the License.
*/
-package com.google.gcloud.bigquery;
+package com.google.cloud.bigquery;
import static org.easymock.EasyMock.anyObject;
import static org.easymock.EasyMock.capture;
@@ -30,10 +30,10 @@
import static org.junit.Assert.assertTrue;
import static org.junit.Assert.fail;
-import com.google.gcloud.RestorableState;
-import com.google.gcloud.WriteChannel;
-import com.google.gcloud.bigquery.spi.BigQueryRpc;
-import com.google.gcloud.bigquery.spi.BigQueryRpcFactory;
+import com.google.cloud.RestorableState;
+import com.google.cloud.WriteChannel;
+import com.google.cloud.bigquery.spi.BigQueryRpc;
+import com.google.cloud.bigquery.spi.BigQueryRpcFactory;
import org.easymock.Capture;
import org.easymock.CaptureType;
diff --git a/gcloud-java-bigquery/src/test/java/com/google/gcloud/bigquery/TableDefinitionTest.java b/gcloud-java-bigquery/src/test/java/com/google/cloud/bigquery/TableDefinitionTest.java
similarity index 97%
rename from gcloud-java-bigquery/src/test/java/com/google/gcloud/bigquery/TableDefinitionTest.java
rename to gcloud-java-bigquery/src/test/java/com/google/cloud/bigquery/TableDefinitionTest.java
index d1e3635d00cb..7c7cf2568462 100644
--- a/gcloud-java-bigquery/src/test/java/com/google/gcloud/bigquery/TableDefinitionTest.java
+++ b/gcloud-java-bigquery/src/test/java/com/google/cloud/bigquery/TableDefinitionTest.java
@@ -14,12 +14,12 @@
* limitations under the License.
*/
-package com.google.gcloud.bigquery;
+package com.google.cloud.bigquery;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertTrue;
-import com.google.gcloud.bigquery.StandardTableDefinition.StreamingBuffer;
+import com.google.cloud.bigquery.StandardTableDefinition.StreamingBuffer;
import org.junit.Test;
diff --git a/gcloud-java-bigquery/src/test/java/com/google/gcloud/bigquery/TableIdTest.java b/gcloud-java-bigquery/src/test/java/com/google/cloud/bigquery/TableIdTest.java
similarity index 98%
rename from gcloud-java-bigquery/src/test/java/com/google/gcloud/bigquery/TableIdTest.java
rename to gcloud-java-bigquery/src/test/java/com/google/cloud/bigquery/TableIdTest.java
index bc013bfa5c31..7db923bdd7ca 100644
--- a/gcloud-java-bigquery/src/test/java/com/google/gcloud/bigquery/TableIdTest.java
+++ b/gcloud-java-bigquery/src/test/java/com/google/cloud/bigquery/TableIdTest.java
@@ -14,7 +14,7 @@
* limitations under the License.
*/
-package com.google.gcloud.bigquery;
+package com.google.cloud.bigquery;
import static org.junit.Assert.assertEquals;
diff --git a/gcloud-java-bigquery/src/test/java/com/google/gcloud/bigquery/TableInfoTest.java b/gcloud-java-bigquery/src/test/java/com/google/cloud/bigquery/TableInfoTest.java
similarity index 95%
rename from gcloud-java-bigquery/src/test/java/com/google/gcloud/bigquery/TableInfoTest.java
rename to gcloud-java-bigquery/src/test/java/com/google/cloud/bigquery/TableInfoTest.java
index 18b8be10d71e..0b67f4be3adf 100644
--- a/gcloud-java-bigquery/src/test/java/com/google/gcloud/bigquery/TableInfoTest.java
+++ b/gcloud-java-bigquery/src/test/java/com/google/cloud/bigquery/TableInfoTest.java
@@ -14,7 +14,7 @@
* limitations under the License.
*/
-package com.google.gcloud.bigquery;
+package com.google.cloud.bigquery;
import static org.junit.Assert.assertEquals;
@@ -27,7 +27,7 @@
public class TableInfoTest {
private static final String ETAG = "etag";
- private static final String ID = "project:dataset:table";
+ private static final String GENERATED_ID = "project:dataset:table";
private static final String SELF_LINK = "selfLink";
private static final TableId TABLE_ID = TableId.of("dataset", "table");
private static final String FRIENDLY_NAME = "friendlyName";
@@ -89,7 +89,7 @@ public class TableInfoTest {
.etag(ETAG)
.expirationTime(EXPIRATION_TIME)
.friendlyName(FRIENDLY_NAME)
- .id(ID)
+ .generatedId(GENERATED_ID)
.lastModifiedTime(LAST_MODIFIED_TIME)
.selfLink(SELF_LINK)
.build();
@@ -99,7 +99,7 @@ public class TableInfoTest {
.etag(ETAG)
.expirationTime(EXPIRATION_TIME)
.friendlyName(FRIENDLY_NAME)
- .id(ID)
+ .generatedId(GENERATED_ID)
.lastModifiedTime(LAST_MODIFIED_TIME)
.selfLink(SELF_LINK)
.build();
@@ -110,7 +110,7 @@ public class TableInfoTest {
.etag(ETAG)
.expirationTime(EXPIRATION_TIME)
.friendlyName(FRIENDLY_NAME)
- .id(ID)
+ .generatedId(GENERATED_ID)
.lastModifiedTime(LAST_MODIFIED_TIME)
.selfLink(SELF_LINK)
.build();
@@ -148,7 +148,7 @@ public void testBuilder() {
assertEquals(ETAG, TABLE_INFO.etag());
assertEquals(EXPIRATION_TIME, TABLE_INFO.expirationTime());
assertEquals(FRIENDLY_NAME, TABLE_INFO.friendlyName());
- assertEquals(ID, TABLE_INFO.id());
+ assertEquals(GENERATED_ID, TABLE_INFO.generatedId());
assertEquals(LAST_MODIFIED_TIME, TABLE_INFO.lastModifiedTime());
assertEquals(TABLE_DEFINITION, TABLE_INFO.definition());
assertEquals(SELF_LINK, TABLE_INFO.selfLink());
@@ -159,7 +159,7 @@ public void testBuilder() {
assertEquals(ETAG, VIEW_INFO.etag());
assertEquals(EXPIRATION_TIME, VIEW_INFO.expirationTime());
assertEquals(FRIENDLY_NAME, VIEW_INFO.friendlyName());
- assertEquals(ID, VIEW_INFO.id());
+ assertEquals(GENERATED_ID, VIEW_INFO.generatedId());
assertEquals(LAST_MODIFIED_TIME, VIEW_INFO.lastModifiedTime());
assertEquals(VIEW_TYPE, VIEW_INFO.definition());
assertEquals(SELF_LINK, VIEW_INFO.selfLink());
@@ -169,7 +169,7 @@ public void testBuilder() {
assertEquals(ETAG, EXTERNAL_TABLE_INFO.etag());
assertEquals(EXPIRATION_TIME, EXTERNAL_TABLE_INFO.expirationTime());
assertEquals(FRIENDLY_NAME, EXTERNAL_TABLE_INFO.friendlyName());
- assertEquals(ID, EXTERNAL_TABLE_INFO.id());
+ assertEquals(GENERATED_ID, EXTERNAL_TABLE_INFO.generatedId());
assertEquals(LAST_MODIFIED_TIME, EXTERNAL_TABLE_INFO.lastModifiedTime());
assertEquals(EXTERNAL_TABLE_DEFINITION, EXTERNAL_TABLE_INFO.definition());
assertEquals(SELF_LINK, EXTERNAL_TABLE_INFO.selfLink());
@@ -198,7 +198,7 @@ private void compareTableInfo(TableInfo expected, TableInfo value) {
assertEquals(expected.etag(), value.etag());
assertEquals(expected.expirationTime(), value.expirationTime());
assertEquals(expected.friendlyName(), value.friendlyName());
- assertEquals(expected.id(), value.id());
+ assertEquals(expected.generatedId(), value.generatedId());
assertEquals(expected.lastModifiedTime(), value.lastModifiedTime());
assertEquals(expected.selfLink(), value.selfLink());
assertEquals(expected.definition(), value.definition());
diff --git a/gcloud-java-bigquery/src/test/java/com/google/gcloud/bigquery/TableTest.java b/gcloud-java-bigquery/src/test/java/com/google/cloud/bigquery/TableTest.java
similarity index 97%
rename from gcloud-java-bigquery/src/test/java/com/google/gcloud/bigquery/TableTest.java
rename to gcloud-java-bigquery/src/test/java/com/google/cloud/bigquery/TableTest.java
index 4866ee9ab8ec..c74fc8e244bc 100644
--- a/gcloud-java-bigquery/src/test/java/com/google/gcloud/bigquery/TableTest.java
+++ b/gcloud-java-bigquery/src/test/java/com/google/cloud/bigquery/TableTest.java
@@ -14,7 +14,7 @@
* limitations under the License.
*/
-package com.google.gcloud.bigquery;
+package com.google.cloud.bigquery;
import static org.easymock.EasyMock.createMock;
import static org.easymock.EasyMock.createStrictMock;
@@ -28,12 +28,12 @@
import static org.junit.Assert.assertSame;
import static org.junit.Assert.assertTrue;
+import com.google.cloud.Page;
+import com.google.cloud.PageImpl;
+import com.google.cloud.bigquery.InsertAllRequest.RowToInsert;
import com.google.common.collect.ImmutableList;
import com.google.common.collect.ImmutableMap;
import com.google.common.collect.Iterators;
-import com.google.gcloud.Page;
-import com.google.gcloud.PageImpl;
-import com.google.gcloud.bigquery.InsertAllRequest.RowToInsert;
import org.junit.After;
import org.junit.Test;
@@ -44,7 +44,7 @@
public class TableTest {
private static final String ETAG = "etag";
- private static final String ID = "project:dataset:table1";
+ private static final String GENERATED_ID = "project:dataset:table1";
private static final String SELF_LINK = "selfLink";
private static final String FRIENDLY_NAME = "friendlyName";
private static final String DESCRIPTION = "description";
@@ -115,7 +115,7 @@ public void testBuilder() {
.etag(ETAG)
.expirationTime(EXPIRATION_TIME)
.friendlyName(FRIENDLY_NAME)
- .id(ID)
+ .generatedId(GENERATED_ID)
.lastModifiedTime(LAST_MODIFIED_TIME)
.selfLink(SELF_LINK)
.build();
@@ -125,7 +125,7 @@ public void testBuilder() {
assertEquals(ETAG, builtTable.etag());
assertEquals(EXPIRATION_TIME, builtTable.expirationTime());
assertEquals(FRIENDLY_NAME, builtTable.friendlyName());
- assertEquals(ID, builtTable.id());
+ assertEquals(GENERATED_ID, builtTable.generatedId());
assertEquals(LAST_MODIFIED_TIME, builtTable.lastModifiedTime());
assertEquals(TABLE_DEFINITION, builtTable.definition());
assertEquals(SELF_LINK, builtTable.selfLink());
@@ -286,11 +286,11 @@ public void testListWithOptions() throws Exception {
initializeExpectedTable(1);
expect(bigquery.options()).andReturn(mockOptions);
PageImpl> tableDataPage = new PageImpl<>(null, "c", ROWS);
- expect(bigquery.listTableData(TABLE_ID1, BigQuery.TableDataListOption.maxResults(10L)))
+ expect(bigquery.listTableData(TABLE_ID1, BigQuery.TableDataListOption.pageSize(10L)))
.andReturn(tableDataPage);
replay(bigquery);
initializeTable();
- Page> dataPage = table.list(BigQuery.TableDataListOption.maxResults(10L));
+ Page> dataPage = table.list(BigQuery.TableDataListOption.pageSize(10L));
Iterator> tableDataIterator = tableDataPage.values().iterator();
Iterator> dataIterator = dataPage.values().iterator();
assertTrue(Iterators.elementsEqual(tableDataIterator, dataIterator));
@@ -398,7 +398,7 @@ private void compareTableInfo(TableInfo expected, TableInfo value) {
assertEquals(expected.etag(), value.etag());
assertEquals(expected.expirationTime(), value.expirationTime());
assertEquals(expected.friendlyName(), value.friendlyName());
- assertEquals(expected.id(), value.id());
+ assertEquals(expected.generatedId(), value.generatedId());
assertEquals(expected.lastModifiedTime(), value.lastModifiedTime());
assertEquals(expected.selfLink(), value.selfLink());
assertEquals(expected.definition(), value.definition());
diff --git a/gcloud-java-bigquery/src/test/java/com/google/gcloud/bigquery/UserDefinedFunctionTest.java b/gcloud-java-bigquery/src/test/java/com/google/cloud/bigquery/UserDefinedFunctionTest.java
similarity index 98%
rename from gcloud-java-bigquery/src/test/java/com/google/gcloud/bigquery/UserDefinedFunctionTest.java
rename to gcloud-java-bigquery/src/test/java/com/google/cloud/bigquery/UserDefinedFunctionTest.java
index 2741aaed89a5..db6cada4e0e5 100644
--- a/gcloud-java-bigquery/src/test/java/com/google/gcloud/bigquery/UserDefinedFunctionTest.java
+++ b/gcloud-java-bigquery/src/test/java/com/google/cloud/bigquery/UserDefinedFunctionTest.java
@@ -14,7 +14,7 @@
* limitations under the License.
*/
-package com.google.gcloud.bigquery;
+package com.google.cloud.bigquery;
import static org.junit.Assert.assertEquals;
diff --git a/gcloud-java-bigquery/src/test/java/com/google/gcloud/bigquery/ViewDefinitionTest.java b/gcloud-java-bigquery/src/test/java/com/google/cloud/bigquery/ViewDefinitionTest.java
similarity index 98%
rename from gcloud-java-bigquery/src/test/java/com/google/gcloud/bigquery/ViewDefinitionTest.java
rename to gcloud-java-bigquery/src/test/java/com/google/cloud/bigquery/ViewDefinitionTest.java
index ebab7a6e87ca..25c880bc8b78 100644
--- a/gcloud-java-bigquery/src/test/java/com/google/gcloud/bigquery/ViewDefinitionTest.java
+++ b/gcloud-java-bigquery/src/test/java/com/google/cloud/bigquery/ViewDefinitionTest.java
@@ -14,7 +14,7 @@
* limitations under the License.
*/
-package com.google.gcloud.bigquery;
+package com.google.cloud.bigquery;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertTrue;
diff --git a/gcloud-java-bigquery/src/test/java/com/google/gcloud/bigquery/WriteChannelConfigurationTest.java b/gcloud-java-bigquery/src/test/java/com/google/cloud/bigquery/WriteChannelConfigurationTest.java
similarity index 97%
rename from gcloud-java-bigquery/src/test/java/com/google/gcloud/bigquery/WriteChannelConfigurationTest.java
rename to gcloud-java-bigquery/src/test/java/com/google/cloud/bigquery/WriteChannelConfigurationTest.java
index dfde4795dacd..ffe1e58dc19e 100644
--- a/gcloud-java-bigquery/src/test/java/com/google/gcloud/bigquery/WriteChannelConfigurationTest.java
+++ b/gcloud-java-bigquery/src/test/java/com/google/cloud/bigquery/WriteChannelConfigurationTest.java
@@ -14,14 +14,14 @@
* limitations under the License.
*/
-package com.google.gcloud.bigquery;
+package com.google.cloud.bigquery;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertNull;
+import com.google.cloud.bigquery.JobInfo.CreateDisposition;
+import com.google.cloud.bigquery.JobInfo.WriteDisposition;
import com.google.common.collect.ImmutableList;
-import com.google.gcloud.bigquery.JobInfo.CreateDisposition;
-import com.google.gcloud.bigquery.JobInfo.WriteDisposition;
import org.junit.Test;
diff --git a/gcloud-java-bigquery/src/test/java/com/google/gcloud/bigquery/it/ITBigQueryTest.java b/gcloud-java-bigquery/src/test/java/com/google/cloud/bigquery/it/ITBigQueryTest.java
similarity index 93%
rename from gcloud-java-bigquery/src/test/java/com/google/gcloud/bigquery/it/ITBigQueryTest.java
rename to gcloud-java-bigquery/src/test/java/com/google/cloud/bigquery/it/ITBigQueryTest.java
index 63a0551ece33..9e462a4d5142 100644
--- a/gcloud-java-bigquery/src/test/java/com/google/gcloud/bigquery/it/ITBigQueryTest.java
+++ b/gcloud-java-bigquery/src/test/java/com/google/cloud/bigquery/it/ITBigQueryTest.java
@@ -14,7 +14,7 @@
* limitations under the License.
*/
-package com.google.gcloud.bigquery.it;
+package com.google.cloud.bigquery.it;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertFalse;
@@ -23,54 +23,55 @@
import static org.junit.Assert.assertTrue;
import static org.junit.Assert.fail;
+import com.google.cloud.Page;
+import com.google.cloud.WriteChannel;
+import com.google.cloud.bigquery.BigQuery;
+import com.google.cloud.bigquery.BigQuery.DatasetField;
+import com.google.cloud.bigquery.BigQuery.DatasetOption;
+import com.google.cloud.bigquery.BigQuery.JobField;
+import com.google.cloud.bigquery.BigQuery.JobListOption;
+import com.google.cloud.bigquery.BigQuery.JobOption;
+import com.google.cloud.bigquery.BigQuery.TableField;
+import com.google.cloud.bigquery.BigQuery.TableOption;
+import com.google.cloud.bigquery.BigQueryError;
+import com.google.cloud.bigquery.BigQueryException;
+import com.google.cloud.bigquery.CopyJobConfiguration;
+import com.google.cloud.bigquery.Dataset;
+import com.google.cloud.bigquery.DatasetId;
+import com.google.cloud.bigquery.DatasetInfo;
+import com.google.cloud.bigquery.ExternalTableDefinition;
+import com.google.cloud.bigquery.ExtractJobConfiguration;
+import com.google.cloud.bigquery.Field;
+import com.google.cloud.bigquery.FieldValue;
+import com.google.cloud.bigquery.FormatOptions;
+import com.google.cloud.bigquery.InsertAllRequest;
+import com.google.cloud.bigquery.InsertAllResponse;
+import com.google.cloud.bigquery.Job;
+import com.google.cloud.bigquery.JobInfo;
+import com.google.cloud.bigquery.JobStatistics;
+import com.google.cloud.bigquery.LoadJobConfiguration;
+import com.google.cloud.bigquery.QueryJobConfiguration;
+import com.google.cloud.bigquery.QueryRequest;
+import com.google.cloud.bigquery.QueryResponse;
+import com.google.cloud.bigquery.Schema;
+import com.google.cloud.bigquery.StandardTableDefinition;
+import com.google.cloud.bigquery.Table;
+import com.google.cloud.bigquery.TableDefinition;
+import com.google.cloud.bigquery.TableId;
+import com.google.cloud.bigquery.TableInfo;
+import com.google.cloud.bigquery.ViewDefinition;
+import com.google.cloud.bigquery.WriteChannelConfiguration;
+import com.google.cloud.bigquery.testing.RemoteBigQueryHelper;
+import com.google.cloud.storage.BlobInfo;
+import com.google.cloud.storage.BucketInfo;
+import com.google.cloud.storage.Storage;
+import com.google.cloud.storage.testing.RemoteStorageHelper;
import com.google.common.collect.ImmutableList;
import com.google.common.collect.ImmutableMap;
-import com.google.gcloud.Page;
-import com.google.gcloud.WriteChannel;
-import com.google.gcloud.bigquery.BigQuery;
-import com.google.gcloud.bigquery.BigQuery.DatasetField;
-import com.google.gcloud.bigquery.BigQuery.DatasetOption;
-import com.google.gcloud.bigquery.BigQuery.JobField;
-import com.google.gcloud.bigquery.BigQuery.JobListOption;
-import com.google.gcloud.bigquery.BigQuery.JobOption;
-import com.google.gcloud.bigquery.BigQuery.TableField;
-import com.google.gcloud.bigquery.BigQuery.TableOption;
-import com.google.gcloud.bigquery.BigQueryError;
-import com.google.gcloud.bigquery.BigQueryException;
-import com.google.gcloud.bigquery.CopyJobConfiguration;
-import com.google.gcloud.bigquery.Dataset;
-import com.google.gcloud.bigquery.DatasetId;
-import com.google.gcloud.bigquery.DatasetInfo;
-import com.google.gcloud.bigquery.ExternalTableDefinition;
-import com.google.gcloud.bigquery.ExtractJobConfiguration;
-import com.google.gcloud.bigquery.Field;
-import com.google.gcloud.bigquery.FieldValue;
-import com.google.gcloud.bigquery.FormatOptions;
-import com.google.gcloud.bigquery.InsertAllRequest;
-import com.google.gcloud.bigquery.InsertAllResponse;
-import com.google.gcloud.bigquery.Job;
-import com.google.gcloud.bigquery.JobInfo;
-import com.google.gcloud.bigquery.JobStatistics;
-import com.google.gcloud.bigquery.LoadJobConfiguration;
-import com.google.gcloud.bigquery.QueryJobConfiguration;
-import com.google.gcloud.bigquery.QueryRequest;
-import com.google.gcloud.bigquery.QueryResponse;
-import com.google.gcloud.bigquery.Schema;
-import com.google.gcloud.bigquery.StandardTableDefinition;
-import com.google.gcloud.bigquery.Table;
-import com.google.gcloud.bigquery.TableDefinition;
-import com.google.gcloud.bigquery.TableId;
-import com.google.gcloud.bigquery.TableInfo;
-import com.google.gcloud.bigquery.ViewDefinition;
-import com.google.gcloud.bigquery.WriteChannelConfiguration;
-import com.google.gcloud.bigquery.testing.RemoteBigQueryHelper;
-import com.google.gcloud.storage.BlobInfo;
-import com.google.gcloud.storage.BucketInfo;
-import com.google.gcloud.storage.Storage;
-import com.google.gcloud.storage.testing.RemoteGcsHelper;
import org.junit.AfterClass;
import org.junit.BeforeClass;
+import org.junit.Ignore;
import org.junit.Rule;
import org.junit.Test;
import org.junit.rules.Timeout;
@@ -134,7 +135,7 @@ public class ITBigQueryTest {
private static final String LOAD_FILE = "load.csv";
private static final String JSON_LOAD_FILE = "load.json";
private static final String EXTRACT_FILE = "extract.csv";
- private static final String BUCKET = RemoteGcsHelper.generateBucketName();
+ private static final String BUCKET = RemoteStorageHelper.generateBucketName();
private static final TableId TABLE_ID = TableId.of(DATASET, "testing_table");
private static final String CSV_CONTENT = "StringValue1\nStringValue2\n";
private static final String JSON_CONTENT = "{"
@@ -171,9 +172,9 @@ public class ITBigQueryTest {
@BeforeClass
public static void beforeClass() throws InterruptedException {
RemoteBigQueryHelper bigqueryHelper = RemoteBigQueryHelper.create();
- RemoteGcsHelper gcsHelper = RemoteGcsHelper.create();
+ RemoteStorageHelper storageHelper = RemoteStorageHelper.create();
bigquery = bigqueryHelper.options().service();
- storage = gcsHelper.options().service();
+ storage = storageHelper.options().service();
storage.create(BucketInfo.of(BUCKET));
storage.create(BlobInfo.builder(BUCKET, LOAD_FILE).contentType("text/plain").build(),
CSV_CONTENT.getBytes(StandardCharsets.UTF_8));
@@ -199,7 +200,7 @@ public static void afterClass() throws ExecutionException, InterruptedException
RemoteBigQueryHelper.forceDelete(bigquery, DATASET);
}
if (storage != null) {
- boolean wasDeleted = RemoteGcsHelper.forceDelete(storage, BUCKET, 10, TimeUnit.SECONDS);
+ boolean wasDeleted = RemoteStorageHelper.forceDelete(storage, BUCKET, 10, TimeUnit.SECONDS);
if (!wasDeleted && LOG.isLoggable(Level.WARNING)) {
LOG.log(Level.WARNING, "Deletion of bucket {0} timed out, bucket is not empty", BUCKET);
}
@@ -214,7 +215,7 @@ public void testGetDataset() {
assertEquals(DESCRIPTION, dataset.description());
assertNotNull(dataset.acl());
assertNotNull(dataset.etag());
- assertNotNull(dataset.id());
+ assertNotNull(dataset.generatedId());
assertNotNull(dataset.lastModified());
assertNotNull(dataset.selfLink());
}
@@ -231,7 +232,7 @@ public void testGetDatasetWithSelectedFields() {
assertNull(dataset.acl());
assertNull(dataset.etag());
assertNull(dataset.friendlyName());
- assertNull(dataset.id());
+ assertNull(dataset.generatedId());
assertNull(dataset.lastModified());
assertNull(dataset.location());
assertNull(dataset.selfLink());
@@ -270,7 +271,7 @@ public void testUpdateDatasetWithSelectedFields() {
assertNull(updatedDataset.acl());
assertNull(updatedDataset.etag());
assertNull(updatedDataset.friendlyName());
- assertNull(updatedDataset.id());
+ assertNull(updatedDataset.generatedId());
assertNull(updatedDataset.lastModified());
assertNull(updatedDataset.location());
assertNull(updatedDataset.selfLink());
@@ -348,7 +349,7 @@ public void testCreateExternalTable() throws InterruptedException {
+ tableName)
.defaultDataset(DatasetId.of(DATASET))
.maxWaitTime(60000L)
- .maxResults(1000L)
+ .pageSize(1000L)
.build();
QueryResponse response = bigquery.query(request);
while (!response.jobCompleted()) {
@@ -411,7 +412,7 @@ public void testCreateViewTable() throws InterruptedException {
QueryRequest request = QueryRequest.builder("SELECT * FROM " + tableName)
.defaultDataset(DatasetId.of(DATASET))
.maxWaitTime(60000L)
- .maxResults(1000L)
+ .pageSize(1000L)
.build();
QueryResponse response = bigquery.query(request);
while (!response.jobCompleted()) {
@@ -623,6 +624,7 @@ public void testInsertAllWithErrors() {
assertTrue(bigquery.delete(TableId.of(DATASET, tableName)));
}
+ @Ignore("Flaky test; see issue #836")
@Test
public void testListAllTableData() {
Page> rows = bigquery.listTableData(TABLE_ID);
@@ -662,7 +664,7 @@ public void testQuery() throws InterruptedException {
QueryRequest request = QueryRequest.builder(query)
.defaultDataset(DatasetId.of(DATASET))
.maxWaitTime(60000L)
- .maxResults(1000L)
+ .pageSize(1000L)
.build();
QueryResponse response = bigquery.query(request);
while (!response.jobCompleted()) {
@@ -697,7 +699,7 @@ public void testListJobs() {
assertNotNull(job.statistics());
assertNotNull(job.status());
assertNotNull(job.userEmail());
- assertNotNull(job.id());
+ assertNotNull(job.generatedId());
}
}
@@ -709,7 +711,7 @@ public void testListJobsWithSelectedFields() {
assertNotNull(job.status());
assertNotNull(job.userEmail());
assertNull(job.statistics());
- assertNull(job.id());
+ assertNull(job.generatedId());
}
}
@@ -906,6 +908,7 @@ public void testCancelNonExistingJob() {
assertFalse(bigquery.cancel("test_cancel_non_existing_job"));
}
+ @Ignore("Flaky test; see #836")
@Test
public void testInsertFromFile() throws InterruptedException {
String destinationTableName = "test_insert_from_file_table";
diff --git a/gcloud-java-bigquery/src/test/java/com/google/gcloud/bigquery/RemoteBigQueryHelperTest.java b/gcloud-java-bigquery/src/test/java/com/google/cloud/bigquery/testing/RemoteBigQueryHelperTest.java
similarity index 95%
rename from gcloud-java-bigquery/src/test/java/com/google/gcloud/bigquery/RemoteBigQueryHelperTest.java
rename to gcloud-java-bigquery/src/test/java/com/google/cloud/bigquery/testing/RemoteBigQueryHelperTest.java
index 267ae161b7aa..46badf7bb7be 100644
--- a/gcloud-java-bigquery/src/test/java/com/google/gcloud/bigquery/RemoteBigQueryHelperTest.java
+++ b/gcloud-java-bigquery/src/test/java/com/google/cloud/bigquery/testing/RemoteBigQueryHelperTest.java
@@ -14,13 +14,14 @@
* limitations under the License.
*/
-package com.google.gcloud.bigquery;
+package com.google.cloud.bigquery.testing;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertTrue;
-import com.google.gcloud.bigquery.BigQuery.DatasetDeleteOption;
-import com.google.gcloud.bigquery.testing.RemoteBigQueryHelper;
+import com.google.cloud.bigquery.BigQuery;
+import com.google.cloud.bigquery.BigQuery.DatasetDeleteOption;
+import com.google.cloud.bigquery.BigQueryOptions;
import org.easymock.EasyMock;
import org.junit.Rule;
diff --git a/gcloud-java-bigquery/src/test/java/com/google/gcloud/bigquery/OptionTest.java b/gcloud-java-bigquery/src/test/java/com/google/gcloud/bigquery/OptionTest.java
deleted file mode 100644
index 2c89ececedb8..000000000000
--- a/gcloud-java-bigquery/src/test/java/com/google/gcloud/bigquery/OptionTest.java
+++ /dev/null
@@ -1,38 +0,0 @@
-/*
- * Copyright 2015 Google Inc. All Rights Reserved.
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-package com.google.gcloud.bigquery;
-
-import static org.junit.Assert.assertEquals;
-
-import com.google.gcloud.bigquery.spi.BigQueryRpc;
-
-import org.junit.Test;
-
-public class OptionTest {
-
- @Test
- public void testOption() {
- Option option = new Option(BigQueryRpc.Option.PAGE_TOKEN, "token");
- assertEquals(BigQueryRpc.Option.PAGE_TOKEN, option.rpcOption());
- assertEquals("token", option.value());
- }
-
- @Test(expected = NullPointerException.class)
- public void testNullRpcOption() {
- new Option(null, "token");
- }
-}
diff --git a/gcloud-java-contrib/pom.xml b/gcloud-java-contrib/pom.xml
index e1370fb0ec8e..0c1f675703b1 100644
--- a/gcloud-java-contrib/pom.xml
+++ b/gcloud-java-contrib/pom.xml
@@ -4,13 +4,14 @@
gcloud-java-contrib
pom
GCloud Java contributions
+ https://github.com/GoogleCloudPlatform/gcloud-java/tree/master/gcloud-java-contrib
Contains packages that provide higher-level abstraction/functionality for common gcloud-java use cases.
- com.google.gcloud
+ com.google.cloud
gcloud-java-pom
- 0.1.6-SNAPSHOT
+ 0.2.1-SNAPSHOT
gcloud-java-contrib
diff --git a/gcloud-java-core/README.md b/gcloud-java-core/README.md
index fc5f481f8ec3..9a659c0f8cc0 100644
--- a/gcloud-java-core/README.md
+++ b/gcloud-java-core/README.md
@@ -5,30 +5,30 @@ This module provides common functionality required by service-specific modules o
[![Build Status](https://travis-ci.org/GoogleCloudPlatform/gcloud-java.svg?branch=master)](https://travis-ci.org/GoogleCloudPlatform/gcloud-java)
[![Coverage Status](https://coveralls.io/repos/GoogleCloudPlatform/gcloud-java/badge.svg?branch=master)](https://coveralls.io/r/GoogleCloudPlatform/gcloud-java?branch=master)
-[![Maven](https://img.shields.io/maven-central/v/com.google.gcloud/gcloud-java-core.svg)](https://img.shields.io/maven-central/v/com.google.gcloud/gcloud-java-core.svg)
+[![Maven](https://img.shields.io/maven-central/v/com.google.cloud/gcloud-java-core.svg)](https://img.shields.io/maven-central/v/com.google.cloud/gcloud-java-core.svg)
[![Codacy Badge](https://api.codacy.com/project/badge/grade/9da006ad7c3a4fe1abd142e77c003917)](https://www.codacy.com/app/mziccard/gcloud-java)
[![Dependency Status](https://www.versioneye.com/user/projects/56bd8ee72a29ed002d2b0969/badge.svg?style=flat)](https://www.versioneye.com/user/projects/56bd8ee72a29ed002d2b0969)
- [Homepage] (https://googlecloudplatform.github.io/gcloud-java/)
-- [API Documentation] (http://googlecloudplatform.github.io/gcloud-java/apidocs/index.html?com/google/gcloud/package-summary.html)
+- [API Documentation] (http://googlecloudplatform.github.io/gcloud-java/apidocs/index.html?com/google/cloud/package-summary.html)
Quickstart
----------
If you are using Maven, add this to your pom.xml file
```xml
- com.google.gcloud
+ com.google.cloud
gcloud-java-core
- 0.1.5
+ 0.2.0
```
If you are using Gradle, add this to your dependencies
```Groovy
-compile 'com.google.gcloud:gcloud-java-core:0.1.5'
+compile 'com.google.cloud:gcloud-java-core:0.2.0'
```
If you are using SBT, add this to your dependencies
```Scala
-libraryDependencies += "com.google.gcloud" % "gcloud-java-core" % "0.1.5"
+libraryDependencies += "com.google.cloud" % "gcloud-java-core" % "0.2.0"
```
Troubleshooting
diff --git a/gcloud-java-core/pom.xml b/gcloud-java-core/pom.xml
index 6d0ed675b423..22648d2e6ffa 100644
--- a/gcloud-java-core/pom.xml
+++ b/gcloud-java-core/pom.xml
@@ -4,13 +4,14 @@
gcloud-java-core
jar
GCloud Java core
+ https://github.com/GoogleCloudPlatform/gcloud-java/tree/master/gcloud-java-core
Core module for the gcloud-java.
- com.google.gcloud
+ com.google.cloud
gcloud-java-pom
- 0.1.6-SNAPSHOT
+ 0.2.1-SNAPSHOT
gcloud-java-core
diff --git a/gcloud-java-core/src/main/java/com/google/gcloud/AuthCredentials.java b/gcloud-java-core/src/main/java/com/google/cloud/AuthCredentials.java
similarity index 73%
rename from gcloud-java-core/src/main/java/com/google/gcloud/AuthCredentials.java
rename to gcloud-java-core/src/main/java/com/google/cloud/AuthCredentials.java
index 6f9e09ca04bc..ec5a631f5f54 100644
--- a/gcloud-java-core/src/main/java/com/google/gcloud/AuthCredentials.java
+++ b/gcloud-java-core/src/main/java/com/google/cloud/AuthCredentials.java
@@ -14,7 +14,7 @@
* limitations under the License.
*/
-package com.google.gcloud;
+package com.google.cloud;
import static com.google.common.base.Preconditions.checkNotNull;
@@ -25,9 +25,15 @@
import java.io.IOException;
import java.io.InputStream;
import java.io.Serializable;
+import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
+import java.security.InvalidKeyException;
+import java.security.NoSuchAlgorithmException;
import java.security.PrivateKey;
+import java.security.Signature;
+import java.security.SignatureException;
import java.util.Collection;
+import java.util.Date;
import java.util.Objects;
/**
@@ -35,16 +41,27 @@
*/
public abstract class AuthCredentials implements Restorable {
- private static class AppEngineAuthCredentials extends AuthCredentials {
+ /**
+ * Represents built-in credentials when running in Google App Engine.
+ */
+ public static class AppEngineAuthCredentials extends AuthCredentials
+ implements ServiceAccountSigner {
private static final AuthCredentials INSTANCE = new AppEngineAuthCredentials();
private static final AppEngineAuthCredentialsState STATE = new AppEngineAuthCredentialsState();
- private static class AppEngineCredentials extends GoogleCredentials {
+ private AppEngineCredentials credentials;
+
+ private static class AppEngineCredentials extends GoogleCredentials
+ implements ServiceAccountSigner {
private final Object appIdentityService;
+ private final String account;
private final Method getAccessToken;
private final Method getAccessTokenResult;
+ private final Method getExpirationTime;
+ private final Method signForApp;
+ private final Method getSignature;
private final Collection scopes;
AppEngineCredentials() {
@@ -59,6 +76,13 @@ private static class AppEngineCredentials extends GoogleCredentials {
"com.google.appengine.api.appidentity.AppIdentityService$GetAccessTokenResult");
this.getAccessTokenResult = serviceClass.getMethod("getAccessToken", Iterable.class);
this.getAccessToken = tokenResultClass.getMethod("getAccessToken");
+ this.getExpirationTime = tokenResultClass.getMethod("getExpirationTime");
+ this.account = (String) serviceClass.getMethod("getServiceAccountName")
+ .invoke(appIdentityService);
+ this.signForApp = serviceClass.getMethod("signForApp", byte[].class);
+ Class> signingResultClass = Class.forName(
+ "com.google.appengine.api.appidentity.AppIdentityService$SigningResult");
+ this.getSignature = signingResultClass.getMethod("getSignature");
this.scopes = null;
} catch (Exception e) {
throw new RuntimeException("Could not create AppEngineCredentials.", e);
@@ -69,11 +93,15 @@ private static class AppEngineCredentials extends GoogleCredentials {
this.appIdentityService = unscoped.appIdentityService;
this.getAccessToken = unscoped.getAccessToken;
this.getAccessTokenResult = unscoped.getAccessTokenResult;
+ this.getExpirationTime = unscoped.getExpirationTime;
+ this.account = unscoped.account;
+ this.signForApp = unscoped.signForApp;
+ this.getSignature = unscoped.getSignature;
this.scopes = scopes;
}
/**
- * Refresh the access token by getting it from the App Identity service
+ * Refresh the access token by getting it from the App Identity service.
*/
@Override
public AccessToken refreshAccessToken() throws IOException {
@@ -83,7 +111,8 @@ public AccessToken refreshAccessToken() throws IOException {
try {
Object accessTokenResult = getAccessTokenResult.invoke(appIdentityService, scopes);
String accessToken = (String) getAccessToken.invoke(accessTokenResult);
- return new AccessToken(accessToken, null);
+ Date expirationTime = (Date) getExpirationTime.invoke(accessTokenResult);
+ return new AccessToken(accessToken, expirationTime);
} catch (Exception e) {
throw new IOException("Could not get the access token.", e);
}
@@ -98,6 +127,21 @@ public boolean createScopedRequired() {
public GoogleCredentials createScoped(Collection scopes) {
return new AppEngineCredentials(scopes, this);
}
+
+ @Override
+ public String account() {
+ return account;
+ }
+
+ @Override
+ public byte[] sign(byte[] toSign) {
+ try {
+ Object signingResult = signForApp.invoke(appIdentityService, toSign);
+ return (byte[]) getSignature.invoke(signingResult);
+ } catch (IllegalAccessException | IllegalArgumentException | InvocationTargetException ex) {
+ throw new SigningException("Failed to sign the provided bytes", ex);
+ }
+ }
}
private static class AppEngineAuthCredentialsState
@@ -122,14 +166,27 @@ public boolean equals(Object obj) {
}
@Override
- public GoogleCredentials credentials() {
- return new AppEngineCredentials();
+ public AppEngineCredentials credentials() {
+ if (credentials == null) {
+ credentials = new AppEngineCredentials();
+ }
+ return credentials;
}
@Override
public RestorableState capture() {
return STATE;
}
+
+ @Override
+ public String account() {
+ return credentials().account();
+ }
+
+ @Override
+ public byte[] sign(byte[] toSign) {
+ return credentials().sign(toSign);
+ }
}
/**
@@ -138,8 +195,10 @@ public RestorableState capture() {
* @see
* User accounts and service accounts
*/
- public static class ServiceAccountAuthCredentials extends AuthCredentials {
+ public static class ServiceAccountAuthCredentials extends AuthCredentials
+ implements ServiceAccountSigner {
+ private final ServiceAccountCredentials credentials;
private final String account;
private final PrivateKey privateKey;
@@ -178,23 +237,44 @@ public boolean equals(Object obj) {
}
ServiceAccountAuthCredentials(String account, PrivateKey privateKey) {
- this.account = checkNotNull(account);
- this.privateKey = checkNotNull(privateKey);
+ this(new ServiceAccountCredentials(null, account, privateKey, null, null));
+ }
+
+ ServiceAccountAuthCredentials(ServiceAccountCredentials credentials) {
+ this.credentials = checkNotNull(credentials);
+ this.account = checkNotNull(credentials.getClientEmail());
+ this.privateKey = checkNotNull(credentials.getPrivateKey());
}
@Override
public ServiceAccountCredentials credentials() {
- return new ServiceAccountCredentials(null, account, privateKey, null, null);
+ return credentials;
}
+ @Override
public String account() {
return account;
}
+ /**
+ * Returns the private key associated with the service account credentials.
+ */
public PrivateKey privateKey() {
return privateKey;
}
+ @Override
+ public byte[] sign(byte[] toSign) {
+ try {
+ Signature signer = Signature.getInstance("SHA256withRSA");
+ signer.initSign(privateKey());
+ signer.update(toSign);
+ return signer.sign();
+ } catch (NoSuchAlgorithmException | InvalidKeyException | SignatureException ex) {
+ throw new SigningException("Failed to sign the provided bytes", ex);
+ }
+ }
+
@Override
public RestorableState capture() {
return new ServiceAccountAuthCredentialsState(account, privateKey);
@@ -242,6 +322,10 @@ public boolean equals(Object obj) {
}
}
+ ApplicationDefaultAuthCredentials(GoogleCredentials credentials) {
+ googleCredentials = credentials;
+ }
+
ApplicationDefaultAuthCredentials() throws IOException {
googleCredentials = GoogleCredentials.getApplicationDefault();
}
@@ -260,7 +344,7 @@ public RestorableState capture() {
/**
* A placeholder for credentials to signify that requests sent to the server should not be
* authenticated. This is typically useful when using the local service emulators, such as
- * {@code LocalGcdHelper} and {@code LocalResourceManagerHelper}.
+ * {@code LocalDatastoreHelper} and {@code LocalResourceManagerHelper}.
*/
public static class NoAuthCredentials extends AuthCredentials {
@@ -276,8 +360,20 @@ private static class NoAuthCredentialsState
public AuthCredentials restore() {
return INSTANCE;
}
+
+ @Override
+ public int hashCode() {
+ return getClass().getName().hashCode();
+ }
+
+ @Override
+ public boolean equals(Object obj) {
+ return obj instanceof NoAuthCredentialsState;
+ }
}
+ private NoAuthCredentials() {}
+
@Override
public GoogleCredentials credentials() {
return null;
@@ -308,7 +404,12 @@ public static AuthCredentials createForAppEngine() {
* @throws IOException if the credentials cannot be created in the current environment
*/
public static AuthCredentials createApplicationDefaults() throws IOException {
- return new ApplicationDefaultAuthCredentials();
+ GoogleCredentials credentials = GoogleCredentials.getApplicationDefault();
+ if (credentials instanceof ServiceAccountCredentials) {
+ ServiceAccountCredentials serviceAccountCredentials = (ServiceAccountCredentials) credentials;
+ return new ServiceAccountAuthCredentials(serviceAccountCredentials);
+ }
+ return new ApplicationDefaultAuthCredentials(credentials);
}
/**
@@ -329,7 +430,7 @@ public static ServiceAccountAuthCredentials createFor(String account, PrivateKey
/**
* Creates a placeholder denoting that no credentials should be used. This is typically useful
- * when using the local service emulators, such as {@code LocalGcdHelper} and
+ * when using the local service emulators, such as {@code LocalDatastoreHelper} and
* {@code LocalResourceManagerHelper}.
*/
public static AuthCredentials noAuth() {
diff --git a/gcloud-java-core/src/main/java/com/google/gcloud/BaseService.java b/gcloud-java-core/src/main/java/com/google/cloud/BaseService.java
similarity index 95%
rename from gcloud-java-core/src/main/java/com/google/gcloud/BaseService.java
rename to gcloud-java-core/src/main/java/com/google/cloud/BaseService.java
index d9e6f2db7c95..d0476b66c29c 100644
--- a/gcloud-java-core/src/main/java/com/google/gcloud/BaseService.java
+++ b/gcloud-java-core/src/main/java/com/google/cloud/BaseService.java
@@ -14,9 +14,9 @@
* limitations under the License.
*/
-package com.google.gcloud;
+package com.google.cloud;
-import com.google.gcloud.ExceptionHandler.Interceptor;
+import com.google.cloud.ExceptionHandler.Interceptor;
/**
* Base class for service objects.
diff --git a/gcloud-java-core/src/main/java/com/google/gcloud/BaseServiceException.java b/gcloud-java-core/src/main/java/com/google/cloud/BaseServiceException.java
similarity index 69%
rename from gcloud-java-core/src/main/java/com/google/gcloud/BaseServiceException.java
rename to gcloud-java-core/src/main/java/com/google/cloud/BaseServiceException.java
index 365243904436..ad2d6bf07144 100644
--- a/gcloud-java-core/src/main/java/com/google/gcloud/BaseServiceException.java
+++ b/gcloud-java-core/src/main/java/com/google/cloud/BaseServiceException.java
@@ -14,7 +14,7 @@
* limitations under the License.
*/
-package com.google.gcloud;
+package com.google.cloud;
import com.google.api.client.googleapis.json.GoogleJsonError;
import com.google.api.client.googleapis.json.GoogleJsonResponseException;
@@ -32,16 +32,32 @@
*/
public class BaseServiceException extends RuntimeException {
+ private static final long serialVersionUID = 759921776378760835L;
+ public static final int UNKNOWN_CODE = 0;
+
+ private final int code;
+ private final boolean retryable;
+ private final String reason;
+ private final boolean idempotent;
+ private final String location;
+ private final String debugInfo;
+
protected static final class Error implements Serializable {
private static final long serialVersionUID = -4019600198652965721L;
private final Integer code;
private final String reason;
+ private final boolean rejected;
public Error(Integer code, String reason) {
+ this(code, reason, false);
+ }
+
+ public Error(Integer code, String reason, boolean rejected) {
this.code = code;
this.reason = reason;
+ this.rejected = rejected;
}
/**
@@ -51,6 +67,15 @@ public Integer code() {
return code;
}
+ /**
+ * Returns true if the error indicates that the API call was certainly not accepted by the
+ * server. For instance, if the server returns a rate limit exceeded error, it certainly did not
+ * process the request and this method will return {@code true}.
+ */
+ public boolean rejected() {
+ return rejected;
+ }
+
/**
* Returns the reason that caused the exception.
*/
@@ -58,11 +83,11 @@ public String reason() {
return reason;
}
- boolean isRetryable(Set retryableErrors) {
+ boolean isRetryable(boolean idempotent, Set retryableErrors) {
for (Error retryableError : retryableErrors) {
if ((retryableError.code() == null || retryableError.code().equals(this.code()))
&& (retryableError.reason() == null || retryableError.reason().equals(this.reason()))) {
- return true;
+ return idempotent || retryableError.rejected();
}
}
return false;
@@ -79,28 +104,20 @@ public int hashCode() {
}
}
- private static final long serialVersionUID = 759921776378760835L;
- public static final int UNKNOWN_CODE = 0;
-
- private final int code;
- private final boolean retryable;
- private final String reason;
- private final boolean idempotent;
- private final String location;
- private final String debugInfo;
-
public BaseServiceException(IOException exception, boolean idempotent) {
super(message(exception), exception);
int code = UNKNOWN_CODE;
String reason = null;
String location = null;
String debugInfo = null;
+ Boolean retryable = null;
if (exception instanceof GoogleJsonResponseException) {
GoogleJsonError jsonError = ((GoogleJsonResponseException) exception).getDetails();
if (jsonError != null) {
- Error error = error(jsonError);
+ Error error = new Error(jsonError.getCode(), reason(jsonError));
code = error.code;
reason = error.reason;
+ retryable = isRetryable(idempotent, error);
if (reason != null) {
GoogleJsonError.ErrorInfo errorInfo = jsonError.getErrors().get(0);
location = errorInfo.getLocation();
@@ -110,8 +127,8 @@ public BaseServiceException(IOException exception, boolean idempotent) {
code = ((GoogleJsonResponseException) exception).getStatusCode();
}
}
+ this.retryable = MoreObjects.firstNonNull(retryable, isRetryable(idempotent, exception));
this.code = code;
- this.retryable = idempotent && isRetryable(exception);
this.reason = reason;
this.idempotent = idempotent;
this.location = location;
@@ -119,13 +136,7 @@ public BaseServiceException(IOException exception, boolean idempotent) {
}
public BaseServiceException(GoogleJsonError error, boolean idempotent) {
- super(error.getMessage());
- this.code = error.getCode();
- this.reason = reason(error);
- this.idempotent = idempotent;
- this.retryable = idempotent && isRetryable(error);
- this.location = null;
- this.debugInfo = null;
+ this(error.getCode(), error.getMessage(), reason(error), idempotent);
}
public BaseServiceException(int code, String message, String reason, boolean idempotent) {
@@ -138,7 +149,7 @@ public BaseServiceException(int code, String message, String reason, boolean ide
this.code = code;
this.reason = reason;
this.idempotent = idempotent;
- this.retryable = idempotent && new Error(code, reason).isRetryable(retryableErrors());
+ this.retryable = isRetryable(idempotent, new Error(code, reason));
this.location = null;
this.debugInfo = null;
}
@@ -147,15 +158,12 @@ protected Set retryableErrors() {
return Collections.emptySet();
}
- protected boolean isRetryable(GoogleJsonError error) {
- return error != null && error(error).isRetryable(retryableErrors());
+ protected boolean isRetryable(boolean idempotent, Error error) {
+ return error.isRetryable(idempotent, retryableErrors());
}
- protected boolean isRetryable(IOException exception) {
- if (exception instanceof GoogleJsonResponseException) {
- return isRetryable(((GoogleJsonResponseException) exception).getDetails());
- }
- return exception instanceof SocketTimeoutException;
+ protected boolean isRetryable(boolean idempotent, IOException exception) {
+ return idempotent && exception instanceof SocketTimeoutException;
}
/**
@@ -187,8 +195,8 @@ public boolean idempotent() {
}
/**
- * Returns the service location where the error causing the exception occurred. Returns
- * {@code null} if not set.
+ * Returns the service location where the error causing the exception occurred. Returns {@code
+ * null} if not available.
*/
public String location() {
return location;
@@ -198,18 +206,39 @@ protected String debugInfo() {
return debugInfo;
}
- protected static String reason(GoogleJsonError error) {
- if (error.getErrors() != null && !error.getErrors().isEmpty()) {
- return error.getErrors().get(0).getReason();
+ @Override
+ public boolean equals(Object obj) {
+ if (obj == this) {
+ return true;
}
- return null;
+ if (!(obj instanceof BaseServiceException)) {
+ return false;
+ }
+ BaseServiceException other = (BaseServiceException) obj;
+ return Objects.equals(getCause(), other.getCause())
+ && Objects.equals(getMessage(), other.getMessage())
+ && code == other.code
+ && retryable == other.retryable
+ && Objects.equals(reason, other.reason)
+ && idempotent == other.idempotent
+ && Objects.equals(location, other.location)
+ && Objects.equals(debugInfo, other.debugInfo);
}
- protected static Error error(GoogleJsonError error) {
- return new Error(error.getCode(), reason(error));
+ @Override
+ public int hashCode() {
+ return Objects.hash(getCause(), getMessage(), code, retryable, reason, idempotent, location,
+ debugInfo);
+ }
+
+ private static String reason(GoogleJsonError error) {
+ if (error.getErrors() != null && !error.getErrors().isEmpty()) {
+ return error.getErrors().get(0).getReason();
+ }
+ return null;
}
- protected static String message(IOException exception) {
+ private static String message(IOException exception) {
if (exception instanceof GoogleJsonResponseException) {
GoogleJsonError details = ((GoogleJsonResponseException) exception).getDetails();
if (details != null) {
diff --git a/gcloud-java-core/src/main/java/com/google/gcloud/BaseWriteChannel.java b/gcloud-java-core/src/main/java/com/google/cloud/BaseWriteChannel.java
similarity index 99%
rename from gcloud-java-core/src/main/java/com/google/gcloud/BaseWriteChannel.java
rename to gcloud-java-core/src/main/java/com/google/cloud/BaseWriteChannel.java
index 1d18a5a27e81..038ef8c362de 100644
--- a/gcloud-java-core/src/main/java/com/google/gcloud/BaseWriteChannel.java
+++ b/gcloud-java-core/src/main/java/com/google/cloud/BaseWriteChannel.java
@@ -14,8 +14,9 @@
* limitations under the License.
*/
-package com.google.gcloud;
+package com.google.cloud;
+import com.google.cloud.BaseWriteChannel.BaseState;
import com.google.common.base.MoreObjects;
import java.io.IOException;
diff --git a/gcloud-java-core/src/main/java/com/google/gcloud/ExceptionHandler.java b/gcloud-java-core/src/main/java/com/google/cloud/ExceptionHandler.java
similarity index 93%
rename from gcloud-java-core/src/main/java/com/google/gcloud/ExceptionHandler.java
rename to gcloud-java-core/src/main/java/com/google/cloud/ExceptionHandler.java
index 39d4c4e75a1a..e72eb1edcf88 100644
--- a/gcloud-java-core/src/main/java/com/google/gcloud/ExceptionHandler.java
+++ b/gcloud-java-core/src/main/java/com/google/cloud/ExceptionHandler.java
@@ -14,7 +14,7 @@
* limitations under the License.
*/
-package com.google.gcloud;
+package com.google.cloud;
import static com.google.common.base.Preconditions.checkNotNull;
@@ -26,6 +26,7 @@
import java.io.Serializable;
import java.lang.reflect.Method;
+import java.util.Objects;
import java.util.Set;
import java.util.concurrent.Callable;
@@ -259,6 +260,26 @@ boolean shouldRetry(Exception ex) {
return retryResult == Interceptor.RetryResult.RETRY;
}
+ @Override
+ public int hashCode() {
+ return Objects.hash(interceptors, retriableExceptions, nonRetriableExceptions, retryInfo);
+ }
+
+ @Override
+ public boolean equals(Object obj) {
+ if (obj == this) {
+ return true;
+ }
+ if (!(obj instanceof ExceptionHandler)) {
+ return false;
+ }
+ ExceptionHandler other = (ExceptionHandler) obj;
+ return Objects.equals(interceptors, other.interceptors)
+ && Objects.equals(retriableExceptions, other.retriableExceptions)
+ && Objects.equals(nonRetriableExceptions, other.nonRetriableExceptions)
+ && Objects.equals(retryInfo, other.retryInfo);
+ }
+
/**
* Returns an instance which retry any checked exception and abort on any runtime exception.
*/
diff --git a/gcloud-java-core/src/main/java/com/google/cloud/FieldSelector.java b/gcloud-java-core/src/main/java/com/google/cloud/FieldSelector.java
new file mode 100644
index 000000000000..5a46d058648d
--- /dev/null
+++ b/gcloud-java-core/src/main/java/com/google/cloud/FieldSelector.java
@@ -0,0 +1,114 @@
+/*
+ * Copyright 2016 Google Inc. All Rights Reserved.
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+package com.google.cloud;
+
+import com.google.common.base.Function;
+import com.google.common.base.Joiner;
+import com.google.common.collect.Lists;
+import com.google.common.collect.Sets;
+
+import java.util.Arrays;
+import java.util.List;
+import java.util.Set;
+
+/**
+ * Interface for Google Cloud resource's fields. Implementations of this interface can be used to
+ * select only desired fields from a returned Google Cloud resource.
+ */
+public interface FieldSelector {
+
+ /**
+ * Returns a string selector. This selector is passed to a Google Cloud service (possibly with
+ * other field selectors) to specify which resource fields should be returned by an API call.
+ */
+ String selector();
+
+ /**
+ * A helper class used to build composite selectors given a number of fields. This class is not
+ * supposed to be used directly by users.
+ */
+ class Helper {
+
+ private static final String[] EMPTY_FIELDS = {};
+
+ private Helper() {}
+
+ private static final Function FIELD_TO_STRING_FUNCTION =
+ new Function() {
+ @Override
+ public String apply(FieldSelector fieldSelector) {
+ return fieldSelector.selector();
+ }
+ };
+
+ private static String selector(List extends FieldSelector> required, FieldSelector[] others,
+ String... extraResourceFields) {
+ Set fieldStrings = Sets.newHashSetWithExpectedSize(required.size() + others.length);
+ fieldStrings.addAll(Lists.transform(required, FIELD_TO_STRING_FUNCTION));
+ fieldStrings.addAll(Lists.transform(Arrays.asList(others), FIELD_TO_STRING_FUNCTION));
+ fieldStrings.addAll(Arrays.asList(extraResourceFields));
+ return Joiner.on(',').join(fieldStrings);
+ }
+
+ /**
+ * Returns a composite selector given a number of resource fields. The string selector returned
+ * by this method can be used for field selection in API calls that return a single resource.
+ * This method is not supposed to be used directly by users.
+ */
+ public static String selector(List extends FieldSelector> required, FieldSelector... others) {
+ return selector(required, others, new String[]{});
+ }
+
+ /**
+ * Returns a composite selector given a number of resource fields and a container name. The
+ * string selector returned by this method can be used for field selection in API calls that
+ * return a list of resources. This method is not supposed to be used directly by users.
+ */
+ public static String listSelector(String containerName, List extends FieldSelector> required,
+ FieldSelector... others) {
+ return "nextPageToken," + containerName + '(' + selector(required, others) + ')';
+ }
+
+ /**
+ * Returns a composite selector given a number of resource fields and a container name. This
+ * method also takes an {@code extraResourceFields} parameter to specify some extra resource
+ * fields as strings. The string selector returned by this method can be used for field
+ * selection in API calls that return a list of resources. This method is not supposed to be
+ * used directly by users.
+ */
+ public static String listSelector(String containerName, List extends FieldSelector> required,
+ FieldSelector[] others, String... extraResourceFields) {
+ return listSelector(EMPTY_FIELDS, containerName, required, others, extraResourceFields);
+ }
+
+ /**
+ * Returns a composite selector given a number of top level fields as strings, a number of
+ * resource fields and a container name. This method also takes an {@code extraResourceFields}
+ * parameter to specify some extra resource fields as strings. The string selector returned by
+ * this method can be used for field selection in API calls that return a list of resources.
+ * This method is not supposed to be used directly by users.
+ */
+ public static String listSelector(String[] topLevelFields, String containerName,
+ List extends FieldSelector> required, FieldSelector[] others,
+ String... extraResourceFields) {
+ Set topLevelStrings = Sets.newHashSetWithExpectedSize(topLevelFields.length + 1);
+ topLevelStrings.addAll(Lists.asList("nextPageToken", topLevelFields));
+ return Joiner.on(',').join(topLevelStrings) + "," + containerName + '('
+ + selector(required, others, extraResourceFields) + ')';
+ }
+ }
+}
diff --git a/gcloud-java-core/src/main/java/com/google/gcloud/IamPolicy.java b/gcloud-java-core/src/main/java/com/google/cloud/IamPolicy.java
similarity index 69%
rename from gcloud-java-core/src/main/java/com/google/gcloud/IamPolicy.java
rename to gcloud-java-core/src/main/java/com/google/cloud/IamPolicy.java
index 748eaba2ab4c..2d15d9907687 100644
--- a/gcloud-java-core/src/main/java/com/google/gcloud/IamPolicy.java
+++ b/gcloud-java-core/src/main/java/com/google/cloud/IamPolicy.java
@@ -14,20 +14,19 @@
* limitations under the License.
*/
-package com.google.gcloud;
+package com.google.cloud;
import static com.google.common.base.Preconditions.checkArgument;
+import static com.google.common.base.Preconditions.checkNotNull;
import com.google.common.collect.ImmutableMap;
import com.google.common.collect.ImmutableSet;
import java.io.Serializable;
import java.util.Arrays;
-import java.util.Collection;
import java.util.HashMap;
import java.util.HashSet;
-import java.util.LinkedList;
-import java.util.List;
+import java.util.LinkedHashSet;
import java.util.Map;
import java.util.Objects;
import java.util.Set;
@@ -69,12 +68,16 @@ protected Builder() {}
/**
* Replaces the builder's map of bindings with the given map of bindings.
*
- * @throws IllegalArgumentException if the provided map is null or contain any null values
+ * @throws NullPointerException if the given map is null or contains any null keys or values
+ * @throws IllegalArgumentException if any identities in the given map are null
*/
public final B bindings(Map> bindings) {
- checkArgument(bindings != null, "The provided map of bindings cannot be null.");
+ checkNotNull(bindings, "The provided map of bindings cannot be null.");
for (Map.Entry> binding : bindings.entrySet()) {
- verifyBinding(binding.getKey(), binding.getValue());
+ checkNotNull(binding.getKey(), "The role cannot be null.");
+ Set identities = binding.getValue();
+ checkNotNull(identities, "A role cannot be assigned to a null set of identities.");
+ checkArgument(!identities.contains(null), "Null identities are not permitted.");
}
this.bindings.clear();
for (Map.Entry> binding : bindings.entrySet()) {
@@ -84,78 +87,50 @@ public final B bindings(Map> bindings) {
}
/**
- * Adds a binding to the policy.
- *
- * @throws IllegalArgumentException if the policy already contains a binding with the same role
- * or if the role or any identities are null
+ * Removes the role (and all identities associated with that role) from the policy.
*/
- public final B addBinding(R role, Set identities) {
- verifyBinding(role, identities);
- checkArgument(!bindings.containsKey(role),
- "The policy already contains a binding with the role " + role.toString() + ".");
- bindings.put(role, new HashSet(identities));
- return self();
- }
-
- /**
- * Adds a binding to the policy.
- *
- * @throws IllegalArgumentException if the policy already contains a binding with the same role
- * or if the role or any identities are null
- */
- public final B addBinding(R role, Identity first, Identity... others) {
- HashSet identities = new HashSet<>();
- identities.add(first);
- identities.addAll(Arrays.asList(others));
- return addBinding(role, identities);
- }
-
- private void verifyBinding(R role, Collection identities) {
- checkArgument(role != null, "The role cannot be null.");
- verifyIdentities(identities);
- }
-
- private void verifyIdentities(Collection identities) {
- checkArgument(identities != null, "A role cannot be assigned to a null set of identities.");
- checkArgument(!identities.contains(null), "Null identities are not permitted.");
- }
-
- /**
- * Removes the binding associated with the specified role.
- */
- public final B removeBinding(R role) {
+ public final B removeRole(R role) {
bindings.remove(role);
return self();
}
/**
- * Adds one or more identities to an existing binding.
+ * Adds one or more identities to the policy under the role specified.
*
- * @throws IllegalArgumentException if the policy doesn't contain a binding with the specified
- * role or any identities are null
+ * @throws NullPointerException if the role or any of the identities is null.
*/
public final B addIdentity(R role, Identity first, Identity... others) {
- checkArgument(bindings.containsKey(role),
- "The policy doesn't contain the role " + role.toString() + ".");
- List toAdd = new LinkedList<>();
+ String nullIdentityMessage = "Null identities are not permitted.";
+ checkNotNull(first, nullIdentityMessage);
+ checkNotNull(others, nullIdentityMessage);
+ for (Identity identity : others) {
+ checkNotNull(identity, nullIdentityMessage);
+ }
+ Set toAdd = new LinkedHashSet<>();
toAdd.add(first);
toAdd.addAll(Arrays.asList(others));
- verifyIdentities(toAdd);
- bindings.get(role).addAll(toAdd);
+ Set identities = bindings.get(checkNotNull(role, "The role cannot be null."));
+ if (identities == null) {
+ identities = new HashSet();
+ bindings.put(role, identities);
+ }
+ identities.addAll(toAdd);
return self();
}
/**
- * Removes one or more identities from an existing binding.
- *
- * @throws IllegalArgumentException if the policy doesn't contain a binding with the specified
- * role
+ * Removes one or more identities from an existing binding. Does nothing if the binding
+ * associated with the provided role doesn't exist.
*/
public final B removeIdentity(R role, Identity first, Identity... others) {
- checkArgument(bindings.containsKey(role),
- "The policy doesn't contain the role " + role.toString() + ".");
- bindings.get(role).remove(first);
- bindings.get(role).removeAll(Arrays.asList(others));
+ Set identities = bindings.get(role);
+ if (identities != null) {
+ identities.remove(first);
+ identities.removeAll(Arrays.asList(others));
+ }
+ if (identities != null && identities.isEmpty()) {
+ bindings.remove(role);
+ }
return self();
}
@@ -244,7 +219,10 @@ public final int hashCode() {
@Override
public final boolean equals(Object obj) {
- if (obj == null || !getClass().equals(obj.getClass())) {
+ if (obj == this) {
+ return true;
+ }
+ if (obj == null || !obj.getClass().equals(getClass())) {
return false;
}
@SuppressWarnings("rawtypes")
diff --git a/gcloud-java-core/src/main/java/com/google/gcloud/Identity.java b/gcloud-java-core/src/main/java/com/google/cloud/Identity.java
similarity index 91%
rename from gcloud-java-core/src/main/java/com/google/gcloud/Identity.java
rename to gcloud-java-core/src/main/java/com/google/cloud/Identity.java
index d1644198f759..fab70dfe6d37 100644
--- a/gcloud-java-core/src/main/java/com/google/gcloud/Identity.java
+++ b/gcloud-java-core/src/main/java/com/google/cloud/Identity.java
@@ -14,7 +14,7 @@
* limitations under the License.
*/
-package com.google.gcloud;
+package com.google.cloud;
import static com.google.common.base.Preconditions.checkNotNull;
@@ -44,7 +44,7 @@ public final class Identity implements Serializable {
private static final long serialVersionUID = -8181841964597657446L;
private final Type type;
- private final String id;
+ private final String value;
/**
* The types of IAM identities.
@@ -82,9 +82,9 @@ public enum Type {
DOMAIN
}
- private Identity(Type type, String id) {
+ private Identity(Type type, String value) {
this.type = type;
- this.id = id;
+ this.value = value;
}
public Type type() {
@@ -92,7 +92,7 @@ public Type type() {
}
/**
- * Returns the string identifier for this identity. The id corresponds to:
+ * Returns the string identifier for this identity. The value corresponds to:
*
* - email address (for identities of type {@code USER}, {@code SERVICE_ACCOUNT}, and
* {@code GROUP})
@@ -101,8 +101,8 @@ public Type type() {
* {@code ALL_AUTHENTICATED_USERS})
*
*/
- public String id() {
- return id;
+ public String value() {
+ return value;
}
/**
@@ -163,7 +163,7 @@ public static Identity domain(String domain) {
@Override
public int hashCode() {
- return Objects.hash(id, type);
+ return Objects.hash(value, type);
}
@Override
@@ -172,7 +172,7 @@ public boolean equals(Object obj) {
return false;
}
Identity other = (Identity) obj;
- return Objects.equals(id, other.id()) && Objects.equals(type, other.type());
+ return Objects.equals(value, other.value()) && Objects.equals(type, other.type());
}
/**
@@ -186,13 +186,13 @@ public String strValue() {
case ALL_AUTHENTICATED_USERS:
return "allAuthenticatedUsers";
case USER:
- return "user:" + id;
+ return "user:" + value;
case SERVICE_ACCOUNT:
- return "serviceAccount:" + id;
+ return "serviceAccount:" + value;
case GROUP:
- return "group:" + id;
+ return "group:" + value;
case DOMAIN:
- return "domain:" + id;
+ return "domain:" + value;
default:
throw new IllegalStateException("Unexpected identity type: " + type);
}
diff --git a/gcloud-java-core/src/main/java/com/google/gcloud/Page.java b/gcloud-java-core/src/main/java/com/google/cloud/Page.java
similarity index 92%
rename from gcloud-java-core/src/main/java/com/google/gcloud/Page.java
rename to gcloud-java-core/src/main/java/com/google/cloud/Page.java
index 53f3a3842a18..8881a98b46ae 100644
--- a/gcloud-java-core/src/main/java/com/google/gcloud/Page.java
+++ b/gcloud-java-core/src/main/java/com/google/cloud/Page.java
@@ -14,15 +14,14 @@
* limitations under the License.
*/
-package com.google.gcloud;
+package com.google.cloud;
import java.util.Iterator;
/**
* Interface for Google Cloud paginated results.
*
- *
- * Use {@code Page} to iterate through all values (also in next pages):
+ *
Use {@code Page} to iterate through all values (also in next pages):
*
{@code
* Page page = ...; // get a Page instance
* Iterator iterator = page.iterateAll();
@@ -30,8 +29,8 @@
* T value = iterator.next();
* // do something with value
* }}
- *
- * Or handle pagination explicitly:
+ *
+ *
Or handle pagination explicitly:
*
{@code
* Page page = ...; // get a Page instance
* while (page != null) {
diff --git a/gcloud-java-core/src/main/java/com/google/gcloud/PageImpl.java b/gcloud-java-core/src/main/java/com/google/cloud/PageImpl.java
similarity index 99%
rename from gcloud-java-core/src/main/java/com/google/gcloud/PageImpl.java
rename to gcloud-java-core/src/main/java/com/google/cloud/PageImpl.java
index 2dc031ab9bd4..de1a3506b750 100644
--- a/gcloud-java-core/src/main/java/com/google/gcloud/PageImpl.java
+++ b/gcloud-java-core/src/main/java/com/google/cloud/PageImpl.java
@@ -14,7 +14,7 @@
* limitations under the License.
*/
-package com.google.gcloud;
+package com.google.cloud;
import com.google.common.collect.AbstractIterator;
import com.google.common.collect.ImmutableMap;
diff --git a/gcloud-java-core/src/main/java/com/google/gcloud/ReadChannel.java b/gcloud-java-core/src/main/java/com/google/cloud/ReadChannel.java
similarity index 98%
rename from gcloud-java-core/src/main/java/com/google/gcloud/ReadChannel.java
rename to gcloud-java-core/src/main/java/com/google/cloud/ReadChannel.java
index 7537c5a8ce0b..2afb8b2d5b32 100644
--- a/gcloud-java-core/src/main/java/com/google/gcloud/ReadChannel.java
+++ b/gcloud-java-core/src/main/java/com/google/cloud/ReadChannel.java
@@ -14,7 +14,7 @@
* limitations under the License.
*/
-package com.google.gcloud;
+package com.google.cloud;
import java.io.Closeable;
import java.io.IOException;
diff --git a/gcloud-java-core/src/main/java/com/google/gcloud/Restorable.java b/gcloud-java-core/src/main/java/com/google/cloud/Restorable.java
similarity index 93%
rename from gcloud-java-core/src/main/java/com/google/gcloud/Restorable.java
rename to gcloud-java-core/src/main/java/com/google/cloud/Restorable.java
index 0b573522e370..e2a515c7861a 100644
--- a/gcloud-java-core/src/main/java/com/google/gcloud/Restorable.java
+++ b/gcloud-java-core/src/main/java/com/google/cloud/Restorable.java
@@ -14,20 +14,19 @@
* limitations under the License.
*/
-package com.google.gcloud;
+package com.google.cloud;
/**
* Implementation of this interface can persist their state and restore from it.
*
- *
- * A typical capture usage:
+ *
A typical capture usage:
*
{@code
* X restorableObj; // X instanceof Restorable
* RestorableState state = restorableObj.capture();
* .. persist state
* }
*
- * A typical restore usage:
+ * A typical restore usage:
*
{@code
* RestorableState state = ... // read from persistence
* X restorableObj = state.restore();
diff --git a/gcloud-java-core/src/main/java/com/google/gcloud/RestorableState.java b/gcloud-java-core/src/main/java/com/google/cloud/RestorableState.java
similarity index 89%
rename from gcloud-java-core/src/main/java/com/google/gcloud/RestorableState.java
rename to gcloud-java-core/src/main/java/com/google/cloud/RestorableState.java
index d6ce736ae856..4874756527f7 100644
--- a/gcloud-java-core/src/main/java/com/google/gcloud/RestorableState.java
+++ b/gcloud-java-core/src/main/java/com/google/cloud/RestorableState.java
@@ -14,13 +14,13 @@
* limitations under the License.
*/
-package com.google.gcloud;
+package com.google.cloud;
/**
* A common interface for restorable states. Implementations of {@code RestorableState} are capable
* of saving the state of an object to restore it for later use.
*
- * Implementations of this class must implement {@link java.io.Serializable} to ensure that the
+ * Implementations of this class must implement {@link java.io.Serializable} to ensure that the
* state of a the object can be correctly serialized.
*
* @param the restored object's type
diff --git a/gcloud-java-core/src/main/java/com/google/gcloud/RetryHelper.java b/gcloud-java-core/src/main/java/com/google/cloud/RetryHelper.java
similarity index 99%
rename from gcloud-java-core/src/main/java/com/google/gcloud/RetryHelper.java
rename to gcloud-java-core/src/main/java/com/google/cloud/RetryHelper.java
index 9b9c1f6a3124..48bd5fcf9324 100644
--- a/gcloud-java-core/src/main/java/com/google/gcloud/RetryHelper.java
+++ b/gcloud-java-core/src/main/java/com/google/cloud/RetryHelper.java
@@ -14,7 +14,7 @@
* limitations under the License.
*/
-package com.google.gcloud;
+package com.google.cloud;
import static com.google.common.base.Preconditions.checkNotNull;
import static java.lang.StrictMath.max;
diff --git a/gcloud-java-core/src/main/java/com/google/gcloud/RetryParams.java b/gcloud-java-core/src/main/java/com/google/cloud/RetryParams.java
similarity index 91%
rename from gcloud-java-core/src/main/java/com/google/gcloud/RetryParams.java
rename to gcloud-java-core/src/main/java/com/google/cloud/RetryParams.java
index ab3644c6d747..02ffda18134f 100644
--- a/gcloud-java-core/src/main/java/com/google/gcloud/RetryParams.java
+++ b/gcloud-java-core/src/main/java/com/google/cloud/RetryParams.java
@@ -14,7 +14,7 @@
* limitations under the License.
*/
-package com.google.gcloud;
+package com.google.cloud;
import static com.google.common.base.Preconditions.checkArgument;
@@ -48,12 +48,16 @@ public final class RetryParams implements Serializable {
private static final long serialVersionUID = -8492751576749007700L;
+ /**
+ * Note that App Engine Standard Environment front-end modules have a 60 second deadline for HTTP
+ * requests. For that reason, we set the default total retry period to less than 60 seconds.
+ */
+ public static final long DEFAULT_TOTAL_RETRY_PERIOD_MILLIS = 50_000L;
public static final int DEFAULT_RETRY_MIN_ATTEMPTS = 3;
public static final int DEFAULT_RETRY_MAX_ATTEMPTS = 6;
- public static final long DEFAULT_INITIAL_RETRY_DELAY_MILLIS = 250L;
- public static final long DEFAULT_MAX_RETRY_DELAY_MILLIS = 10_000L;
+ public static final long DEFAULT_INITIAL_RETRY_DELAY_MILLIS = 1000L;
+ public static final long DEFAULT_MAX_RETRY_DELAY_MILLIS = 32_000L;
public static final double DEFAULT_RETRY_DELAY_BACKOFF_FACTOR = 2.0;
- public static final long DEFAULT_TOTAL_RETRY_PERIOD_MILLIS = 50_000L;
private final int retryMinAttempts;
private final int retryMaxAttempts;
@@ -62,6 +66,9 @@ public final class RetryParams implements Serializable {
private final double retryDelayBackoffFactor;
private final long totalRetryPeriodMillis;
+ // Some services may have different backoff requirements listed in their SLAs. Be sure to override
+ // ServiceOptions.defaultRetryParams() in options subclasses when the service's backoff
+ // requirement differs from the default parameters used here.
private static final RetryParams DEFAULT_INSTANCE = new RetryParams(new Builder());
private static final RetryParams NO_RETRIES =
builder().retryMaxAttempts(1).retryMinAttempts(1).build();
@@ -156,7 +163,9 @@ public Builder retryDelayBackoffFactor(double retryDelayBackoffFactor) {
}
/**
- * Sets totalRetryPeriodMillis.
+ * Sets totalRetryPeriodMillis. Note that App Engine Standard Environment front-end modules have
+ * a 60 second deadline for HTTP requests. For that reason, you should set the total retry
+ * period to under 60 seconds if you are using it on an App Engine front-end module.
*
* @param totalRetryPeriodMillis the totalRetryPeriodMillis to set
* @return the Builder for chaining
@@ -295,4 +304,8 @@ public String toString() {
public static Builder builder() {
return new Builder();
}
+
+ public Builder toBuilder() {
+ return new Builder(this);
+ }
}
diff --git a/gcloud-java-core/src/main/java/com/google/gcloud/Service.java b/gcloud-java-core/src/main/java/com/google/cloud/Service.java
similarity index 96%
rename from gcloud-java-core/src/main/java/com/google/gcloud/Service.java
rename to gcloud-java-core/src/main/java/com/google/cloud/Service.java
index 60bc26670f2e..a3797eca30b9 100644
--- a/gcloud-java-core/src/main/java/com/google/gcloud/Service.java
+++ b/gcloud-java-core/src/main/java/com/google/cloud/Service.java
@@ -14,7 +14,7 @@
* limitations under the License.
*/
-package com.google.gcloud;
+package com.google.cloud;
/**
* Interface for service objects.
diff --git a/gcloud-java-core/src/main/java/com/google/cloud/ServiceAccountSigner.java b/gcloud-java-core/src/main/java/com/google/cloud/ServiceAccountSigner.java
new file mode 100644
index 000000000000..c68d14116aa8
--- /dev/null
+++ b/gcloud-java-core/src/main/java/com/google/cloud/ServiceAccountSigner.java
@@ -0,0 +1,67 @@
+/*
+ * Copyright 2016 Google Inc. All Rights Reserved.
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+package com.google.cloud;
+
+import java.util.Objects;
+
+/**
+ * Interface for a service account signer. A signer for a service account is capable of signing
+ * bytes using the private key associated with its service account.
+ */
+public interface ServiceAccountSigner {
+
+ class SigningException extends RuntimeException {
+
+ private static final long serialVersionUID = 8962780757822799255L;
+
+ SigningException(String message, Exception cause) {
+ super(message, cause);
+ }
+
+ @Override
+ public boolean equals(Object obj) {
+ if (obj == this) {
+ return true;
+ }
+ if (!(obj instanceof SigningException)) {
+ return false;
+ }
+ SigningException other = (SigningException) obj;
+ return Objects.equals(getCause(), other.getCause())
+ && Objects.equals(getMessage(), other.getMessage());
+ }
+
+ @Override
+ public int hashCode() {
+ return Objects.hash(getMessage(), getCause());
+ }
+ }
+
+ /**
+ * Returns the service account associated with the signer.
+ */
+ String account();
+
+ /**
+ * Signs the provided bytes using the private key associated with the service account.
+ *
+ * @param toSign bytes to sign
+ * @return signed bytes
+ * @throws SigningException if the attempt to sign the provided bytes failed
+ */
+ byte[] sign(byte[] toSign);
+}
diff --git a/gcloud-java-core/src/main/java/com/google/gcloud/ServiceFactory.java b/gcloud-java-core/src/main/java/com/google/cloud/ServiceFactory.java
similarity index 97%
rename from gcloud-java-core/src/main/java/com/google/gcloud/ServiceFactory.java
rename to gcloud-java-core/src/main/java/com/google/cloud/ServiceFactory.java
index 1727e9c3976f..bb06127c77c6 100644
--- a/gcloud-java-core/src/main/java/com/google/gcloud/ServiceFactory.java
+++ b/gcloud-java-core/src/main/java/com/google/cloud/ServiceFactory.java
@@ -14,7 +14,7 @@
* limitations under the License.
*/
-package com.google.gcloud;
+package com.google.cloud;
/**
* A base interface for all service factories.
diff --git a/gcloud-java-core/src/main/java/com/google/gcloud/ServiceOptions.java b/gcloud-java-core/src/main/java/com/google/cloud/ServiceOptions.java
similarity index 89%
rename from gcloud-java-core/src/main/java/com/google/gcloud/ServiceOptions.java
rename to gcloud-java-core/src/main/java/com/google/cloud/ServiceOptions.java
index d45069434a26..194f61b45c42 100644
--- a/gcloud-java-core/src/main/java/com/google/gcloud/ServiceOptions.java
+++ b/gcloud-java-core/src/main/java/com/google/cloud/ServiceOptions.java
@@ -14,7 +14,7 @@
* limitations under the License.
*/
-package com.google.gcloud;
+package com.google.cloud;
import static com.google.common.base.MoreObjects.firstNonNull;
import static com.google.common.base.Preconditions.checkArgument;
@@ -26,11 +26,17 @@
import com.google.api.client.http.HttpTransport;
import com.google.api.client.http.javanet.NetHttpTransport;
import com.google.auth.http.HttpCredentialsAdapter;
+import com.google.cloud.spi.ServiceRpcFactory;
import com.google.common.collect.Iterables;
-import com.google.gcloud.spi.ServiceRpcFactory;
+import com.google.common.io.Files;
+
+import org.json.JSONException;
+import org.json.JSONObject;
+import org.json.JSONTokener;
import java.io.BufferedReader;
import java.io.File;
+import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;
@@ -42,6 +48,7 @@
import java.lang.reflect.Method;
import java.net.HttpURLConnection;
import java.net.URL;
+import java.nio.charset.Charset;
import java.util.Enumeration;
import java.util.Locale;
import java.util.Objects;
@@ -93,8 +100,8 @@ public abstract class ServiceOptions, Service
/**
* A base interface for all {@link HttpTransport} factories.
*
- * Implementation must provide a public no-arg constructor. Loading of a factory implementation is
- * done via {@link java.util.ServiceLoader}.
+ * Implementation must provide a public no-arg constructor. Loading of a factory implementation
+ * is done via {@link java.util.ServiceLoader}.
*/
public interface HttpTransportFactory {
HttpTransport create();
@@ -122,7 +129,7 @@ public HttpTransport create() {
* A class providing access to the current time in milliseconds. This class is mainly used for
* testing and will be replaced by Java8's {@code java.time.Clock}.
*
- * Implementations should implement {@code Serializable} wherever possible and must document
+ *
Implementations should implement {@code Serializable} wherever possible and must document
* whether or not they do support serialization.
*/
public abstract static class Clock {
@@ -326,7 +333,7 @@ protected ServiceOptions(Class extends ServiceFactory> ser
authCredentials =
builder.authCredentials != null ? builder.authCredentials : defaultAuthCredentials();
authCredentialsState = authCredentials != null ? authCredentials.capture() : null;
- retryParams = firstNonNull(builder.retryParams, RetryParams.defaultInstance());
+ retryParams = firstNonNull(builder.retryParams, defaultRetryParams());
serviceFactory = firstNonNull(builder.serviceFactory,
getFromServiceLoader(serviceFactoryClass, defaultServiceFactory()));
serviceFactoryClassName = serviceFactory.getClass().getName();
@@ -376,11 +383,26 @@ protected String defaultHost() {
protected String defaultProject() {
String projectId = System.getProperty(PROJECT_ENV_NAME, System.getenv(PROJECT_ENV_NAME));
if (projectId == null) {
- projectId = getAppEngineProjectId();
+ projectId = appEngineProjectId();
+ }
+ if (projectId == null) {
+ projectId = serviceAccountProjectId();
}
return projectId != null ? projectId : googleCloudProjectId();
}
+ private static String activeGoogleCloudConfig(File configDir) {
+ String activeGoogleCloudConfig = null;
+ try {
+ activeGoogleCloudConfig =
+ Files.readFirstLine(new File(configDir, "active_config"), Charset.defaultCharset());
+ } catch (IOException ex) {
+ // ignore
+ }
+ // if reading active_config failed or the file is empty we try default
+ return firstNonNull(activeGoogleCloudConfig, "default");
+ }
+
protected static String googleCloudProjectId() {
File configDir;
if (System.getenv().containsKey("CLOUDSDK_CONFIG")) {
@@ -390,9 +412,10 @@ protected static String googleCloudProjectId() {
} else {
configDir = new File(System.getProperty("user.home"), ".config/gcloud");
}
+ String activeConfig = activeGoogleCloudConfig(configDir);
FileReader fileReader = null;
try {
- fileReader = new FileReader(new File(configDir, "configurations/config_default"));
+ fileReader = new FileReader(new File(configDir, "configurations/config_" + activeConfig));
} catch (FileNotFoundException newConfigFileNotFoundEx) {
try {
fileReader = new FileReader(new File(configDir, "properties"));
@@ -446,7 +469,7 @@ private static boolean isWindows() {
return System.getProperty("os.name").toLowerCase(Locale.ENGLISH).contains("windows");
}
- protected static String getAppEngineProjectId() {
+ protected static String appEngineProjectId() {
try {
Class> factoryClass =
Class.forName("com.google.appengine.api.appidentity.AppIdentityServiceFactory");
@@ -464,6 +487,20 @@ protected static String getAppEngineProjectId() {
}
}
+ protected static String serviceAccountProjectId() {
+ String project = null;
+ String credentialsPath = System.getenv("GOOGLE_APPLICATION_CREDENTIALS");
+ if (credentialsPath != null) {
+ try (InputStream credentialsStream = new FileInputStream(credentialsPath)) {
+ JSONObject json = new JSONObject(new JSONTokener(credentialsStream));
+ project = json.getString("project_id");
+ } catch (IOException | JSONException ex) {
+ // ignore
+ }
+ }
+ return project;
+ }
+
@SuppressWarnings("unchecked")
public ServiceT service() {
if (service == null) {
@@ -481,9 +518,8 @@ public ServiceRpcT rpc() {
}
/**
- * Returns the project id.
- *
- * Return value can be null (for services that don't require a project id).
+ * Returns the project id. Return value can be null (for services that don't require a project
+ * id).
*/
public String projectId() {
return projectId;
@@ -610,14 +646,23 @@ private static T newInstance(String className) throws IOException, ClassNotF
}
}
- protected abstract > T defaultServiceFactory();
+ protected abstract ServiceFactory defaultServiceFactory();
- protected abstract > T defaultRpcFactory();
+ protected abstract ServiceRpcFactory defaultRpcFactory();
protected abstract Set scopes();
public abstract > B toBuilder();
+ /**
+ * Some services may have different backoff requirements listed in their SLAs. Be sure to override
+ * this method in options subclasses when the service's backoff requirement differs from the
+ * default parameters listed in {@link RetryParams}.
+ */
+ protected RetryParams defaultRetryParams() {
+ return RetryParams.defaultInstance();
+ }
+
private static T getFromServiceLoader(Class extends T> clazz, T defaultInstance) {
return Iterables.getFirst(ServiceLoader.load(clazz), defaultInstance);
}
diff --git a/gcloud-java-core/src/main/java/com/google/gcloud/WriteChannel.java b/gcloud-java-core/src/main/java/com/google/cloud/WriteChannel.java
similarity index 98%
rename from gcloud-java-core/src/main/java/com/google/gcloud/WriteChannel.java
rename to gcloud-java-core/src/main/java/com/google/cloud/WriteChannel.java
index e6f06e23dc04..636bc60d0243 100644
--- a/gcloud-java-core/src/main/java/com/google/gcloud/WriteChannel.java
+++ b/gcloud-java-core/src/main/java/com/google/cloud/WriteChannel.java
@@ -14,7 +14,7 @@
* limitations under the License.
*/
-package com.google.gcloud;
+package com.google.cloud;
import java.io.Closeable;
import java.nio.channels.WritableByteChannel;
diff --git a/gcloud-java-core/src/main/java/com/google/gcloud/package-info.java b/gcloud-java-core/src/main/java/com/google/cloud/package-info.java
similarity index 96%
rename from gcloud-java-core/src/main/java/com/google/gcloud/package-info.java
rename to gcloud-java-core/src/main/java/com/google/cloud/package-info.java
index d527640c99f9..8b548e3d26e8 100644
--- a/gcloud-java-core/src/main/java/com/google/gcloud/package-info.java
+++ b/gcloud-java-core/src/main/java/com/google/cloud/package-info.java
@@ -17,4 +17,4 @@
/**
* Core classes for the {@code gcloud-java} library.
*/
-package com.google.gcloud;
+package com.google.cloud;
diff --git a/gcloud-java-core/src/main/java/com/google/gcloud/spi/ServiceRpcFactory.java b/gcloud-java-core/src/main/java/com/google/cloud/spi/ServiceRpcFactory.java
similarity index 74%
rename from gcloud-java-core/src/main/java/com/google/gcloud/spi/ServiceRpcFactory.java
rename to gcloud-java-core/src/main/java/com/google/cloud/spi/ServiceRpcFactory.java
index d19f6047e4b2..21a061f4a5dc 100644
--- a/gcloud-java-core/src/main/java/com/google/gcloud/spi/ServiceRpcFactory.java
+++ b/gcloud-java-core/src/main/java/com/google/cloud/spi/ServiceRpcFactory.java
@@ -14,15 +14,13 @@
* limitations under the License.
*/
-package com.google.gcloud.spi;
+package com.google.cloud.spi;
-import com.google.gcloud.ServiceOptions;
+import com.google.cloud.ServiceOptions;
/**
- * A base interface for all service RPC factories.
- *
- * Implementation must provide a public no-arg constructor.
- * Loading of a factory implementation is done via {@link java.util.ServiceLoader}.
+ * A base interface for all service RPC factories. Implementation must provide a public no-arg
+ * constructor. Loading of a factory implementation is done via {@link java.util.ServiceLoader}.
*/
@SuppressWarnings("rawtypes")
public interface ServiceRpcFactory {
diff --git a/gcloud-java-core/src/test/java/com/google/cloud/BaseSerializationTest.java b/gcloud-java-core/src/test/java/com/google/cloud/BaseSerializationTest.java
new file mode 100644
index 000000000000..57603b9026d8
--- /dev/null
+++ b/gcloud-java-core/src/test/java/com/google/cloud/BaseSerializationTest.java
@@ -0,0 +1,86 @@
+/*
+ * Copyright 2016 Google Inc. All Rights Reserved.
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+package com.google.cloud;
+
+import static com.google.common.base.MoreObjects.firstNonNull;
+import static org.junit.Assert.assertEquals;
+import static org.junit.Assert.assertNotSame;
+
+import org.junit.Test;
+
+import java.io.ByteArrayInputStream;
+import java.io.ByteArrayOutputStream;
+import java.io.IOException;
+import java.io.ObjectInputStream;
+import java.io.ObjectOutputStream;
+import java.io.Serializable;
+
+/**
+ * Base class for serialization tests. To use this class in your tests override the
+ * {@code serializableObjects()} method to return all objects that must be serializable. Also
+ * override {@code restorableObjects()} method to return all restorable objects whose state must be
+ * tested for proper serialization. Both methods can return {@code null} if no such object needs to
+ * be tested.
+ */
+public abstract class BaseSerializationTest {
+
+ /**
+ * Returns all objects for which correct serialization must be tested.
+ */
+ protected abstract Serializable[] serializableObjects();
+
+ /**
+ * Returns all restorable objects whose state must be tested for proper serialization.
+ */
+ protected abstract Restorable>[] restorableObjects();
+
+ @Test
+ public void testSerializableObjects() throws Exception {
+ for (Serializable obj : firstNonNull(serializableObjects(), new Serializable[0])) {
+ Object copy = serializeAndDeserialize(obj);
+ assertEquals(obj, obj);
+ assertEquals(obj, copy);
+ assertEquals(obj.hashCode(), copy.hashCode());
+ assertEquals(obj.toString(), copy.toString());
+ assertNotSame(obj, copy);
+ assertEquals(copy, copy);
+ }
+ }
+
+ @Test
+ public void testRestorableObjects() throws Exception {
+ for (Restorable restorable : firstNonNull(restorableObjects(), new Restorable[0])) {
+ RestorableState> state = restorable.capture();
+ RestorableState> deserializedState = serializeAndDeserialize(state);
+ assertEquals(state, deserializedState);
+ assertEquals(state.hashCode(), deserializedState.hashCode());
+ assertEquals(state.toString(), deserializedState.toString());
+ }
+ }
+
+ @SuppressWarnings("unchecked")
+ public T serializeAndDeserialize(T obj) throws IOException, ClassNotFoundException {
+ ByteArrayOutputStream bytes = new ByteArrayOutputStream();
+ try (ObjectOutputStream output = new ObjectOutputStream(bytes)) {
+ output.writeObject(obj);
+ }
+ try (ObjectInputStream input =
+ new ObjectInputStream(new ByteArrayInputStream(bytes.toByteArray()))) {
+ return (T) input.readObject();
+ }
+ }
+}
diff --git a/gcloud-java-core/src/test/java/com/google/gcloud/BaseServiceExceptionTest.java b/gcloud-java-core/src/test/java/com/google/cloud/BaseServiceExceptionTest.java
similarity index 98%
rename from gcloud-java-core/src/test/java/com/google/gcloud/BaseServiceExceptionTest.java
rename to gcloud-java-core/src/test/java/com/google/cloud/BaseServiceExceptionTest.java
index e3c6abb7d1ee..52bc3b2b51a4 100644
--- a/gcloud-java-core/src/test/java/com/google/gcloud/BaseServiceExceptionTest.java
+++ b/gcloud-java-core/src/test/java/com/google/cloud/BaseServiceExceptionTest.java
@@ -14,9 +14,9 @@
* limitations under the License.
*/
-package com.google.gcloud;
+package com.google.cloud;
-import static com.google.gcloud.BaseServiceException.UNKNOWN_CODE;
+import static com.google.cloud.BaseServiceException.UNKNOWN_CODE;
import static org.easymock.EasyMock.createMock;
import static org.easymock.EasyMock.expect;
import static org.easymock.EasyMock.replay;
diff --git a/gcloud-java-core/src/test/java/com/google/gcloud/BaseWriteChannelTest.java b/gcloud-java-core/src/test/java/com/google/cloud/BaseWriteChannelTest.java
similarity index 96%
rename from gcloud-java-core/src/test/java/com/google/gcloud/BaseWriteChannelTest.java
rename to gcloud-java-core/src/test/java/com/google/cloud/BaseWriteChannelTest.java
index 6d5306a3bc7f..fc476b11ae6e 100644
--- a/gcloud-java-core/src/test/java/com/google/gcloud/BaseWriteChannelTest.java
+++ b/gcloud-java-core/src/test/java/com/google/cloud/BaseWriteChannelTest.java
@@ -14,7 +14,7 @@
* limitations under the License.
*/
-package com.google.gcloud;
+package com.google.cloud;
import static junit.framework.TestCase.assertFalse;
import static junit.framework.TestCase.assertTrue;
@@ -22,7 +22,7 @@
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertNull;
-import com.google.gcloud.spi.ServiceRpcFactory;
+import com.google.cloud.spi.ServiceRpcFactory;
import org.junit.Before;
import org.junit.Rule;
@@ -82,7 +82,7 @@ protected BaseState.Builder stateBuilder() {
}
@Test
- public void testConstructor() throws IOException {
+ public void testConstructor() {
assertEquals(null, channel.options());
assertEquals(ENTITY, channel.entity());
assertEquals(0, channel.position());
@@ -108,7 +108,7 @@ public void testValidateOpen() throws IOException {
}
@Test
- public void testChunkSize() throws IOException {
+ public void testChunkSize() {
channel.chunkSize(42);
assertEquals(MIN_CHUNK_SIZE, channel.chunkSize());
channel.chunkSize(2 * MIN_CHUNK_SIZE);
diff --git a/gcloud-java-core/src/test/java/com/google/gcloud/ExceptionHandlerTest.java b/gcloud-java-core/src/test/java/com/google/cloud/ExceptionHandlerTest.java
similarity index 97%
rename from gcloud-java-core/src/test/java/com/google/gcloud/ExceptionHandlerTest.java
rename to gcloud-java-core/src/test/java/com/google/cloud/ExceptionHandlerTest.java
index cedc995ddbd0..ddbd2ced841c 100644
--- a/gcloud-java-core/src/test/java/com/google/gcloud/ExceptionHandlerTest.java
+++ b/gcloud-java-core/src/test/java/com/google/cloud/ExceptionHandlerTest.java
@@ -14,14 +14,14 @@
* limitations under the License.
*/
-package com.google.gcloud;
+package com.google.cloud;
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertTrue;
import static org.junit.Assert.fail;
-import com.google.gcloud.ExceptionHandler.Interceptor;
-import com.google.gcloud.ExceptionHandler.Interceptor.RetryResult;
+import com.google.cloud.ExceptionHandler.Interceptor;
+import com.google.cloud.ExceptionHandler.Interceptor.RetryResult;
import org.junit.Rule;
import org.junit.Test;
diff --git a/gcloud-java-core/src/test/java/com/google/cloud/FieldSelectorHelperTest.java b/gcloud-java-core/src/test/java/com/google/cloud/FieldSelectorHelperTest.java
new file mode 100644
index 000000000000..02d5847946e0
--- /dev/null
+++ b/gcloud-java-core/src/test/java/com/google/cloud/FieldSelectorHelperTest.java
@@ -0,0 +1,101 @@
+/*
+ * Copyright 2016 Google Inc. All Rights Reserved.
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+package com.google.cloud;
+
+import static org.junit.Assert.assertEquals;
+import static org.junit.Assert.assertTrue;
+
+import com.google.cloud.FieldSelector.Helper;
+import com.google.common.collect.ImmutableList;
+
+import org.junit.Test;
+
+import java.util.List;
+
+public class FieldSelectorHelperTest {
+
+ private static final FieldSelector FIELD1 = new FieldSelector() {
+ @Override
+ public String selector() {
+ return "field1";
+ }
+ };
+ private static final FieldSelector FIELD2 = new FieldSelector() {
+ @Override
+ public String selector() {
+ return "field2";
+ }
+ };
+ private static final FieldSelector FIELD3 = new FieldSelector() {
+ @Override
+ public String selector() {
+ return "field3";
+ }
+ };
+ private static final String[] FIRST_LEVEL_FIELDS = {"firstLevel1", "firstLevel2"};
+ private static final List REQUIRED_FIELDS = ImmutableList.of(FIELD1, FIELD2);
+ private static final String CONTAINER = "container";
+
+ @Test
+ public void testSelector() {
+ String selector = Helper.selector(REQUIRED_FIELDS, FIELD3);
+ assertTrue(selector.contains("field1"));
+ assertTrue(selector.contains("field2"));
+ assertTrue(selector.contains("field3"));
+ assertEquals(20, selector.length());
+ }
+
+ @Test
+ public void testListSelector() {
+ String selector = Helper.listSelector(CONTAINER, REQUIRED_FIELDS, FIELD3);
+ assertTrue(selector.startsWith("nextPageToken,container("));
+ assertTrue(selector.contains("field1"));
+ assertTrue(selector.contains("field2"));
+ assertTrue(selector.contains("field3"));
+ assertTrue(selector.endsWith(")"));
+ assertEquals(45, selector.length());
+ }
+
+ @Test
+ public void testListSelectorWithExtraFields() {
+ String selector = Helper.listSelector(CONTAINER, REQUIRED_FIELDS,
+ new FieldSelector[]{FIELD3}, "field4");
+ assertTrue(selector.startsWith("nextPageToken,container("));
+ assertTrue(selector.contains("field1"));
+ assertTrue(selector.contains("field2"));
+ assertTrue(selector.contains("field3"));
+ assertTrue(selector.contains("field4"));
+ assertTrue(selector.endsWith(")"));
+ assertEquals(52, selector.length());
+ }
+
+ @Test
+ public void testListSelectorWithFirstLevelFields() {
+ String selector = Helper.listSelector(FIRST_LEVEL_FIELDS, CONTAINER, REQUIRED_FIELDS,
+ new FieldSelector[]{FIELD3}, "field4");
+ assertTrue(selector.contains("firstLevel1"));
+ assertTrue(selector.contains("firstLevel2"));
+ assertTrue(selector.contains("nextPageToken"));
+ assertTrue(selector.contains("container("));
+ assertTrue(selector.contains("field1"));
+ assertTrue(selector.contains("field2"));
+ assertTrue(selector.contains("field3"));
+ assertTrue(selector.contains("field4"));
+ assertTrue(selector.endsWith(")"));
+ assertEquals(76, selector.length());
+ }
+}
diff --git a/gcloud-java-core/src/test/java/com/google/gcloud/IamPolicyTest.java b/gcloud-java-core/src/test/java/com/google/cloud/IamPolicyTest.java
similarity index 70%
rename from gcloud-java-core/src/test/java/com/google/gcloud/IamPolicyTest.java
rename to gcloud-java-core/src/test/java/com/google/cloud/IamPolicyTest.java
index db0935c4766d..e79cfd96554c 100644
--- a/gcloud-java-core/src/test/java/com/google/gcloud/IamPolicyTest.java
+++ b/gcloud-java-core/src/test/java/com/google/cloud/IamPolicyTest.java
@@ -14,7 +14,7 @@
* limitations under the License.
*/
-package com.google.gcloud;
+package com.google.cloud;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertNotEquals;
@@ -28,6 +28,8 @@
import org.junit.Test;
+import java.util.HashMap;
+import java.util.HashSet;
import java.util.Map;
import java.util.Set;
@@ -46,8 +48,8 @@ public class IamPolicyTest {
"editor",
ImmutableSet.of(ALL_AUTH_USERS, GROUP, DOMAIN));
private static final PolicyImpl SIMPLE_POLICY = PolicyImpl.builder()
- .addBinding("viewer", ImmutableSet.of(USER, SERVICE_ACCOUNT, ALL_USERS))
- .addBinding("editor", ImmutableSet.of(ALL_AUTH_USERS, GROUP, DOMAIN))
+ .addIdentity("viewer", USER, SERVICE_ACCOUNT, ALL_USERS)
+ .addIdentity("editor", ALL_AUTH_USERS, GROUP, DOMAIN)
.build();
private static final PolicyImpl FULL_POLICY =
new PolicyImpl.Builder(SIMPLE_POLICY.bindings(), "etag", 1).build();
@@ -93,7 +95,7 @@ public void testBuilder() {
assertEquals(editorBinding, policy.bindings());
assertEquals("etag", policy.etag());
assertEquals(1, policy.version().intValue());
- policy = SIMPLE_POLICY.toBuilder().removeBinding("editor").build();
+ policy = SIMPLE_POLICY.toBuilder().removeRole("editor").build();
assertEquals(ImmutableMap.of("viewer", BINDINGS.get("viewer")), policy.bindings());
assertNull(policy.etag());
assertNull(policy.version());
@@ -105,22 +107,61 @@ public void testBuilder() {
policy.bindings());
assertNull(policy.etag());
assertNull(policy.version());
- policy = PolicyImpl.builder().addBinding("owner", USER, SERVICE_ACCOUNT).build();
+ policy = PolicyImpl.builder()
+ .removeIdentity("viewer", USER)
+ .addIdentity("owner", USER, SERVICE_ACCOUNT)
+ .addIdentity("editor", GROUP)
+ .removeIdentity("editor", GROUP)
+ .build();
assertEquals(
ImmutableMap.of("owner", ImmutableSet.of(USER, SERVICE_ACCOUNT)), policy.bindings());
assertNull(policy.etag());
assertNull(policy.version());
+ }
+
+ @Test
+ public void testIllegalPolicies() {
+ try {
+ PolicyImpl.builder().addIdentity(null, USER);
+ fail("Null role should cause exception.");
+ } catch (NullPointerException ex) {
+ assertEquals("The role cannot be null.", ex.getMessage());
+ }
+ try {
+ PolicyImpl.builder().addIdentity("viewer", null, USER);
+ fail("Null identity should cause exception.");
+ } catch (NullPointerException ex) {
+ assertEquals("Null identities are not permitted.", ex.getMessage());
+ }
+ try {
+ PolicyImpl.builder().addIdentity("viewer", USER, (Identity[]) null);
+ fail("Null identity should cause exception.");
+ } catch (NullPointerException ex) {
+ assertEquals("Null identities are not permitted.", ex.getMessage());
+ }
+ try {
+ PolicyImpl.builder().bindings(null);
+ fail("Null bindings map should cause exception.");
+ } catch (NullPointerException ex) {
+ assertEquals("The provided map of bindings cannot be null.", ex.getMessage());
+ }
try {
- SIMPLE_POLICY.toBuilder().addBinding("viewer", USER);
- fail("Should have failed due to duplicate role.");
- } catch (IllegalArgumentException e) {
- assertEquals("The policy already contains a binding with the role viewer.", e.getMessage());
+ Map> bindings = new HashMap<>();
+ bindings.put("viewer", null);
+ PolicyImpl.builder().bindings(bindings);
+ fail("Null set of identities should cause exception.");
+ } catch (NullPointerException ex) {
+ assertEquals("A role cannot be assigned to a null set of identities.", ex.getMessage());
}
try {
- SIMPLE_POLICY.toBuilder().addBinding("editor", ImmutableSet.of(USER));
- fail("Should have failed due to duplicate role.");
- } catch (IllegalArgumentException e) {
- assertEquals("The policy already contains a binding with the role editor.", e.getMessage());
+ Map> bindings = new HashMap<>();
+ Set identities = new HashSet<>();
+ identities.add(null);
+ bindings.put("viewer", identities);
+ PolicyImpl.builder().bindings(bindings);
+ fail("Null identity should cause exception.");
+ } catch (IllegalArgumentException ex) {
+ assertEquals("Null identities are not permitted.", ex.getMessage());
}
}
diff --git a/gcloud-java-core/src/test/java/com/google/gcloud/IdentityTest.java b/gcloud-java-core/src/test/java/com/google/cloud/IdentityTest.java
similarity index 88%
rename from gcloud-java-core/src/test/java/com/google/gcloud/IdentityTest.java
rename to gcloud-java-core/src/test/java/com/google/cloud/IdentityTest.java
index 828f1c839431..e720503c547d 100644
--- a/gcloud-java-core/src/test/java/com/google/gcloud/IdentityTest.java
+++ b/gcloud-java-core/src/test/java/com/google/cloud/IdentityTest.java
@@ -14,7 +14,7 @@
* limitations under the License.
*/
-package com.google.gcloud;
+package com.google.cloud;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertNull;
@@ -34,19 +34,19 @@ public class IdentityTest {
@Test
public void testAllUsers() {
assertEquals(Identity.Type.ALL_USERS, ALL_USERS.type());
- assertNull(ALL_USERS.id());
+ assertNull(ALL_USERS.value());
}
@Test
public void testAllAuthenticatedUsers() {
assertEquals(Identity.Type.ALL_AUTHENTICATED_USERS, ALL_AUTH_USERS.type());
- assertNull(ALL_AUTH_USERS.id());
+ assertNull(ALL_AUTH_USERS.value());
}
@Test
public void testUser() {
assertEquals(Identity.Type.USER, USER.type());
- assertEquals("abc@gmail.com", USER.id());
+ assertEquals("abc@gmail.com", USER.value());
}
@Test(expected = NullPointerException.class)
@@ -57,7 +57,7 @@ public void testUserNullEmail() {
@Test
public void testServiceAccount() {
assertEquals(Identity.Type.SERVICE_ACCOUNT, SERVICE_ACCOUNT.type());
- assertEquals("service-account@gmail.com", SERVICE_ACCOUNT.id());
+ assertEquals("service-account@gmail.com", SERVICE_ACCOUNT.value());
}
@Test(expected = NullPointerException.class)
@@ -68,7 +68,7 @@ public void testServiceAccountNullEmail() {
@Test
public void testGroup() {
assertEquals(Identity.Type.GROUP, GROUP.type());
- assertEquals("group@gmail.com", GROUP.id());
+ assertEquals("group@gmail.com", GROUP.value());
}
@Test(expected = NullPointerException.class)
@@ -79,7 +79,7 @@ public void testGroupNullEmail() {
@Test
public void testDomain() {
assertEquals(Identity.Type.DOMAIN, DOMAIN.type());
- assertEquals("google.com", DOMAIN.id());
+ assertEquals("google.com", DOMAIN.value());
}
@Test(expected = NullPointerException.class)
@@ -100,6 +100,6 @@ public void testIdentityToAndFromPb() {
private void compareIdentities(Identity expected, Identity actual) {
assertEquals(expected, actual);
assertEquals(expected.type(), actual.type());
- assertEquals(expected.id(), actual.id());
+ assertEquals(expected.value(), actual.value());
}
}
diff --git a/gcloud-java-core/src/test/java/com/google/gcloud/PageImplTest.java b/gcloud-java-core/src/test/java/com/google/cloud/PageImplTest.java
similarity index 98%
rename from gcloud-java-core/src/test/java/com/google/gcloud/PageImplTest.java
rename to gcloud-java-core/src/test/java/com/google/cloud/PageImplTest.java
index 4389171fb49c..07d979ad857c 100644
--- a/gcloud-java-core/src/test/java/com/google/gcloud/PageImplTest.java
+++ b/gcloud-java-core/src/test/java/com/google/cloud/PageImplTest.java
@@ -14,7 +14,7 @@
* limitations under the License.
*/
-package com.google.gcloud;
+package com.google.cloud;
import static org.junit.Assert.assertEquals;
diff --git a/gcloud-java-core/src/test/java/com/google/gcloud/RetryHelperTest.java b/gcloud-java-core/src/test/java/com/google/cloud/RetryHelperTest.java
similarity index 98%
rename from gcloud-java-core/src/test/java/com/google/gcloud/RetryHelperTest.java
rename to gcloud-java-core/src/test/java/com/google/cloud/RetryHelperTest.java
index 9a7cc2104f4a..3887cecd6a83 100644
--- a/gcloud-java-core/src/test/java/com/google/gcloud/RetryHelperTest.java
+++ b/gcloud-java-core/src/test/java/com/google/cloud/RetryHelperTest.java
@@ -14,7 +14,7 @@
* limitations under the License.
*/
-package com.google.gcloud;
+package com.google.cloud;
import static java.util.concurrent.Executors.callable;
import static org.junit.Assert.assertEquals;
@@ -22,10 +22,10 @@
import static org.junit.Assert.assertTrue;
import static org.junit.Assert.fail;
+import com.google.cloud.RetryHelper.NonRetriableException;
+import com.google.cloud.RetryHelper.RetriesExhaustedException;
import com.google.common.base.Stopwatch;
import com.google.common.base.Ticker;
-import com.google.gcloud.RetryHelper.NonRetriableException;
-import com.google.gcloud.RetryHelper.RetriesExhaustedException;
import org.junit.Test;
diff --git a/gcloud-java-core/src/test/java/com/google/gcloud/RetryParamsTest.java b/gcloud-java-core/src/test/java/com/google/cloud/RetryParamsTest.java
similarity index 87%
rename from gcloud-java-core/src/test/java/com/google/gcloud/RetryParamsTest.java
rename to gcloud-java-core/src/test/java/com/google/cloud/RetryParamsTest.java
index eae44693929b..c3041053110b 100644
--- a/gcloud-java-core/src/test/java/com/google/gcloud/RetryParamsTest.java
+++ b/gcloud-java-core/src/test/java/com/google/cloud/RetryParamsTest.java
@@ -14,18 +14,18 @@
* limitations under the License.
*/
-package com.google.gcloud;
+package com.google.cloud;
-import static com.google.gcloud.RetryParams.DEFAULT_INITIAL_RETRY_DELAY_MILLIS;
-import static com.google.gcloud.RetryParams.DEFAULT_MAX_RETRY_DELAY_MILLIS;
-import static com.google.gcloud.RetryParams.DEFAULT_RETRY_DELAY_BACKOFF_FACTOR;
-import static com.google.gcloud.RetryParams.DEFAULT_RETRY_MAX_ATTEMPTS;
-import static com.google.gcloud.RetryParams.DEFAULT_RETRY_MIN_ATTEMPTS;
-import static com.google.gcloud.RetryParams.DEFAULT_TOTAL_RETRY_PERIOD_MILLIS;
+import static com.google.cloud.RetryParams.DEFAULT_INITIAL_RETRY_DELAY_MILLIS;
+import static com.google.cloud.RetryParams.DEFAULT_MAX_RETRY_DELAY_MILLIS;
+import static com.google.cloud.RetryParams.DEFAULT_RETRY_DELAY_BACKOFF_FACTOR;
+import static com.google.cloud.RetryParams.DEFAULT_RETRY_MAX_ATTEMPTS;
+import static com.google.cloud.RetryParams.DEFAULT_RETRY_MIN_ATTEMPTS;
+import static com.google.cloud.RetryParams.DEFAULT_TOTAL_RETRY_PERIOD_MILLIS;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.fail;
-import com.google.gcloud.RetryParams.Builder;
+import com.google.cloud.RetryParams.Builder;
import org.junit.Test;
import org.junit.runner.RunWith;
diff --git a/gcloud-java-core/src/test/java/com/google/cloud/SerializationTest.java b/gcloud-java-core/src/test/java/com/google/cloud/SerializationTest.java
new file mode 100644
index 000000000000..75347b250227
--- /dev/null
+++ b/gcloud-java-core/src/test/java/com/google/cloud/SerializationTest.java
@@ -0,0 +1,103 @@
+/*
+ * Copyright 2016 Google Inc. All Rights Reserved.
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+package com.google.cloud;
+
+import com.google.cloud.ServiceAccountSigner.SigningException;
+import com.google.common.collect.ImmutableList;
+
+import java.io.ByteArrayInputStream;
+import java.io.IOException;
+import java.io.Serializable;
+
+public class SerializationTest extends BaseSerializationTest {
+
+ private static final BaseServiceException BASE_SERVICE_EXCEPTION =
+ new BaseServiceException(42, "message", "reason", true);
+ private static final ExceptionHandler EXCEPTION_HANDLER = ExceptionHandler.defaultInstance();
+ private static final Identity IDENTITY = Identity.allAuthenticatedUsers();
+ private static final PageImpl PAGE =
+ new PageImpl<>(null, "cursor", ImmutableList.of("string1", "string2"));
+ private static final SigningException SIGNING_EXCEPTION =
+ new SigningException("message", BASE_SERVICE_EXCEPTION);
+ private static final RetryParams RETRY_PARAMS = RetryParams.defaultInstance();
+ private static final SomeIamPolicy SOME_IAM_POLICY = new SomeIamPolicy.Builder().build();
+ private static final String JSON_KEY = "{\n"
+ + " \"private_key_id\": \"somekeyid\",\n"
+ + " \"private_key\": \"-----BEGIN PRIVATE KEY-----\\nMIIEvgIBADANBgkqhkiG9w0BAQEFAASCBKgwggS"
+ + "kAgEAAoIBAQC+K2hSuFpAdrJI\\nnCgcDz2M7t7bjdlsadsasad+fvRSW6TjNQZ3p5LLQY1kSZRqBqylRkzteMOyHg"
+ + "aR\\n0Pmxh3ILCND5men43j3h4eDbrhQBuxfEMalkG92sL+PNQSETY2tnvXryOvmBRwa/\\nQP/9dJfIkIDJ9Fw9N4"
+ + "Bhhhp6mCcRpdQjV38H7JsyJ7lih/oNjECgYAt\\nknddadwkwewcVxHFhcZJO+XWf6ofLUXpRwiTZakGMn8EE1uVa2"
+ + "LgczOjwWHGi99MFjxSer5m9\\n1tCa3/KEGKiS/YL71JvjwX3mb+cewlkcmweBKZHM2JPTk0ZednFSpVZMtycjkbLa"
+ + "\\ndYOS8V85AgMBewECggEBAKksaldajfDZDV6nGqbFjMiizAKJolr/M3OQw16K6o3/\\n0S31xIe3sSlgW0+UbYlF"
+ + "4U8KifhManD1apVSC3csafaspP4RZUHFhtBywLO9pR5c\\nr6S5aLp+gPWFyIp1pfXbWGvc5VY/v9x7ya1VEa6rXvL"
+ + "sKupSeWAW4tMj3eo/64ge\\nsdaceaLYw52KeBYiT6+vpsnYrEkAHO1fF/LavbLLOFJmFTMxmsNaG0tuiJHgjshB\\"
+ + "n82DpMCbXG9YcCgI/DbzuIjsdj2JC1cascSP//3PmefWysucBQe7Jryb6NQtASmnv\\nCdDw/0jmZTEjpe4S1lxfHp"
+ + "lAhHFtdgYTvyYtaLZiVVkCgYEA8eVpof2rceecw/I6\\n5ng1q3Hl2usdWV/4mZMvR0fOemacLLfocX6IYxT1zA1FF"
+ + "JlbXSRsJMf/Qq39mOR2\\nSpW+hr4jCoHeRVYLgsbggtrevGmILAlNoqCMpGZ6vDmJpq6ECV9olliDvpPgWOP+\\nm"
+ + "YPDreFBGxWvQrADNbRt2dmGsrsCgYEAyUHqB2wvJHFqdmeBsaacewzV8x9WgmeX\\ngUIi9REwXlGDW0Mz50dxpxcK"
+ + "CAYn65+7TCnY5O/jmL0VRxU1J2mSWyWTo1C+17L0\\n3fUqjxL1pkefwecxwecvC+gFFYdJ4CQ/MHHXU81Lwl1iWdF"
+ + "Cd2UoGddYaOF+KNeM\\nHC7cmqra+JsCgYEAlUNywzq8nUg7282E+uICfCB0LfwejuymR93CtsFgb7cRd6ak\\nECR"
+ + "8FGfCpH8ruWJINllbQfcHVCX47ndLZwqv3oVFKh6pAS/vVI4dpOepP8++7y1u\\ncoOvtreXCX6XqfrWDtKIvv0vjl"
+ + "HBhhhp6mCcRpdQjV38H7JsyJ7lih/oNjECgYAt\\nkndj5uNl5SiuVxHFhcZJO+XWf6ofLUregtevZakGMn8EE1uVa"
+ + "2AY7eafmoU/nZPT\\n00YB0TBATdCbn/nBSuKDESkhSg9s2GEKQZG5hBmL5uCMfo09z3SfxZIhJdlerreP\\nJ7gSi"
+ + "dI12N+EZxYd4xIJh/HFDgp7RRO87f+WJkofMQKBgGTnClK1VMaCRbJZPriw\\nEfeFCoOX75MxKwXs6xgrw4W//AYG"
+ + "GUjDt83lD6AZP6tws7gJ2IwY/qP7+lyhjEqN\\nHtfPZRGFkGZsdaksdlaksd323423d+15/UvrlRSFPNj1tWQmNKk"
+ + "XyRDW4IG1Oa2p\\nrALStNBx5Y9t0/LQnFI4w3aG\\n-----END PRIVATE KEY-----\\n\",\n"
+ + " \"client_email\": \"someclientid@developer.gserviceaccount.com\",\n"
+ + " \"client_id\": \"someclientid.apps.googleusercontent.com\",\n"
+ + " \"type\": \"service_account\"\n"
+ + "}";
+
+ private static class SomeIamPolicy extends IamPolicy {
+
+ private static final long serialVersionUID = 271243551016958285L;
+
+ private static class Builder extends IamPolicy.Builder {
+
+ @Override
+ public SomeIamPolicy build() {
+ return new SomeIamPolicy(this);
+ }
+ }
+
+ protected SomeIamPolicy(Builder builder) {
+ super(builder);
+ }
+
+ @Override
+ public Builder toBuilder() {
+ return new Builder();
+ }
+ }
+
+ @Override
+ protected Serializable[] serializableObjects() {
+ return new Serializable[]{BASE_SERVICE_EXCEPTION, EXCEPTION_HANDLER, IDENTITY, PAGE,
+ RETRY_PARAMS, SOME_IAM_POLICY, SIGNING_EXCEPTION};
+ }
+
+ @Override
+ protected Restorable>[] restorableObjects() {
+ try {
+ return new Restorable>[]{AuthCredentials.createForAppEngine(), AuthCredentials.noAuth(),
+ AuthCredentials.createForJson(new ByteArrayInputStream(JSON_KEY.getBytes()))};
+ } catch (IOException ex) {
+ // never reached
+ throw new RuntimeException(ex);
+ }
+ }
+}
diff --git a/gcloud-java-core/src/test/java/com/google/gcloud/ServiceOptionsTest.java b/gcloud-java-core/src/test/java/com/google/cloud/ServiceOptionsTest.java
similarity index 97%
rename from gcloud-java-core/src/test/java/com/google/gcloud/ServiceOptionsTest.java
rename to gcloud-java-core/src/test/java/com/google/cloud/ServiceOptionsTest.java
index d0e3db2d2a55..b6f7a5453ddc 100644
--- a/gcloud-java-core/src/test/java/com/google/gcloud/ServiceOptionsTest.java
+++ b/gcloud-java-core/src/test/java/com/google/cloud/ServiceOptionsTest.java
@@ -14,7 +14,7 @@
* limitations under the License.
*/
-package com.google.gcloud;
+package com.google.cloud;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertNotEquals;
@@ -22,10 +22,10 @@
import static org.junit.Assert.assertTrue;
import static org.junit.Assert.fail;
-import com.google.gcloud.ServiceOptions.Clock;
-import com.google.gcloud.ServiceOptions.DefaultHttpTransportFactory;
-import com.google.gcloud.ServiceOptions.HttpTransportFactory;
-import com.google.gcloud.spi.ServiceRpcFactory;
+import com.google.cloud.ServiceOptions.Clock;
+import com.google.cloud.ServiceOptions.DefaultHttpTransportFactory;
+import com.google.cloud.ServiceOptions.HttpTransportFactory;
+import com.google.cloud.spi.ServiceRpcFactory;
import org.easymock.EasyMock;
import org.junit.Test;
diff --git a/gcloud-java-datastore/README.md b/gcloud-java-datastore/README.md
index 0d89a0a07e3e..86b77c6bf49a 100644
--- a/gcloud-java-datastore/README.md
+++ b/gcloud-java-datastore/README.md
@@ -5,12 +5,12 @@ Java idiomatic client for [Google Cloud Datastore] (https://cloud.google.com/dat
[![Build Status](https://travis-ci.org/GoogleCloudPlatform/gcloud-java.svg?branch=master)](https://travis-ci.org/GoogleCloudPlatform/gcloud-java)
[![Coverage Status](https://coveralls.io/repos/GoogleCloudPlatform/gcloud-java/badge.svg?branch=master)](https://coveralls.io/r/GoogleCloudPlatform/gcloud-java?branch=master)
-[![Maven](https://img.shields.io/maven-central/v/com.google.gcloud/gcloud-java-datastore.svg)]( https://img.shields.io/maven-central/v/com.google.gcloud/gcloud-java-datastore.svg)
+[![Maven](https://img.shields.io/maven-central/v/com.google.cloud/gcloud-java-datastore.svg)]( https://img.shields.io/maven-central/v/com.google.cloud/gcloud-java-datastore.svg)
[![Codacy Badge](https://api.codacy.com/project/badge/grade/9da006ad7c3a4fe1abd142e77c003917)](https://www.codacy.com/app/mziccard/gcloud-java)
[![Dependency Status](https://www.versioneye.com/user/projects/56bd8ee72a29ed002d2b0969/badge.svg?style=flat)](https://www.versioneye.com/user/projects/56bd8ee72a29ed002d2b0969)
- [Homepage] (https://googlecloudplatform.github.io/gcloud-java/)
-- [API Documentation] (http://googlecloudplatform.github.io/gcloud-java/apidocs/index.html?com/google/gcloud/datastore/package-summary.html)
+- [API Documentation] (http://googlecloudplatform.github.io/gcloud-java/apidocs/index.html?com/google/cloud/datastore/package-summary.html)
> Note: This client is a work-in-progress, and may occasionally
> make backwards-incompatible changes.
@@ -20,23 +20,23 @@ Quickstart
If you are using Maven, add this to your pom.xml file
```xml
- com.google.gcloud
+ com.google.cloud
gcloud-java-datastore
- 0.1.5
+ 0.2.0
```
If you are using Gradle, add this to your dependencies
```Groovy
-compile 'com.google.gcloud:gcloud-java-datastore:0.1.5'
+compile 'com.google.cloud:gcloud-java-datastore:0.2.0'
```
If you are using SBT, add this to your dependencies
```Scala
-libraryDependencies += "com.google.gcloud" % "gcloud-java-datastore" % "0.1.5"
+libraryDependencies += "com.google.cloud" % "gcloud-java-datastore" % "0.2.0"
```
Example Application
--------------------
-[`DatastoreExample`](../gcloud-java-examples/src/main/java/com/google/gcloud/examples/datastore/DatastoreExample.java) is a simple command line interface for the Cloud Datastore. Read more about using the application on the [`DatastoreExample` docs page](http://googlecloudplatform.github.io/gcloud-java/apidocs/?com/google/gcloud/examples/datastore/DatastoreExample.html).
+[`DatastoreExample`](../gcloud-java-examples/src/main/java/com/google/cloud/examples/datastore/DatastoreExample.java) is a simple command line interface for the Cloud Datastore. Read more about using the application on the [`DatastoreExample` docs page](http://googlecloudplatform.github.io/gcloud-java/apidocs/?com/google/cloud/examples/datastore/DatastoreExample.html).
Authentication
--------------
@@ -70,8 +70,8 @@ You'll need to obtain the `gcloud-java-datastore` library. See the [Quickstart]
To make authenticated requests to Google Cloud Datastore, you must create a service object with credentials. You can then make API calls by calling methods on the Datastore service object. The simplest way to authenticate is to use [Application Default Credentials](https://developers.google.com/identity/protocols/application-default-credentials). These credentials are automatically inferred from your environment, so you only need the following code to create your service object:
```java
-import com.google.gcloud.datastore.Datastore;
-import com.google.gcloud.datastore.DatastoreOptions;
+import com.google.cloud.datastore.Datastore;
+import com.google.cloud.datastore.DatastoreOptions;
Datastore datastore = DatastoreOptions.defaultInstance().service();
```
@@ -82,9 +82,9 @@ For other authentication options, see the [Authentication](https://github.com/Go
Objects in Datastore are known as entities. Entities are grouped by "kind" and have keys for easy access. In this code snippet, we will create a new entity representing a person and store that data by the person's email. First, add the following imports at the top of your file:
```java
-import com.google.gcloud.datastore.Entity;
-import com.google.gcloud.datastore.Key;
-import com.google.gcloud.datastore.KeyFactory;
+import com.google.cloud.datastore.Entity;
+import com.google.cloud.datastore.Key;
+import com.google.cloud.datastore.KeyFactory;
```
Then add the following code to put an entity in Datastore.
@@ -112,10 +112,10 @@ In addition to retrieving entities by their keys, you can perform queries to ret
Suppose that you've added more people to Datastore, and now you want to find all people whose favorite food is pizza. Import the following:
```java
-import com.google.gcloud.datastore.Query;
-import com.google.gcloud.datastore.QueryResults;
-import com.google.gcloud.datastore.StructuredQuery;
-import com.google.gcloud.datastore.StructuredQuery.PropertyFilter;
+import com.google.cloud.datastore.Query;
+import com.google.cloud.datastore.QueryResults;
+import com.google.cloud.datastore.StructuredQuery;
+import com.google.cloud.datastore.StructuredQuery.PropertyFilter;
```
Then add the following code to your program:
@@ -137,7 +137,7 @@ Cloud Datastore relies on indexing to run queries. Indexing is turned on by defa
#### Complete source code
In
-[AddEntitiesAndRunQuery.java](../gcloud-java-examples/src/main/java/com/google/gcloud/examples/datastore/snippets/AddEntitiesAndRunQuery.java)
+[AddEntitiesAndRunQuery.java](../gcloud-java-examples/src/main/java/com/google/cloud/examples/datastore/snippets/AddEntitiesAndRunQuery.java)
we put together all the code shown above into one program. The program assumes that you are
running on Compute Engine or from your own desktop. To run the example on App Engine, simply move
the code from the main method to your application's servlet class and change the print statements to
@@ -191,4 +191,4 @@ Apache 2.0 - See [LICENSE] for more information.
[cloud-platform]: https://cloud.google.com/
[cloud-datastore-docs]: https://cloud.google.com/datastore/docs
[cloud-datastore-activation]: https://cloud.google.com/datastore/docs/activate
-[datastore-api]: http://googlecloudplatform.github.io/gcloud-java/apidocs/index.html?com/google/gcloud/datastore/package-summary.html
+[datastore-api]: http://googlecloudplatform.github.io/gcloud-java/apidocs/index.html?com/google/cloud/datastore/package-summary.html
diff --git a/gcloud-java-datastore/pom.xml b/gcloud-java-datastore/pom.xml
index 977b6db22b14..2e76072b2881 100644
--- a/gcloud-java-datastore/pom.xml
+++ b/gcloud-java-datastore/pom.xml
@@ -4,13 +4,14 @@
gcloud-java-datastore
jar
GCloud Java datastore
+ https://github.com/GoogleCloudPlatform/gcloud-java/tree/master/gcloud-java-datastore
Java idiomatic client for Google Cloud Datastore.
- com.google.gcloud
+ com.google.cloud
gcloud-java-pom
- 0.1.6-SNAPSHOT
+ 0.2.1-SNAPSHOT
gcloud-java-datastore
@@ -22,16 +23,21 @@
${project.version}
- com.google.apis
- google-api-services-datastore-protobuf
- v1beta2-rev1-4.0.0
- compile
-
-
- com.google.api-client
- google-api-client
-
-
+ com.google.cloud.datastore
+ datastore-v1beta3-protos
+ 1.0.0-beta
+
+
+ com.google.cloud.datastore
+ datastore-v1beta3-proto-client
+ 1.0.0-beta
+
+
+ ${project.groupId}
+ gcloud-java-core
+ ${project.version}
+ test-jar
+ test
junit
diff --git a/gcloud-java-datastore/src/main/java/com/google/gcloud/datastore/BaseDatastoreBatchWriter.java b/gcloud-java-datastore/src/main/java/com/google/cloud/datastore/BaseDatastoreBatchWriter.java
similarity index 87%
rename from gcloud-java-datastore/src/main/java/com/google/gcloud/datastore/BaseDatastoreBatchWriter.java
rename to gcloud-java-datastore/src/main/java/com/google/cloud/datastore/BaseDatastoreBatchWriter.java
index b42c07d62320..8804ef7e8dda 100644
--- a/gcloud-java-datastore/src/main/java/com/google/gcloud/datastore/BaseDatastoreBatchWriter.java
+++ b/gcloud-java-datastore/src/main/java/com/google/cloud/datastore/BaseDatastoreBatchWriter.java
@@ -14,13 +14,13 @@
* limitations under the License.
*/
-package com.google.gcloud.datastore;
+package com.google.cloud.datastore;
-import com.google.api.services.datastore.DatastoreV1;
import com.google.common.base.Preconditions;
import com.google.common.collect.Iterables;
import com.google.common.collect.Lists;
+import java.util.ArrayList;
import java.util.Collections;
import java.util.Iterator;
import java.util.LinkedHashMap;
@@ -88,9 +88,7 @@ public final List add(FullEntity>... entities) {
for (FullEntity> entity : entities) {
IncompleteKey key = entity.key();
Preconditions.checkArgument(key != null, "Entity must have a key");
- if (key instanceof Key) {
- addInternal((FullEntity) entity);
- } else {
+ if (!(key instanceof Key)) {
incompleteKeys.add(key);
}
}
@@ -104,6 +102,7 @@ public final List add(FullEntity>... entities) {
List answer = Lists.newArrayListWithExpectedSize(entities.length);
for (FullEntity> entity : entities) {
if (entity.key() instanceof Key) {
+ addInternal((FullEntity) entity);
answer.add(Entity.convert((FullEntity) entity));
} else {
Entity entityWithAllocatedId = Entity.builder(allocated.next(), entity).build();
@@ -199,24 +198,30 @@ protected DatastoreException newInvalidRequest(String msg, Object... params) {
return DatastoreException.throwInvalidRequest(String.format(msg, params));
}
- DatastoreV1.Mutation.Builder toMutationPb() {
- DatastoreV1.Mutation.Builder mutationPb = DatastoreV1.Mutation.newBuilder();
+ protected List toMutationPbList() {
+ List mutationsPb =
+ new ArrayList<>();
for (FullEntity entity : toAddAutoId()) {
- mutationPb.addInsertAutoId(entity.toPb());
+ mutationsPb.add(
+ com.google.datastore.v1beta3.Mutation.newBuilder().setInsert(entity.toPb()).build());
}
for (FullEntity entity : toAdd().values()) {
- mutationPb.addInsert(entity.toPb());
+ mutationsPb.add(
+ com.google.datastore.v1beta3.Mutation.newBuilder().setInsert(entity.toPb()).build());
}
for (FullEntity entity : toUpdate().values()) {
- mutationPb.addUpdate(entity.toPb());
+ mutationsPb.add(
+ com.google.datastore.v1beta3.Mutation.newBuilder().setUpdate(entity.toPb()).build());
}
for (FullEntity entity : toPut().values()) {
- mutationPb.addUpsert(entity.toPb());
+ mutationsPb.add(
+ com.google.datastore.v1beta3.Mutation.newBuilder().setUpsert(entity.toPb()).build());
}
for (Key key : toDelete()) {
- mutationPb.addDelete(key.toPb());
+ mutationsPb.add(
+ com.google.datastore.v1beta3.Mutation.newBuilder().setDelete(key.toPb()).build());
}
- return mutationPb;
+ return mutationsPb;
}
protected abstract Datastore datastore();
diff --git a/gcloud-java-datastore/src/main/java/com/google/gcloud/datastore/BaseEntity.java b/gcloud-java-datastore/src/main/java/com/google/cloud/datastore/BaseEntity.java
similarity index 85%
rename from gcloud-java-datastore/src/main/java/com/google/gcloud/datastore/BaseEntity.java
rename to gcloud-java-datastore/src/main/java/com/google/cloud/datastore/BaseEntity.java
index 20c0b13e5001..c7417faa79f3 100644
--- a/gcloud-java-datastore/src/main/java/com/google/gcloud/datastore/BaseEntity.java
+++ b/gcloud-java-datastore/src/main/java/com/google/cloud/datastore/BaseEntity.java
@@ -14,20 +14,20 @@
* limitations under the License.
*/
-package com.google.gcloud.datastore;
-
-import static com.google.gcloud.datastore.BlobValue.of;
-import static com.google.gcloud.datastore.BooleanValue.of;
-import static com.google.gcloud.datastore.DateTimeValue.of;
-import static com.google.gcloud.datastore.DoubleValue.of;
-import static com.google.gcloud.datastore.EntityValue.of;
-import static com.google.gcloud.datastore.KeyValue.of;
-import static com.google.gcloud.datastore.ListValue.of;
-import static com.google.gcloud.datastore.LongValue.of;
-import static com.google.gcloud.datastore.NullValue.of;
-import static com.google.gcloud.datastore.StringValue.of;
-
-import com.google.api.services.datastore.DatastoreV1;
+package com.google.cloud.datastore;
+
+import static com.google.cloud.datastore.BlobValue.of;
+import static com.google.cloud.datastore.BooleanValue.of;
+import static com.google.cloud.datastore.DateTimeValue.of;
+import static com.google.cloud.datastore.DoubleValue.of;
+import static com.google.cloud.datastore.EntityValue.of;
+import static com.google.cloud.datastore.KeyValue.of;
+import static com.google.cloud.datastore.LatLngValue.of;
+import static com.google.cloud.datastore.ListValue.of;
+import static com.google.cloud.datastore.LongValue.of;
+import static com.google.cloud.datastore.NullValue.of;
+import static com.google.cloud.datastore.StringValue.of;
+
import com.google.common.collect.ImmutableSortedMap;
import com.google.common.collect.Maps;
import com.google.protobuf.InvalidProtocolBufferException;
@@ -43,13 +43,14 @@
* A base class for entities (key and properties).
* An entity is a Google Cloud Datastore persistent data object.
* An entity holds one or more properties, represented by a name (as {@link String})
- * and a value (as {@link com.google.gcloud.datastore.Value}), and may be associated with a
+ * and a value (as {@link com.google.cloud.datastore.Value}), and may be associated with a
* key. For a list of possible values see {@link ValueType}.
*
* @see Google Cloud Datastore
* Entities, Properties, and Keys
*/
-public abstract class BaseEntity extends Serializable {
+public abstract class BaseEntity
+ extends Serializable {
private static final long serialVersionUID = 8175618724683792766L;
@@ -91,10 +92,11 @@ private B self() {
}
@SuppressWarnings("unchecked")
- B fill(DatastoreV1.Entity entityPb) {
+ B fill(com.google.datastore.v1beta3.Entity entityPb) {
Map> copiedProperties = Maps.newHashMap();
- for (DatastoreV1.Property property : entityPb.getPropertyList()) {
- copiedProperties.put(property.getName(), Value.fromPb(property.getValue()));
+ for (Map.Entry entry :
+ entityPb.getProperties().entrySet()) {
+ copiedProperties.put(entry.getKey(), Value.fromPb(entry.getValue()));
}
properties(copiedProperties);
if (entityPb.hasKey()) {
@@ -290,6 +292,36 @@ public B set(String name, DateTime first, DateTime second, DateTime... others) {
return self();
}
+ /**
+ * Sets a property of type {@link LatLng}.
+ *
+ * @param name name of the property
+ * @param value value associated with the property
+ */
+ public B set(String name, LatLng value) {
+ properties.put(name, of(value));
+ return self();
+ }
+
+ /**
+ * Sets a list property containing elements of type {@link LatLng}.
+ *
+ * @param name name of the property
+ * @param first the first {@link LatLng} in the list
+ * @param second the second {@link LatLng} in the list
+ * @param others other {@link LatLng}s in the list
+ */
+ public B set(String name, LatLng first, LatLng second, LatLng... others) {
+ List values = new LinkedList<>();
+ values.add(of(first));
+ values.add(of(second));
+ for (LatLng other : others) {
+ values.add(of(other));
+ }
+ properties.put(name, of(values));
+ return self();
+ }
+
/**
* Sets a property of type {@link KeyValue}.
*
@@ -545,6 +577,17 @@ public DateTime getDateTime(String name) {
return ((Value) getValue(name)).get();
}
+ /**
+ * Returns the property value as a LatLng.
+ *
+ * @throws DatastoreException if not such property.
+ * @throws ClassCastException if value is not a LatLng.
+ */
+ @SuppressWarnings("unchecked")
+ public LatLng getLatLng(String name) {
+ return ((Value) getValue(name)).get();
+ }
+
/**
* Returns the property value as a Key.
*
@@ -603,20 +646,19 @@ ImmutableSortedMap> properties() {
@Override
Object fromPb(byte[] bytesPb) throws InvalidProtocolBufferException {
Builder, ?> builder = emptyBuilder();
- builder.fill(DatastoreV1.Entity.parseFrom(bytesPb));
+ builder.fill(com.google.datastore.v1beta3.Entity.parseFrom(bytesPb));
return builder.build();
}
protected abstract Builder, ?> emptyBuilder();
@Override
- final DatastoreV1.Entity toPb() {
- DatastoreV1.Entity.Builder entityPb = DatastoreV1.Entity.newBuilder();
+ final com.google.datastore.v1beta3.Entity toPb() {
+ com.google.datastore.v1beta3.Entity.Builder entityPb =
+ com.google.datastore.v1beta3.Entity.newBuilder();
+ Map propertiesPb = entityPb.getMutableProperties();
for (Map.Entry> entry : properties.entrySet()) {
- DatastoreV1.Property.Builder propertyPb = DatastoreV1.Property.newBuilder();
- propertyPb.setName(entry.getKey());
- propertyPb.setValue(entry.getValue().toPb());
- entityPb.addProperty(propertyPb.build());
+ propertiesPb.put(entry.getKey(), entry.getValue().toPb());
}
if (key != null) {
entityPb.setKey(key.toPb());
diff --git a/gcloud-java-datastore/src/main/java/com/google/gcloud/datastore/BaseKey.java b/gcloud-java-datastore/src/main/java/com/google/cloud/datastore/BaseKey.java
similarity index 82%
rename from gcloud-java-datastore/src/main/java/com/google/gcloud/datastore/BaseKey.java
rename to gcloud-java-datastore/src/main/java/com/google/cloud/datastore/BaseKey.java
index 4ab6f51b6767..73f98562e0e5 100644
--- a/gcloud-java-datastore/src/main/java/com/google/gcloud/datastore/BaseKey.java
+++ b/gcloud-java-datastore/src/main/java/com/google/cloud/datastore/BaseKey.java
@@ -14,13 +14,12 @@
* limitations under the License.
*/
-package com.google.gcloud.datastore;
+package com.google.cloud.datastore;
-import static com.google.gcloud.datastore.Validator.validateDatabase;
-import static com.google.gcloud.datastore.Validator.validateKind;
-import static com.google.gcloud.datastore.Validator.validateNamespace;
+import static com.google.cloud.datastore.Validator.validateDatabase;
+import static com.google.cloud.datastore.Validator.validateKind;
+import static com.google.cloud.datastore.Validator.validateNamespace;
-import com.google.api.services.datastore.DatastoreV1;
import com.google.common.base.Preconditions;
import com.google.common.collect.ImmutableList;
@@ -31,7 +30,7 @@
/**
* Base class for keys.
*/
-public abstract class BaseKey extends Serializable {
+public abstract class BaseKey extends Serializable {
private static final long serialVersionUID = -4671243265877410635L;
@@ -46,8 +45,8 @@ public abstract class BaseKey extends Serializable {
*/
protected abstract static class Builder> {
- String projectId;
- String namespace;
+ String projectId = "";
+ String namespace = "";
String kind;
final List ancestors;
@@ -179,20 +178,15 @@ public boolean equals(Object obj) {
}
@Override
- DatastoreV1.Key toPb() {
- DatastoreV1.Key.Builder keyPb = DatastoreV1.Key.newBuilder();
- DatastoreV1.PartitionId.Builder partitionIdPb = DatastoreV1.PartitionId.newBuilder();
- if (projectId != null) {
- partitionIdPb.setDatasetId(projectId);
- }
- if (namespace != null) {
- partitionIdPb.setNamespace(namespace);
- }
- if (partitionIdPb.hasDatasetId() || partitionIdPb.hasNamespace()) {
- keyPb.setPartitionId(partitionIdPb.build());
- }
+ com.google.datastore.v1beta3.Key toPb() {
+ com.google.datastore.v1beta3.Key.Builder keyPb = com.google.datastore.v1beta3.Key.newBuilder();
+ com.google.datastore.v1beta3.PartitionId.Builder partitionIdPb =
+ com.google.datastore.v1beta3.PartitionId.newBuilder();
+ partitionIdPb.setProjectId(projectId);
+ partitionIdPb.setNamespaceId(namespace);
+ keyPb.setPartitionId(partitionIdPb.build());
for (PathElement pathEntry : path) {
- keyPb.addPathElement(pathEntry.toPb());
+ keyPb.addPath(pathEntry.toPb());
}
return keyPb.build();
}
diff --git a/gcloud-java-datastore/src/main/java/com/google/gcloud/datastore/Batch.java b/gcloud-java-datastore/src/main/java/com/google/cloud/datastore/Batch.java
similarity index 97%
rename from gcloud-java-datastore/src/main/java/com/google/gcloud/datastore/Batch.java
rename to gcloud-java-datastore/src/main/java/com/google/cloud/datastore/Batch.java
index 5306a685195a..dbe6f86c4b99 100644
--- a/gcloud-java-datastore/src/main/java/com/google/gcloud/datastore/Batch.java
+++ b/gcloud-java-datastore/src/main/java/com/google/cloud/datastore/Batch.java
@@ -14,7 +14,7 @@
* limitations under the License.
*/
-package com.google.gcloud.datastore;
+package com.google.cloud.datastore;
import java.util.List;
diff --git a/gcloud-java-datastore/src/main/java/com/google/cloud/datastore/BatchImpl.java b/gcloud-java-datastore/src/main/java/com/google/cloud/datastore/BatchImpl.java
new file mode 100644
index 000000000000..603e9464c9c1
--- /dev/null
+++ b/gcloud-java-datastore/src/main/java/com/google/cloud/datastore/BatchImpl.java
@@ -0,0 +1,72 @@
+/*
+ * Copyright 2015 Google Inc. All Rights Reserved.
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+package com.google.cloud.datastore;
+
+import java.util.ArrayList;
+import java.util.Iterator;
+import java.util.List;
+
+
+class BatchImpl extends BaseDatastoreBatchWriter implements Batch {
+
+ private final DatastoreImpl datastore;
+
+ static class ResponseImpl implements Batch.Response {
+
+ private final com.google.datastore.v1beta3.CommitResponse response;
+ private final int numAutoAllocatedIds;
+
+ ResponseImpl(com.google.datastore.v1beta3.CommitResponse response, int numAutoAllocatedIds) {
+ this.response = response;
+ this.numAutoAllocatedIds = numAutoAllocatedIds;
+ }
+
+ @Override
+ public List generatedKeys() {
+ Iterator results =
+ response.getMutationResultsList().iterator();
+ List generated = new ArrayList<>(numAutoAllocatedIds);
+ for (int i = 0; i < numAutoAllocatedIds; i++) {
+ generated.add(Key.fromPb(results.next().getKey()));
+ }
+ return generated;
+ }
+ }
+
+ BatchImpl(DatastoreImpl datastore) {
+ super("batch");
+ this.datastore = datastore;
+ }
+
+ @Override
+ public Batch.Response submit() {
+ validateActive();
+ List mutationsPb = toMutationPbList();
+ com.google.datastore.v1beta3.CommitRequest.Builder requestPb =
+ com.google.datastore.v1beta3.CommitRequest.newBuilder();
+ requestPb.setMode(com.google.datastore.v1beta3.CommitRequest.Mode.NON_TRANSACTIONAL);
+ requestPb.addAllMutations(mutationsPb);
+ com.google.datastore.v1beta3.CommitResponse responsePb = datastore.commit(requestPb.build());
+ deactivate();
+ return new ResponseImpl(responsePb, toAddAutoId().size());
+ }
+
+ @Override
+ public Datastore datastore() {
+ return datastore;
+ }
+}
diff --git a/gcloud-java-datastore/src/main/java/com/google/gcloud/datastore/Blob.java b/gcloud-java-datastore/src/main/java/com/google/cloud/datastore/Blob.java
similarity index 91%
rename from gcloud-java-datastore/src/main/java/com/google/gcloud/datastore/Blob.java
rename to gcloud-java-datastore/src/main/java/com/google/cloud/datastore/Blob.java
index 42a98e60b5e6..0fd7213d7be3 100644
--- a/gcloud-java-datastore/src/main/java/com/google/gcloud/datastore/Blob.java
+++ b/gcloud-java-datastore/src/main/java/com/google/cloud/datastore/Blob.java
@@ -14,12 +14,10 @@
* limitations under the License.
*/
-package com.google.gcloud.datastore;
+package com.google.cloud.datastore;
import static com.google.common.base.Preconditions.checkNotNull;
-import com.google.api.services.datastore.DatastoreV1;
-import com.google.api.services.datastore.DatastoreV1.Value;
import com.google.common.base.MoreObjects;
import com.google.common.base.MoreObjects.ToStringHelper;
import com.google.protobuf.ByteString;
@@ -38,7 +36,7 @@
* @see
* Google Cloud Datastore Entities, Properties, and Keys
*/
-public final class Blob extends Serializable {
+public final class Blob extends Serializable {
private static final long serialVersionUID = 3835421019618247721L;
@@ -147,12 +145,12 @@ public static Blob copyFrom(InputStream input) throws IOException {
}
@Override
- Value toPb() {
- return DatastoreV1.Value.newBuilder().setBlobValue(byteString).build();
+ com.google.datastore.v1beta3.Value toPb() {
+ return com.google.datastore.v1beta3.Value.newBuilder().setBlobValue(byteString).build();
}
@Override
Object fromPb(byte[] bytesPb) throws InvalidProtocolBufferException {
- return new Blob(DatastoreV1.Value.parseFrom(bytesPb).getBlobValue());
+ return new Blob(com.google.datastore.v1beta3.Value.parseFrom(bytesPb).getBlobValue());
}
}
diff --git a/gcloud-java-datastore/src/main/java/com/google/gcloud/datastore/BlobValue.java b/gcloud-java-datastore/src/main/java/com/google/cloud/datastore/BlobValue.java
similarity index 85%
rename from gcloud-java-datastore/src/main/java/com/google/gcloud/datastore/BlobValue.java
rename to gcloud-java-datastore/src/main/java/com/google/cloud/datastore/BlobValue.java
index fb61c0b9ad34..d65bb6ee8652 100644
--- a/gcloud-java-datastore/src/main/java/com/google/gcloud/datastore/BlobValue.java
+++ b/gcloud-java-datastore/src/main/java/com/google/cloud/datastore/BlobValue.java
@@ -14,11 +14,9 @@
* limitations under the License.
*/
-package com.google.gcloud.datastore;
+package com.google.cloud.datastore;
-import static com.google.api.services.datastore.DatastoreV1.Value.BLOB_VALUE_FIELD_NUMBER;
-
-import com.google.api.services.datastore.DatastoreV1;
+import static com.google.datastore.v1beta3.Value.BLOB_VALUE_FIELD_NUMBER;
public final class BlobValue extends Value {
@@ -40,12 +38,12 @@ public Builder newBuilder(Blob value) {
}
@Override
- protected Blob getValue(DatastoreV1.Value from) {
+ protected Blob getValue(com.google.datastore.v1beta3.Value from) {
return new Blob(from.getBlobValue());
}
@Override
- protected void setValue(BlobValue from, DatastoreV1.Value.Builder to) {
+ protected void setValue(BlobValue from, com.google.datastore.v1beta3.Value.Builder to) {
to.setBlobValue(from.get().byteString());
}
};
diff --git a/gcloud-java-datastore/src/main/java/com/google/gcloud/datastore/BooleanValue.java b/gcloud-java-datastore/src/main/java/com/google/cloud/datastore/BooleanValue.java
similarity index 85%
rename from gcloud-java-datastore/src/main/java/com/google/gcloud/datastore/BooleanValue.java
rename to gcloud-java-datastore/src/main/java/com/google/cloud/datastore/BooleanValue.java
index 2dd98a5013ac..c5d7910b5984 100644
--- a/gcloud-java-datastore/src/main/java/com/google/gcloud/datastore/BooleanValue.java
+++ b/gcloud-java-datastore/src/main/java/com/google/cloud/datastore/BooleanValue.java
@@ -14,11 +14,9 @@
* limitations under the License.
*/
-package com.google.gcloud.datastore;
+package com.google.cloud.datastore;
-import static com.google.api.services.datastore.DatastoreV1.Value.BOOLEAN_VALUE_FIELD_NUMBER;
-
-import com.google.api.services.datastore.DatastoreV1;
+import static com.google.datastore.v1beta3.Value.BOOLEAN_VALUE_FIELD_NUMBER;
public final class BooleanValue extends Value {
@@ -40,12 +38,12 @@ public Builder newBuilder(Boolean value) {
}
@Override
- protected Boolean getValue(DatastoreV1.Value from) {
+ protected Boolean getValue(com.google.datastore.v1beta3.Value from) {
return from.getBooleanValue();
}
@Override
- protected void setValue(BooleanValue from, DatastoreV1.Value.Builder to) {
+ protected void setValue(BooleanValue from, com.google.datastore.v1beta3.Value.Builder to) {
to.setBooleanValue(from.get());
}
};
diff --git a/gcloud-java-datastore/src/main/java/com/google/gcloud/datastore/Cursor.java b/gcloud-java-datastore/src/main/java/com/google/cloud/datastore/Cursor.java
similarity index 86%
rename from gcloud-java-datastore/src/main/java/com/google/gcloud/datastore/Cursor.java
rename to gcloud-java-datastore/src/main/java/com/google/cloud/datastore/Cursor.java
index 5e577f7feb6c..f9d51638b35b 100644
--- a/gcloud-java-datastore/src/main/java/com/google/gcloud/datastore/Cursor.java
+++ b/gcloud-java-datastore/src/main/java/com/google/cloud/datastore/Cursor.java
@@ -14,12 +14,10 @@
* limitations under the License.
*/
-package com.google.gcloud.datastore;
+package com.google.cloud.datastore;
import static com.google.common.base.Preconditions.checkNotNull;
-import com.google.api.services.datastore.DatastoreV1;
-import com.google.api.services.datastore.DatastoreV1.Value;
import com.google.common.base.MoreObjects;
import com.google.common.base.MoreObjects.ToStringHelper;
import com.google.common.io.BaseEncoding;
@@ -30,7 +28,7 @@
* A Google Cloud Datastore cursor.
* The cursor can be used to as a starting point or an ending point for a {@link Query}
*/
-public final class Cursor extends Serializable {
+public final class Cursor extends Serializable {
private static final long serialVersionUID = -1423744878777486541L;
@@ -87,16 +85,16 @@ public static Cursor copyFrom(byte[] bytes) {
}
@Override
- Value toPb() {
- return DatastoreV1.Value.newBuilder().setBlobValue(byteString).build();
+ com.google.datastore.v1beta3.Value toPb() {
+ return com.google.datastore.v1beta3.Value.newBuilder().setBlobValue(byteString).build();
}
@Override
Object fromPb(byte[] bytesPb) throws InvalidProtocolBufferException {
- return fromPb(DatastoreV1.Value.parseFrom(bytesPb));
+ return fromPb(com.google.datastore.v1beta3.Value.parseFrom(bytesPb));
}
- static Cursor fromPb(DatastoreV1.Value valuePb) {
+ static Cursor fromPb(com.google.datastore.v1beta3.Value valuePb) {
return new Cursor(valuePb.getBlobValue());
}
}
diff --git a/gcloud-java-datastore/src/main/java/com/google/gcloud/datastore/Datastore.java b/gcloud-java-datastore/src/main/java/com/google/cloud/datastore/Datastore.java
similarity index 63%
rename from gcloud-java-datastore/src/main/java/com/google/gcloud/datastore/Datastore.java
rename to gcloud-java-datastore/src/main/java/com/google/cloud/datastore/Datastore.java
index 870ed8d9474f..8b2afcb5ad0c 100644
--- a/gcloud-java-datastore/src/main/java/com/google/gcloud/datastore/Datastore.java
+++ b/gcloud-java-datastore/src/main/java/com/google/cloud/datastore/Datastore.java
@@ -14,10 +14,11 @@
* limitations under the License.
*/
-package com.google.gcloud.datastore;
+package com.google.cloud.datastore;
-import com.google.gcloud.Service;
+import com.google.cloud.Service;
+import java.util.Iterator;
import java.util.List;
/**
@@ -30,12 +31,11 @@ public interface Datastore extends Service, DatastoreReaderWri
*
* @throws DatastoreException upon failure
*/
- Transaction newTransaction(TransactionOption... options);
-
+ Transaction newTransaction();
/**
* A callback for running with a transactional
- * {@link com.google.gcloud.datastore.DatastoreReaderWriter}.
+ * {@link com.google.cloud.datastore.DatastoreReaderWriter}.
* The associated transaction will be committed after a successful return from the {@code run}
* method. Any propagated exception will cause the transaction to be rolled-back.
*
@@ -45,7 +45,6 @@ interface TransactionCallable {
T run(DatastoreReaderWriter readerWriter) throws Exception;
}
-
/**
* Invokes the callback's {@link Datastore.TransactionCallable#run} method with a
* {@link DatastoreReaderWriter} that is associated with a new transaction.
@@ -54,15 +53,14 @@ interface TransactionCallable {
* as a {@link DatastoreException} with the original exception as its root cause.
*
* @param callable the callback to call with a newly created transactional readerWriter
- * @param options the options for the created transaction
* @throws DatastoreException upon failure
*/
- T runInTransaction(TransactionCallable callable, TransactionOption... options);
+ T runInTransaction(TransactionCallable callable);
/**
* Returns a new Batch for processing multiple write operations in one request.
*/
- Batch newBatch(BatchOption... options);
+ Batch newBatch();
/**
* Allocate a unique id for the given key.
@@ -106,4 +104,39 @@ interface TransactionCallable {
* Returns a new KeyFactory for this service
*/
KeyFactory newKeyFactory();
+
+ /**
+ * Returns an {@link Entity} for the given {@link Key} or {@code null} if it doesn't exist.
+ * {@link ReadOption}s can be specified if desired.
+ *
+ * @throws DatastoreException upon failure
+ */
+ Entity get(Key key, ReadOption... options);
+
+ /**
+ * Returns an {@link Entity} for each given {@link Key} that exists in the Datastore. The order of
+ * the result is unspecified. Results are loaded lazily, so it is possible to get a
+ * {@code DatastoreException} from the returned {@code Iterator}'s
+ * {@link Iterator#hasNext hasNext} or {@link Iterator#next next} methods. {@link ReadOption}s can
+ * be specified if desired.
+ *
+ * @throws DatastoreException upon failure
+ * @see #get(Key)
+ */
+ Iterator get(Iterable keys, ReadOption... options);
+
+ /**
+ * Returns a list with a value for each given key (ordered by input). {@code null} values are
+ * returned for nonexistent keys. When possible prefer using {@link #get(Key...)} to avoid eagerly
+ * loading the results. {@link ReadOption}s can be specified if desired.
+ */
+ List fetch(Iterable keys, ReadOption... options);
+
+ /**
+ * Submits a {@link Query} and returns its result. {@link ReadOption}s can be specified if
+ * desired.
+ *
+ * @throws DatastoreException upon failure
+ */
+ QueryResults run(Query query, ReadOption... options);
}
diff --git a/gcloud-java-datastore/src/main/java/com/google/gcloud/datastore/DatastoreBatchWriter.java b/gcloud-java-datastore/src/main/java/com/google/cloud/datastore/DatastoreBatchWriter.java
similarity index 98%
rename from gcloud-java-datastore/src/main/java/com/google/gcloud/datastore/DatastoreBatchWriter.java
rename to gcloud-java-datastore/src/main/java/com/google/cloud/datastore/DatastoreBatchWriter.java
index 3a80452349dc..918711aa2822 100644
--- a/gcloud-java-datastore/src/main/java/com/google/gcloud/datastore/DatastoreBatchWriter.java
+++ b/gcloud-java-datastore/src/main/java/com/google/cloud/datastore/DatastoreBatchWriter.java
@@ -14,7 +14,7 @@
* limitations under the License.
*/
-package com.google.gcloud.datastore;
+package com.google.cloud.datastore;
import java.util.List;
diff --git a/gcloud-java-datastore/src/main/java/com/google/gcloud/datastore/DatastoreException.java b/gcloud-java-datastore/src/main/java/com/google/cloud/datastore/DatastoreException.java
similarity index 89%
rename from gcloud-java-datastore/src/main/java/com/google/gcloud/datastore/DatastoreException.java
rename to gcloud-java-datastore/src/main/java/com/google/cloud/datastore/DatastoreException.java
index ecad69ac635b..419cffc7bf3e 100644
--- a/gcloud-java-datastore/src/main/java/com/google/gcloud/datastore/DatastoreException.java
+++ b/gcloud-java-datastore/src/main/java/com/google/cloud/datastore/DatastoreException.java
@@ -14,12 +14,12 @@
* limitations under the License.
*/
-package com.google.gcloud.datastore;
+package com.google.cloud.datastore;
+import com.google.cloud.BaseServiceException;
+import com.google.cloud.RetryHelper.RetryHelperException;
+import com.google.cloud.RetryHelper.RetryInterruptedException;
import com.google.common.collect.ImmutableSet;
-import com.google.gcloud.BaseServiceException;
-import com.google.gcloud.RetryHelper.RetryHelperException;
-import com.google.gcloud.RetryHelper.RetryInterruptedException;
import java.io.IOException;
import java.util.Set;
@@ -34,9 +34,7 @@ public class DatastoreException extends BaseServiceException {
// see https://cloud.google.com/datastore/docs/concepts/errors#Error_Codes"
private static final Set RETRYABLE_ERRORS = ImmutableSet.of(
- new Error(409, "ABORTED"),
- new Error(403, "DEADLINE_EXCEEDED"),
- new Error(503, "UNAVAILABLE"));
+ new Error(10, "ABORTED"), new Error(4, "DEADLINE_EXCEEDED"), new Error(14, "UNAVAILABLE"));
private static final long serialVersionUID = 2663750991205874435L;
public DatastoreException(int code, String message, String reason, Throwable cause) {
diff --git a/gcloud-java-datastore/src/main/java/com/google/gcloud/datastore/DatastoreFactory.java b/gcloud-java-datastore/src/main/java/com/google/cloud/datastore/DatastoreFactory.java
similarity index 90%
rename from gcloud-java-datastore/src/main/java/com/google/gcloud/datastore/DatastoreFactory.java
rename to gcloud-java-datastore/src/main/java/com/google/cloud/datastore/DatastoreFactory.java
index b1f5a026a3e5..1a1b49cf71b3 100644
--- a/gcloud-java-datastore/src/main/java/com/google/gcloud/datastore/DatastoreFactory.java
+++ b/gcloud-java-datastore/src/main/java/com/google/cloud/datastore/DatastoreFactory.java
@@ -14,10 +14,10 @@
* limitations under the License.
*/
-package com.google.gcloud.datastore;
+package com.google.cloud.datastore;
-import com.google.gcloud.ServiceFactory;
+import com.google.cloud.ServiceFactory;
/**
* An interface for Datastore factories.
diff --git a/gcloud-java-datastore/src/main/java/com/google/gcloud/datastore/DatastoreHelper.java b/gcloud-java-datastore/src/main/java/com/google/cloud/datastore/DatastoreHelper.java
similarity index 64%
rename from gcloud-java-datastore/src/main/java/com/google/gcloud/datastore/DatastoreHelper.java
rename to gcloud-java-datastore/src/main/java/com/google/cloud/datastore/DatastoreHelper.java
index a74d06642740..04b3e96c5175 100644
--- a/gcloud-java-datastore/src/main/java/com/google/gcloud/datastore/DatastoreHelper.java
+++ b/gcloud-java-datastore/src/main/java/com/google/cloud/datastore/DatastoreHelper.java
@@ -14,12 +14,14 @@
* limitations under the License.
*/
-package com.google.gcloud.datastore;
+package com.google.cloud.datastore;
import com.google.common.collect.Iterators;
import com.google.common.collect.Maps;
import java.util.ArrayList;
+import java.util.Arrays;
+import java.util.Collections;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
@@ -33,13 +35,16 @@ class DatastoreHelper {
private DatastoreHelper() {
}
-
static Key allocateId(Datastore service, IncompleteKey key) {
return service.allocateId(new IncompleteKey[]{key}).get(0);
}
- static Entity get(DatastoreReader reader, Key key) {
- return Iterators.getNext(reader.get(new Key[]{key}), null);
+ static Entity get(Transaction reader, Key key) {
+ return Iterators.getNext(reader.get(new Key[] {key}), null);
+ }
+
+ static Entity get(Datastore reader, Key key, ReadOption... options) {
+ return Iterators.getNext(reader.get(Collections.singletonList(key), options), null);
}
static Entity add(DatastoreWriter writer, FullEntity> entity) {
@@ -51,11 +56,22 @@ static KeyFactory newKeyFactory(DatastoreOptions options) {
}
/**
- * Returns a list with a value for each given key (ordered by input).
- * A {@code null} would be returned for non-existing keys.
+ * Returns a list with a value for each given key (ordered by input). {@code null} values are
+ * returned for nonexistent keys.
*/
- static List fetch(DatastoreReader reader, Key... keys) {
- Iterator entities = reader.get(keys);
+ static List fetch(Transaction reader, Key... keys) {
+ return compileEntities(keys, reader.get(keys));
+ }
+
+ /**
+ * Returns a list with a value for each given key (ordered by input). {@code null} values are
+ * returned for nonexistent keys.
+ */
+ static List fetch(Datastore reader, Key[] keys, ReadOption... options) {
+ return compileEntities(keys, reader.get(Arrays.asList(keys), options));
+ }
+
+ private static List compileEntities(Key[] keys, Iterator entities) {
Map map = Maps.newHashMapWithExpectedSize(keys.length);
while (entities.hasNext()) {
Entity entity = entities.next();
@@ -63,15 +79,14 @@ static List fetch(DatastoreReader reader, Key... keys) {
}
List list = new ArrayList<>(keys.length);
for (Key key : keys) {
- // this will include nulls for non-existing keys
+ // this will include nulls for nonexistent keys
list.add(map.get(key));
}
return list;
}
- static T runInTransaction(Datastore datastore,
- Datastore.TransactionCallable callable, TransactionOption... options) {
- Transaction transaction = datastore.newTransaction(options);
+ static T runInTransaction(Datastore datastore, Datastore.TransactionCallable callable) {
+ Transaction transaction = datastore.newTransaction();
try {
T value = callable.run(transaction);
transaction.commit();
diff --git a/gcloud-java-datastore/src/main/java/com/google/cloud/datastore/DatastoreImpl.java b/gcloud-java-datastore/src/main/java/com/google/cloud/datastore/DatastoreImpl.java
new file mode 100644
index 000000000000..2aa0638bfa7c
--- /dev/null
+++ b/gcloud-java-datastore/src/main/java/com/google/cloud/datastore/DatastoreImpl.java
@@ -0,0 +1,416 @@
+/*
+ * Copyright 2015 Google Inc. All Rights Reserved.
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+package com.google.cloud.datastore;
+
+import com.google.cloud.BaseService;
+import com.google.cloud.RetryHelper;
+import com.google.cloud.RetryHelper.RetryHelperException;
+import com.google.cloud.RetryParams;
+import com.google.cloud.datastore.ReadOption.EventualConsistency;
+import com.google.cloud.datastore.spi.DatastoreRpc;
+import com.google.common.base.MoreObjects;
+import com.google.common.base.Preconditions;
+import com.google.common.collect.AbstractIterator;
+import com.google.common.collect.ImmutableList;
+import com.google.common.collect.Iterables;
+import com.google.common.collect.Sets;
+import com.google.datastore.v1beta3.ReadOptions.ReadConsistency;
+import com.google.protobuf.ByteString;
+
+import java.util.ArrayList;
+import java.util.Arrays;
+import java.util.Collections;
+import java.util.Iterator;
+import java.util.LinkedHashMap;
+import java.util.LinkedHashSet;
+import java.util.List;
+import java.util.Map;
+import java.util.Set;
+import java.util.concurrent.Callable;
+
+final class DatastoreImpl extends BaseService implements Datastore {
+
+ private final DatastoreRpc datastoreRpc;
+ private final RetryParams retryParams;
+
+ DatastoreImpl(DatastoreOptions options) {
+ super(options);
+ this.datastoreRpc = options.rpc();
+ retryParams = MoreObjects.firstNonNull(options.retryParams(), RetryParams.noRetries());
+ }
+
+ @Override
+ public Batch newBatch() {
+ return new BatchImpl(this);
+ }
+
+ @Override
+ public Transaction newTransaction() {
+ return new TransactionImpl(this);
+ }
+
+ @Override
+ public T runInTransaction(TransactionCallable callable) {
+ return DatastoreHelper.runInTransaction(this, callable);
+ }
+
+ @Override
+ public QueryResults run(Query query) {
+ return run(null, query);
+ }
+
+ @Override
+ public QueryResults run(Query query, ReadOption... options) {
+ return run(toReadOptionsPb(options), query);
+ }
+
+ QueryResults run(com.google.datastore.v1beta3.ReadOptions readOptionsPb, Query query) {
+ return new QueryResultsImpl<>(this, readOptionsPb, query);
+ }
+
+ com.google.datastore.v1beta3.RunQueryResponse runQuery(
+ final com.google.datastore.v1beta3.RunQueryRequest requestPb) {
+ try {
+ return RetryHelper.runWithRetries(
+ new Callable() {
+ @Override public com.google.datastore.v1beta3.RunQueryResponse call()
+ throws DatastoreException {
+ return datastoreRpc.runQuery(requestPb);
+ }
+ }, retryParams, EXCEPTION_HANDLER);
+ } catch (RetryHelperException e) {
+ throw DatastoreException.translateAndThrow(e);
+ }
+ }
+
+ @Override
+ public Key allocateId(IncompleteKey key) {
+ return DatastoreHelper.allocateId(this, key);
+ }
+
+ @Override
+ public List allocateId(IncompleteKey... keys) {
+ if (keys.length == 0) {
+ return Collections.emptyList();
+ }
+ com.google.datastore.v1beta3.AllocateIdsRequest.Builder requestPb =
+ com.google.datastore.v1beta3.AllocateIdsRequest.newBuilder();
+ for (IncompleteKey key : keys) {
+ requestPb.addKeys(trimNameOrId(key).toPb());
+ }
+ com.google.datastore.v1beta3.AllocateIdsResponse responsePb = allocateIds(requestPb.build());
+ ImmutableList.Builder keyList = ImmutableList.builder();
+ for (com.google.datastore.v1beta3.Key keyPb : responsePb.getKeysList()) {
+ keyList.add(Key.fromPb(keyPb));
+ }
+ return keyList.build();
+ }
+
+ com.google.datastore.v1beta3.AllocateIdsResponse allocateIds(
+ final com.google.datastore.v1beta3.AllocateIdsRequest requestPb) {
+ try {
+ return RetryHelper.runWithRetries(
+ new Callable() {
+ @Override public com.google.datastore.v1beta3.AllocateIdsResponse call()
+ throws DatastoreException {
+ return datastoreRpc.allocateIds(requestPb);
+ }
+ }, retryParams, EXCEPTION_HANDLER);
+ } catch (RetryHelperException e) {
+ throw DatastoreException.translateAndThrow(e);
+ }
+ }
+
+ private IncompleteKey trimNameOrId(IncompleteKey key) {
+ if (key instanceof Key) {
+ return IncompleteKey.builder(key).build();
+ }
+ return key;
+ }
+
+ @Override
+ public Entity add(FullEntity> entity) {
+ return DatastoreHelper.add(this, entity);
+ }
+
+ @SuppressWarnings("unchecked")
+ @Override
+ public List add(FullEntity>... entities) {
+ if (entities.length == 0) {
+ return Collections.emptyList();
+ }
+ List mutationsPb = new ArrayList<>();
+ Map completeEntities = new LinkedHashMap<>();
+ for (FullEntity> entity : entities) {
+ Entity completeEntity = null;
+ if (entity.key() instanceof Key) {
+ completeEntity = Entity.convert((FullEntity) entity);
+ }
+ if (completeEntity != null) {
+ if (completeEntities.put(completeEntity.key(), completeEntity) != null) {
+ throw DatastoreException.throwInvalidRequest(
+ "Duplicate entity with the key %s", entity.key());
+ }
+ } else {
+ Preconditions.checkArgument(entity.hasKey(), "entity %s is missing a key", entity);
+ }
+ mutationsPb.add(com.google.datastore.v1beta3.Mutation.newBuilder()
+ .setInsert(entity.toPb()).build());
+ }
+ com.google.datastore.v1beta3.CommitResponse commitResponse = commitMutation(mutationsPb);
+ Iterator mutationResults =
+ commitResponse.getMutationResultsList().iterator();
+ ImmutableList.Builder responseBuilder = ImmutableList.builder();
+ for (FullEntity> entity : entities) {
+ Entity completeEntity = completeEntities.get(entity.key());
+ if (completeEntity != null) {
+ responseBuilder.add(completeEntity);
+ mutationResults.next();
+ } else {
+ responseBuilder.add(
+ Entity.builder(Key.fromPb(mutationResults.next().getKey()), entity).build());
+ }
+ }
+ return responseBuilder.build();
+ }
+
+ @Override
+ public Entity get(Key key) {
+ return DatastoreHelper.get(this, key);
+ }
+
+ @Override
+ public Entity get(Key key, ReadOption... options) {
+ return DatastoreHelper.get(this, key, options);
+ }
+
+ @Override
+ public Iterator get(Key... keys) {
+ return get(null, keys);
+ }
+
+ @Override
+ public Iterator get(Iterable keys, ReadOption... options) {
+ return get(toReadOptionsPb(options), Iterables.toArray(keys, Key.class));
+ }
+
+ private static com.google.datastore.v1beta3.ReadOptions toReadOptionsPb(ReadOption... options) {
+ com.google.datastore.v1beta3.ReadOptions readOptionsPb = null;
+ if (options != null
+ && ReadOption.asImmutableMap(options).containsKey(EventualConsistency.class)) {
+ readOptionsPb = com.google.datastore.v1beta3.ReadOptions.newBuilder()
+ .setReadConsistency(ReadConsistency.EVENTUAL)
+ .build();
+ }
+ return readOptionsPb;
+ }
+
+ @Override
+ public List fetch(Key... keys) {
+ return DatastoreHelper.fetch(this, keys);
+ }
+
+ @Override
+ public List fetch(Iterable keys, ReadOption... options) {
+ return DatastoreHelper.fetch(this, Iterables.toArray(keys, Key.class), options);
+ }
+
+ Iterator get(com.google.datastore.v1beta3.ReadOptions readOptionsPb, final Key... keys) {
+ if (keys.length == 0) {
+ return Collections.emptyIterator();
+ }
+ com.google.datastore.v1beta3.LookupRequest.Builder requestPb =
+ com.google.datastore.v1beta3.LookupRequest.newBuilder();
+ if (readOptionsPb != null) {
+ requestPb.setReadOptions(readOptionsPb);
+ }
+ for (Key k : Sets.newLinkedHashSet(Arrays.asList(keys))) {
+ requestPb.addKeys(k.toPb());
+ }
+ return new ResultsIterator(requestPb);
+ }
+
+ final class ResultsIterator extends AbstractIterator {
+
+ private final com.google.datastore.v1beta3.LookupRequest.Builder requestPb;
+ Iterator iter;
+
+ ResultsIterator(com.google.datastore.v1beta3.LookupRequest.Builder requestPb) {
+ this.requestPb = requestPb;
+ loadResults();
+ }
+
+ private void loadResults() {
+ com.google.datastore.v1beta3.LookupResponse responsePb = lookup(requestPb.build());
+ iter = responsePb.getFoundList().iterator();
+ requestPb.clearKeys();
+ if (responsePb.getDeferredCount() > 0) {
+ requestPb.addAllKeys(responsePb.getDeferredList());
+ }
+ }
+
+ @SuppressWarnings("unchecked")
+ @Override
+ protected Entity computeNext() {
+ while (!iter.hasNext()) {
+ if (requestPb.getKeysCount() == 0) {
+ return endOfData();
+ }
+ loadResults();
+ }
+ return Entity.fromPb(iter.next().getEntity());
+ }
+ }
+
+ com.google.datastore.v1beta3.LookupResponse lookup(
+ final com.google.datastore.v1beta3.LookupRequest requestPb) {
+ try {
+ return RetryHelper.runWithRetries(
+ new Callable() {
+ @Override public com.google.datastore.v1beta3.LookupResponse call()
+ throws DatastoreException {
+ return datastoreRpc.lookup(requestPb);
+ }
+ }, retryParams, EXCEPTION_HANDLER);
+ } catch (RetryHelperException e) {
+ throw DatastoreException.translateAndThrow(e);
+ }
+ }
+
+ @SafeVarargs
+ @Override
+ public final void update(Entity... entities) {
+ if (entities.length > 0) {
+ List mutationsPb =
+ new ArrayList<>();
+ Map dedupEntities = new LinkedHashMap<>();
+ for (Entity entity : entities) {
+ dedupEntities.put(entity.key(), entity);
+ }
+ for (Entity entity : dedupEntities.values()) {
+ mutationsPb.add(
+ com.google.datastore.v1beta3.Mutation.newBuilder().setUpdate(entity.toPb()).build());
+ }
+ commitMutation(mutationsPb);
+ }
+ }
+
+ @SafeVarargs
+ @Override
+ public final void put(Entity... entities) {
+ if (entities.length > 0) {
+ List mutationsPb =
+ new ArrayList<>();
+ Map dedupEntities = new LinkedHashMap<>();
+ for (Entity entity : entities) {
+ dedupEntities.put(entity.key(), entity);
+ }
+ for (Entity e : dedupEntities.values()) {
+ mutationsPb.add(
+ com.google.datastore.v1beta3.Mutation.newBuilder().setUpsert(e.toPb()).build());
+ }
+ commitMutation(mutationsPb);
+ }
+ }
+
+ @Override
+ public void delete(Key... keys) {
+ if (keys.length > 0) {
+ List mutationsPb = new ArrayList<>();
+ Set dedupKeys = new LinkedHashSet<>(Arrays.asList(keys));
+ for (Key key : dedupKeys) {
+ mutationsPb.add(
+ com.google.datastore.v1beta3.Mutation.newBuilder().setDelete(key.toPb()).build());
+ }
+ commitMutation(mutationsPb);
+ }
+ }
+
+ @Override
+ public KeyFactory newKeyFactory() {
+ return DatastoreHelper.newKeyFactory(options());
+ }
+
+ private com.google.datastore.v1beta3.CommitResponse commitMutation(
+ List mutationsPb) {
+ com.google.datastore.v1beta3.CommitRequest.Builder requestPb =
+ com.google.datastore.v1beta3.CommitRequest.newBuilder();
+ requestPb.setMode(com.google.datastore.v1beta3.CommitRequest.Mode.NON_TRANSACTIONAL);
+ requestPb.addAllMutations(mutationsPb);
+ return commit(requestPb.build());
+ }
+
+ com.google.datastore.v1beta3.CommitResponse commit(
+ final com.google.datastore.v1beta3.CommitRequest requestPb) {
+ try {
+ return RetryHelper.runWithRetries(
+ new Callable() {
+ @Override
+ public com.google.datastore.v1beta3.CommitResponse call() throws DatastoreException {
+ return datastoreRpc.commit(requestPb);
+ }
+ },
+ retryParams,
+ EXCEPTION_HANDLER);
+ } catch (RetryHelperException e) {
+ throw DatastoreException.translateAndThrow(e);
+ }
+ }
+
+ ByteString requestTransactionId(
+ com.google.datastore.v1beta3.BeginTransactionRequest.Builder requestPb) {
+ return beginTransaction(requestPb.build()).getTransaction();
+ }
+
+ com.google.datastore.v1beta3.BeginTransactionResponse beginTransaction(
+ final com.google.datastore.v1beta3.BeginTransactionRequest requestPb) {
+ try {
+ return RetryHelper.runWithRetries(
+ new Callable() {
+ @Override
+ public com.google.datastore.v1beta3.BeginTransactionResponse call()
+ throws DatastoreException {
+ return datastoreRpc.beginTransaction(requestPb);
+ }
+ },
+ retryParams,
+ EXCEPTION_HANDLER);
+ } catch (RetryHelperException e) {
+ throw DatastoreException.translateAndThrow(e);
+ }
+ }
+
+ void rollbackTransaction(ByteString transaction) {
+ com.google.datastore.v1beta3.RollbackRequest.Builder requestPb =
+ com.google.datastore.v1beta3.RollbackRequest.newBuilder();
+ requestPb.setTransaction(transaction);
+ rollback(requestPb.build());
+ }
+
+ void rollback(final com.google.datastore.v1beta3.RollbackRequest requestPb) {
+ try {
+ RetryHelper.runWithRetries(new Callable() {
+ @Override public Void call() throws DatastoreException {
+ datastoreRpc.rollback(requestPb);
+ return null;
+ }
+ }, retryParams, EXCEPTION_HANDLER);
+ } catch (RetryHelperException e) {
+ throw DatastoreException.translateAndThrow(e);
+ }
+ }
+}
diff --git a/gcloud-java-datastore/src/main/java/com/google/gcloud/datastore/DatastoreOptions.java b/gcloud-java-datastore/src/main/java/com/google/cloud/datastore/DatastoreOptions.java
similarity index 53%
rename from gcloud-java-datastore/src/main/java/com/google/gcloud/datastore/DatastoreOptions.java
rename to gcloud-java-datastore/src/main/java/com/google/cloud/datastore/DatastoreOptions.java
index db1a5f800ce8..d456af51bde1 100644
--- a/gcloud-java-datastore/src/main/java/com/google/gcloud/datastore/DatastoreOptions.java
+++ b/gcloud-java-datastore/src/main/java/com/google/cloud/datastore/DatastoreOptions.java
@@ -14,37 +14,28 @@
* limitations under the License.
*/
-package com.google.gcloud.datastore;
+package com.google.cloud.datastore;
-import static com.google.gcloud.datastore.Validator.validateNamespace;
+import static com.google.cloud.datastore.Validator.validateNamespace;
-import com.google.api.services.datastore.DatastoreV1;
-import com.google.api.services.datastore.DatastoreV1.EntityResult;
-import com.google.api.services.datastore.DatastoreV1.LookupResponse;
+import com.google.cloud.ServiceOptions;
+import com.google.cloud.datastore.spi.DatastoreRpc;
+import com.google.cloud.datastore.spi.DatastoreRpcFactory;
+import com.google.cloud.datastore.spi.DefaultDatastoreRpc;
+import com.google.common.base.MoreObjects;
import com.google.common.collect.ImmutableSet;
-import com.google.common.collect.Iterables;
-import com.google.gcloud.ServiceOptions;
-import com.google.gcloud.datastore.spi.DatastoreRpc;
-import com.google.gcloud.datastore.spi.DatastoreRpcFactory;
-import com.google.gcloud.datastore.spi.DefaultDatastoreRpc;
import java.lang.reflect.Method;
-import java.util.Iterator;
import java.util.Objects;
import java.util.Set;
public class DatastoreOptions extends ServiceOptions {
private static final long serialVersionUID = 5056049000758143852L;
- private static final String DATASET_ENV_NAME = "DATASTORE_DATASET";
- private static final String HOST_ENV_NAME = "DATASTORE_HOST";
private static final String DATASTORE_SCOPE = "https://www.googleapis.com/auth/datastore";
- private static final String USERINFO_SCOPE = "https://www.googleapis.com/auth/userinfo.email";
- private static final Set SCOPES = ImmutableSet.of(DATASTORE_SCOPE, USERINFO_SCOPE);
+ private static final Set SCOPES = ImmutableSet.of(DATASTORE_SCOPE);
private final String namespace;
- private final boolean force;
- private final boolean normalizeDataset;
public static class DefaultDatastoreFactory implements DatastoreFactory {
@@ -70,95 +61,52 @@ public static class Builder extends
ServiceOptions.Builder {
private String namespace;
- private boolean force;
- private boolean normalizeDataset = true;
private Builder() {
}
private Builder(DatastoreOptions options) {
super(options);
- force = options.force;
namespace = options.namespace;
- normalizeDataset = options.normalizeDataset;
}
@Override
public DatastoreOptions build() {
- DatastoreOptions options = new DatastoreOptions(this);
- return normalizeDataset ? options.normalize() : options;
+ return new DatastoreOptions(this);
}
public Builder namespace(String namespace) {
this.namespace = validateNamespace(namespace);
return this;
}
-
- public Builder force(boolean force) {
- this.force = force;
- return this;
- }
-
- Builder normalizeDataset(boolean normalizeDataset) {
- this.normalizeDataset = normalizeDataset;
- return this;
- }
}
private DatastoreOptions(Builder builder) {
super(DatastoreFactory.class, DatastoreRpcFactory.class, builder);
- normalizeDataset = builder.normalizeDataset;
namespace = builder.namespace != null ? builder.namespace : defaultNamespace();
- force = builder.force;
- }
-
- private DatastoreOptions normalize() {
- if (!normalizeDataset) {
- return this;
- }
-
- Builder builder = toBuilder();
- builder.normalizeDataset(false);
- // Replace provided project-id with full project-id (s~xxx, e~xxx,...)
- DatastoreV1.LookupRequest.Builder requestPb = DatastoreV1.LookupRequest.newBuilder();
- DatastoreV1.Key key = DatastoreV1.Key.newBuilder()
- .addPathElement(DatastoreV1.Key.PathElement.newBuilder().setKind("__foo__").setName("bar"))
- .build();
- requestPb.addKey(key);
- LookupResponse responsePb = rpc().lookup(requestPb.build());
- if (responsePb.getDeferredCount() > 0) {
- key = responsePb.getDeferred(0);
- } else {
- Iterator combinedIter =
- Iterables.concat(responsePb.getMissingList(), responsePb.getFoundList()).iterator();
- key = combinedIter.next().getEntity().getKey();
- }
- builder.projectId(key.getPartitionId().getDatasetId());
- return new DatastoreOptions(builder);
}
@Override
protected String defaultHost() {
- String host = System.getProperty(HOST_ENV_NAME, System.getenv(HOST_ENV_NAME));
- return host != null ? host : super.defaultHost();
+ String host = System.getProperty(
+ com.google.datastore.v1beta3.client.DatastoreHelper.LOCAL_HOST_ENV_VAR,
+ System.getenv(com.google.datastore.v1beta3.client.DatastoreHelper.LOCAL_HOST_ENV_VAR));
+ return host != null ? host : com.google.datastore.v1beta3.client.DatastoreFactory.DEFAULT_HOST;
}
@Override
protected String defaultProject() {
- String projectId = System.getProperty(DATASET_ENV_NAME, System.getenv(DATASET_ENV_NAME));
- if (projectId == null) {
- projectId = appEngineAppId();
- }
+ String projectId = System.getProperty(
+ com.google.datastore.v1beta3.client.DatastoreHelper.PROJECT_ID_ENV_VAR,
+ System.getenv(com.google.datastore.v1beta3.client.DatastoreHelper.PROJECT_ID_ENV_VAR));
return projectId != null ? projectId : super.defaultProject();
}
- @SuppressWarnings("unchecked")
@Override
protected DatastoreFactory defaultServiceFactory() {
return DefaultDatastoreFactory.INSTANCE;
}
- @SuppressWarnings("unchecked")
@Override
protected DatastoreRpcFactory defaultRpcFactory() {
return DefaultDatastoreRpcFactory.INSTANCE;
@@ -180,17 +128,13 @@ private static String defaultNamespace() {
Class> clazz = Class.forName("com.google.appengine.api.NamespaceManager");
Method method = clazz.getMethod("get");
String namespace = (String) method.invoke(null);
- return namespace == null || namespace.isEmpty() ? null : namespace;
+ return MoreObjects.firstNonNull(namespace, "");
} catch (Exception ignore) {
- // return null (Datastore default namespace) if could not automatically determine
- return null;
+ // return empty string (Datastore default namespace) if could not automatically determine
+ return "";
}
}
- public boolean force() {
- return force;
- }
-
@Override
protected Set scopes() {
return SCOPES;
@@ -204,7 +148,7 @@ public Builder toBuilder() {
@Override
public int hashCode() {
- return baseHashCode() ^ Objects.hash(namespace, force, normalizeDataset);
+ return Objects.hash(baseHashCode(), namespace);
}
@Override
@@ -213,9 +157,7 @@ public boolean equals(Object obj) {
return false;
}
DatastoreOptions other = (DatastoreOptions) obj;
- return baseEquals(other) && Objects.equals(namespace, other.namespace)
- && Objects.equals(force, other.force)
- && Objects.equals(normalizeDataset, other.normalizeDataset);
+ return baseEquals(other) && Objects.equals(namespace, other.namespace);
}
public static Builder builder() {
diff --git a/gcloud-java-datastore/src/main/java/com/google/gcloud/datastore/DatastoreReader.java b/gcloud-java-datastore/src/main/java/com/google/cloud/datastore/DatastoreReader.java
similarity index 70%
rename from gcloud-java-datastore/src/main/java/com/google/gcloud/datastore/DatastoreReader.java
rename to gcloud-java-datastore/src/main/java/com/google/cloud/datastore/DatastoreReader.java
index 4852dd53e16c..e3989f29ef8b 100644
--- a/gcloud-java-datastore/src/main/java/com/google/gcloud/datastore/DatastoreReader.java
+++ b/gcloud-java-datastore/src/main/java/com/google/cloud/datastore/DatastoreReader.java
@@ -14,7 +14,7 @@
* limitations under the License.
*/
-package com.google.gcloud.datastore;
+package com.google.cloud.datastore;
import java.util.Iterator;
import java.util.List;
@@ -25,18 +25,17 @@
public interface DatastoreReader {
/**
- * Returns an {@link Entity} for the given {@link Key} or {@code null} if does not exists.
+ * Returns an {@link Entity} for the given {@link Key} or {@code null} if it doesn't exist.
*
* @throws DatastoreException upon failure
*/
Entity get(Key key);
/**
- * Returns an {@link Entity} for each given {@link Key} that exists in the Datastore.
- * The order of the result is unspecified.
- * Results are loaded lazily therefore it is possible to get a {@code DatastoreException}
- * from the returned {@code Iterator}'s {@link Iterator#hasNext hasNext} or
- * {@link Iterator#next next} methods.
+ * Returns an {@link Entity} for each given {@link Key} that exists in the Datastore. The order of
+ * the result is unspecified. Results are loaded lazily, so it is possible to get a
+ * {@code DatastoreException} from the returned {@code Iterator}'s
+ * {@link Iterator#hasNext hasNext} or {@link Iterator#next next} methods.
*
* @throws DatastoreException upon failure
* @see #get(Key)
@@ -44,14 +43,14 @@ public interface DatastoreReader {
Iterator get(Key... key);
/**
- * Returns a list with a value for each given key (ordered by input).
- * A {@code null} would be returned for non-existing keys.
- * When possible prefer using {@link #get(Key...)} which does not eagerly loads the results.
+ * Returns a list with a value for each given key (ordered by input). {@code null} values are
+ * returned for nonexistent keys. When possible prefer using {@link #get(Key...)} to avoid eagerly
+ * loading the results.
*/
List fetch(Key... keys);
/**
- * Submit a {@link Query} and returns its result.
+ * Submits a {@link Query} and returns its result.
*
* @throws DatastoreException upon failure
*/
diff --git a/gcloud-java-datastore/src/main/java/com/google/gcloud/datastore/DatastoreReaderWriter.java b/gcloud-java-datastore/src/main/java/com/google/cloud/datastore/DatastoreReaderWriter.java
similarity index 95%
rename from gcloud-java-datastore/src/main/java/com/google/gcloud/datastore/DatastoreReaderWriter.java
rename to gcloud-java-datastore/src/main/java/com/google/cloud/datastore/DatastoreReaderWriter.java
index c64f86a8d0a3..16b6af881929 100644
--- a/gcloud-java-datastore/src/main/java/com/google/gcloud/datastore/DatastoreReaderWriter.java
+++ b/gcloud-java-datastore/src/main/java/com/google/cloud/datastore/DatastoreReaderWriter.java
@@ -14,7 +14,7 @@
* limitations under the License.
*/
-package com.google.gcloud.datastore;
+package com.google.cloud.datastore;
/**
diff --git a/gcloud-java-datastore/src/main/java/com/google/gcloud/datastore/DatastoreWriter.java b/gcloud-java-datastore/src/main/java/com/google/cloud/datastore/DatastoreWriter.java
similarity index 98%
rename from gcloud-java-datastore/src/main/java/com/google/gcloud/datastore/DatastoreWriter.java
rename to gcloud-java-datastore/src/main/java/com/google/cloud/datastore/DatastoreWriter.java
index 66ba98aed9e9..2771bb39ea60 100644
--- a/gcloud-java-datastore/src/main/java/com/google/gcloud/datastore/DatastoreWriter.java
+++ b/gcloud-java-datastore/src/main/java/com/google/cloud/datastore/DatastoreWriter.java
@@ -14,7 +14,7 @@
* limitations under the License.
*/
-package com.google.gcloud.datastore;
+package com.google.cloud.datastore;
import java.util.List;
diff --git a/gcloud-java-datastore/src/main/java/com/google/gcloud/datastore/DateTime.java b/gcloud-java-datastore/src/main/java/com/google/cloud/datastore/DateTime.java
similarity index 76%
rename from gcloud-java-datastore/src/main/java/com/google/gcloud/datastore/DateTime.java
rename to gcloud-java-datastore/src/main/java/com/google/cloud/datastore/DateTime.java
index d22edd9697e4..fd72edc9806f 100644
--- a/gcloud-java-datastore/src/main/java/com/google/gcloud/datastore/DateTime.java
+++ b/gcloud-java-datastore/src/main/java/com/google/cloud/datastore/DateTime.java
@@ -14,12 +14,10 @@
* limitations under the License.
*/
-package com.google.gcloud.datastore;
+package com.google.cloud.datastore;
import static com.google.common.base.Preconditions.checkNotNull;
-import com.google.api.services.datastore.DatastoreV1;
-import com.google.api.services.datastore.DatastoreV1.Value;
import com.google.protobuf.InvalidProtocolBufferException;
import org.joda.time.format.ISODateTimeFormat;
@@ -34,7 +32,7 @@
* @see Google Cloud Datastore
* Entities, Properties, and Keys
*/
-public final class DateTime extends Serializable
+public final class DateTime extends Serializable
implements Comparable {
private static final long serialVersionUID = 7343324797621228378L;
@@ -98,12 +96,23 @@ public static DateTime copyFrom(Calendar calendar) {
}
@Override
- Value toPb() {
- return DatastoreV1.Value.newBuilder().setIntegerValue(timestampMicroseconds).build();
+ com.google.protobuf.Timestamp toPb() {
+ return microsecondsToTimestampPb(timestampMicroseconds);
}
@Override
Object fromPb(byte[] bytesPb) throws InvalidProtocolBufferException {
- return new DateTime(DatastoreV1.Value.parseFrom(bytesPb).getIntegerValue());
+ return new DateTime(timestampPbToMicroseconds(
+ com.google.protobuf.Timestamp.parseFrom(bytesPb)));
+ }
+
+ static long timestampPbToMicroseconds(com.google.protobuf.Timestamp timestampPb) {
+ return timestampPb.getSeconds() * 1000000 + timestampPb.getNanos() / 1000;
+ }
+
+ static com.google.protobuf.Timestamp microsecondsToTimestampPb(long microseconds) {
+ long seconds = microseconds / 1000000;
+ int nanos = (int) (microseconds % 1000000) * 1000;
+ return com.google.protobuf.Timestamp.newBuilder().setSeconds(seconds).setNanos(nanos).build();
}
}
diff --git a/gcloud-java-datastore/src/main/java/com/google/gcloud/datastore/DateTimeValue.java b/gcloud-java-datastore/src/main/java/com/google/cloud/datastore/DateTimeValue.java
similarity index 77%
rename from gcloud-java-datastore/src/main/java/com/google/gcloud/datastore/DateTimeValue.java
rename to gcloud-java-datastore/src/main/java/com/google/cloud/datastore/DateTimeValue.java
index 7aec5c7d3c47..8ffa98ea5e74 100644
--- a/gcloud-java-datastore/src/main/java/com/google/gcloud/datastore/DateTimeValue.java
+++ b/gcloud-java-datastore/src/main/java/com/google/cloud/datastore/DateTimeValue.java
@@ -14,11 +14,9 @@
* limitations under the License.
*/
-package com.google.gcloud.datastore;
+package com.google.cloud.datastore;
-import static com.google.api.services.datastore.DatastoreV1.Value.TIMESTAMP_MICROSECONDS_VALUE_FIELD_NUMBER;
-
-import com.google.api.services.datastore.DatastoreV1;
+import static com.google.datastore.v1beta3.Value.TIMESTAMP_VALUE_FIELD_NUMBER;
public final class DateTimeValue extends Value {
@@ -31,7 +29,7 @@ public final class DateTimeValue extends Value {
@Override
public int getProtoFieldId() {
- return TIMESTAMP_MICROSECONDS_VALUE_FIELD_NUMBER;
+ return TIMESTAMP_VALUE_FIELD_NUMBER;
}
@Override
@@ -40,13 +38,14 @@ public Builder newBuilder(DateTime value) {
}
@Override
- protected DateTime getValue(DatastoreV1.Value from) {
- return new DateTime(from.getTimestampMicrosecondsValue());
+ protected DateTime getValue(com.google.datastore.v1beta3.Value from) {
+ return new DateTime(DateTime.timestampPbToMicroseconds(from.getTimestampValue()));
}
@Override
- protected void setValue(DateTimeValue from, DatastoreV1.Value.Builder to) {
- to.setTimestampMicrosecondsValue(from.get().timestampMicroseconds());
+ protected void setValue(DateTimeValue from, com.google.datastore.v1beta3.Value.Builder to) {
+ to.setTimestampValue(DateTime.microsecondsToTimestampPb(from.get()
+ .timestampMicroseconds()));
}
};
diff --git a/gcloud-java-datastore/src/main/java/com/google/gcloud/datastore/DoubleValue.java b/gcloud-java-datastore/src/main/java/com/google/cloud/datastore/DoubleValue.java
similarity index 85%
rename from gcloud-java-datastore/src/main/java/com/google/gcloud/datastore/DoubleValue.java
rename to gcloud-java-datastore/src/main/java/com/google/cloud/datastore/DoubleValue.java
index d12bbe317aef..51d175bb51c4 100644
--- a/gcloud-java-datastore/src/main/java/com/google/gcloud/datastore/DoubleValue.java
+++ b/gcloud-java-datastore/src/main/java/com/google/cloud/datastore/DoubleValue.java
@@ -14,11 +14,9 @@
* limitations under the License.
*/
-package com.google.gcloud.datastore;
+package com.google.cloud.datastore;
-import static com.google.api.services.datastore.DatastoreV1.Value.DOUBLE_VALUE_FIELD_NUMBER;
-
-import com.google.api.services.datastore.DatastoreV1;
+import static com.google.datastore.v1beta3.Value.DOUBLE_VALUE_FIELD_NUMBER;
public final class DoubleValue extends Value {
@@ -40,12 +38,12 @@ public Builder newBuilder(Double value) {
}
@Override
- protected Double getValue(DatastoreV1.Value from) {
+ protected Double getValue(com.google.datastore.v1beta3.Value from) {
return from.getDoubleValue();
}
@Override
- protected void setValue(DoubleValue from, DatastoreV1.Value.Builder to) {
+ protected void setValue(DoubleValue from, com.google.datastore.v1beta3.Value.Builder to) {
to.setDoubleValue(from.get());
}
};
diff --git a/gcloud-java-datastore/src/main/java/com/google/gcloud/datastore/Entity.java b/gcloud-java-datastore/src/main/java/com/google/cloud/datastore/Entity.java
similarity index 94%
rename from gcloud-java-datastore/src/main/java/com/google/gcloud/datastore/Entity.java
rename to gcloud-java-datastore/src/main/java/com/google/cloud/datastore/Entity.java
index dc1af5b8a2d9..3449693fe521 100644
--- a/gcloud-java-datastore/src/main/java/com/google/gcloud/datastore/Entity.java
+++ b/gcloud-java-datastore/src/main/java/com/google/cloud/datastore/Entity.java
@@ -14,11 +14,10 @@
* limitations under the License.
*/
-package com.google.gcloud.datastore;
+package com.google.cloud.datastore;
import static com.google.common.base.Preconditions.checkNotNull;
-import com.google.api.services.datastore.DatastoreV1;
import com.google.common.base.Preconditions;
/**
@@ -93,7 +92,7 @@ public static Builder builder(Key key, FullEntity> copyFrom) {
return new Builder(key, copyFrom);
}
- static Entity fromPb(DatastoreV1.Entity entityPb) {
+ static Entity fromPb(com.google.datastore.v1beta3.Entity entityPb) {
return new Builder().fill(entityPb).build();
}
}
diff --git a/gcloud-java-datastore/src/main/java/com/google/gcloud/datastore/EntityQuery.java b/gcloud-java-datastore/src/main/java/com/google/cloud/datastore/EntityQuery.java
similarity index 90%
rename from gcloud-java-datastore/src/main/java/com/google/gcloud/datastore/EntityQuery.java
rename to gcloud-java-datastore/src/main/java/com/google/cloud/datastore/EntityQuery.java
index 902168f20f48..40249b7ff26b 100644
--- a/gcloud-java-datastore/src/main/java/com/google/gcloud/datastore/EntityQuery.java
+++ b/gcloud-java-datastore/src/main/java/com/google/cloud/datastore/EntityQuery.java
@@ -14,9 +14,7 @@
* limitations under the License.
*/
-package com.google.gcloud.datastore;
-
-import com.google.api.services.datastore.DatastoreV1;
+package com.google.cloud.datastore;
/**
* An implementation of a Google Cloud Datastore entity query that can be constructed by providing
@@ -43,10 +41,10 @@ public static final class Builder extends StructuredQuery.BuilderImpl> {
@@ -41,12 +38,12 @@ public Builder newBuilder(FullEntity> value) {
}
@Override
- protected FullEntity> getValue(DatastoreV1.Value from) {
+ protected FullEntity> getValue(com.google.datastore.v1beta3.Value from) {
return FullEntity.fromPb(from.getEntityValue());
}
@Override
- protected void setValue(EntityValue from, DatastoreV1.Value.Builder to) {
+ protected void setValue(EntityValue from, com.google.datastore.v1beta3.Value.Builder to) {
to.setEntityValue(from.get().toPb());
}
};
@@ -57,13 +54,6 @@ private Builder() {
super(ValueType.ENTITY);
}
- @Override
- public Builder indexed(boolean indexed) {
- // see issue #25
- Preconditions.checkArgument(!indexed, "EntityValue can't be indexed");
- return super.indexed(indexed);
- }
-
@Override
public EntityValue build() {
return new EntityValue(this);
@@ -88,6 +78,6 @@ public static EntityValue of(FullEntity> entity) {
}
public static Builder builder(FullEntity> entity) {
- return new Builder().set(entity).indexed(false);
+ return new Builder().set(entity);
}
}
diff --git a/gcloud-java-datastore/src/main/java/com/google/gcloud/datastore/FullEntity.java b/gcloud-java-datastore/src/main/java/com/google/cloud/datastore/FullEntity.java
similarity index 92%
rename from gcloud-java-datastore/src/main/java/com/google/gcloud/datastore/FullEntity.java
rename to gcloud-java-datastore/src/main/java/com/google/cloud/datastore/FullEntity.java
index 55c573b9a636..aa88a92d3554 100644
--- a/gcloud-java-datastore/src/main/java/com/google/gcloud/datastore/FullEntity.java
+++ b/gcloud-java-datastore/src/main/java/com/google/cloud/datastore/FullEntity.java
@@ -14,9 +14,7 @@
* limitations under the License.
*/
-package com.google.gcloud.datastore;
-
-import com.google.api.services.datastore.DatastoreV1;
+package com.google.cloud.datastore;
/**
* A full entity is a {@link BaseEntity} that holds all the properties associated with a
@@ -71,7 +69,7 @@ public static Builder builder(FullEntity copyFro
}
- static FullEntity> fromPb(DatastoreV1.Entity entityPb) {
+ static FullEntity> fromPb(com.google.datastore.v1beta3.Entity entityPb) {
return new Builder<>().fill(entityPb).build();
}
}
diff --git a/gcloud-java-datastore/src/main/java/com/google/gcloud/datastore/GqlQuery.java b/gcloud-java-datastore/src/main/java/com/google/cloud/datastore/GqlQuery.java
similarity index 71%
rename from gcloud-java-datastore/src/main/java/com/google/gcloud/datastore/GqlQuery.java
rename to gcloud-java-datastore/src/main/java/com/google/cloud/datastore/GqlQuery.java
index 7c03b69d9f39..2af3559f6899 100644
--- a/gcloud-java-datastore/src/main/java/com/google/gcloud/datastore/GqlQuery.java
+++ b/gcloud-java-datastore/src/main/java/com/google/cloud/datastore/GqlQuery.java
@@ -14,12 +14,11 @@
* limitations under the License.
*/
-package com.google.gcloud.datastore;
+package com.google.cloud.datastore;
+import static com.google.cloud.datastore.Validator.validateNamespace;
import static com.google.common.base.Preconditions.checkNotNull;
-import static com.google.gcloud.datastore.Validator.validateNamespace;
-import com.google.api.services.datastore.DatastoreV1;
import com.google.common.base.MoreObjects;
import com.google.common.collect.ImmutableList;
import com.google.common.collect.ImmutableMap;
@@ -75,25 +74,22 @@ public final class GqlQuery extends Query {
private final transient String queryString;
private final transient boolean allowLiteral;
- private final transient ImmutableList