当前位置: 首页>>代码示例>>Java>>正文


Java GoogleCredentials.getApplicationDefault方法代码示例

本文整理汇总了Java中com.google.auth.oauth2.GoogleCredentials.getApplicationDefault方法的典型用法代码示例。如果您正苦于以下问题:Java GoogleCredentials.getApplicationDefault方法的具体用法?Java GoogleCredentials.getApplicationDefault怎么用?Java GoogleCredentials.getApplicationDefault使用的例子?那么, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在com.google.auth.oauth2.GoogleCredentials的用法示例。


在下文中一共展示了GoogleCredentials.getApplicationDefault方法的11个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Java代码示例。

示例1: createApplicationDefaultCredential

import com.google.auth.oauth2.GoogleCredentials; //导入方法依赖的package包/类
private static GoogleCredentials createApplicationDefaultCredential() throws IOException {
  final MockTokenServerTransport transport = new MockTokenServerTransport();
  transport.addServiceAccount(ServiceAccount.EDITOR.getEmail(), ACCESS_TOKEN);

  // Set the GOOGLE_APPLICATION_CREDENTIALS environment variable for application-default
  // credentials. This requires us to write the credentials to the location specified by the
  // environment variable.
  File credentialsFile = File.createTempFile("google-test-credentials", "json");
  PrintWriter writer = new PrintWriter(Files.newBufferedWriter(credentialsFile.toPath(), UTF_8));
  writer.print(ServiceAccount.EDITOR.asString());
  writer.close();
  Map<String, String> environmentVariables =
      ImmutableMap.<String, String>builder()
          .put("GOOGLE_APPLICATION_CREDENTIALS", credentialsFile.getAbsolutePath())
          .build();
  TestUtils.setEnvironmentVariables(environmentVariables);
  credentialsFile.deleteOnExit();

  return GoogleCredentials.getApplicationDefault(new HttpTransportFactory() {
    @Override
    public HttpTransport create() {
      return transport;
    }
  });
}
 
开发者ID:firebase,项目名称:firebase-admin-java,代码行数:26,代码来源:FirebaseAuthTest.java

示例2: getApplicationDefaultCredentials

import com.google.auth.oauth2.GoogleCredentials; //导入方法依赖的package包/类
/**
 * Ensures initialization of Google Application Default Credentials. Any test that depends on
 * ADC should consider this as a fixture, and invoke it before hand. Since ADC are initialized
 * once per JVM, this makes sure that all dependent tests get the same ADC instance, and
 * can reliably reason about the tokens minted using it.
 */
public static synchronized GoogleCredentials getApplicationDefaultCredentials()
    throws IOException {
  if (defaultCredentials != null) {
    return defaultCredentials;
  }
  final MockTokenServerTransport transport = new MockTokenServerTransport();
  transport.addServiceAccount(ServiceAccount.EDITOR.getEmail(), TEST_ADC_ACCESS_TOKEN);
  File serviceAccount = new File("src/test/resources/service_accounts", "editor.json");
  Map<String, String> environmentVariables =
      ImmutableMap.<String, String>builder()
          .put("GOOGLE_APPLICATION_CREDENTIALS", serviceAccount.getAbsolutePath())
          .build();
  setEnvironmentVariables(environmentVariables);
  defaultCredentials = GoogleCredentials.getApplicationDefault(new HttpTransportFactory() {
    @Override
    public HttpTransport create() {
      return transport;
    }
  });
  return defaultCredentials;
}
 
开发者ID:firebase,项目名称:firebase-admin-java,代码行数:28,代码来源:TestUtils.java

示例3: build

import com.google.auth.oauth2.GoogleCredentials; //导入方法依赖的package包/类
/**
 * Builds a new TraceGrpcApiService.
 */
public TraceGrpcApiService build() throws IOException {
  if (credentials == null) {
    credentials = GoogleCredentials.getApplicationDefault();
  }

  if(executorService == null) {
    ScheduledThreadPoolExecutor scheduledThreadPoolExecutor = new ScheduledThreadPoolExecutor(1);
    // Have the flushing threads shutdown if idle for the scheduled delay.
    scheduledThreadPoolExecutor.setKeepAliveTime(scheduledDelay, TimeUnit.SECONDS);
    scheduledThreadPoolExecutor.allowCoreThreadTimeOut(true);
    executorService = scheduledThreadPoolExecutor;
  }

  return new TraceGrpcApiService(projectId, optionsFactory, bufferSize,
      scheduledDelay, credentials, executorService);
}
 
开发者ID:GoogleCloudPlatform,项目名称:cloud-trace-java,代码行数:20,代码来源:TraceGrpcApiService.java

示例4: newCredentials

