com.google.api.client.auth.oauth2.Credential Java Examples

The following examples show how to use com.google.api.client.auth.oauth2.Credential. 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: DriveActivityQuickstart.java    From java-samples with Apache License 2.0 7 votes vote down vote up
/**
 * Creates an authorized Credential object.
 *
 * @return an authorized Credential object.
 * @throws IOException
 */
public static Credential authorize() throws IOException {
    // Load client secrets.
    InputStream in = DriveActivityQuickstart.class.getResourceAsStream(CREDENTIALS_FILE_PATH);
    if (in == null) {
        throw new FileNotFoundException("Resource not found: " + CREDENTIALS_FILE_PATH);
    }
    GoogleClientSecrets clientSecrets =
            GoogleClientSecrets.load(JSON_FACTORY, new InputStreamReader(in));

    // Build flow and trigger user authorization request.
    GoogleAuthorizationCodeFlow flow =
            new GoogleAuthorizationCodeFlow.Builder(
                            HTTP_TRANSPORT, JSON_FACTORY, clientSecrets, SCOPES)
                    .setDataStoreFactory(DATA_STORE_FACTORY)
                    .setAccessType("offline")
                    .build();
    Credential credential =
            new AuthorizationCodeInstalledApp(flow, new LocalServerReceiver())
                    .authorize("user");
    System.out.println("Credentials saved to " + DATA_STORE_DIR.getAbsolutePath());
    return credential;
}
 
Example #2
Source File: GoogleCloudStorageFileSystemNewIntegrationTest.java    From hadoop-connectors with Apache License 2.0 6 votes vote down vote up
@BeforeClass
public static void before() throws Throwable {
  String projectId =
      checkNotNull(TestConfiguration.getInstance().getProjectId(), "projectId can not be null");
  String appName = GoogleCloudStorageIntegrationHelper.APP_NAME;
  Credential credential =
      checkNotNull(GoogleCloudStorageTestHelper.getCredential(), "credential must not be null");

  gcsOptions =
      GoogleCloudStorageOptions.builder().setAppName(appName).setProjectId(projectId).build();
  httpRequestsInitializer =
      new RetryHttpInitializer(credential, gcsOptions.toRetryHttpInitializerOptions());

  GoogleCloudStorageFileSystem gcsfs =
      new GoogleCloudStorageFileSystem(
          credential,
          GoogleCloudStorageFileSystemOptions.builder()
              .setBucketDeleteEnabled(true)
              .setCloudStorageOptions(gcsOptions)
              .build());

  gcsfsIHelper = new GoogleCloudStorageFileSystemIntegrationHelper(gcsfs);
  gcsfsIHelper.beforeAllTests();
}
 
Example #3
Source File: OutputJSON.java    From java-samples with Apache License 2.0 6 votes vote down vote up
/**
 * Creates an authorized Credential object.
 *
 * @param HTTP_TRANSPORT The network HTTP Transport.
 * @return An authorized Credential object.
 * @throws IOException If the credentials.json file cannot be found.
 */
private static Credential getCredentials(final NetHttpTransport HTTP_TRANSPORT)
        throws IOException {
    // Load client secrets.
    InputStream in = OutputJSON.class.getResourceAsStream(CREDENTIALS_FILE_PATH);
    GoogleClientSecrets credentials =
            GoogleClientSecrets.load(JSON_FACTORY, new InputStreamReader(in));

    // Build flow and trigger user authorization request.
    GoogleAuthorizationCodeFlow flow =
            new GoogleAuthorizationCodeFlow.Builder(HTTP_TRANSPORT, JSON_FACTORY, credentials, SCOPES)
                    .setDataStoreFactory(new FileDataStoreFactory(new java.io.File(TOKENS_DIRECTORY_PATH)))
                    .setAccessType("offline")
                    .build();
    LocalServerReceiver receiver = new LocalServerReceiver.Builder().setPort(8888).build();
    return new AuthorizationCodeInstalledApp(flow, receiver).authorize("user");
}
 
