Migrate users of ManagedChannelBuilder.{forTarget,forAddress} to ChannelCredentials
diff --git a/android-interop-testing/src/main/java/io/grpc/android/integrationtest/TesterOkHttpChannelBuilder.java b/android-interop-testing/src/main/java/io/grpc/android/integrationtest/TesterOkHttpChannelBuilder.java
index 417df61..36a3b0a 100644
--- a/android-interop-testing/src/main/java/io/grpc/android/integrationtest/TesterOkHttpChannelBuilder.java
+++ b/android-interop-testing/src/main/java/io/grpc/android/integrationtest/TesterOkHttpChannelBuilder.java
@@ -17,9 +17,12 @@
 package io.grpc.android.integrationtest;
 
 import android.support.annotation.Nullable;
+import io.grpc.ChannelCredentials;
+import io.grpc.Grpc;
+import io.grpc.InsecureChannelCredentials;
 import io.grpc.ManagedChannel;
 import io.grpc.ManagedChannelBuilder;
-import io.grpc.okhttp.OkHttpChannelBuilder;
+import io.grpc.okhttp.SslSocketFactoryChannelCredentials;
 import java.io.InputStream;
 import java.security.KeyStore;
 import java.security.cert.CertificateFactory;
@@ -40,21 +43,23 @@
       @Nullable String serverHostOverride,
       boolean useTls,
       @Nullable InputStream testCa) {
-    ManagedChannelBuilder<?> channelBuilder = ManagedChannelBuilder.forAddress(host, port)
-        .maxInboundMessageSize(16 * 1024 * 1024);
-    if (serverHostOverride != null) {
-      // Force the hostname to match the cert the server uses.
-      channelBuilder.overrideAuthority(serverHostOverride);
-    }
+    ChannelCredentials credentials;
     if (useTls) {
       try {
-        ((OkHttpChannelBuilder) channelBuilder).useTransportSecurity();
-        ((OkHttpChannelBuilder) channelBuilder).sslSocketFactory(getSslSocketFactory(testCa));
+        credentials = SslSocketFactoryChannelCredentials.create(getSslSocketFactory(testCa));
       } catch (Exception e) {
         throw new RuntimeException(e);
       }
     } else {
-      channelBuilder.usePlaintext();
+      credentials = InsecureChannelCredentials.create();
+    }
+
+    ManagedChannelBuilder<?> channelBuilder = Grpc.newChannelBuilderForAddress(
+          host, port, credentials)
+        .maxInboundMessageSize(16 * 1024 * 1024);
+    if (serverHostOverride != null) {
+      // Force the hostname to match the cert the server uses.
+      channelBuilder.overrideAuthority(serverHostOverride);
     }
     return channelBuilder.build();
   }
diff --git a/gae-interop-testing/gae-jdk8/src/main/java/io/grpc/testing/integration/LongLivedChannel.java b/gae-interop-testing/gae-jdk8/src/main/java/io/grpc/testing/integration/LongLivedChannel.java
index 51f23e5..90e56c1 100644
--- a/gae-interop-testing/gae-jdk8/src/main/java/io/grpc/testing/integration/LongLivedChannel.java
+++ b/gae-interop-testing/gae-jdk8/src/main/java/io/grpc/testing/integration/LongLivedChannel.java
@@ -17,8 +17,9 @@
 package io.grpc.testing.integration;
 
 import com.google.protobuf.ByteString;
+import io.grpc.Grpc;
 import io.grpc.ManagedChannel;
-import io.grpc.ManagedChannelBuilder;
+import io.grpc.TlsChannelCredentials;
 import io.grpc.testing.integration.Messages.Payload;
 import io.grpc.testing.integration.Messages.SimpleRequest;
 import io.grpc.testing.integration.Messages.SimpleResponse;