import com.google.auth.oauth2.GoogleCredentials; //导入方法依赖的package包/类
private static Credentials newCredentials(
    @Nullable InputStream credentialsFile, List<String> authScopes) throws IOException {
  try {
    GoogleCredentials creds =
        credentialsFile == null
            ? GoogleCredentials.getApplicationDefault()
            : GoogleCredentials.fromStream(credentialsFile);
    if (!authScopes.isEmpty()) {
      creds = creds.createScoped(authScopes);
    }
    return creds;
  } catch (IOException e) {
    String message = "Failed to init auth credentials: " + e.getMessage();
    throw new IOException(message, e);
  }
}
 
开发者ID:bazelbuild,项目名称:bazel,代码行数:17,代码来源:GoogleAuthUtils.java

示例5: googleContainerRegistryAuthSupplier

import com.google.auth.oauth2.GoogleCredentials; //导入方法依赖的package包/类
/**
 * Attempt to load a GCR compatible RegistryAuthSupplier based on a few conditions:
 * <ol>
 * <li>First check to see if the environemnt variable DOCKER_GOOGLE_CREDENTIALS is set and points
 * to a readable file</li>
 * <li>Otherwise check if the Google Application Default Credentials can be loaded</li>
 * </ol>
 * Note that we use a special environment variable of our own in addition to any environment
 * variable that the ADC loading uses (GOOGLE_APPLICATION_CREDENTIALS) in case there is a need for
 * the user to use the latter env var for some other purpose in their build.
 *
 * @return a GCR RegistryAuthSupplier, or null
 * @throws IOException if an IOException occurs while loading the credentials
 */
@Nullable
private RegistryAuthSupplier googleContainerRegistryAuthSupplier() throws IOException {
  GoogleCredentials credentials = null;

  final String googleCredentialsPath = System.getenv("DOCKER_GOOGLE_CREDENTIALS");
  if (googleCredentialsPath != null) {
    final File file = new File(googleCredentialsPath);
    if (file.exists()) {
      try (FileInputStream inputStream = new FileInputStream(file)) {
        credentials = GoogleCredentials.fromStream(inputStream);
        getLog().info("Using Google credentials from file: " + file.getAbsolutePath());
      }
    }
  }

  // use the ADC last
  if (credentials == null) {
    try {
      credentials = GoogleCredentials.getApplicationDefault();
      getLog().info("Using Google application default credentials");
    } catch (IOException ex) {
      // No GCP default credentials available
      getLog().debug("Failed to load Google application default credentials", ex);
    }
  }

  if (credentials == null) {
    return null;
  }

  return ContainerRegistryAuthSupplier.forCredentials(credentials).build();
}
 
开发者ID:spotify,项目名称:dockerfile-maven,代码行数:47,代码来源:AbstractDockerMojo.java

示例6: getDefaultCredential

import com.google.auth.oauth2.GoogleCredentials; //导入方法依赖的package包/类
private Credentials getDefaultCredential() {
  GoogleCredentials credential;
  try {
    credential = GoogleCredentials.getApplicationDefault();
  } catch (IOException e) {
    throw new RuntimeException("Failed to get application default credential.", e);
  }

  if (credential.createScopedRequired()) {
    Collection<String> bigqueryScope =
        Lists.newArrayList(BigqueryScopes.CLOUD_PLATFORM_READ_ONLY);
    credential = credential.createScoped(bigqueryScope);
  }
  return credential;
}
 
开发者ID:apache,项目名称:beam,代码行数:16,代码来源:BigqueryMatcher.java

示例7: main

import com.google.auth.oauth2.GoogleCredentials; //导入方法依赖的package包/类
public static void main(final String[] args) throws Exception {

        if (args.length == 0) {
            System.err.println("Please specify your project name.");
            System.exit(1);
        }
        final String project = args[0];
        ManagedChannelImpl channelImpl = NettyChannelBuilder
            .forAddress("pubsub.googleapis.com", 443)
            .negotiationType(NegotiationType.TLS)
            .build();
        GoogleCredentials creds = GoogleCredentials.getApplicationDefault();
        // Down-scope the credential to just the scopes required by the service
        creds = creds.createScoped(Arrays.asList("https://www.googleapis.com/auth/pubsub"));
        // Intercept the channel to bind the credential
        ExecutorService executor = Executors.newSingleThreadExecutor();
        ClientAuthInterceptor interceptor = new ClientAuthInterceptor(creds, executor);
        Channel channel = ClientInterceptors.intercept(channelImpl, interceptor);
        // Create a stub using the channel that has the bound credential
        PublisherGrpc.PublisherBlockingStub publisherStub = PublisherGrpc.newBlockingStub(channel);
        ListTopicsRequest request = ListTopicsRequest.newBuilder()
                .setPageSize(10)
                .setProject("projects/" + project)
                .build();
        ListTopicsResponse resp = publisherStub.listTopics(request);
        System.out.println("Found " + resp.getTopicsCount() + " topics.");
        for (Topic topic : resp.getTopicsList()) {
            System.out.println(topic.getName());
        }
    }
 