Example #4
Source File: MigrationHelper.java    From java-samples with Apache License 2.0 6 votes vote down vote up
/**
 * Creates an authorized Credential object.
 *
 * @return an authorized Credential object.
 * @throws IOException
 */
public static Credential authorize() throws IOException {
  // Load client secrets.
  InputStream in = MigrationHelper.class.getResourceAsStream("/credentials.json");
  GoogleClientSecrets clientSecrets =
      GoogleClientSecrets.load(JSON_FACTORY, new InputStreamReader(in));

  // Build flow and trigger user authorization request.
  GoogleAuthorizationCodeFlow flow =
      new GoogleAuthorizationCodeFlow.Builder(HTTP_TRANSPORT, JSON_FACTORY, clientSecrets, SCOPES)
          .setDataStoreFactory(DATA_STORE_FACTORY)
          .setAccessType("offline")
          .build();
  Credential credential =
      new AuthorizationCodeInstalledApp(flow, new LocalServerReceiver()).authorize("user");
  System.out.println("Credentials saved to " + DATA_STORE_DIR.getAbsolutePath());
  return credential;
}
 
Example #5
Source File: SimpleOAuth10aActivity.java    From android-oauth-client with Apache License 2.0 6 votes vote down vote up
@Override
public void onLoadFinished(Loader<Result<Credential>> loader,
        Result<Credential> result) {
    if (loader.getId() == LOADER_GET_TOKEN) {
        message.setText(result.success ? result.data.getAccessToken() : "");
    } else {
        message.setText("");
    }
    if (result.success) {
        if (loader.getId() == LOADER_GET_TOKEN) {
            setButtonText(R.string.delete_token);
        } else {
            setButtonText(R.string.get_token);
        }
    } else {
        setButtonText(R.string.get_token);
        Crouton.makeText(getActivity(), result.errorMessage, Style.ALERT).show();
    }
    getActivity().setProgressBarIndeterminateVisibility(false);
    button.setEnabled(true);
}
 
Example #6
Source File: AdExchangeBuyerSample.java    From googleads-adxbuyer-examples with Apache License 2.0 6 votes vote down vote up
/**
 * Runs all the Ad Exchange Buyer API samples.
 *
 * @param args command-line arguments.
 */
public static void main(String[] args) throws Exception {
  httpTransport = GoogleNetHttpTransport.newTrustedTransport();
  initSamples();
  Credential credentials = authorize();
  AdExchangeBuyer adXBuyerClient = initAdExchangeBuyerClient(credentials);
  AdExchangeBuyerII adXBuyerIIClient = initAdExchangeBuyerIIClient(
      credentials);
  BaseSample sample = null;

  while ((sample = selectSample()) != null) {
    try {
      System.out.printf("%nExecuting sample: %s%n%n", sample.getName());
      BaseSample.ClientType clientType = sample.getClientType();
      if (clientType == BaseSample.ClientType.ADEXCHANGEBUYER) {
        sample.execute(adXBuyerClient);
      } else if (clientType == BaseSample.ClientType.ADEXCHANGEBUYERII) {
        sample.execute(adXBuyerIIClient);
      }
    } catch (IOException e) {
      e.printStackTrace();
    }
  }
}
 
Example #7
Source File: Quickstart.java    From java-samples with Apache License 2.0 6 votes vote down vote up
/**
 * Creates an authorized Credential object.
 * @return an authorized Credential object.
 * @throws IOException
 */
public static Credential authorize() throws IOException {
    // Load client secrets.
    InputStream in =
        Quickstart.class.getResourceAsStream("/credentials.json");
    if (in == null) {
        throw new FileNotFoundException("Resource not found: " + CREDENTIALS_FILE_PATH);
    }
    GoogleClientSecrets clientSecrets =
            GoogleClientSecrets.load(JSON_FACTORY, new InputStreamReader(in));

    // Build flow and trigger user authorization request.
    GoogleAuthorizationCodeFlow flow =
            new GoogleAuthorizationCodeFlow.Builder(
                    HTTP_TRANSPORT, JSON_FACTORY, clientSecrets, SCOPES)
            .setDataStoreFactory(DATA_STORE_FACTORY)
            .setAccessType("offline")
            .build();
    Credential credential = new AuthorizationCodeInstalledApp(
        flow, new LocalServerReceiver()).authorize("user");
    System.out.println(
            "Credentials saved to " + DATA_STORE_DIR.getAbsolutePath());
    return credential;
}
 
