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 Project: java-samples   Author: gsuitedevs   File: OutputJSON.java    License: 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 #2
Source Project: java-samples   Author: gsuitedevs   File: DriveActivityQuickstart.java    License: 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 = 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 #3
Source Project: android-oauth-client   Author: wuman   File: SimpleOAuth10aActivity.java    License: 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 #4
Source Project: java-samples   Author: gsuitedevs   File: MigrationHelper.java    License: 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 Project: googleads-adxbuyer-examples   Author: googleads   File: AdExchangeBuyerSample.java    License: 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 #6
Source Project: java-samples   Author: gsuitedevs   File: Quickstart.java    License: 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 #7
Source Project: pentaho-kettle   Author: pentaho   File: GoogleAnalyticsApiFacade.java    License: 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 #8
Source Project: rides-java-sdk   Author: uber   File: OAuth2CredentialsTest.java    License: 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 #9
Source Project: google-sites-liberation   Author: sih4sing5hong5   File: GuiMain.java    License: 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 #10
Source Project: async-datastore-client   Author: spotify   File: DatastoreImpl.java    License: 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 #11
Source Project: jbpm-work-items   Author: kiegroup   File: GoogleDriveAuth.java    License: 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 #12
Source Project: rides-java-sdk   Author: uber   File: OAuth2CredentialsTest.java    License: 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 #13
Source Project: hadoop-connectors   Author: GoogleCloudDataproc   File: GoogleCloudStorageFileSystemNewIntegrationTest.java    License: 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 #14
Source Project: android-oauth-client   Author: wuman   File: SimpleOAuth2ExplicitActivity.java    License: 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 #15
Source Project: Xero-Java   Author: XeroAPI   File: PayrollAuApi.java    License: 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 #16
Source Project: connector-sdk   Author: google-cloudsearch   File: SearchHelper.java    License: Apache License 2.0 5 votes vote down vote up
private static Credential createCredentials(
    HttpTransport httpTransport, SearchAuthInfo searchAuthInfo)
    throws IOException {
  GoogleClientSecrets clientSecrets = GoogleClientSecrets.load(
      JSON_FACTORY, new InputStreamReader(searchAuthInfo.getClientSecretsStream(), UTF_8));
  GoogleAuthorizationCodeFlow flow =
      new GoogleAuthorizationCodeFlow.Builder(
          httpTransport, JSON_FACTORY, clientSecrets, API_SCOPES)
          .setDataStoreFactory(new FileDataStoreFactory(searchAuthInfo.getCredentialsDirectory()))
          .build();
  return flow.loadCredential(searchAuthInfo.getUserEmail());
}
 
Example #17
Source Project: incubator-heron   Author: apache   File: GcsUploader.java    License: Apache License 2.0 5 votes vote down vote up
GcsController createGcsController(Config configuration, String storageBucket)
    throws IOException, GeneralSecurityException {
  final Credential credential = createCredentials(configuration);
  final Storage storage = createStorage(credential);

  return GcsController.create(storage, storageBucket);
}
 
Example #18
Source Project: drivemarks   Author: googlearchive   File: CredentialManager.java    License: Apache License 2.0 5 votes vote down vote up
/**
 * Builds an empty credential object.
 * @return An empty credential object.
 */
public Credential buildEmpty() {
  return new GoogleCredential.Builder()
      .setClientSecrets(this.clientSecrets)
      .setTransport(transport)
      .setJsonFactory(jsonFactory)
      .build();
}
 
Example #19
Source Project: google-oauth-java-client   Author: googleapis   File: FileCredentialStoreTest.java    License: 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 #20
Source Project: google-cloud-eclipse   Author: GoogleCloudPlatform   File: CredentialHelperTest.java    License: 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;
}
 
Example #21
Source Project: google-cloud-eclipse   Author: GoogleCloudPlatform   File: AppEngineDeployPreferencesPanelTest.java    License: 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 #22
Source Project: google-cloud-datastore   Author: GoogleCloudPlatform   File: DatastoreTest.java    License: 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 #23
Source Project: android-oauth-client   Author: wuman   File: SharedPreferencesCredentialStore.java    License: 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 #24
Source Project: jdrivesync   Author: siom79   File: CredentialStoreTest.java    License: 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 #25
Source Project: data-transfer-project   Author: google   File: GoogleMailImporter.java    License: 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 #26
Source Project: googleads-adxseller-examples   Author: googleads   File: AdExchangeSellerSample.java    License: 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 #27
Source Project: tutorials   Author: eugenp   File: GoogleAuthorizeUtil.java    License: MIT License 5 votes vote down vote up
public static Credential authorize() throws IOException, GeneralSecurityException {
    InputStream in = GoogleAuthorizeUtil.class.getResourceAsStream("/google-sheets-client-secret.json");
    GoogleClientSecrets clientSecrets = GoogleClientSecrets.load(JacksonFactory.getDefaultInstance(), new InputStreamReader(in));

    List<String> scopes = Arrays.asList(SheetsScopes.SPREADSHEETS);

    GoogleAuthorizationCodeFlow flow = new GoogleAuthorizationCodeFlow.Builder(GoogleNetHttpTransport.newTrustedTransport(), JacksonFactory.getDefaultInstance(), clientSecrets, scopes).setDataStoreFactory(new MemoryDataStoreFactory())
            .setAccessType("offline").build();
    Credential credential = new AuthorizationCodeInstalledApp(flow, new LocalServerReceiver()).authorize("user");

    return credential;
}
 
Example #28
Source Project: jdrivesync   Author: siom79   File: GoogleDriveAdapterTest.java    License: 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 #29
Source Project: teammates   Author: TEAMMATES   File: GmailServiceMaker.java    License: 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 #30
Source Project: Xero-Java   Author: XeroAPI   File: AssetApi.java    License: MIT License 5 votes vote down vote up
public HttpResponse createAssetForHttpResponse(String accessToken,  String xeroTenantId,  Asset asset) throws IOException {
    // verify the required parameter 'xeroTenantId' is set
    if (xeroTenantId == null) {
        throw new IllegalArgumentException("Missing the required parameter 'xeroTenantId' when calling createAsset");
    }// verify the required parameter 'asset' is set
    if (asset == null) {
        throw new IllegalArgumentException("Missing the required parameter 'asset' when calling createAsset");
    }
    if (accessToken == null) {
        throw new IllegalArgumentException("Missing the required parameter 'accessToken' when calling createAsset");
    }
    HttpHeaders headers = new HttpHeaders();
    headers.set("Xero-Tenant-Id", xeroTenantId);
    headers.setAccept("application/json"); 
    headers.setUserAgent(this.getUserAgent());
    UriBuilder uriBuilder = UriBuilder.fromUri(apiClient.getBasePath() + "/Assets");
    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(asset);
    
    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();  
}