com.google.api.client.http.HttpTransport Java Examples

The following examples show how to use com.google.api.client.http.HttpTransport. 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: GcloudPubsub.java    From cloud-pubsub-mqtt-proxy with Apache License 2.0 6 votes vote down vote up
/**
 * Constructor that will automatically instantiate a Google Cloud Pub/Sub instance.
 *
 * @throws IOException when the initialization of the Google Cloud Pub/Sub client fails.
 */
public GcloudPubsub() throws IOException {
  if (CLOUD_PUBSUB_PROJECT_ID == null) {
    throw new IllegalStateException(GCLOUD_PUBSUB_PROJECT_ID_NOT_SET_ERROR);
  }
  try {
    serverName = InetAddress.getLocalHost().getCanonicalHostName();
  } catch (UnknownHostException e) {
    throw new IllegalStateException("Unable to retrieve the hostname of the system");
  }
  HttpTransport httpTransport = checkNotNull(Utils.getDefaultTransport());
  JsonFactory jsonFactory = checkNotNull(Utils.getDefaultJsonFactory());
  GoogleCredential credential = GoogleCredential.getApplicationDefault(
      httpTransport, jsonFactory);
  if (credential.createScopedRequired()) {
    credential = credential.createScoped(PubsubScopes.all());
  }
  HttpRequestInitializer initializer =
      new RetryHttpInitializerWrapper(credential);
  pubsub = new Pubsub.Builder(httpTransport, jsonFactory, initializer).build();
  logger.info("Google Cloud Pub/Sub Initialization SUCCESS");
}
 
Example #2
Source File: AbstractGoogleClientRequestTest.java    From google-api-java-client with Apache License 2.0 6 votes vote down vote up
public void testReturnRawInputStream_True() throws Exception {
  HttpTransport transport = new MockHttpTransport() {
    @Override
    public LowLevelHttpRequest buildRequest(final String method, final String url) {
      return new MockLowLevelHttpRequest() {
        @Override
        public LowLevelHttpResponse execute() {
          return new MockLowLevelHttpResponse().setContentEncoding("gzip").setContent(new ByteArrayInputStream(
              BaseEncoding.base64()
                  .decode("H4sIAAAAAAAAAPNIzcnJV3DPz0/PSVVwzskvTVEILskvSkxPVQQA/LySchsAAAA=")));
        }
      };
    }
  };
  MockGoogleClient client = new MockGoogleClient.Builder(transport, ROOT_URL, SERVICE_PATH,
      JSON_OBJECT_PARSER, null).setApplicationName(
      "Test Application").build();
  MockGoogleClientRequest<String> request = new MockGoogleClientRequest<String>(
      client, HttpMethods.GET, URI_TEMPLATE, null, String.class);
  request.setReturnRawInputStream(true);
  InputStream inputStream = request.executeAsInputStream();
  // The response will not be wrapped due to setReturnRawInputStream(true)
  assertTrue(inputStream instanceof ByteArrayInputStream);
}
 
Example #3
Source File: BaseApiServiceTest.java    From connector-sdk with Apache License 2.0 6 votes vote down vote up
@Test
public void testApiServiceWithPrebuiltClient() throws Exception {
  MockLowLevelHttpRequest request = buildRequest(200, new GenericJson());
  HttpTransport transport = new TestingHttpTransport(ImmutableList.of(request));
  TestApi apiClient =
      (TestApi)
          new TestApi.Builder(transport, JSON_FACTORY, null)
              .setApplicationName("bring your own client")
              .build();
  TestApiService apiService =
      new TestApiService.Builder()
          .setService(apiClient)
          .setTransport(transport)
          .setCredentialFactory(scopes -> new MockGoogleCredential.Builder().build())
          .build();
  validateEmptyItem(apiService.get());
  assertThat(
      request.getHeaderValues("user-agent").get(0), containsString("bring your own client"));
}
 