Example #8
Source File: OAuth2CredentialsTest.java    From rides-java-sdk with MIT License 6 votes vote down vote up
@Test
public void loadCredential() throws Exception {
    OAuth2Credentials oAuth2Credentials = new OAuth2Credentials.Builder()
            .setClientSecrets("CLIENT_ID", "CLIENT_SECRET")
            .setRedirectUri("http://redirect")
            .setHttpTransport(mockHttpTransport)
            .setScopes(Arrays.asList(Scope.PROFILE, Scope.REQUEST))
            .build();

    oAuth2Credentials.authenticate("authorizationCode", "userId");

    Credential credential = oAuth2Credentials.loadCredential("userId");

    assertEquals("Refresh token does not match.", "refreshToken", credential.getRefreshToken());
    assertTrue("Expected expires_in between 0 and 3600. Was actually: " + credential.getExpiresInSeconds(),
            credential.getExpiresInSeconds() > 0 && credential.getExpiresInSeconds() <= 3600);
    assertEquals("Access token does not match.", "accessToken", credential.getAccessToken());
    assertEquals("Access method (Bearer) does not match",
            BearerToken.authorizationHeaderAccessMethod().getClass(), credential.getMethod().getClass());
}
 
Example #9
Source File: GoogleAnalyticsApiFacade.java    From pentaho-kettle with Apache License 2.0 6 votes vote down vote up
public GoogleAnalyticsApiFacade( HttpTransport httpTransport, JsonFactory jsonFactory, String application,
                                 String oathServiceEmail, File keyFile )
  throws IOException, GeneralSecurityException {

  Assert.assertNotNull( httpTransport, "HttpTransport cannot be null" );
  Assert.assertNotNull( jsonFactory, "JsonFactory cannot be null" );
  Assert.assertNotBlank( application, "Application name cannot be empty" );
  Assert.assertNotBlank( oathServiceEmail, "OAuth Service Email name cannot be empty" );
  Assert.assertNotNull( keyFile, "OAuth secret key file cannot be null" );

  this.httpTransport = httpTransport;

  Credential credential = new GoogleCredential.Builder()
    .setTransport( httpTransport )
    .setJsonFactory( jsonFactory )
    .setServiceAccountScopes( AnalyticsScopes.all() )
    .setServiceAccountId( oathServiceEmail )
    .setServiceAccountPrivateKeyFromP12File( keyFile )
    .build();

  analytics = new Analytics.Builder( httpTransport, jsonFactory, credential )
    .setApplicationName( application )
    .build();
}
 
Example #10
Source File: GoogleDriveAuth.java    From jbpm-work-items with Apache License 2.0 6 votes vote down vote up
public Credential authorize(String clientSecretJSON) throws Exception {
    GoogleClientSecrets clientSecrets =
            GoogleClientSecrets.load(JSON_FACTORY,
                                     new StringReader(clientSecretJSON));

    GoogleAuthorizationCodeFlow flow =
            new GoogleAuthorizationCodeFlow.Builder(
                    HTTP_TRANSPORT,
                    JSON_FACTORY,
                    clientSecrets,
                    SCOPES)
                    .build();
    Credential credential = new AuthorizationCodeInstalledApp(
            flow,
            new LocalServerReceiver()).authorize("user");
    return credential;
}
 
Example #11
Source File: DatastoreImpl.java    From async-datastore-client with Apache License 2.0 6 votes vote down vote up
void refreshAccessToken() {
  final Credential credential = config.getCredential();
  final Long expiresIn = credential.getExpiresInSeconds();

  // trigger refresh if token is null or is about to expire
  if (credential.getAccessToken() == null
      || expiresIn != null && expiresIn <= 60) {
    try {
      credential.refreshToken();
    } catch (final IOException e) {
      log.error("Storage exception", Throwables.getRootCause(e));
    }
  }

  // update local token if the credentials token has refreshed since last update
  final String accessTokenLocal = credential.getAccessToken();

  if (this.accessToken == null || !accessToken.equals(accessTokenLocal)) {
      this.accessToken = accessTokenLocal;
  }
}
 