@@ -40,7 +41,7 @@
 public final class LongLivedChannel extends HttpServlet {
   private static final String INTEROP_TEST_ADDRESS = "grpc-test.sandbox.googleapis.com:443";
   private final ManagedChannel channel =
-      ManagedChannelBuilder.forTarget(INTEROP_TEST_ADDRESS).build();
+      Grpc.newChannelBuilder(INTEROP_TEST_ADDRESS, TlsChannelCredentials.create()).build();
 
   @Override
   public void destroy() {
diff --git a/gae-interop-testing/gae-jdk8/src/main/java/io/grpc/testing/integration/NettyClientInteropServlet.java b/gae-interop-testing/gae-jdk8/src/main/java/io/grpc/testing/integration/NettyClientInteropServlet.java
index 2a9c195..6af0222 100644
--- a/gae-interop-testing/gae-jdk8/src/main/java/io/grpc/testing/integration/NettyClientInteropServlet.java
+++ b/gae-interop-testing/gae-jdk8/src/main/java/io/grpc/testing/integration/NettyClientInteropServlet.java
@@ -19,7 +19,9 @@
 import static org.junit.Assert.assertEquals;
 import static org.junit.Assert.assertTrue;
 
+import io.grpc.Grpc;
 import io.grpc.ManagedChannelBuilder;
+import io.grpc.TlsChannelCredentials;
 import io.grpc.netty.NettyChannelBuilder;
 import java.io.IOException;
 import java.io.PrintWriter;
@@ -131,7 +133,7 @@
           "1.8",
           System.getProperty("java.specification.version"));
       ManagedChannelBuilder<?> builder =
-          ManagedChannelBuilder.forTarget(INTEROP_TEST_ADDRESS)
+          Grpc.newChannelBuilder(INTEROP_TEST_ADDRESS, TlsChannelCredentials.create())
               .maxInboundMessageSize(AbstractInteropTest.MAX_MESSAGE_SIZE);
       assertTrue(builder instanceof NettyChannelBuilder);
       ((NettyChannelBuilder) builder)
diff --git a/interop-testing/src/main/java/io/grpc/testing/integration/TestServiceClient.java b/interop-testing/src/main/java/io/grpc/testing/integration/TestServiceClient.java
index ff4c6ca..32bd31e 100644
--- a/interop-testing/src/main/java/io/grpc/testing/integration/TestServiceClient.java
+++ b/interop-testing/src/main/java/io/grpc/testing/integration/TestServiceClient.java
@@ -18,26 +18,30 @@
 
 import com.google.common.annotations.VisibleForTesting;
 import com.google.common.io.Files;
+import io.grpc.ChannelCredentials;
+import io.grpc.Grpc;
+import io.grpc.InsecureChannelCredentials;
 import io.grpc.ManagedChannel;
 import io.grpc.ManagedChannelBuilder;
-import io.grpc.alts.AltsChannelBuilder;
-import io.grpc.alts.ComputeEngineChannelBuilder;
-import io.grpc.alts.GoogleDefaultChannelBuilder;
+import io.grpc.TlsChannelCredentials;
+import io.grpc.alts.AltsChannelCredentials;
+import io.grpc.alts.ComputeEngineChannelCredentials;
+import io.grpc.alts.GoogleDefaultChannelCredentials;
 import io.grpc.internal.GrpcUtil;
 import io.grpc.internal.testing.TestUtils;
 import io.grpc.netty.GrpcSslContexts;
+import io.grpc.netty.InsecureFromHttp1ChannelCredentials;
 import io.grpc.netty.InternalNettyChannelBuilder;
-import io.grpc.netty.NegotiationType;
 import io.grpc.netty.NettyChannelBuilder;
+import io.grpc.netty.NettySslContextChannelCredentials;
 import io.grpc.okhttp.InternalOkHttpChannelBuilder;
 import io.grpc.okhttp.OkHttpChannelBuilder;
+import io.grpc.okhttp.SslSocketFactoryChannelCredentials;
 import io.grpc.okhttp.internal.Platform;
-import io.netty.handler.ssl.SslContext;
 import java.io.File;
 import java.io.FileInputStream;
 import java.nio.charset.Charset;
 import java.util.concurrent.TimeUnit;
-import javax.net.ssl.SSLSocketFactory;
 
 /**
  * Application that starts a client for the {@link TestServiceGrpc.TestServiceImplBase} and runs
@@ -282,8 +286,8 @@
         break;
 
       case COMPUTE_ENGINE_CHANNEL_CREDENTIALS: {
-        ManagedChannel channel = ComputeEngineChannelBuilder
-            .forAddress(serverHost, serverPort).build();
+        ManagedChannel channel = Grpc.newChannelBuilderForAddress(
+            serverHost, serverPort, ComputeEngineChannelCredentials.create()).build();
         try {
           TestServiceGrpc.TestServiceBlockingStub computeEngineStub =
               TestServiceGrpc.newBlockingStub(channel);
@@ -323,8 +327,8 @@
       }
 
       case GOOGLE_DEFAULT_CREDENTIALS: {
-        ManagedChannel channel = GoogleDefaultChannelBuilder.forAddress(
-            serverHost, serverPort).build();
+        ManagedChannel channel = Grpc.newChannelBuilderForAddress(
+            serverHost, serverPort, GoogleDefaultChannelCredentials.create()).build();
         try {
           TestServiceGrpc.TestServiceBlockingStub googleDefaultStub =
               TestServiceGrpc.newBlockingStub(channel);
@@ -392,34 +396,56 @@
   private class Tester extends AbstractInteropTest {
     @Override
     protected ManagedChannelBuilder<?> createChannelBuilder() {
-      if (customCredentialsType != null
-          && customCredentialsType.equals("google_default_credentials")) {
-        return GoogleDefaultChannelBuilder.forAddress(serverHost, serverPort);
-      }
-      if (customCredentialsType != null
-          && customCredentialsType.equals("compute_engine_channel_creds")) {
-        return ComputeEngineChannelBuilder.forAddress(serverHost, serverPort);
-      }
-      if (useAlts) {
-        return AltsChannelBuilder.forAddress(serverHost, serverPort);
-      }
+      ChannelCredentials channelCredentials;
+      if (customCredentialsType != null) {
+        useOkHttp = false; // Retain old behavior; avoids erroring if incompatible
+        if (customCredentialsType.equals("google_default_credentials")) {
+          channelCredentials = GoogleDefaultChannelCredentials.create();
+        } else if (customCredentialsType.equals("compute_engine_channel_creds")) {
+          channelCredentials = ComputeEngineChannelCredentials.create();
+        } else {
+          throw new IllegalArgumentException(
+              "Unknown custom credentials: " + customCredentialsType);
+        }
 
-      if (!useOkHttp) {
-        SslContext sslContext = null;
-        if (useTestCa) {
+      } else if (useAlts) {
+        useOkHttp = false; // Retain old behavior; avoids erroring if incompatible
+        channelCredentials = AltsChannelCredentials.create();
+
+      } else if (useTls) {
+        if (!useTestCa) {
+          channelCredentials = TlsChannelCredentials.create();
+        } else {
           try {
-            sslContext = GrpcSslContexts.forClient().trustManager(
-                    TestUtils.loadCert("ca.pem")).build();
+            if (useOkHttp) {
+              channelCredentials = SslSocketFactoryChannelCredentials.create(
+                  TestUtils.newSslSocketFactoryForCa(
+                      Platform.get().getProvider(), TestUtils.loadCert("ca.pem")));
+            } else {
+              channelCredentials = NettySslContextChannelCredentials.create(
+                  GrpcSslContexts.forClient().trustManager(
+                      TestUtils.loadCert("ca.pem")).build());
+            }
           } catch (Exception ex) {
             throw new RuntimeException(ex);
           }
         }
+
+      } else {
+        if (useH2cUpgrade) {
+          if (useOkHttp) {
+            throw new IllegalArgumentException("OkHttp does not support HTTP/1 upgrade");
+          } else {
+            channelCredentials = InsecureFromHttp1ChannelCredentials.create();
+          }
+        } else {
+          channelCredentials = InsecureChannelCredentials.create();
+        }
+      }
+      if (!useOkHttp) {
         NettyChannelBuilder nettyBuilder =
-            NettyChannelBuilder.forAddress(serverHost, serverPort)
-                .flowControlWindow(AbstractInteropTest.TEST_FLOW_CONTROL_WINDOW)
-                .negotiationType(useTls ? NegotiationType.TLS :
-                  (useH2cUpgrade ? NegotiationType.PLAINTEXT_UPGRADE : NegotiationType.PLAINTEXT))
-                .sslContext(sslContext);
+            NettyChannelBuilder.forAddress(serverHost, serverPort, channelCredentials)
+                .flowControlWindow(AbstractInteropTest.TEST_FLOW_CONTROL_WINDOW);
         if (serverHostOverride != null) {
           nettyBuilder.overrideAuthority(serverHostOverride);
         }
@@ -431,25 +457,13 @@
         return nettyBuilder.intercept(createCensusStatsClientInterceptor());
       }
 
-      OkHttpChannelBuilder okBuilder = OkHttpChannelBuilder.forAddress(serverHost, serverPort);
+      OkHttpChannelBuilder okBuilder =
+          OkHttpChannelBuilder.forAddress(serverHost, serverPort, channelCredentials);
       if (serverHostOverride != null) {
         // Force the hostname to match the cert the server uses.
         okBuilder.overrideAuthority(
             GrpcUtil.authorityFromHostAndPort(serverHostOverride, serverPort));
       }
-      if (useTls) {
-        if (useTestCa) {
-          try {
-            SSLSocketFactory factory = TestUtils.newSslSocketFactoryForCa(
-                Platform.get().getProvider(), TestUtils.loadCert("ca.pem"));
-            okBuilder.sslSocketFactory(factory);
-          } catch (Exception e) {
-            throw new RuntimeException(e);
-          }
-        }
-      } else {
-        okBuilder.usePlaintext();
-      }
       if (fullStreamDecompression) {
         okBuilder.enableFullStreamDecompression();
       }
diff --git a/interop-testing/src/test/java/io/grpc/testing/integration/CompressionTest.java b/interop-testing/src/test/java/io/grpc/testing/integration/CompressionTest.java
index 360557c..208eb40 100644
--- a/interop-testing/src/test/java/io/grpc/testing/integration/CompressionTest.java
+++ b/interop-testing/src/test/java/io/grpc/testing/integration/CompressionTest.java
@@ -35,8 +35,9 @@
 import io.grpc.DecompressorRegistry;
 import io.grpc.ForwardingClientCall.SimpleForwardingClientCall;
 import io.grpc.ForwardingClientCallListener.SimpleForwardingClientCallListener;
+import io.grpc.Grpc;
+import io.grpc.InsecureChannelCredentials;
 import io.grpc.ManagedChannel;
-import io.grpc.ManagedChannelBuilder;
 import io.grpc.Metadata;
 import io.grpc.MethodDescriptor;
 import io.grpc.Server;
@@ -189,11 +190,11 @@
         .build()
         .start();
 
-    channel = ManagedChannelBuilder.forAddress("localhost", server.getPort())
+    channel = Grpc.newChannelBuilder(
+            "localhost:" + server.getPort(), InsecureChannelCredentials.create())
         .decompressorRegistry(clientDecompressors)
         .compressorRegistry(clientCompressors)
         .intercept(new ClientCompressorInterceptor())
-        .usePlaintext()
         .build();
     stub = TestServiceGrpc.newBlockingStub(channel);
 
diff --git a/interop-testing/src/test/java/io/grpc/testing/integration/ManagedChannelBuilderSpiTest.java b/interop-testing/src/test/java/io/grpc/testing/integration/ManagedChannelBuilderSpiTest.java
new file mode 100644
index 0000000..737e5a3
--- /dev/null
+++ b/interop-testing/src/test/java/io/grpc/testing/integration/ManagedChannelBuilderSpiTest.java
@@ -0,0 +1,36 @@
+/*
+ * Copyright 2020 The gRPC Authors
+ *
+ * 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 io.grpc.testing.integration;
+
+import io.grpc.ManagedChannelBuilder;
+import org.junit.Test;
+import org.junit.runner.RunWith;
+import org.junit.runners.JUnit4;
+
+/** Tests for integration between {@link ManagedChannelBuilder} and providers. */
+@RunWith(JUnit4.class)
+public final class ManagedChannelBuilderSpiTest {
+  @Test
+  public void forAddress_isntObviouslyBroken() {
+    ManagedChannelBuilder.forAddress("localhost", 443).build().shutdownNow();
+  }
+
+  @Test
+  public void forTarget_isntObviouslyBroken() {
+    ManagedChannelBuilder.forTarget("localhost:443").build().shutdownNow();
+  }
+}
diff --git a/interop-testing/src/test/java/io/grpc/testing/integration/StressTestClientTest.java b/interop-testing/src/test/java/io/grpc/testing/integration/StressTestClientTest.java
index 52ded41..c1f193b 100644
--- a/interop-testing/src/test/java/io/grpc/testing/integration/StressTestClientTest.java
+++ b/interop-testing/src/test/java/io/grpc/testing/integration/StressTestClientTest.java
@@ -22,8 +22,9 @@
 import static org.junit.Assert.assertTrue;
 
 import com.google.common.collect.ImmutableList;
+import io.grpc.Grpc;
+import io.grpc.InsecureChannelCredentials;
 import io.grpc.ManagedChannel;
-import io.grpc.ManagedChannelBuilder;
 import io.grpc.testing.integration.Metrics.EmptyMessage;
 import io.grpc.testing.integration.Metrics.GaugeResponse;
 import io.grpc.testing.integration.StressTestClient.TestCaseWeightPair;
@@ -128,8 +129,8 @@
     client.runStressTest();
 
     // Connect to the metrics service
-    ManagedChannel ch = ManagedChannelBuilder.forAddress("localhost", client.getMetricServerPort())
-        .usePlaintext()
+    ManagedChannel ch = Grpc.newChannelBuilder(
+          "localhost:" + client.getMetricServerPort(), InsecureChannelCredentials.create())
         .build();
 
     MetricsServiceGrpc.MetricsServiceBlockingStub stub = MetricsServiceGrpc.newBlockingStub(ch);
diff --git a/xds/src/main/java/io/grpc/xds/XdsChannelFactory.java b/xds/src/main/java/io/grpc/xds/XdsChannelFactory.java
index 2ba7a6f..4e3a2c4 100644
--- a/xds/src/main/java/io/grpc/xds/XdsChannelFactory.java
+++ b/xds/src/main/java/io/grpc/xds/XdsChannelFactory.java
@@ -17,9 +17,12 @@
 package io.grpc.xds;
 
 import com.google.common.annotations.VisibleForTesting;
+import io.grpc.ChannelCredentials;
+import io.grpc.Grpc;
+import io.grpc.InsecureChannelCredentials;
 import io.grpc.ManagedChannel;
-import io.grpc.ManagedChannelBuilder;
-import io.grpc.alts.GoogleDefaultChannelBuilder;
+import io.grpc.TlsChannelCredentials;
+import io.grpc.alts.GoogleDefaultChannelCredentials;
 import io.grpc.xds.Bootstrapper.ChannelCreds;
 import io.grpc.xds.Bootstrapper.ServerInfo;
 import io.grpc.xds.XdsClient.XdsChannel;
@@ -50,33 +53,33 @@
       String serverUri = serverInfo.getServerUri();
       logger.log(XdsLogLevel.INFO, "Creating channel to {0}", serverUri);
       List<ChannelCreds> channelCredsList = serverInfo.getChannelCredentials();
-      ManagedChannelBuilder<?> channelBuilder = null;
+      ChannelCredentials channelCreds = null;
       // Use the first supported channel credentials configuration.
       for (ChannelCreds creds : channelCredsList) {
         switch (creds.getType()) {
           case "google_default":
             logger.log(XdsLogLevel.INFO, "Using channel credentials: google_default");
-            channelBuilder = GoogleDefaultChannelBuilder.forTarget(serverUri);
+            channelCreds = GoogleDefaultChannelCredentials.create();
             break;
           case "insecure":
             logger.log(XdsLogLevel.INFO, "Using channel credentials: insecure");
-            channelBuilder = ManagedChannelBuilder.forTarget(serverUri).usePlaintext();
+            channelCreds = InsecureChannelCredentials.create();
             break;
           case "tls":
             logger.log(XdsLogLevel.INFO, "Using channel credentials: tls");
-            channelBuilder = ManagedChannelBuilder.forTarget(serverUri);
+            channelCreds = TlsChannelCredentials.create();
             break;
           default:
         }
-        if (channelBuilder != null) {
+        if (channelCreds != null) {
           break;
         }
       }
-      if (channelBuilder == null) {
+      if (channelCreds == null) {
         throw new XdsInitializationException("No server with supported channel creds found");
       }
 
-      ManagedChannel channel = channelBuilder
+      ManagedChannel channel = Grpc.newChannelBuilder(serverUri, channelCreds)
           .keepAliveTime(5, TimeUnit.MINUTES)
           .build();
       boolean useProtocolV3 = experimentalV3SupportEnvVar
diff --git a/xds/src/main/java/io/grpc/xds/internal/certprovider/MeshCaCertificateProvider.java b/xds/src/main/java/io/grpc/xds/internal/certprovider/MeshCaCertificateProvider.java
index efb9a54..dee649a 100644
--- a/xds/src/main/java/io/grpc/xds/internal/certprovider/MeshCaCertificateProvider.java
+++ b/xds/src/main/java/io/grpc/xds/internal/certprovider/MeshCaCertificateProvider.java
@@ -39,13 +39,14 @@
 import io.grpc.ClientCall;
 import io.grpc.ClientInterceptor;
 import io.grpc.ForwardingClientCall;
+import io.grpc.Grpc;
 import io.grpc.InternalLogId;
 import io.grpc.ManagedChannel;
-import io.grpc.ManagedChannelBuilder;
 import io.grpc.Metadata;
 import io.grpc.MethodDescriptor;
 import io.grpc.Status;
 import io.grpc.SynchronizationContext;
+import io.grpc.TlsChannelCredentials;
 import io.grpc.auth.MoreCallCredentials;
 import io.grpc.internal.BackoffPolicy;
 import io.grpc.internal.TimeProvider;
@@ -361,8 +362,9 @@
             checkArgument(serverUri != null && !serverUri.isEmpty(), "serverUri is null/empty!");
             logger.log(Level.INFO, "Creating channel to {0}", serverUri);
 
-            ManagedChannelBuilder<?> channelBuilder = ManagedChannelBuilder.forTarget(serverUri);
-            return channelBuilder.keepAliveTime(1, TimeUnit.MINUTES).build();
+            return Grpc.newChannelBuilder(serverUri, TlsChannelCredentials.create())
+                .keepAliveTime(1, TimeUnit.MINUTES)
+                .build();
           }
         };