Example #4
Source File: RemoteGoogleDriveConnector.java    From cloudsync with GNU General Public License v2.0 6 votes vote down vote up
public void initService(Handler handler) throws CloudsyncException
{

	if (service != null) return;

	final HttpTransport httpTransport = new NetHttpTransport();
	final JsonFactory jsonFactory = new JacksonFactory();
	service = new Drive.Builder(httpTransport, jsonFactory, null)
		.setApplicationName("Backup")
		.setHttpRequestInitializer(credential)
		.build();
	if (StringUtils.isEmpty(credential.getServiceAccountId())) {
		credential.setExpiresInSeconds(MIN_TOKEN_REFRESH_TIMEOUT);
	}
	try
	{
		refreshCredential();
	}
	catch (IOException e)
	{
		throw new CloudsyncException("couldn't refresh google drive token");
	}
	handler.getRootItem().setRemoteIdentifier(_getBackupFolder().getId());
}
 
Example #5
Source File: AuthorizationFlow.java    From android-oauth-client with Apache License 2.0 6 votes vote down vote up
/**
 * @param method method of presenting the access token to the resource
 *            server (for example
 *            {@link BearerToken#authorizationHeaderAccessMethod})
 * @param transport HTTP transport
 * @param jsonFactory JSON factory
 * @param tokenServerUrl token server URL
 * @param clientAuthentication client authentication or {@code null} for
 *            none (see
 *            {@link TokenRequest#setClientAuthentication(HttpExecuteInterceptor)}
 *            )
 * @param clientId client identifier
 * @param authorizationServerEncodedUrl authorization server encoded URL
 */
public Builder(AccessMethod method,
        HttpTransport transport,
        JsonFactory jsonFactory,
        GenericUrl tokenServerUrl,
        HttpExecuteInterceptor clientAuthentication,
        String clientId,
        String authorizationServerEncodedUrl) {
    super(method,
            transport,
            jsonFactory,
            tokenServerUrl,
            clientAuthentication,
            clientId,
            authorizationServerEncodedUrl);
}
 
Example #6
Source File: AuthorizationFlow.java    From mirror with Apache License 2.0 6 votes vote down vote up
/**
 * @param method                        method of presenting the access token to the resource
 *                                      server (for example
 *                                      {@link BearerToken#authorizationHeaderAccessMethod})
 * @param transport                     HTTP transport
 * @param jsonFactory                   JSON factory
 * @param tokenServerUrl                token server URL
 * @param clientAuthentication          client authentication or {@code null} for
 *                                      none (see
 *                                      {@link TokenRequest#setClientAuthentication(HttpExecuteInterceptor)}
 *                                      )
 * @param clientId                      client identifier
 * @param authorizationServerEncodedUrl authorization server encoded URL
 */
public Builder(AccessMethod method,
               HttpTransport transport,
               JsonFactory jsonFactory,
               GenericUrl tokenServerUrl,
               HttpExecuteInterceptor clientAuthentication,
               String clientId,
               String authorizationServerEncodedUrl) {
    super(method,
            transport,
            jsonFactory,
            tokenServerUrl,
            clientAuthentication,
            clientId,
            authorizationServerEncodedUrl);
}
 
Example #7
Source File: OAuth1DataGenerator.java    From data-transfer-project with Apache License 2.0 6 votes vote down vote up
OAuth1DataGenerator(
    OAuth1Config config,
    AppCredentials appCredentials,
    HttpTransport httpTransport,
    String datatype,
    AuthMode mode,
    Monitor monitor) {
  this.config = config;
  this.monitor = monitor;
  validateConfig();

  this.clientId = appCredentials.getKey();
  this.clientSecret = appCredentials.getSecret();
  this.httpTransport = httpTransport;
  this.scope =
      mode == AuthMode.EXPORT
          ? config.getExportScopes().get(datatype)
          : config.getImportScopes().get(datatype);
}
 