Example #12
Source File: GuiMain.java    From google-sites-liberation with Apache License 2.0 6 votes vote down vote up
/**
 * Retrieve OAuth 2.0 credentials.
 * 
 * @return OAuth 2.0 Credential instance.
 * @throws IOException
 */
private Credential getCredentials() throws IOException {
  String code = tokenField.getText();
  HttpTransport transport = new NetHttpTransport();
  JacksonFactory jsonFactory = new JacksonFactory();
  String CLIENT_SECRET = "EPME5fbwiNLCcMsnj3jVoXeY";

  // Step 2: Exchange -->
  GoogleTokenResponse response = new GoogleAuthorizationCodeTokenRequest(
      transport, jsonFactory, CLIENT_ID, CLIENT_SECRET, code,
      REDIRECT_URI).execute();
  // End of Step 2 <--

  // Build a new GoogleCredential instance and return it.
  return new GoogleCredential.Builder()
      .setClientSecrets(CLIENT_ID, CLIENT_SECRET)
      .setJsonFactory(jsonFactory).setTransport(transport).build()
      .setAccessToken(response.getAccessToken())
      .setRefreshToken(response.getRefreshToken());
}
 
Example #13
Source File: OAuth2CredentialsTest.java    From rides-java-sdk with MIT License 6 votes vote down vote up
@Test
public void clearCredential() throws Exception {
    OAuth2Credentials oAuth2Credentials = new OAuth2Credentials.Builder()
            .setClientSecrets("CLIENT_ID", "CLIENT_SECRET")
            .setRedirectUri("http://redirect")
            .setHttpTransport(mockHttpTransport)
            .setScopes(Arrays.asList(Scope.PROFILE, Scope.REQUEST))
            .build();

    oAuth2Credentials.authenticate("authorizationCode", "userId");

    Credential credential = oAuth2Credentials.loadCredential("userId");

    assertNotNull(credential);

    oAuth2Credentials.clearCredential("userId");

    credential = oAuth2Credentials.loadCredential("userId");
    assertNull(credential);
}
 
Example #14
Source File: FileCredentialStoreTest.java    From google-oauth-java-client with Apache License 2.0 5 votes vote down vote up
public void testLoadCredentials_empty() throws Exception {
  File file = createTempFile();
  FileCredentialStore store = new FileCredentialStore(file, JSON_FACTORY);
  Credential actual = createEmptyCredential();
  boolean loaded = store.load(USER_ID, actual);
  assertFalse(loaded);
  assertNull(actual.getAccessToken());
  assertNull(actual.getRefreshToken());
  assertNull(actual.getExpirationTimeMilliseconds());
}
 
Example #15
Source File: GmailServiceMaker.java    From teammates with GNU General Public License v2.0 5 votes vote down vote up
/**
 * Builds and returns an authorized Gmail client service.
 */
Gmail makeGmailService() throws IOException {
    Credential credential = authorizeAndCreateCredentials();
    return new Gmail.Builder(HTTP_TRANSPORT, JSON_FACTORY, credential)
            .setApplicationName("teammates")
            .build();
}
 
Example #16
Source File: GoogleApiFactory.java    From google-cloud-eclipse with Apache License 2.0 5 votes vote down vote up
@Override
public Iam newIamApi(Credential credential) {
  Preconditions.checkNotNull(transportCache, "transportCache is null");
  HttpTransport transport = transportCache.getUnchecked(GoogleApi.IAM_API);
  Preconditions.checkNotNull(transport, "transport is null");
  Preconditions.checkNotNull(jsonFactory, "jsonFactory is null");

  Iam iam = new Iam.Builder(transport, jsonFactory, credential)
      .setApplicationName(CloudToolsInfo.USER_AGENT).build();
  return iam;
}
 
