com.google.auth.http.HttpTransportFactory Java Examples

The following examples show how to use com.google.auth.http.HttpTransportFactory. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source File: TestUtils.java    From firebase-admin-java with Apache License 2.0 6 votes vote down vote up
/**
 * 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(
      "https://accounts.google.com/o/oauth2/token");
  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;
}
 
Example #2
Source File: EntityManagerFactory.java    From catatumbo with Apache License 2.0 5 votes vote down vote up
/**
 * Creates and returns HttpTransportOptions from the given connection parameters.
 * 
 * @param parameters
 *          the connection parameters
 * @return the HttpTransportOptions
 */
private static HttpTransportOptions getHttpTransportOptions(ConnectionParameters parameters) {
  HttpTransportOptions.Builder httpOptionsBuilder = HttpTransportOptions.newBuilder();
  httpOptionsBuilder.setConnectTimeout(parameters.getConnectionTimeout());
  httpOptionsBuilder.setReadTimeout(parameters.getReadTimeout());

  HttpTransportFactory httpTransportFactory = parameters.getHttpTransportFactory();
  if (httpTransportFactory != null) {
    httpOptionsBuilder.setHttpTransportFactory(httpTransportFactory);
  }
  return httpOptionsBuilder.build();
}
 
Example #3
Source File: GoogleAuthLibraryCallCredentialsTest.java    From grpc-java with Apache License 2.0 5 votes vote down vote up
@Test
public void serviceAccountToJwt() throws Exception {
  KeyPair pair = KeyPairGenerator.getInstance("RSA").generateKeyPair();

  HttpTransportFactory factory = Mockito.mock(HttpTransportFactory.class);
  Mockito.when(factory.create()).thenThrow(new AssertionError());

  ServiceAccountCredentials credentials =
      ServiceAccountCredentials.newBuilder()
          .setClientEmail("[email protected]")
          .setPrivateKey(pair.getPrivate())
          .setPrivateKeyId("test-private-key-id")
          .setHttpTransportFactory(factory)
          .build();

  GoogleAuthLibraryCallCredentials callCredentials =
      new GoogleAuthLibraryCallCredentials(credentials);
  callCredentials.applyRequestMetadata(new RequestInfoImpl(), executor, applier);
  assertEquals(0, runPendingRunnables());

  verify(applier).apply(headersCaptor.capture());
  Metadata headers = headersCaptor.getValue();
  String[] authorization = Iterables.toArray(headers.getAll(AUTHORIZATION), String.class);
  assertEquals(1, authorization.length);
  assertTrue(authorization[0], authorization[0].startsWith("Bearer "));
  // JWT is reasonably long. Normal tokens aren't.
  assertTrue(authorization[0], authorization[0].length() > 300);
}
 
Example #4
Source File: GCPCredentialsControllerService.java    From nifi with Apache License 2.0 5 votes vote down vote up
@OnEnabled
public void onConfigured(final ConfigurationContext context) throws InitializationException {
    try {
        final ProxyConfiguration proxyConfiguration = ProxyConfiguration.getConfiguration(context);
        final HttpTransportFactory transportFactory = new ProxyAwareTransportFactory(proxyConfiguration);
        googleCredentials = credentialsProviderFactory.getGoogleCredentials(context.getProperties(), transportFactory);
    } catch (IOException e) {
        throw new InitializationException(e);
    }
}
 
Example #5
Source File: TestApp.java    From gcpsamples with Apache License 2.0 4 votes vote down vote up
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);
	}
  }
 
Example #6
Source File: TestApp.java    From gcpsamples with Apache License 2.0 4 votes vote down vote up
public TestApp() {
        try
        {
            
            /*
          JacksonFactory jsonFactory = new JacksonFactory(); 
              
            Authenticator.setDefault(
                new Authenticator() {
                   @Override
                   public PasswordAuthentication getPasswordAuthentication() {
                      return new PasswordAuthentication(
                            "user1", "user1".toCharArray());
                   }
                }
             );                          
            Proxy proxy = new Proxy(Proxy.Type.HTTP, new InetSocketAddress("127.0.0.1", 3128));
            NetHttpTransport mHttpTransport = new NetHttpTransport.Builder().setProxy(proxy).build();
            */
           

            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);



/*
            com.google.api.client.googleapis.auth.oauth2.GoogleCredential credential = com.google.api.client.googleapis.auth.oauth2.GoogleCredential.getApplicationDefault(mHttpTransport,jsonFactory);
            if (credential.createScopedRequired())
                credential = credential.createScoped(Arrays.asList(StorageScopes.DEVSTORAGE_READ_ONLY));

            com.google.api.services.storage.Storage service = new com.google.api.services.storage.Storage.Builder(mHttpTransport, jsonFactory, credential)
                .setApplicationName("oauth client")   
                .build(); 
                
            com.google.api.services.storage.model.Buckets dl = service.buckets().list("mineral-minutia-820").execute();
            for (com.google.api.services.storage.model.Bucket bucket: dl.getItems()) 
                System.out.println(bucket.getName());
*/

            
           // System.setProperty("https.proxyHost", "localhost");
           // System.setProperty("https.proxyPort", "3128");
/*
            Authenticator.setDefault(
                new Authenticator() {
                @Override
                public PasswordAuthentication getPasswordAuthentication() {
                    return new PasswordAuthentication(
                            "user1", "user1".toCharArray());
                }
                }
            );
*/


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

            com.google.auth.oauth2.GoogleCredentials credential = com.google.auth.oauth2.GoogleCredentials.getApplicationDefault(hf);
            if (credential.createScopedRequired())
                credential = credential.createScoped(Arrays.asList("https://www.googleapis.com/auth/devstorage.read_write"));

            TransportOptions options = HttpTransportOptions.newBuilder().setHttpTransportFactory(hf).build();            
            com.google.cloud.storage.Storage storage = com.google.cloud.storage.StorageOptions.newBuilder()
                .setCredentials(credential)
                .setProjectId("mineral-minutia-820")
                .setTransportOptions(options)
                .build().getService();
            
            System.out.println("My buckets:");        
            for (com.google.cloud.storage.Bucket bucket : storage.list().iterateAll()) 
              System.out.println(bucket);              
          
        } 
        catch (Exception ex) {
            System.out.println("Error:  " + ex);
        }
    
    }
 