Example #8
Source File: LocalFileCredentialFactoryTest.java    From connector-sdk with Apache License 2.0 6 votes vote down vote up
@Test
public void testfromConfigurationJsonKey() throws Exception {
  File tmpfile = temporaryFolder.newFile("testfromConfiguration" + SERVICE_ACCOUNT_FILE_JSON);
  createConfig(tmpfile.getAbsolutePath(), "");
  GoogleCredential mockCredential = new MockGoogleCredential.Builder().build();
  List<String> scopes = Arrays.asList("profile");
  when(mockCredentialHelper.getJsonCredential(
      eq(tmpfile.toPath()),
      any(HttpTransport.class),
      any(JsonFactory.class),
      any(HttpRequestInitializer.class),
      eq(scopes)))
      .thenReturn(mockCredential);
  LocalFileCredentialFactory credentialFactory = LocalFileCredentialFactory.fromConfiguration();
  assertEquals(mockCredential, credentialFactory.getCredential(scopes));
}
 
Example #9
Source File: LocalFileCredentialFactoryTest.java    From connector-sdk with Apache License 2.0 6 votes vote down vote up
@Test
public void testGetCredentialP12() throws Exception {
  File tmpfile = temporaryFolder.newFile(SERVICE_ACCOUNT_FILE_P12);
  GoogleCredential mockCredential = new MockGoogleCredential.Builder().build();
  List<String> scopes = Arrays.asList("profile, calendar");
  when(mockCredentialHelper.getP12Credential(
      eq("ServiceAccount"),
      eq(tmpfile.toPath()),
      any(HttpTransport.class),
      any(JsonFactory.class),
      any(HttpRequestInitializer.class),
      eq(scopes)))
      .thenReturn(mockCredential);
  LocalFileCredentialFactory credentialFactory =
      new LocalFileCredentialFactory.Builder()
          .setServiceAccountKeyFilePath(tmpfile.getAbsolutePath())
          .setServiceAccountId("ServiceAccount")
          .build();
  assertEquals(mockCredential, credentialFactory.getCredential(scopes));
}
 
Example #10
Source File: CredentialStore.java    From jdrivesync with Apache License 2.0 6 votes vote down vote up
public Optional<Credential> load() {
     Properties properties = new Properties();
     try {
File file = getAuthenticationFile(options);
         if(!file.exists() || !file.canRead()) {
             LOGGER.log(Level.FINE, "Cannot find or read properties file. Returning empty credentials.");
             return Optional.empty();
         }
         properties.load(new FileReader(file));
         HttpTransport httpTransport = new NetHttpTransport();
         JsonFactory jsonFactory = new JacksonFactory();
         GoogleCredential credential = new GoogleCredential.Builder().setJsonFactory(jsonFactory)
                 .setTransport(httpTransport).setClientSecrets(OAuth2ClientCredentials.CLIENT_ID, OAuth2ClientCredentials.CLIENT_SECRET).build();
         credential.setAccessToken(properties.getProperty(PROP_ACCESS_TOKEN));
         credential.setRefreshToken(properties.getProperty(PROP_REFRESH_TOKEN));
         return Optional.of(credential);
     } catch (IOException e) {
         throw new JDriveSyncException(JDriveSyncException.Reason.IOException, "Failed to load properties file: " + e.getMessage(), e);
     }
 }
 
Example #11
Source File: DataflowPipelineLaunchDelegateTest.java    From google-cloud-eclipse with Apache License 2.0 6 votes vote down vote up
@Before
public void setup() throws Exception {
  when(pipelineOptionsHierarchyFactory.forProject(
          eq(project), eq(MajorVersion.ONE), any(IProgressMonitor.class)))
      .thenReturn(pipelineOptionsHierarchy);

  credential = new GoogleCredential.Builder()
      .setJsonFactory(mock(JsonFactory.class))
      .setTransport(mock(HttpTransport.class))
      .setClientSecrets("clientId", "clientSecret").build();
  credential.setRefreshToken("fake-refresh-token");
  when(loginService.getCredential("[email protected]")).thenReturn(credential);

  when(dependencyManager.getProjectMajorVersion(project)).thenReturn(MajorVersion.ONE);
  dataflowDelegate = new DataflowPipelineLaunchDelegate(javaDelegate,
      pipelineOptionsHierarchyFactory, dependencyManager, workspaceRoot, loginService);

  pipelineArguments.put("accountEmail", "");
  when(configurationWorkingCopy.getAttribute(
      eq(ILaunchManager.ATTR_ENVIRONMENT_VARIABLES), anyMapOf(String.class, String.class)))
      .thenReturn(environmentMap);
}
 
