Java Code Examples for com.google.api.client.googleapis.auth.oauth2.GoogleCredential#setAccessToken()
The following examples show how to use
com.google.api.client.googleapis.auth.oauth2.GoogleCredential#setAccessToken() .
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: CredentialStore.java From jdrivesync with Apache License 2.0 | 6 votes |
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 2
Source File: AdWordsAxisSoapIntegrationTest.java From googleads-java-lib with Apache License 2.0 | 6 votes |
/** * Tests making an Axis AdWords API call with OAuth2 and compression enabled. */ @Test public void testGoldenSoap_oauth2() throws Exception { testHttpServer.setMockResponseBody(SoapResponseXmlProvider.getTestSoapResponse(API_VERSION)); GoogleCredential credential = new GoogleCredential.Builder() .setTransport(new NetHttpTransport()).setJsonFactory(new JacksonFactory()).build(); credential.setAccessToken("TEST_ACCESS_TOKEN"); AdWordsSession session = new AdWordsSession.Builder() .withUserAgent("TEST_APP") .withOAuth2Credential(credential) .withEndpoint(testHttpServer.getServerUrl()) .withDeveloperToken("TEST_DEVELOPER_TOKEN") .withClientCustomerId("TEST_CLIENT_CUSTOMER_ID") .build(); testBudgetServiceMutateRequest(session); assertEquals("Bearer TEST_ACCESS_TOKEN", testHttpServer.getLastAuthorizationHttpHeader()); }
Example 3
Source File: CredentialStore.java From jdrivesync with Apache License 2.0 | 6 votes |
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 4
Source File: AdManagerAxisSoapIntegrationTest.java From googleads-java-lib with Apache License 2.0 | 5 votes |
/** Tests making a Axis Ad Manager API call with OAuth2. */ @Test public void testGoldenSoap_oauth2() throws Exception { testHttpServer.setMockResponseBody(SoapResponseXmlProvider.getTestSoapResponse(API_VERSION)); GoogleCredential credential = new GoogleCredential.Builder() .setTransport(new NetHttpTransport()) .setJsonFactory(new JacksonFactory()) .build(); credential.setAccessToken("TEST_ACCESS_TOKEN"); AdManagerSession session = new AdManagerSession.Builder() .withApplicationName("TEST_APP") .withOAuth2Credential(credential) .withEndpoint(testHttpServer.getServerUrl()) .withNetworkCode("TEST_NETWORK_CODE") .build(); CompanyServiceInterface companyService = new AdManagerServices().get(session, CompanyServiceInterface.class); Company[] companies = companyService.createCompanies(new Company[] {new Company()}); assertEquals(1234L, companies[0].getId().longValue()); XMLAssert.assertXMLEqual( SoapRequestXmlProvider.getOAuth2SoapRequest(API_VERSION), testHttpServer.getLastRequestBody()); assertFalse( "Did not request compression but request was compressed", testHttpServer.wasLastRequestBodyCompressed()); assertEquals("Bearer TEST_ACCESS_TOKEN", testHttpServer.getLastAuthorizationHttpHeader()); }
Example 5
Source File: GSpreadFeedProcessor.java From micro-integrator with Apache License 2.0 | 5 votes |
/** * helper method to refresh the access token and authenticate * * @throws Exception */ private void refreshAndAuthenticate() throws Exception { GoogleCredential credential = getBaseCredential(); credential.setAccessToken(this.accessToken); credential.setRefreshToken(this.refreshToken); credential.refreshToken(); this.accessToken = credential.getAccessToken(); this.service.setOAuth2Credentials(credential); }
Example 6
Source File: AdManagerJaxWsSoapTimeoutIntegrationTest.java From googleads-java-lib with Apache License 2.0 | 5 votes |
/** Tests that the request timeout in ads.properties is enforced. */ @Test public void testRequestTimeoutEnforced() throws Exception { testHttpServer.setMockResponseBody(SoapResponseXmlProvider.getTestSoapResponse(API_VERSION)); testHttpServer.setDelay(200); GoogleCredential credential = new GoogleCredential.Builder() .setTransport(new NetHttpTransport()) .setJsonFactory(new JacksonFactory()) .build(); credential.setAccessToken("TEST_ACCESS_TOKEN"); AdManagerSession session = new AdManagerSession.Builder() .withApplicationName("TEST_APP") .withOAuth2Credential(credential) .withEndpoint(testHttpServer.getServerUrl()) .withNetworkCode("TEST_NETWORK_CODE") .build(); CompanyServiceInterface companyService = new AdManagerServices().get(session, CompanyServiceInterface.class); thrown.expect(WebServiceException.class); thrown.expectMessage("Read timed out"); companyService.createCompanies(Lists.newArrayList(new Company())); }
Example 7
Source File: AdManagerJaxWsSoapCompressionIntegrationTest.java From googleads-java-lib with Apache License 2.0 | 5 votes |
/** Tests making a JAX-WS Ad Manager API call with OAuth2 and compression enabled. */ @Test public void testGoldenSoap_oauth2() throws Exception { testHttpServer.setMockResponseBody(SoapResponseXmlProvider.getTestSoapResponse(API_VERSION)); GoogleCredential credential = new GoogleCredential.Builder() .setTransport(new NetHttpTransport()) .setJsonFactory(new JacksonFactory()) .build(); credential.setAccessToken("TEST_ACCESS_TOKEN"); AdManagerSession session = new AdManagerSession.Builder() .withApplicationName("TEST_APP") .withOAuth2Credential(credential) .withEndpoint(testHttpServer.getServerUrl()) .withNetworkCode("TEST_NETWORK_CODE") .build(); CompanyServiceInterface companyService = new AdManagerServices().get(session, CompanyServiceInterface.class); List<Company> companies = companyService.createCompanies(Lists.newArrayList(new Company())); assertEquals(1234L, companies.get(0).getId().longValue()); assertTrue( "Compression was enabled but the last request body was not compressed", testHttpServer.wasLastRequestBodyCompressed()); XMLAssert.assertXMLEqual( SoapRequestXmlProvider.getOAuth2SoapRequest(API_VERSION), testHttpServer.getLastRequestBody()); assertEquals("Bearer TEST_ACCESS_TOKEN", testHttpServer.getLastAuthorizationHttpHeader()); }
Example 8
Source File: AdManagerJaxWsSoapIntegrationTest.java From googleads-java-lib with Apache License 2.0 | 5 votes |
/** Tests making a JAX-WS Ad Manager API call with OAuth2. */ @Test public void testGoldenSoap_oauth2() throws Exception { testHttpServer.setMockResponseBody(SoapResponseXmlProvider.getTestSoapResponse(API_VERSION)); GoogleCredential credential = new GoogleCredential.Builder() .setTransport(new NetHttpTransport()) .setJsonFactory(new JacksonFactory()) .build(); credential.setAccessToken("TEST_ACCESS_TOKEN"); AdManagerSession session = new AdManagerSession.Builder() .withApplicationName("TEST_APP") .withOAuth2Credential(credential) .withEndpoint(testHttpServer.getServerUrl()) .withNetworkCode("TEST_NETWORK_CODE") .build(); CompanyServiceInterface companyService = new AdManagerServices().get(session, CompanyServiceInterface.class); List<Company> companies = companyService.createCompanies(Lists.newArrayList(new Company())); assertEquals(1234L, companies.get(0).getId().longValue()); XMLAssert.assertXMLEqual( SoapRequestXmlProvider.getOAuth2SoapRequest(API_VERSION), testHttpServer.getLastRequestBody()); assertFalse( "Did not request compression but request was compressed", testHttpServer.wasLastRequestBodyCompressed()); assertEquals("Bearer TEST_ACCESS_TOKEN", testHttpServer.getLastAuthorizationHttpHeader()); }
Example 9
Source File: AdWordsJaxWsSoapTimeoutIntegrationTest.java From googleads-java-lib with Apache License 2.0 | 5 votes |
/** * Tests that the request timeout in ads.properties is enforced. */ @Test public void testRequestTimeoutEnforced() throws Exception { testHttpServer.setMockResponseBody(SoapResponseXmlProvider.getTestSoapResponse(API_VERSION)); testHttpServer.setDelay(200L); GoogleCredential credential = new GoogleCredential.Builder().setTransport( new NetHttpTransport()).setJsonFactory(new JacksonFactory()).build(); credential.setAccessToken("TEST_ACCESS_TOKEN"); AdWordsSession session = new AdWordsSession.Builder() .withUserAgent("TEST_APP") .withOAuth2Credential(credential) .withEndpoint(testHttpServer.getServerUrl()) .withDeveloperToken("TEST_DEVELOPER_TOKEN") .withClientCustomerId("TEST_CLIENT_CUSTOMER_ID") .build(); BudgetServiceInterface budgetService = new AdWordsServices().get(session, BudgetServiceInterface.class); Budget budget = new Budget(); budget.setName("Test Budget Name"); Money money = new Money(); money.setMicroAmount(50000000L); budget.setAmount(money); budget.setDeliveryMethod(BudgetBudgetDeliveryMethod.STANDARD); BudgetOperation operation = new BudgetOperation(); operation.setOperand(budget); operation.setOperator(Operator.ADD); thrown.expect(WebServiceException.class); thrown.expectMessage("Read timed out"); budgetService.mutate(Lists.newArrayList(operation)); }
Example 10
Source File: AdManagerAxisSoapCompressionIntegrationTest.java From googleads-java-lib with Apache License 2.0 | 5 votes |
/** Tests making a Axis Ad Manager API call with OAuth2 and compression enabled. */ @Test public void testGoldenSoap_oauth2() throws Exception { testHttpServer.setMockResponseBody(SoapResponseXmlProvider.getTestSoapResponse(API_VERSION)); GoogleCredential credential = new GoogleCredential.Builder() .setTransport(new NetHttpTransport()) .setJsonFactory(new JacksonFactory()) .build(); credential.setAccessToken("TEST_ACCESS_TOKEN"); AdManagerSession session = new AdManagerSession.Builder() .withApplicationName("TEST_APP") .withOAuth2Credential(credential) .withEndpoint(testHttpServer.getServerUrl()) .withNetworkCode("TEST_NETWORK_CODE") .build(); CompanyServiceInterface companyService = new AdManagerServices().get(session, CompanyServiceInterface.class); Company[] companies = companyService.createCompanies(new Company[] {new Company()}); assertEquals(1234L, companies[0].getId().longValue()); assertTrue( "Compression was enabled but the last request body was not compressed", testHttpServer.wasLastRequestBodyCompressed()); XMLAssert.assertXMLEqual( SoapRequestXmlProvider.getOAuth2SoapRequest(API_VERSION), testHttpServer.getLastRequestBody()); assertEquals("Bearer TEST_ACCESS_TOKEN", testHttpServer.getLastAuthorizationHttpHeader()); }
Example 11
Source File: GcpIamAuthenticationUnitTests.java From spring-vault with Apache License 2.0 | 5 votes |
@Test void shouldLogin() { MockLowLevelHttpResponse response = new MockLowLevelHttpResponse(); response.setStatusCode(200); response.setContent("{\"keyId\":\"keyid\", \"signedJwt\":\"my-jwt\"}"); this.mockHttpTransport = new MockHttpTransport.Builder().setLowLevelHttpResponse(response).build(); this.mockRest.expect(requestTo("/auth/gcp/login")).andExpect(method(HttpMethod.POST)) .andExpect(jsonPath("$.role").value("dev-role")).andExpect(jsonPath("$.jwt").value("my-jwt")) .andRespond(withSuccess().contentType(MediaType.APPLICATION_JSON).body( "{" + "\"auth\":{\"client_token\":\"my-token\", \"renewable\": true, \"lease_duration\": 10}" + "}")); PrivateKey privateKeyMock = mock(PrivateKey.class); GoogleCredential credential = new Builder().setServiceAccountId("hello@world") .setServiceAccountProjectId("foobar").setServiceAccountPrivateKey(privateKeyMock) .setServiceAccountPrivateKeyId("key-id").build(); credential.setAccessToken("foobar"); GcpIamAuthenticationOptions options = GcpIamAuthenticationOptions.builder().role("dev-role") .credential(credential).build(); GcpIamAuthentication authentication = new GcpIamAuthentication(options, this.restTemplate, this.mockHttpTransport); VaultToken login = authentication.login(); assertThat(login).isInstanceOf(LoginToken.class); assertThat(login.getToken()).isEqualTo("my-token"); LoginToken loginToken = (LoginToken) login; assertThat(loginToken.isRenewable()).isTrue(); assertThat(loginToken.getLeaseDuration()).isEqualTo(Duration.ofSeconds(10)); }
Example 12
Source File: CalendarAuth.java From DisCal-Discord-Bot with GNU Lesser General Public License v3.0 | 5 votes |
private static Credential authorize(GuildSettings g) throws Exception { if (g.getEncryptedAccessToken().equalsIgnoreCase("N/a")) throw new IllegalAccessException("Guild does not have proper access token!"); AESEncryption encryption = new AESEncryption(g); String accessToken = Authorization.getAuth().requestNewAccessToken(g, encryption); GoogleCredential credential = new GoogleCredential(); credential.setAccessToken(accessToken); return credential; }
Example 13
Source File: TestServlet.java From gcpsamples with Apache License 2.0 | 5 votes |
public void doGet(HttpServletRequest req, HttpServletResponse resp) throws IOException { resp.setContentType("text/plain"); resp.getWriter().println("Hello, world"); HttpTransport httpTransport = new UrlFetchTransport(); JacksonFactory jsonFactory = new JacksonFactory(); AppIdentityService appIdentity = AppIdentityServiceFactory.getAppIdentityService(); AppIdentityService.GetAccessTokenResult accessToken = appIdentity.getAccessToken(Arrays.asList(Oauth2Scopes.USERINFO_EMAIL)); GoogleCredential credential = new GoogleCredential.Builder() .setTransport(httpTransport) .setJsonFactory(jsonFactory).build(); credential.setAccessToken(accessToken.getAccessToken()); Oauth2 service = new Oauth2.Builder(httpTransport, jsonFactory, credential) .setApplicationName("oauth client").build(); Userinfoplus ui = service.userinfo().get().execute(); resp.getWriter().println(ui.getEmail()); // Using Google Cloud APIs Storage storage_service = StorageOptions.newBuilder() .build() .getService(); for (Bucket b : storage_service.list().iterateAll()){ System.out.println(b); } }
Example 14
Source File: CalendarAuth.java From DisCal-Discord-Bot with GNU Lesser General Public License v3.0 | 5 votes |
private static Credential authorize(GuildSettings g) throws Exception { if (g.getEncryptedAccessToken().equalsIgnoreCase("N/a")) throw new IllegalAccessException("Guild does not have proper access token!"); AESEncryption encryption = new AESEncryption(g); String accessToken = Authorization.getAuth().requestNewAccessToken(g, encryption); GoogleCredential credential = new GoogleCredential(); credential.setAccessToken(accessToken); return credential; }
Example 15
Source File: CredentialHelperTest.java From google-cloud-eclipse with Apache License 2.0 | 5 votes |
private static Credential createCredential(String accessToken, String refreshToken) { GoogleCredential credential = new GoogleCredential.Builder() .setTransport(new NetHttpTransport()) .setJsonFactory(new JacksonFactory()) .setClientSecrets(Constants.getOAuthClientId(), Constants.getOAuthClientSecret()) .build(); credential.setAccessToken(accessToken); credential.setRefreshToken(refreshToken); return credential; }
Example 16
Source File: GcpIamAuthenticationUnitTests.java From spring-vault with Apache License 2.0 | 5 votes |
@Test void shouldCreateNewGcpIamObjectInstance() throws GeneralSecurityException, IOException { PrivateKey privateKeyMock = mock(PrivateKey.class); GoogleCredential credential = new Builder().setServiceAccountId("hello@world") .setServiceAccountProjectId("foobar").setServiceAccountPrivateKey(privateKeyMock) .setServiceAccountPrivateKeyId("key-id").build(); credential.setAccessToken("foobar"); GcpIamAuthenticationOptions options = GcpIamAuthenticationOptions.builder().role("dev-role") .credential(credential).build(); new GcpIamAuthentication(options, this.restTemplate); }
Example 17
Source File: GSpreadFeedProcessor.java From micro-integrator with Apache License 2.0 | 4 votes |
/** * helper method to authenticate using just access token */ private void authenticateWithAccessToken() { GoogleCredential credential = getBaseCredential(); credential.setAccessToken(this.accessToken); this.service.setOAuth2Credentials(credential); }
Example 18
Source File: AdWordsAxisSoapCompressionIntegrationTest.java From googleads-java-lib with Apache License 2.0 | 4 votes |
/** * Tests making an Axis AdWords API call with OAuth2 and compression enabled. */ @Test public void testGoldenSoap_oauth2_compressionEnabled() throws Exception { testHttpServer.setMockResponseBody(SoapResponseXmlProvider.getTestSoapResponse(API_VERSION)); GoogleCredential credential = new GoogleCredential.Builder().setTransport( new NetHttpTransport()).setJsonFactory(new JacksonFactory()).build(); credential.setAccessToken("TEST_ACCESS_TOKEN"); AdWordsSession session = new AdWordsSession.Builder().withUserAgent("TEST_APP") .withOAuth2Credential(credential) .withEndpoint(testHttpServer.getServerUrl()) .withDeveloperToken("TEST_DEVELOPER_TOKEN") .withClientCustomerId("TEST_CLIENT_CUSTOMER_ID") .build(); BudgetServiceInterface companyService = new AdWordsServices().get(session, BudgetServiceInterface.class); Budget budget = new Budget(); budget.setName("Test Budget Name"); Money money = new Money(); money.setMicroAmount(50000000L); budget.setAmount(money); budget.setDeliveryMethod(BudgetBudgetDeliveryMethod.STANDARD); BudgetOperation operation = new BudgetOperation(); operation.setOperand(budget); operation.setOperator(Operator.ADD); Budget responseBudget = companyService.mutate(new BudgetOperation[] {operation}).getValue(0); assertEquals("Budget ID does not match", 251877074L, responseBudget.getBudgetId().longValue()); assertEquals("Budget name does not match", budget.getName(), responseBudget.getName()); assertEquals("Budget amount does not match", budget.getAmount().getMicroAmount(), responseBudget.getAmount().getMicroAmount()); assertEquals("Budget delivery method does not match", budget.getDeliveryMethod(), responseBudget.getDeliveryMethod()); assertTrue("Compression was enabled but the last request body was not compressed", testHttpServer.wasLastRequestBodyCompressed()); XMLAssert.assertXMLEqual(SoapRequestXmlProvider.getOAuth2SoapRequest(API_VERSION), testHttpServer.getLastRequestBody()); assertEquals("Bearer TEST_ACCESS_TOKEN", testHttpServer.getLastAuthorizationHttpHeader()); }
Example 19
Source File: AdWordsJaxWsSoapIntegrationTest.java From googleads-java-lib with Apache License 2.0 | 4 votes |
/** * Tests making a JAX-WS Ad Manager API call with OAuth2. */ @Test public void testGoldenSoap_oauth2() throws Exception { testHttpServer.setMockResponseBody(SoapResponseXmlProvider.getTestSoapResponse(API_VERSION)); GoogleCredential credential = new GoogleCredential.Builder().setTransport( new NetHttpTransport()).setJsonFactory(new JacksonFactory()).build(); credential.setAccessToken("TEST_ACCESS_TOKEN"); AdWordsSession session = new AdWordsSession.Builder() .withUserAgent("TEST_APP") .withOAuth2Credential(credential) .withEndpoint(testHttpServer.getServerUrl()) .withDeveloperToken("TEST_DEVELOPER_TOKEN") .withClientCustomerId("TEST_CLIENT_CUSTOMER_ID") .build(); BudgetServiceInterface budgetService = new AdWordsServices().get(session, BudgetServiceInterface.class); Budget budget = new Budget(); budget.setName("Test Budget Name"); Money money = new Money(); money.setMicroAmount(50000000L); budget.setAmount(money); budget.setDeliveryMethod(BudgetBudgetDeliveryMethod.STANDARD); BudgetOperation operation = new BudgetOperation(); operation.setOperand(budget); operation.setOperator(Operator.ADD); Budget responseBudget = budgetService.mutate(Lists.newArrayList(operation)).getValue().get(0); assertEquals("Budget ID does not match", 251877074L, responseBudget.getBudgetId().longValue()); assertEquals("Budget name does not match", budget.getName(), responseBudget.getName()); assertEquals("Budget amount does not match", budget.getAmount().getMicroAmount(), responseBudget.getAmount().getMicroAmount()); assertEquals("Budget delivery method does not match", budget.getDeliveryMethod(), responseBudget.getDeliveryMethod()); XMLAssert.assertXMLEqual(SoapRequestXmlProvider.getOAuth2SoapRequest(API_VERSION), testHttpServer.getLastRequestBody()); assertFalse("Did not request compression but request was compressed", testHttpServer.wasLastRequestBodyCompressed()); assertEquals("Bearer TEST_ACCESS_TOKEN", testHttpServer.getLastAuthorizationHttpHeader()); }
Example 20
Source File: GcpIamAuthenticationOptionsBuilderUnitTests.java From spring-vault with Apache License 2.0 | 3 votes |
private static GoogleCredential createGoogleCredential() { GoogleCredential credential = new GoogleCredential.Builder().setServiceAccountId("hello@world") .setServiceAccountProjectId("project-id").setServiceAccountPrivateKey(mock(PrivateKey.class)) .setServiceAccountPrivateKeyId("key-id").build(); credential.setAccessToken("foobar"); return credential; }