Example #7
Source File: DefaultCredentialsModule.java    From cloud-trace-java with Apache License 2.0 4 votes vote down vote up
@Override
protected final void configure() {
  requireBinding(HttpTransportFactory.class);
  requireBinding(Key.get(new TypeLiteral<List<String>>() {}, Scopes.class));
}
 
Example #8
Source File: DefaultCredentialsModule.java    From cloud-trace-java with Apache License 2.0 4 votes vote down vote up
@Provides
@Singleton
final Credentials provideCredentials(HttpTransportFactory transport, @Scopes List<String> scopes)
    throws IOException {
  return GoogleCredentials.getApplicationDefault(checkNotNull(transport)).createScoped(scopes);
}
 
Example #9
Source File: ExplicitApplicationDefaultCredentialsStrategy.java    From nifi with Apache License 2.0 4 votes vote down vote up
@Override
public GoogleCredentials getGoogleCredentials(Map<PropertyDescriptor, String> properties, HttpTransportFactory transportFactory) throws IOException {
    return GoogleCredentials.getApplicationDefault(transportFactory);
}
 
Example #10
Source File: ComputeEngineCredentialsStrategy.java    From nifi with Apache License 2.0 4 votes vote down vote up
@Override
public GoogleCredentials getGoogleCredentials(Map<PropertyDescriptor, String> properties, HttpTransportFactory transportFactory) throws IOException {
    return ComputeEngineCredentials.newBuilder()
            .setHttpTransportFactory(transportFactory)
            .build();
}
 
Example #11
Source File: AbstractServiceAccountCredentialsStrategy.java    From nifi with Apache License 2.0 4 votes vote down vote up
@Override
public GoogleCredentials getGoogleCredentials(Map<PropertyDescriptor, String> properties, HttpTransportFactory transportFactory) throws IOException {
        return GoogleCredentials.fromStream(getServiceAccountJson(properties), transportFactory);
}
 
Example #12
Source File: ImplicitApplicationDefaultCredentialsStrategy.java    From nifi with Apache License 2.0 4 votes vote down vote up
@Override
public GoogleCredentials getGoogleCredentials(Map<PropertyDescriptor, String> properties, HttpTransportFactory transportFactory) throws IOException {
    return GoogleCredentials.getApplicationDefault(transportFactory);
}
 
Example #13
Source File: ConnectionParameters.java    From catatumbo with Apache License 2.0 2 votes vote down vote up
/**
 * Returns the HttpTransportFactory.
 * 
 * @return the HttpTransportFactory.
 */
public HttpTransportFactory getHttpTransportFactory() {
  return httpTransportFactory;
}
 
Example #14
Source File: ConnectionParameters.java    From catatumbo with Apache License 2.0 2 votes vote down vote up
/**
 * Sets the HttpTransportFactory.
 * 
 * @param httpTransportFactory
 *          the HttpTransportFactory
 */
public void setHttpTransportFactory(HttpTransportFactory httpTransportFactory) {
  this.httpTransportFactory = httpTransportFactory;
}
 
Example #15
Source File: CredentialsFactory.java    From nifi with Apache License 2.0 2 votes vote down vote up
/**
 * Produces the AuthCredentials according to the given property set and the strategies configured in
 * the factory.
 * @return AuthCredentials
 *
 * @throws IOException if there is an issue accessing the credential files
 */
public GoogleCredentials getGoogleCredentials(final Map<PropertyDescriptor, String> properties, final HttpTransportFactory transportFactory) throws IOException {
    final CredentialsStrategy primaryStrategy = selectPrimaryStrategy(properties);
    return primaryStrategy.getGoogleCredentials(properties, transportFactory);
}
 
Example #16
Source File: CredentialsStrategy.java    From nifi with Apache License 2.0 2 votes vote down vote up
/**
 * Creates an AuthCredentials instance for this strategy, given the properties defined by the user.
 * @param transportFactory Sub-classes should utilize this transport factory
 *                        to support common network related configs such as proxy
 * @throws IOException if the provided credentials cannot be accessed or are invalid
 */
GoogleCredentials getGoogleCredentials(Map<PropertyDescriptor, String> properties, HttpTransportFactory transportFactory) throws IOException;