Example #12
Source File: TransferClientCreator.java    From java-docs-samples with Apache License 2.0 6 votes vote down vote up
/**
 * Create a Storage Transfer client using user-supplied credentials and other settings.
 *
 * @param httpTransport a user-supplied HttpTransport
 * @param jsonFactory a user-supplied JsonFactory
 * @param credential a user-supplied Google credential
 * @return a Storage Transfer client
 */
public static Storagetransfer createStorageTransferClient(
    HttpTransport httpTransport, JsonFactory jsonFactory, GoogleCredentials credential) {
  Preconditions.checkNotNull(httpTransport);
  Preconditions.checkNotNull(jsonFactory);
  Preconditions.checkNotNull(credential);

  // In some cases, you need to add the scope explicitly.
  if (credential.createScopedRequired()) {
    credential = credential.createScoped(StoragetransferScopes.all());
  }
  // Please use custom HttpRequestInitializer for automatic
  // retry upon failures. We provide a simple reference
  // implementation in the "Retry Handling" section.
  HttpRequestInitializer initializer = new HttpCredentialsAdapter(credential);
  return new Storagetransfer.Builder(httpTransport, jsonFactory, initializer)
      .setApplicationName("storagetransfer-sample")
      .build();
}
 
Example #13
Source File: DefaultCredentialProvider.java    From google-api-java-client with Apache License 2.0 6 votes vote down vote up
private final GoogleCredential getDefaultCredentialUnsynchronized(
    HttpTransport transport, JsonFactory jsonFactory) throws IOException {
  if (detectedEnvironment == null) {
    detectedEnvironment = detectEnvironment(transport);
  }

  switch (detectedEnvironment) {
    case ENVIRONMENT_VARIABLE:
      return getCredentialUsingEnvironmentVariable(transport, jsonFactory);
    case WELL_KNOWN_FILE:
      return getCredentialUsingWellKnownFile(transport, jsonFactory);
    case APP_ENGINE:
      return getAppEngineCredential(transport, jsonFactory);
    case CLOUD_SHELL:
      return getCloudShellCredential(jsonFactory);
    case COMPUTE_ENGINE:
      return getComputeCredential(transport, jsonFactory);
    default:
      return null;
  }
}
 
Example #14
Source File: LocalFileCredentialFactory.java    From connector-sdk with Apache License 2.0 6 votes vote down vote up
/**
 * Gets {@link GoogleCredential} instance constructed for service account.
 */
@Override
public GoogleCredential getCredential(Collection<String> scopes)
    throws GeneralSecurityException, IOException {

  JsonFactory jsonFactory = JacksonFactory.getDefaultInstance();

  HttpTransport transport = proxy.getHttpTransport();
  if (!isJsonKey) {
    return credentialHelper.getP12Credential(
        serviceAccountId,
        serviceAccountKeyFilePath,
        transport,
        jsonFactory,
        proxy.getHttpRequestInitializer(),
        scopes);
  }
  return credentialHelper.getJsonCredential(
      serviceAccountKeyFilePath,
      transport,
      jsonFactory,
      proxy.getHttpRequestInitializer(),
      scopes);
}
 
Example #15
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 #16
Source File: InjectorUtils.java    From deployment-examples with MIT License 6 votes vote down vote up
/** Builds a new Pubsub client and returns it. */
public static Pubsub getClient(final HttpTransport httpTransport, final JsonFactory jsonFactory)
    throws IOException {
  checkNotNull(httpTransport);
  checkNotNull(jsonFactory);
  GoogleCredential credential =
      GoogleCredential.getApplicationDefault(httpTransport, jsonFactory);
  if (credential.createScopedRequired()) {
    credential = credential.createScoped(PubsubScopes.all());
  }
  if (credential.getClientAuthentication() != null) {
    System.out.println(
        "\n***Warning! You are not using service account credentials to "
            + "authenticate.\nYou need to use service account credentials for this example,"
            + "\nsince user-level credentials do not have enough pubsub quota,\nand so you will run "
            + "out of PubSub quota very quickly.\nSee "
            + "https://developers.google.com/identity/protocols/application-default-credentials.");
    System.exit(1);
  }
  HttpRequestInitializer initializer = new RetryHttpInitializerWrapper(credential);
  return new Pubsub.Builder(httpTransport, jsonFactory, initializer)
      .setApplicationName(APP_NAME)
      .build();
}
 