Example #17
Source File: PayrollAuApi.java    From Xero-Java with MIT License 5 votes vote down vote up
public HttpResponse updateEmployeeForHttpResponse(String accessToken,  String xeroTenantId,  UUID employeeId,  List<Employee> employee) throws IOException {
    // verify the required parameter 'xeroTenantId' is set
    if (xeroTenantId == null) {
        throw new IllegalArgumentException("Missing the required parameter 'xeroTenantId' when calling updateEmployee");
    }// verify the required parameter 'employeeId' is set
    if (employeeId == null) {
        throw new IllegalArgumentException("Missing the required parameter 'employeeId' when calling updateEmployee");
    }
    if (accessToken == null) {
        throw new IllegalArgumentException("Missing the required parameter 'accessToken' when calling updateEmployee");
    }
    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("EmployeeId", employeeId);

    UriBuilder uriBuilder = UriBuilder.fromUri(apiClient.getBasePath() + "/Employees/{EmployeeId}");
    String url = uriBuilder.buildFromMap(uriVariables).toString();
    GenericUrl genericUrl = new GenericUrl(url);
    if (logger.isDebugEnabled()) {
        logger.debug("POST " + genericUrl.toString());
    }
    
    HttpContent content = null;
    content = apiClient.new JacksonJsonHttpContent(employee);
    
    Credential credential = new Credential(BearerToken.authorizationHeaderAccessMethod()).setAccessToken(accessToken);
    HttpTransport transport = apiClient.getHttpTransport();       
    HttpRequestFactory requestFactory = transport.createRequestFactory(credential);
    return requestFactory.buildRequest(HttpMethods.POST, genericUrl, content).setHeaders(headers)
        .setConnectTimeout(apiClient.getConnectionTimeout())
        .setReadTimeout(apiClient.getReadTimeout()).execute();  
}
 
Example #18
Source File: AppEngineDeployPreferencesPanelTest.java    From google-cloud-eclipse with Apache License 2.0 5 votes vote down vote up
@Before
public void setUp() {
  parent = new Composite(shellTestResource.getShell(), SWT.NONE);
  when(project.getName()).thenReturn("testProject");
  when(account1.getEmail()).thenReturn(EMAIL_1);
  when(account2.getEmail()).thenReturn(EMAIL_2);
  when(account1.getOAuth2Credential()).thenReturn(credential);
  when(account2.getOAuth2Credential()).thenReturn(mock(Credential.class));
  oneAccountSet = new HashSet<>(Arrays.asList(account1));
  twoAccountSet = new HashSet<>(Arrays.asList(account1, account2));
  model = new DeployPreferences(project);
}
 
Example #19
Source File: GoogleDriveAdapterTest.java    From jdrivesync with Apache License 2.0 5 votes vote down vote up
@Test
public void testChunkedUpload() {
	Credential credentials = mock(Credential.class);
	Options options = new Options();
	DriveFactory driveFactory = mock(DriveFactory.class);
	Drive drive = mock(Drive.class);
	when(driveFactory.getDrive(anyObject())).thenReturn(drive);
	HttpRequestFactory requestFactory = mock(HttpRequestFactory.class);
	when(drive.getRequestFactory()).thenReturn(requestFactory);
	GoogleDriveAdapter googleDriveAdapter = new GoogleDriveAdapter(credentials, options, driveFactory);
}
 
Example #20
Source File: SimpleOAuth2ExplicitActivity.java    From android-oauth-client with Apache License 2.0 5 votes vote down vote up
@Override
public Credential loadResourceInBackground() throws Exception {
    success = oauth.deleteCredential(getContext().getString(R.string.token_linkedin_explicit), null,
            null).getResult();
    LOGGER.info("token deleted: " + success);
    return null;
}
 