开发者ID:GoogleCloudPlatform,项目名称:cloud-pubsub-samples-java,代码行数:31,代码来源:Main.java

示例8: loadCredentials

import com.google.auth.oauth2.GoogleCredentials; //导入方法依赖的package包/类
public static GoogleCredentials loadCredentials(S3UploadMetadata uploadMetadata, JsonObjectFileHelper jsonHelper) {
  try {
    if (!uploadMetadata.getGcsCredentials().isEmpty()) {
      return GoogleCredentials.fromStream(jsonHelper.toInputStream(uploadMetadata.getGcsCredentials()));
    }

    // Load from default credentials as determined by GOOGLE_APPLICATION_CREDENTIALS var if none provided in metadata
    return GoogleCredentials.getApplicationDefault();
  } catch (IOException e) {
    throw new RuntimeException("Issue reading credentials file specified in `GOOGLE_APPLICATION_CREDENTIALS`", e);
  }
}
 
开发者ID:HubSpot,项目名称:Singularity,代码行数:13,代码来源:SingularityGCSUploader.java

示例9: ApplicationDefaultCredential

import com.google.auth.oauth2.GoogleCredentials; //导入方法依赖的package包/类
ApplicationDefaultCredential(HttpTransport transport) throws IOException {
  super(GoogleCredentials.getApplicationDefault(wrap(transport)));
}
 
开发者ID:firebase,项目名称:firebase-admin-java,代码行数:4,代码来源:FirebaseCredentials.java

示例10: TestApp

import com.google.auth.oauth2.GoogleCredentials; //导入方法依赖的package包/类
public TestApp()  {

    String projectId = ServiceOptions.getDefaultProjectId();
	try {

		//export GRPC_PROXY_EXP=localhost:3128
		HttpHost proxy = new HttpHost("127.0.0.1",3128);
		DefaultHttpClient httpClient = new DefaultHttpClient();
		httpClient.getParams().setParameter(ConnRoutePNames.DEFAULT_PROXY, proxy);
					
		httpClient.addRequestInterceptor(new HttpRequestInterceptor(){            
			@Override
			public void process(org.apache.http.HttpRequest request, HttpContext context) throws HttpException, IOException {
					//if (request.getRequestLine().getMethod().equals("CONNECT"))                 
					//   request.addHeader(new BasicHeader("Proxy-Authorization","Basic dXNlcjE6dXNlcjE="));
				}
			});
		
		mHttpTransport =  new ApacheHttpTransport(httpClient);		

		HttpTransportFactory hf = new HttpTransportFactory(){
			@Override
			public HttpTransport create() {
				return mHttpTransport;
			}
		};            
		
		credential = GoogleCredentials.getApplicationDefault(hf);

		CredentialsProvider credentialsProvider =  new GoogleCredentialsProvider(){
			public List<String> getScopesToApply(){
				return Arrays.asList("https://www.googleapis.com/auth/pubsub");
			   }

			public Credentials getCredentials()  {
				return credential;
			}
		};

		TopicAdminSettings topicAdminSettings =
		     TopicAdminSettings.newBuilder().setCredentialsProvider(credentialsProvider)
				 .build();
				 
		 TopicAdminClient topicAdminClient =
		     TopicAdminClient.create(topicAdminSettings);
		
		//TopicAdminClient topicAdminClient = TopicAdminClient.create();
		ProjectName project = ProjectName.create(projectId);
		for (Topic element : topicAdminClient.listTopics(project).iterateAll()) 
	  		System.out.println(element.getName());
	
	} catch (Exception ex) 
	{
		System.out.println("ERROR " + ex);
	}
  }
 
开发者ID:salrashid123,项目名称:gcpsamples,代码行数:57,代码来源:TestApp.java

示例11: getApplicationDefaultCredentials

import com.google.auth.oauth2.GoogleCredentials; //导入方法依赖的package包/类
/**
 * Obtain the Application Default com.google.auth.oauth2.GoogleCredentials
 *
 * This is from the newer OAuth library https://github.com/google/google-auth-library-java
 * which is used by gRPC.
 *
 * @return the Application Default Credentials
 */
public static GoogleCredentials getApplicationDefaultCredentials() {
  try {
    return GoogleCredentials.getApplicationDefault();
  } catch (IOException e) {
    throw new RuntimeException(MISSING_ADC_EXCEPTION_MESSAGE, e);
  }
}
 
开发者ID:googlegenomics,项目名称:utils-java,代码行数:16,代码来源:CredentialFactory.java


注:本文中的com.google.auth.oauth2.GoogleCredentials.getApplicationDefault方法示例由纯净天空整理自Github/MSDocs等开源代码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。