Example #17
Source File: GoogleAuth.java    From liberty-bikes with Eclipse Public License 1.0 6 votes vote down vote up
@GET
public Response getGoogleCallbackURL(@Context HttpServletRequest request) {

    JsonFactory jsonFactory = new JacksonFactory();
    HttpTransport httpTransport = new NetHttpTransport();

    GoogleAuthorizationCodeFlow flow = new GoogleAuthorizationCodeFlow(httpTransport, jsonFactory, config.google_key, config.google_secret, Arrays
                    .asList("https://www.googleapis.com/auth/userinfo.profile", "https://www.googleapis.com/auth/userinfo.email"));

    try {
        // google will tell the users browser to go to this address once
        // they are done authing.
        String callbackURL = config.authUrl + "/GoogleCallback";
        request.getSession().setAttribute("google", flow);

        String authorizationUrl = flow.newAuthorizationUrl().setRedirectUri(callbackURL).build();

        // send the user to google to be authenticated.
        return Response.temporaryRedirect(new URI(authorizationUrl)).build();
    } catch (Exception e) {
        e.printStackTrace();
        return Response.status(500).build();
    }
}
 
Example #18
Source File: CoreSocketFactory.java    From cloud-sql-jdbc-socket-factory with Apache License 2.0 6 votes vote down vote up
private static SQLAdmin createAdminApiClient(HttpRequestInitializer requestInitializer) {
  HttpTransport httpTransport;
  try {
    httpTransport = GoogleNetHttpTransport.newTrustedTransport();
  } catch (GeneralSecurityException | IOException err) {
    throw new RuntimeException("Unable to initialize HTTP transport", err);
  }

  String rootUrl = System.getProperty(API_ROOT_URL_PROPERTY);
  String servicePath = System.getProperty(API_SERVICE_PATH_PROPERTY);

  JsonFactory jsonFactory = JacksonFactory.getDefaultInstance();
  SQLAdmin.Builder adminApiBuilder =
      new Builder(httpTransport, jsonFactory, requestInitializer)
          .setApplicationName(getUserAgents());
  if (rootUrl != null) {
    logTestPropertyWarning(API_ROOT_URL_PROPERTY);
    adminApiBuilder.setRootUrl(rootUrl);
  }
  if (servicePath != null) {
    logTestPropertyWarning(API_SERVICE_PATH_PROPERTY);
    adminApiBuilder.setServicePath(servicePath);
  }
  return adminApiBuilder.build();
}
 
Example #19
Source File: AbstractGoogleJsonClientTest.java    From google-api-java-client with Apache License 2.0 5 votes vote down vote up
public void testExecuteUnparsed_error() throws Exception {
  HttpTransport transport = new MockHttpTransport() {
      @Override
    public LowLevelHttpRequest buildRequest(String name, String url) {
      return new MockLowLevelHttpRequest() {
          @Override
        public LowLevelHttpResponse execute() {
          MockLowLevelHttpResponse result = new MockLowLevelHttpResponse();
          result.setStatusCode(HttpStatusCodes.STATUS_CODE_UNAUTHORIZED);
          result.setContentType(Json.MEDIA_TYPE);
          result.setContent("{\"error\":{\"code\":401,\"errors\":[{\"domain\":\"global\","
              + "\"location\":\"Authorization\",\"locationType\":\"header\","
              + "\"message\":\"me\",\"reason\":\"authError\"}],\"message\":\"me\"}}");
          return result;
        }
      };
    }
  };
  JsonFactory jsonFactory = new JacksonFactory();
  MockGoogleJsonClient client = new MockGoogleJsonClient.Builder(
      transport, jsonFactory, HttpTesting.SIMPLE_URL, "", null, false).setApplicationName(
      "Test Application").build();
  MockGoogleJsonClientRequest<String> request =
      new MockGoogleJsonClientRequest<String>(client, "GET", "foo", null, String.class);
  try {
    request.executeUnparsed();
    fail("expected " + GoogleJsonResponseException.class);
  } catch (GoogleJsonResponseException e) {
    // expected
    GoogleJsonError details = e.getDetails();
    assertEquals("me", details.getMessage());
    assertEquals("me", details.getErrors().get(0).getMessage());
  }
}
 