Example #21
Source File: CredentialStore.java    From jdrivesync with Apache License 2.0 5 votes vote down vote up
public void store(Credential credential) {
     this.credential = Optional.of(credential);
     Properties properties = new Properties();
     properties.setProperty(PROP_ACCESS_TOKEN, credential.getAccessToken());
     properties.setProperty(PROP_REFRESH_TOKEN, credential.getRefreshToken());
     try {
File file = getAuthenticationFile(options);
         properties.store(new FileWriter(file), "Properties of jdrivesync.");
     } catch (IOException e) {
         throw new JDriveSyncException(JDriveSyncException.Reason.IOException, "Failed to store properties file: " + e.getMessage(), e);
     }
 }
 
Example #22
Source File: SimpleOAuth2ExplicitActivity.java    From android-oauth-client with Apache License 2.0 5 votes vote down vote up
@Override
public Loader<Result<Credential>> onCreateLoader(int id, Bundle args) {
    getActivity().setProgressBarIndeterminateVisibility(true);
    button.setEnabled(false);
    message.setText("");
    if (id == LOADER_GET_TOKEN) {
        return new GetTokenLoader(getActivity(), oauth);
    } else {
        return new DeleteTokenLoader(getActivity(), oauth);
    }
}
 
Example #23
Source File: DatastoreTest.java    From google-cloud-datastore with Apache License 2.0 5 votes vote down vote up
@Override
public HttpRequestFactory makeClient(DatastoreOptions options) {
  HttpTransport transport = new MockHttpTransport() {
      @Override
      public LowLevelHttpRequest buildRequest(String method, String url) {
        return new MockLowLevelHttpRequest(url) {
          @Override
          public LowLevelHttpResponse execute() throws IOException {
            lastPath = new GenericUrl(getUrl()).getRawPath();
            lastMimeType = getContentType();
            lastCookies = getHeaderValues("Cookie");
            lastApiFormatHeaderValue =
                Iterables.getOnlyElement(getHeaderValues("X-Goog-Api-Format-Version"));
            ByteArrayOutputStream out = new ByteArrayOutputStream();
            getStreamingContent().writeTo(out);
            lastBody = out.toByteArray();
            if (nextException != null) {
              throw nextException;
            }
            MockLowLevelHttpResponse response = new MockLowLevelHttpResponse()
                .setStatusCode(nextStatus)
                .setContentType("application/x-protobuf");
            if (nextError != null) {
              assertNull(nextResponse);
              response.setContent(new TestableByteArrayInputStream(nextError.toByteArray()));
            } else {
              response.setContent(new TestableByteArrayInputStream(nextResponse.toByteArray()));
            }
            return response;
          }
        };
      }
    };
  Credential credential = options.getCredential();
  return transport.createRequestFactory(credential);
}
 
