Skip to content

Commit

Permalink
Add NoCredentials class and remove setNoCredentials method
Browse files Browse the repository at this point in the history
  • Loading branch information
mziccard committed Nov 7, 2016
1 parent 96c2b60 commit 85e06c2
Show file tree
Hide file tree
Showing 20 changed files with 88 additions and 49 deletions.
4 changes: 2 additions & 2 deletions TESTING.md
Original file line number Diff line number Diff line change
Expand Up @@ -102,7 +102,7 @@ You can test against a remote Datastore emulator as well. To do this, set the `
DatastoreOptions options = DatastoreOptions.newBuilder()
.setProjectId("my-project-id") // must match project ID specified on remote machine
.setHost("http://<hostname of machine>:<port>")
.setNoCredentials()
.setCredentials(NoCredentials.getInstance())
.build();
Datastore localDatastore = options.getService();
```
Expand Down Expand Up @@ -209,7 +209,7 @@ endpoint to the hostname of the remote machine, like the example below.
PubSubOptions options = PubSubOptions.newBuilder()
.setProjectId("my-project-id") // must match project ID specified on remote machine
.setHost("<hostname of machine>:<port>")
.setNoCredentials()
.setCredentials(NoCredentials.getInstance())
.build();
PubSub localPubsub = options.getService();
```
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -17,6 +17,7 @@
package com.google.cloud.bigquery;

import com.google.cloud.BaseSerializationTest;
import com.google.cloud.NoCredentials;
import com.google.cloud.Restorable;
import com.google.cloud.bigquery.StandardTableDefinition.StreamingBuffer;
import com.google.common.collect.ImmutableList;
Expand Down Expand Up @@ -228,7 +229,7 @@ public class SerializationTest extends BaseSerializationTest {
protected Serializable[] serializableObjects() {
BigQueryOptions options = BigQueryOptions.newBuilder()
.setProjectId("p1")
.setNoCredentials()
.setCredentials(NoCredentials.getInstance())
.build();
BigQueryOptions otherOptions = options.toBuilder().setProjectId("p2").build();
return new Serializable[]{DOMAIN_ACCESS, GROUP_ACCESS, USER_ACCESS, VIEW_ACCESS, DATASET_ID,
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -17,6 +17,7 @@
package com.google.cloud.compute;

import com.google.cloud.BaseSerializationTest;
import com.google.cloud.NoCredentials;
import com.google.cloud.Restorable;
import com.google.cloud.RetryParams;
import com.google.cloud.compute.AttachedDisk.CreateDiskConfiguration;
Expand Down Expand Up @@ -264,7 +265,7 @@ public class SerializationTest extends BaseSerializationTest {
protected Serializable[] serializableObjects() {
ComputeOptions options = ComputeOptions.newBuilder()
.setProjectId("p1")
.setNoCredentials()
.setCredentials(NoCredentials.getInstance())
.build();
ComputeOptions otherOptions = options.toBuilder()
.setProjectId("p2")
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -320,7 +320,7 @@ protected ConnectionSettings.Builder getConnectionSettings() {
.setServiceAddress(hostAndPort.getHostText())
.setPort(hostAndPort.getPort());
Credentials scopedCredentials = getScopedCredentials();
if (scopedCredentials != null) {
if (scopedCredentials != null && scopedCredentials != NoCredentials.getInstance()) {
builder.provideCredentialsWith(scopedCredentials);
}
return builder;
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -215,7 +215,8 @@ public HttpRequestInitializer httpRequestInitializer() {
public HttpRequestInitializer getHttpRequestInitializer() {
Credentials scopedCredentials = getScopedCredentials();
final HttpRequestInitializer delegate =
scopedCredentials != null ? new HttpCredentialsAdapter(scopedCredentials) : null;
scopedCredentials != null && scopedCredentials != NoCredentials.getInstance()
? new HttpCredentialsAdapter(scopedCredentials) : null;
return new HttpRequestInitializer() {
@Override
public void initialize(HttpRequest httpRequest) throws IOException {
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,41 @@
/*
* 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.auth.oauth2.OAuth2Credentials;

import java.io.ObjectStreamException;

/**
* A placeholder for credentials to signify that requests sent to the server should not be
* authenticated. This is typically useful when using local service emulators.
*/
public class NoCredentials extends OAuth2Credentials {

private static final long serialVersionUID = -6263971603971044288L;
private static final NoCredentials INSTANCE = new NoCredentials();

private NoCredentials() {}

private Object readResolve() throws ObjectStreamException {
return INSTANCE;
}

public static NoCredentials getInstance() {
return INSTANCE;
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -84,7 +84,6 @@ public abstract class ServiceOptions<ServiceT extends Service<OptionsT>, Service
private final String serviceRpcFactoryClassName;
private final String serviceFactoryClassName;
private final Clock clock;
private final boolean noCredentials;
private final Credentials credentials;

private transient ServiceRpcFactory<ServiceRpcT, OptionsT> serviceRpcFactory;
Expand All @@ -106,7 +105,6 @@ protected abstract static class Builder<ServiceT extends Service<OptionsT>, Serv

private String projectId;
private String host;
private boolean noCredentials;
private Credentials credentials;
private RetryParams retryParams;
private ServiceFactory<ServiceT, OptionsT> serviceFactory;
Expand All @@ -118,7 +116,6 @@ protected Builder() {}
protected Builder(ServiceOptions<ServiceT, ServiceRpcT, OptionsT> options) {
projectId = options.projectId;
host = options.host;
noCredentials = options.noCredentials;
credentials = options.credentials;
retryParams = options.retryParams;
serviceFactory = options.serviceFactory;
Expand Down Expand Up @@ -214,29 +211,18 @@ public B setHost(String host) {
}

/**
* Sets the service authentication credentials. If this method or {@link #setNoCredentials() are
* not used on the builder, {@link GoogleCredentials#getApplicationDefault()} will be used to
* attempt getting credentials from the environment.
* Sets the service authentication credentials. If no credentials are set,
* {@link GoogleCredentials#getApplicationDefault()} will be used to attempt getting credentials
* from the environment. Use {@link NoCredentials#getInstance()} to skip authentication, this is
* typically useful when using local service emulators.
*
* @param credentials authentication credentials, should not be {@code null}
* @return the builder
* @throws NullPointerException if {@code credentials} is {@code null}. To disable
* authentication use {@link Builder#setNoCredentials()}
* authentication use {@link NoCredentials#getInstance()}
*/
public B setCredentials(Credentials credentials) {
this.credentials = checkNotNull(credentials);
this.noCredentials = false;
return self();
}

/**
* Sets that no credentials should be used. This is typically useful when using the local
* service emulators, such as {@code LocalDatastoreHelper}, {@code LocalPubsubHelper} and
* {@code LocalResourceManagerHelper}.
*/
public B setNoCredentials() {
this.noCredentials = true;
this.credentials = null;
return self();
}

Expand Down Expand Up @@ -296,9 +282,7 @@ protected ServiceOptions(Class<? extends ServiceFactory<ServiceT, OptionsT>> ser
+ "or the environment. Please set a project ID using the builder.");
}
host = firstNonNull(builder.host, getDefaultHost());
noCredentials = builder.noCredentials;
credentials = builder.credentials != null || noCredentials
? builder.credentials : defaultCredentials();
credentials = builder.credentials != null ? builder.credentials : defaultCredentials();
retryParams = firstNonNull(builder.retryParams, defaultRetryParams());
serviceFactory = firstNonNull(builder.serviceFactory,
getFromServiceLoader(serviceFactoryClass, getDefaultServiceFactory()));
Expand Down Expand Up @@ -540,8 +524,8 @@ public Credentials getCredentials() {
*/
public Credentials getScopedCredentials() {
Credentials credentialsToReturn = credentials;
if (credentials instanceof GoogleCredentials &&
((GoogleCredentials) credentials).createScopedRequired()) {
if (credentials instanceof GoogleCredentials
&& ((GoogleCredentials) credentials).createScopedRequired()) {
credentialsToReturn = ((GoogleCredentials) credentials).createScoped(getScopes());
}
return credentialsToReturn;
Expand Down Expand Up @@ -626,13 +610,12 @@ public String getLibraryVersion() {
}

protected int baseHashCode() {
return Objects.hash(projectId, host, noCredentials, credentials, retryParams,
serviceFactoryClassName, serviceRpcFactoryClassName, clock);
return Objects.hash(projectId, host, credentials, retryParams, serviceFactoryClassName,
serviceRpcFactoryClassName, clock);
}

protected boolean baseEquals(ServiceOptions<?, ?, ?> other) {
return noCredentials == other.noCredentials
&& Objects.equals(projectId, other.projectId)
return Objects.equals(projectId, other.projectId)
&& Objects.equals(host, other.host)
&& Objects.equals(credentials, other.credentials)
&& Objects.equals(retryParams, other.retryParams)
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -84,7 +84,7 @@ public class ServiceOptionsTest {
.build();
private static final TestServiceOptions OPTIONS_NO_CREDENTIALS =
TestServiceOptions.newBuilder()
.setNoCredentials()
.setCredentials(NoCredentials.getInstance())
.setClock(TEST_CLOCK)
.setHost("host")
.setProjectId("project-id")
Expand Down Expand Up @@ -224,7 +224,7 @@ public void testBuilder() {

@Test
public void testBuilderNoCredentials() {
assertNull(OPTIONS_NO_CREDENTIALS.getCredentials());
assertEquals(NoCredentials.getInstance(), OPTIONS_NO_CREDENTIALS.getCredentials());
assertSame(TEST_CLOCK, OPTIONS_NO_CREDENTIALS.getClock());
assertEquals("host", OPTIONS_NO_CREDENTIALS.getHost());
assertEquals("project-id", OPTIONS_NO_CREDENTIALS.getProjectId());
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -19,6 +19,7 @@
import static com.google.common.base.MoreObjects.firstNonNull;
import static com.google.common.base.Preconditions.checkArgument;

import com.google.cloud.NoCredentials;
import com.google.cloud.RetryParams;
import com.google.cloud.datastore.DatastoreOptions;
import com.google.common.base.Strings;
Expand Down Expand Up @@ -639,7 +640,7 @@ private DatastoreOptions.Builder optionsBuilder() {
return DatastoreOptions.newBuilder()
.setProjectId(projectId)
.setHost("localhost:" + Integer.toString(port))
.setNoCredentials()
.setCredentials(NoCredentials.getInstance())
.setRetryParams(RetryParams.noRetries());
}

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -19,6 +19,7 @@
import static java.nio.charset.StandardCharsets.UTF_8;

import com.google.cloud.BaseSerializationTest;
import com.google.cloud.NoCredentials;
import com.google.cloud.Restorable;
import com.google.cloud.datastore.StructuredQuery.CompositeFilter;
import com.google.cloud.datastore.StructuredQuery.OrderBy;
Expand Down Expand Up @@ -110,7 +111,7 @@ public class SerializationTest extends BaseSerializationTest {
@Override
protected java.io.Serializable[] serializableObjects() {
DatastoreOptions options = DatastoreOptions.newBuilder()
.setNoCredentials()
.setCredentials(NoCredentials.getInstance())
.setProjectId("ds1")
.build();
DatastoreOptions otherOptions = options.toBuilder().setNamespace("ns1").build();
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -22,6 +22,7 @@
import static org.junit.Assert.assertSame;
import static org.junit.Assert.assertTrue;

import com.google.cloud.NoCredentials;
import com.google.cloud.datastore.Datastore;
import com.google.cloud.datastore.DatastoreException;
import com.google.cloud.datastore.DatastoreOptions;
Expand Down Expand Up @@ -72,11 +73,11 @@ public void testOptions() {
DatastoreOptions options = helper.getOptions();
assertTrue(options.getProjectId().startsWith(PROJECT_ID_PREFIX));
assertTrue(options.getHost().startsWith("localhost:"));
assertNull(options.getCredentials());
assertSame(NoCredentials.getInstance(), options.getCredentials());
options = helper.getOptions(NAMESPACE);
assertTrue(options.getProjectId().startsWith(PROJECT_ID_PREFIX));
assertTrue(options.getHost().startsWith("localhost:"));
assertNull(options.getCredentials());
assertSame(NoCredentials.getInstance(), options.getCredentials());
assertEquals(NAMESPACE, options.getNamespace());
}

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -28,6 +28,7 @@
import com.google.api.services.dns.model.Project;
import com.google.api.services.dns.model.Quota;
import com.google.api.services.dns.model.ResourceRecordSet;
import com.google.cloud.NoCredentials;
import com.google.cloud.dns.DnsOptions;
import com.google.common.annotations.VisibleForTesting;
import com.google.common.base.Joiner;
Expand Down Expand Up @@ -506,7 +507,7 @@ public DnsOptions getOptions() {
return DnsOptions.newBuilder()
.setProjectId(PROJECT_ID)
.setHost("http://localhost:" + port)
.setNoCredentials()
.setCredentials(NoCredentials.getInstance())
.build();
}

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -17,6 +17,7 @@
package com.google.cloud.dns;

import com.google.cloud.BaseSerializationTest;
import com.google.cloud.NoCredentials;
import com.google.cloud.Restorable;
import com.google.cloud.RetryParams;
import com.google.common.collect.ImmutableList;
Expand Down Expand Up @@ -88,7 +89,7 @@ public class SerializationTest extends BaseSerializationTest {
@Override
protected Serializable[] serializableObjects() {
DnsOptions options = DnsOptions.newBuilder()
.setNoCredentials()
.setCredentials(NoCredentials.getInstance())
.setProjectId("id1")
.build();
DnsOptions otherOptions = options.toBuilder().build();
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -18,6 +18,7 @@

import com.google.cloud.BaseSerializationTest;
import com.google.cloud.MonitoredResource;
import com.google.cloud.NoCredentials;
import com.google.cloud.Restorable;
import com.google.cloud.logging.Logging.EntryListOption;
import com.google.cloud.logging.Logging.ListOption;
Expand All @@ -40,7 +41,7 @@ public class SerializationTest extends BaseSerializationTest {

private static final Logging LOGGING = LoggingOptions.newBuilder()
.setProjectId("p")
.setNoCredentials()
.setCredentials(NoCredentials.getInstance())
.setHost("localhost")
.build().getService();
private static final HttpRequest HTTP_REQUEST = HttpRequest.newBuilder()
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -19,6 +19,7 @@
import com.google.api.gax.testing.DownloadableEmulatorRunner;
import com.google.api.gax.testing.GCloudEmulatorRunner;
import com.google.api.gax.testing.LocalServiceHelper;
import com.google.cloud.NoCredentials;
import com.google.cloud.RetryParams;
import com.google.cloud.pubsub.PubSubOptions;

Expand Down Expand Up @@ -157,7 +158,7 @@ public PubSubOptions getOptions() {
return PubSubOptions.newBuilder()
.setProjectId(projectId)
.setHost("localhost:" + port)
.setNoCredentials()
.setCredentials(NoCredentials.getInstance())
.setRetryParams(RetryParams.noRetries())
.build();
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -18,6 +18,7 @@

import com.google.cloud.BaseSerializationTest;
import com.google.cloud.GrpcServiceOptions.ExecutorFactory;
import com.google.cloud.NoCredentials;
import com.google.cloud.Restorable;
import com.google.cloud.pubsub.PubSub.ListOption;
import com.google.cloud.pubsub.PubSub.PullOption;
Expand All @@ -29,7 +30,7 @@ public class SerializationTest extends BaseSerializationTest {

private static final PubSub PUB_SUB = PubSubOptions.newBuilder()
.setProjectId("p")
.setNoCredentials()
.setCredentials(NoCredentials.getInstance())
.setHost("localhost")
.build().getService();
private static final Message MESSAGE = Message.of("payload");
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -27,6 +27,7 @@
import com.google.api.services.cloudresourcemanager.model.SetIamPolicyRequest;
import com.google.api.services.cloudresourcemanager.model.TestIamPermissionsRequest;
import com.google.api.services.cloudresourcemanager.model.TestIamPermissionsResponse;
import com.google.cloud.NoCredentials;
import com.google.cloud.resourcemanager.ResourceManagerOptions;
import com.google.common.base.Joiner;
import com.google.common.base.Objects;
Expand Down Expand Up @@ -685,7 +686,7 @@ public ResourceManagerOptions options() {
public ResourceManagerOptions getOptions() {
return ResourceManagerOptions.newBuilder()
.setHost("http://localhost:" + port)
.setNoCredentials()
.setCredentials(NoCredentials.getInstance())
.build();
}

Expand Down
Loading

0 comments on commit 85e06c2

Please sign in to comment.