Example #20
Source File: GoogleJsonResponseExceptionTest.java    From google-api-java-client with Apache License 2.0 5 votes vote down vote up
public void testFrom_withDetails() throws Exception {
  HttpTransport transport = new ErrorTransport();
  HttpRequest request =
      transport.createRequestFactory().buildGetRequest(HttpTesting.SIMPLE_GENERIC_URL);
  request.setThrowExceptionOnExecuteError(false);
  HttpResponse response = request.execute();
  GoogleJsonResponseException ge =
      GoogleJsonResponseException.from(GoogleJsonErrorTest.FACTORY, response);
  assertEquals(GoogleJsonErrorTest.ERROR, GoogleJsonErrorTest.FACTORY.toString(ge.getDetails()));
  assertTrue(
      ge.getMessage(), ge.getMessage().startsWith("403" + StringUtils.LINE_SEPARATOR + "{"));
}
 
Example #21
Source File: FirebaseInstanceId.java    From firebase-admin-java with Apache License 2.0 5 votes vote down vote up
private FirebaseInstanceId(FirebaseApp app) {
  HttpTransport httpTransport = app.getOptions().getHttpTransport();
  this.app = app;
  this.requestFactory = httpTransport.createRequestFactory(new FirebaseRequestInitializer(app));
  this.jsonFactory = app.getOptions().getJsonFactory();
  this.projectId = ImplFirebaseTrampolines.getProjectId(app);
  checkArgument(!Strings.isNullOrEmpty(projectId),
      "Project ID is required to access instance ID service. Use a service account credential or "
          + "set the project ID explicitly via FirebaseOptions. Alternatively you can also "
          + "set the project ID via the GOOGLE_CLOUD_PROJECT environment variable.");
}
 
Example #22
Source File: GoogleCredential.java    From google-api-java-client with Apache License 2.0 5 votes vote down vote up
@Beta
private static GoogleCredential fromStreamServiceAccount(GenericJson fileContents,
    HttpTransport transport, JsonFactory jsonFactory) throws IOException {
  String clientId = (String) fileContents.get("client_id");
  String clientEmail = (String) fileContents.get("client_email");
  String privateKeyPem = (String) fileContents.get("private_key");
  String privateKeyId = (String) fileContents.get("private_key_id");
  if (clientId == null || clientEmail == null || privateKeyPem == null
      || privateKeyId == null) {
    throw new IOException("Error reading service account credential from stream, "
        + "expecting  'client_id', 'client_email', 'private_key' and 'private_key_id'.");
  }

  PrivateKey privateKey = privateKeyFromPkcs8(privateKeyPem);

  Collection<String> emptyScopes = Collections.emptyList();

  Builder credentialBuilder = new GoogleCredential.Builder()
      .setTransport(transport)
      .setJsonFactory(jsonFactory)
      .setServiceAccountId(clientEmail)
      .setServiceAccountScopes(emptyScopes)
      .setServiceAccountPrivateKey(privateKey)
      .setServiceAccountPrivateKeyId(privateKeyId);
  String tokenUri = (String) fileContents.get("token_uri");
  if (tokenUri != null) {
    credentialBuilder.setTokenServerEncodedUrl(tokenUri);
  }
  String projectId = (String) fileContents.get("project_id");
  if (projectId != null) {
    credentialBuilder.setServiceAccountProjectId(projectId);
  }

  // Don't do a refresh at this point, as it will always fail before the scopes are added.
  return credentialBuilder.build();
}
 