Example #24
Source File: PayrollAuApi.java    From Xero-Java with MIT License 5 votes vote down vote up
public HttpResponse getEmployeeForHttpResponse(String accessToken,  String xeroTenantId,  UUID employeeId) throws IOException {
    // verify the required parameter 'xeroTenantId' is set
    if (xeroTenantId == null) {
        throw new IllegalArgumentException("Missing the required parameter 'xeroTenantId' when calling getEmployee");
    }// verify the required parameter 'employeeId' is set
    if (employeeId == null) {
        throw new IllegalArgumentException("Missing the required parameter 'employeeId' when calling getEmployee");
    }
    if (accessToken == null) {
        throw new IllegalArgumentException("Missing the required parameter 'accessToken' when calling getEmployee");
    }
    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("EmployeeId", employeeId);

    UriBuilder uriBuilder = UriBuilder.fromUri(apiClient.getBasePath() + "/Employees/{EmployeeId}");
    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 #25
Source File: SharedPreferencesCredentialStore.java    From android-oauth-client with Apache License 2.0 5 votes vote down vote up
@Override
public void store(String userId, Credential credential) throws IOException {
    Preconditions.checkNotNull(userId);
    FilePersistedCredential fileCredential = new FilePersistedCredential();
    fileCredential.store(credential);
    String credentialJson = jsonFactory.toString(fileCredential);
    prefs.edit().putString(userId, credentialJson).apply();
}
 
Example #26
Source File: CredentialStoreTest.java    From jdrivesync with Apache License 2.0 5 votes vote down vote up
@Test
public void testAuthFileCreatedAtGivenLocation() {
	Options options = new Options();
	Path path = Paths.get(System.getProperty("user.dir"), "target", "credential-store-test.properties");
	options.setAuthenticationFile(Optional.of(path.toString()));
	CredentialStore credentialStore = new CredentialStore(options);
	Credential credential = mock(Credential.class);
	when(credential.getAccessToken()).thenReturn("");
	when(credential.getRefreshToken()).thenReturn("");
	credentialStore.store(credential);
	assertThat(Files.exists(path), is(true));
}
 
Example #27
Source File: GoogleMailImporter.java    From data-transfer-project with Apache License 2.0 5 votes vote down vote up
private synchronized Gmail makeGmailService(TokensAndUrlAuthData authData) {
  Credential credential = credentialFactory.createCredential(authData);
  return new Gmail.Builder(
          credentialFactory.getHttpTransport(), credentialFactory.getJsonFactory(), credential)
      .setApplicationName(GoogleStaticObjects.APP_NAME)
      .build();
}
 
Example #28
Source File: PayrollAuApi.java    From Xero-Java with MIT License 5 votes vote down vote up
public HttpResponse createPayrollCalendarForHttpResponse(String accessToken,  String xeroTenantId,  List<PayrollCalendar> payrollCalendar) throws IOException {
    // verify the required parameter 'xeroTenantId' is set
    if (xeroTenantId == null) {
        throw new IllegalArgumentException("Missing the required parameter 'xeroTenantId' when calling createPayrollCalendar");
    }// verify the required parameter 'payrollCalendar' is set
    if (payrollCalendar == null) {
        throw new IllegalArgumentException("Missing the required parameter 'payrollCalendar' when calling createPayrollCalendar");
    }
    if (accessToken == null) {
        throw new IllegalArgumentException("Missing the required parameter 'accessToken' when calling createPayrollCalendar");
    }
    HttpHeaders headers = new HttpHeaders();
    headers.set("Xero-Tenant-Id", xeroTenantId);
    headers.setAccept("application/json"); 
    headers.setUserAgent(this.getUserAgent());
    UriBuilder uriBuilder = UriBuilder.fromUri(apiClient.getBasePath() + "/PayrollCalendars");
    String url = uriBuilder.build().toString();
    GenericUrl genericUrl = new GenericUrl(url);
    if (logger.isDebugEnabled()) {
        logger.debug("POST " + genericUrl.toString());
    }
    
    HttpContent content = null;
    content = apiClient.new JacksonJsonHttpContent(payrollCalendar);
    
    Credential credential = new Credential(BearerToken.authorizationHeaderAccessMethod()).setAccessToken(accessToken);
    HttpTransport transport = apiClient.getHttpTransport();       
    HttpRequestFactory requestFactory = transport.createRequestFactory(credential);
    return requestFactory.buildRequest(HttpMethods.POST, genericUrl, content).setHeaders(headers)
        .setConnectTimeout(apiClient.getConnectionTimeout())
        .setReadTimeout(apiClient.getReadTimeout()).execute();  
}
 
Example #29
Source File: AdExchangeSellerSample.java    From googleads-adxseller-examples with Apache License 2.0 5 votes vote down vote up
/**
 * Performs all necessary setup steps for running requests against the API.
 *
 * @return An initialized AdExchangeSeller service object.
 * @throws Exception
 */
private static AdExchangeSeller initializeAdExchangeSeller() throws Exception {
  // Authorization.
  Credential credential = authorize();

  // Set up Ad Exchange Seller REST API client.
  AdExchangeSeller adExchangeSeller = new AdExchangeSeller.Builder(
      new NetHttpTransport(), JSON_FACTORY, credential).setApplicationName(APPLICATION_NAME)
      .build();

  return adExchangeSeller;
}
 
Example #30
Source File: CredentialHelperTest.java    From google-cloud-eclipse with Apache License 2.0 5 votes vote down vote up
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;
}