Example #23
Source File: FirebaseTokenVerifierImplTest.java    From firebase-admin-java with Apache License 2.0 5 votes vote down vote up
private GooglePublicKeysManager newPublicKeysManager(String certificate) {
  String serviceAccountCertificates =
      String.format("{\"%s\" : \"%s\"}", TestTokenFactory.PRIVATE_KEY_ID, certificate);
  HttpTransport transport = new MockHttpTransport.Builder()
      .setLowLevelHttpResponse(
          new MockLowLevelHttpResponse().setContent(serviceAccountCertificates))
      .build();
  return newPublicKeysManager(transport);
}
 
Example #24
Source File: ClientConfig.java    From mutual-tls-ssl with Apache License 2.0 5 votes vote down vote up
@Bean
public HttpTransport googleHttpClient(@Autowired(required = false) SSLFactory sslFactory) {
    if (nonNull(sslFactory)) {
        return new NetHttpTransport.Builder()
                .setSslSocketFactory(sslFactory.getSslContext().getSocketFactory())
                .setHostnameVerifier(sslFactory.getHostnameVerifier())
                .build();
    } else {
        return new NetHttpTransport();
    }
}
 
Example #25
Source File: PayrollAuApi.java    From Xero-Java with MIT License 5 votes vote down vote up
public HttpResponse getLeaveApplicationForHttpResponse(String accessToken,  String xeroTenantId,  UUID leaveApplicationId) throws IOException {
    // verify the required parameter 'xeroTenantId' is set
    if (xeroTenantId == null) {
        throw new IllegalArgumentException("Missing the required parameter 'xeroTenantId' when calling getLeaveApplication");
    }// verify the required parameter 'leaveApplicationId' is set
    if (leaveApplicationId == null) {
        throw new IllegalArgumentException("Missing the required parameter 'leaveApplicationId' when calling getLeaveApplication");
    }
    if (accessToken == null) {
        throw new IllegalArgumentException("Missing the required parameter 'accessToken' when calling getLeaveApplication");
    }
    HttpHeaders headers = new HttpHeaders();
    headers.set("Xero-Tenant-Id", xeroTenantId);
    headers.setAccept("application/json"); 
    headers.setUserAgent(this.getUserAgent()); 
    // create a map of path variables
    final Map<String, Object> uriVariables = new HashMap<String, Object>();
    uriVariables.put("LeaveApplicationId", leaveApplicationId);

    UriBuilder uriBuilder = UriBuilder.fromUri(apiClient.getBasePath() + "/LeaveApplications/{LeaveApplicationId}");
    String url = uriBuilder.buildFromMap(uriVariables).toString();
    GenericUrl genericUrl = new GenericUrl(url);
    if (logger.isDebugEnabled()) {
        logger.debug("GET " + genericUrl.toString());
    }
    
    HttpContent content = null;
    Credential credential = new Credential(BearerToken.authorizationHeaderAccessMethod()).setAccessToken(accessToken);
    HttpTransport transport = apiClient.getHttpTransport();       
    HttpRequestFactory requestFactory = transport.createRequestFactory(credential);
    return requestFactory.buildRequest(HttpMethods.GET, genericUrl, content).setHeaders(headers)
        .setConnectTimeout(apiClient.getConnectionTimeout())
        .setReadTimeout(apiClient.getReadTimeout()).execute();  
}
 
Example #26
Source File: BaragonServiceModule.java    From Baragon with Apache License 2.0 5 votes vote down vote up
@Provides
@Singleton
@Named(GOOGLE_CLOUD_COMPUTE_SERVICE)
public Optional<Compute> provideComputeService(BaragonConfiguration config) throws Exception {
  if (!config.getGoogleCloudConfiguration().isEnabled()) {
    return Optional.absent();
  }
  HttpTransport httpTransport = GoogleNetHttpTransport.newTrustedTransport();
  JsonFactory jsonFactory = JacksonFactory.getDefaultInstance();

  GoogleCredential credential = null;

  if (config.getGoogleCloudConfiguration().getGoogleCredentialsFile() != null) {
    File credentialsFile = new File(config.getGoogleCloudConfiguration().getGoogleCredentialsFile());
    credential = GoogleCredential.fromStream(
        new FileInputStream(credentialsFile)
    );
  } else if (config.getGoogleCloudConfiguration().getGoogleCredentials() != null) {
    credential = GoogleCredential.fromStream(
        new ByteArrayInputStream(config.getGoogleCloudConfiguration().getGoogleCredentials().getBytes("UTF-8"))
    );
  } else {
    throw new RuntimeException("Must specify googleCloudCredentials or googleCloudCredentialsFile when using google cloud api");
  }

  if (credential.createScopedRequired()) {
    credential =
        credential.createScoped(Collections.singletonList("https://www.googleapis.com/auth/cloud-platform"));
  }

  return Optional.of(new Compute.Builder(httpTransport, jsonFactory, credential)
      .setApplicationName("BaragonService")
      .build());
}
 
Example #27
Source File: GcsClientImpl.java    From exhibitor with Apache License 2.0 5 votes vote down vote up
@Override
public Storage getClient() throws Exception {
    Credential credential = authorize();
    HttpTransport httpTransport = GoogleNetHttpTransport.newTrustedTransport();
    return new Storage.Builder(httpTransport, JSON_FACTORY, credential)
            .setApplicationName(APPLICATION_NAME).build();
}
 
Example #28
Source File: GmailService.java    From mail-importer with Apache License 2.0 5 votes vote down vote up
@Inject
GmailService(
    User user,
    Credential credential,
    Provider<BackOff> backOffProvider,
    HttpTransport httpTransport,
    JsonFactory jsonFactory) {
  this.credential = credential;
  this.backOffProvider = backOffProvider;
  this.httpTransport = httpTransport;
  this.jsonFactory = jsonFactory;
}
 
Example #29
Source File: ApiClient.java    From openapi-generator with Apache License 2.0 5 votes vote down vote up
public ApiClient(
    String basePath,
    HttpTransport httpTransport,
    HttpRequestInitializer initializer,
    ObjectMapper objectMapper
) {
    this.basePath = basePath == null ? defaultBasePath : (
        basePath.endsWith("/") ? basePath.substring(0, basePath.length() - 1) : basePath
    );
    this.httpRequestFactory = (httpTransport == null ? Utils.getDefaultTransport() : httpTransport).createRequestFactory(initializer);
    this.objectMapper = (objectMapper == null ? createDefaultObjectMapper() : objectMapper);
}
 
Example #30
Source File: IdentityApi.java    From Xero-Java with MIT License 5 votes vote down vote up
public HttpResponse getConnectionsForHttpResponse(String accessToken,  UUID authEventId) throws IOException {
    
    if (accessToken == null) {
        throw new IllegalArgumentException("Missing the required parameter 'accessToken' when calling getConnections");
    }
    HttpHeaders headers = new HttpHeaders();
    headers.setAccept("application/json"); 
    headers.setUserAgent(this.getUserAgent());
    UriBuilder uriBuilder = UriBuilder.fromUri(apiClient.getBasePath() + "/connections");
    if (authEventId != null) {
        String key = "authEventId";
        Object value = authEventId;
        if (value instanceof Collection) {
            uriBuilder = uriBuilder.queryParam(key, ((Collection) value).toArray());
        } else if (value instanceof Object[]) {
            uriBuilder = uriBuilder.queryParam(key, (Object[]) value);
        } else {
            uriBuilder = uriBuilder.queryParam(key, value);
        }
    }
    String url = uriBuilder.build().toString();
    GenericUrl genericUrl = new GenericUrl(url);
    if (logger.isDebugEnabled()) {
        logger.debug("GET " + genericUrl.toString());
    }
    
    HttpContent content = null;
    Credential credential = new Credential(BearerToken.authorizationHeaderAccessMethod()).setAccessToken(accessToken);
    HttpTransport transport = apiClient.getHttpTransport();       
    HttpRequestFactory requestFactory = transport.createRequestFactory(credential);
    return requestFactory.buildRequest(HttpMethods.GET, genericUrl, content).setHeaders(headers)
        .setConnectTimeout(apiClient.getConnectionTimeout())
        .setReadTimeout(apiClient.getReadTimeout()).execute();  
}