com.google.api.client.http.javanet.NetHttpTransport Java Examples

The following examples show how to use com.google.api.client.http.javanet.NetHttpTransport. 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: HotswapAgentExamples   Author: HotswapProjects   File: DevelopersSharedModule.java    License: GNU General Public License v2.0 6 votes vote down vote up
@Override
	public void configure(Binder binder) {

//		binder.bind(HttpTransport.class).toInstance(new UrlFetchTransport());
		binder.bind(HttpTransport.class).toInstance(new NetHttpTransport());

		/*
		 * TODO HH?
		 */
		binder.bind(DateFormat.class).toInstance(
				new SimpleDateFormat("yyyy-MM-dd'T'hh:mm:ss.SSS'Z'"));

		binder.bind(JsonFactory.class).toInstance(
				JacksonFactory.getDefaultInstance());

		/*
		 * Global instance of the {@link DataStoreFactory}. The best practice is
		 * to make it a single globally shared instance across your application.
		 */
		binder.bind(DataStoreFactory.class).toInstance(
				AppEngineDataStoreFactory.getDefaultInstance());
		binder.bind(AppEngineDataStoreFactory.class).in(Singleton.class);
	}
 
Example #2
Source Project: jelectrum   Author: fireduck64   File: JelectrumDBCloudData.java    License: MIT License 6 votes vote down vote up
private GoogleCredential openCredential()
    throws java.security.GeneralSecurityException, java.io.IOException
{
   NetHttpTransport transport = GoogleNetHttpTransport.newTrustedTransport();
    JacksonFactory jsonFactory = new JacksonFactory();

    GoogleCredential cred = new GoogleCredential.Builder()
        .setTransport(transport)
        .setJsonFactory(jsonFactory)
        .setServiceAccountId(conf.get("google_api_account"))
        .setServiceAccountScopes(DatastoreOptions.SCOPES)
        .setServiceAccountPrivateKeyFromP12File(new File(conf.get("google_api_keyfile")))
        .build();


    return cred;


}
 
Example #3
Source Project: java-samples   Author: gsuitedevs   File: AppsScriptQuickstart.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 = AppsScriptQuickstart.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(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 Project: oauth1-signer-java   Author: Mastercard   File: GoogleApiClientSignerTest.java    License: MIT License 6 votes vote down vote up
@Test
public void testSign_ShouldAddOAuth1HeaderToPostRequest() throws Exception {

    // GIVEN
    PrivateKey signingKey = TestUtils.getTestSigningKey();
    String consumerKey = "Some key";
    HttpRequestFactory requestFactory = new NetHttpTransport().createRequestFactory();
    HttpContent httpContent = new ByteArrayContent("application/json; charset=" + UTF8_CHARSET.name(), "{\"foo\":\"bår\"}".getBytes());
    HttpRequest request = requestFactory.buildPostRequest(new GenericUrl("https://api.mastercard.com/service"), httpContent);
    request.setRequestMethod("POST");

    // WHEN
    GoogleApiClientSigner instanceUnderTest = new GoogleApiClientSigner(consumerKey, signingKey);
    instanceUnderTest.sign(request);

    // THEN
    String authorizationHeaderValue = request.getHeaders().getAuthorization();
    Assert.assertNotNull(authorizationHeaderValue);
}
 
Example #5
Source Project: java-samples   Author: gsuitedevs   File: DriveQuickstart.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 = DriveQuickstart.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(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 #6
Source Project: java-samples   Author: gsuitedevs   File: PeopleQuickstart.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 = PeopleQuickstart.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(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 #7
Source Project: UTubeTV   Author: sgehrman   File: YouTubeAPI.java    License: The Unlicense 6 votes vote down vote up
public YouTube youTube() {
  if (youTube == null) {
    try {
      HttpRequestInitializer credentials;

      if (mUseAuthCredentials)
        credentials = Auth.getCredentials(mContext, mUseDefaultAccount);
      else
        credentials = Auth.nullCredentials(mContext);

      youTube = new YouTube.Builder(new NetHttpTransport(), new AndroidJsonFactory(), credentials).setApplicationName("YouTubeAPI")
          .build();
    } catch (Exception e) {
      e.printStackTrace();
    } catch (Throwable t) {
      t.printStackTrace();
    }
  }

  return youTube;
}
 
Example #8
Source Project: liberty-bikes   Author: OpenLiberty   File: GoogleAuth.java    License: 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 #9
Source Project: java-samples   Author: gsuitedevs   File: SlidesQuickstart.java    License: Apache License 2.0 6 votes vote down vote up
public static void main(String... args) throws IOException, GeneralSecurityException {
    // Build a new authorized API client service.
    final NetHttpTransport HTTP_TRANSPORT = GoogleNetHttpTransport.newTrustedTransport();
    Slides service = new Slides.Builder(HTTP_TRANSPORT, JSON_FACTORY, getCredentials(HTTP_TRANSPORT))
            .setApplicationName(APPLICATION_NAME)
            .build();

    // Prints the number of slides and elements in a sample presentation:
    // https://docs.google.com/presentation/d/1EAYk18WDjIG-zp_0vLm3CsfQh_i8eXc67Jo2O9C6Vuc/edit
    String presentationId = "1EAYk18WDjIG-zp_0vLm3CsfQh_i8eXc67Jo2O9C6Vuc";
    Presentation response = service.presentations().get(presentationId).execute();
    List<Page> slides = response.getSlides();

    System.out.printf("The presentation contains %s slides:\n", slides.size());
    for (int i = 0; i < slides.size(); ++i) {
        System.out.printf("- Slide #%s contains %s elements.\n", i + 1, slides.get(i).getPageElements().size());
    }
}
 
Example #10
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 #11
Source Project: vpn-over-dns   Author: AlexandreFenyo   File: OAuthServlet.java    License: BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
@Override
protected AuthorizationCodeFlow initializeFlow() throws IOException {
	return new AuthorizationCodeFlow.Builder(BearerToken.authorizationHeaderAccessMethod(),
			new NetHttpTransport(),
			new JacksonFactory(),
			// token server URL:
			// new GenericUrl("https://server.example.com/token"),
			new GenericUrl("https://accounts.google.com/o/oauth2/auth"),
			new BasicAuthentication("458072371664.apps.googleusercontent.com",
					"mBp75wknGsGu0WMzHaHhqfXT"),
			"458072371664.apps.googleusercontent.com",
			// authorization server URL:
			"https://accounts.google.com/o/oauth2/auth").
			// setCredentialStore(new JdoCredentialStore(JDOHelper.getPersistenceManagerFactory("transactions-optional")))
			setCredentialStore(new MemoryCredentialStore()).setScopes("https://mail.google.com/")
			// setCredentialStore(new MyCredentialStore())
			.build();
}
 
Example #12
Source Project: java-samples   Author: gsuitedevs   File: AdminSDKReportsQuickstart.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 = AdminSDKReportsQuickstart.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(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 #13
Source Project: googleads-java-lib   Author: googleads   File: OfflineCredentialsTest.java    License: Apache License 2.0 6 votes vote down vote up
/**
 * Tests that the builder builds correctly.
 */
@Test
public void testBuilder() throws Exception {
  HttpTransport httpTransport = new NetHttpTransport();

  OfflineCredentials offlineCredentials = new OfflineCredentials.Builder()
      .forApi(OfflineCredentials.Api.AD_MANAGER)
      .withClientSecrets("clientId", "clientSecret")
      .withRefreshToken("refreshToken")
      .withHttpTransport(httpTransport)
      .build();

  assertEquals("clientId", offlineCredentials.getClientId());
  assertEquals("clientSecret", offlineCredentials.getClientSecret());
  assertEquals("refreshToken", offlineCredentials.getRefreshToken());
  assertSame(httpTransport, offlineCredentials.getHttpTransport());
}
 
Example #14
Source Project: java-samples   Author: gsuitedevs   File: ClassroomQuickstart.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 = ClassroomQuickstart.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(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 #15
Source Project: beam   Author: apache   File: HttpHealthcareApiClient.java    License: Apache License 2.0 6 votes vote down vote up
private void initClient() throws IOException {

    credentials = GoogleCredentials.getApplicationDefault();
    // Create a HttpRequestInitializer, which will provide a baseline configuration to all requests.
    HttpRequestInitializer requestInitializer =
        new AuthenticatedRetryInitializer(
            credentials.createScoped(
                CloudHealthcareScopes.CLOUD_PLATFORM, StorageScopes.CLOUD_PLATFORM_READ_ONLY));

    client =
        new CloudHealthcare.Builder(
                new NetHttpTransport(), new JacksonFactory(), requestInitializer)
            .setApplicationName("apache-beam-hl7v2-io")
            .build();
    httpClient =
        HttpClients.custom().setRetryHandler(new DefaultHttpRequestRetryHandler(10, false)).build();
  }
 
Example #16
Source Project: google-cloud-datastore   Author: GoogleCloudPlatform   File: DatastoreFactoryTest.java    License: Apache License 2.0 6 votes vote down vote up
/**
 * Specifying both credential and transport, the factory will use the
 * transport specified and not the one in the credential.
 */
@Test
public void makeClient_WithCredentialTransport() {
  NetHttpTransport credTransport = new NetHttpTransport();
  NetHttpTransport transport = new NetHttpTransport();
  GoogleCredential credential = new GoogleCredential.Builder()
      .setTransport(credTransport)
      .build();
  DatastoreOptions options = new DatastoreOptions.Builder()
      .projectId(PROJECT_ID)
      .credential(credential)
      .transport(transport)
      .build();
  HttpRequestFactory f = factory.makeClient(options);
  assertNotSame(credTransport, f.getTransport());
  assertEquals(transport, f.getTransport());
}
 
Example #17
Source Project: java-samples   Author: gsuitedevs   File: AdminSDKResellerQuickstart.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 = AdminSDKResellerQuickstart.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(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 #18
Source Project: java-samples   Author: gsuitedevs   File: AppsScriptQuickstart.java    License: Apache License 2.0 6 votes vote down vote up
public static void main(String... args) throws IOException, GeneralSecurityException {
    // Build a new authorized API client service.
    final NetHttpTransport HTTP_TRANSPORT = GoogleNetHttpTransport.newTrustedTransport();
    Script service = new Script.Builder(HTTP_TRANSPORT, JSON_FACTORY, getCredentials(HTTP_TRANSPORT))
            .setApplicationName(APPLICATION_NAME)
            .build();
    Script.Projects projects = service.projects();

    // Creates a new script project.
    Project createOp = projects.create(new CreateProjectRequest().setTitle("My Script")).execute();

    // Uploads two files to the project.
    File file1 = new File()
            .setName("hello")
            .setType("SERVER_JS")
            .setSource("function helloWorld() {\n  console.log(\"Hello, world!\");\n}");
    File file2 = new File()
            .setName("appsscript")
            .setType("JSON")
            .setSource("{\"timeZone\":\"America/New_York\",\"exceptionLogging\":\"CLOUD\"}");
    Content content = new Content().setFiles(Arrays.asList(file1, file2));
    Content updatedContent = projects.updateContent(createOp.getScriptId(), content).execute();

    // Logs the project URL.
    System.out.printf("https://script.google.com/d/%s/edit\n", updatedContent.getScriptId());
}
 
Example #19
Source Project: cloudsync   Author: HolgerHees   File: RemoteGoogleDriveConnector.java    License: 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 #20
Source Project: nomulus   Author: google   File: RequestFactoryModule.java    License: Apache License 2.0 6 votes vote down vote up
@Provides
static HttpRequestFactory provideHttpRequestFactory(
    @DefaultCredential GoogleCredentialsBundle credentialsBundle) {
  if (RegistryConfig.areServersLocal()) {
    return new NetHttpTransport()
        .createRequestFactory(
            request ->
                request
                    .getHeaders()
                    .setCookie("[email protected]:true:1858047912411"));
  } else {
    return new NetHttpTransport()
        .createRequestFactory(
            request -> {
              credentialsBundle.getHttpRequestInitializer().initialize(request);
              // GAE request times out after 10 min, so here we set the timeout to 10 min. This is
              // needed to support some nomulus commands like updating premium lists that take
              // a lot of time to complete.
              // See
              // https://developers.google.com/api-client-library/java/google-api-java-client/errors
              request.setConnectTimeout(REQUEST_TIMEOUT_MS);
              request.setReadTimeout(REQUEST_TIMEOUT_MS);
            });
  }
}
 
Example #21
Source Project: oncokb   Author: oncokb   File: GoogleAuth.java    License: GNU Affero General Public License v3.0 6 votes vote down vote up
private static void createGoogleCredential() throws GeneralSecurityException, IOException {

        if (SERVICE_ACCOUNT_EMAIL == null) {
            SERVICE_ACCOUNT_EMAIL = PropertiesUtils.getProperties("google.service_account_email");
        }

        if (SERVICE_ACCOUNT_PKCS12_FILE == null) {
            openFile();
        }

        if (CREDENTIAL == null) {
            HttpTransport httpTransport = new NetHttpTransport();
            JacksonFactory jsonFactory = new JacksonFactory();

            String[] SCOPESArray = {"https://spreadsheets.google.com/feeds", "https://www.googleapis.com/auth/gmail.compose"};
            CREDENTIAL = new GoogleCredential.Builder()
                .setTransport(httpTransport)
                .setJsonFactory(jsonFactory)
                .setServiceAccountId(SERVICE_ACCOUNT_EMAIL)
                .setServiceAccountScopes(getScopes())
                .setServiceAccountPrivateKeyFromP12File(SERVICE_ACCOUNT_PKCS12_FILE)
                .build();
        } else {
            refreshToken();
        }
    }
 
Example #22
Source Project: googleads-java-lib   Author: googleads   File: OfflineCredentialsTest.java    License: Apache License 2.0 6 votes vote down vote up
/**
 * Tests generating OAuth2 credentials.
 */
@Test
public void testGenerateCredential() throws Exception {
  HttpTransport httpTransport = new NetHttpTransport();

  OfflineCredentials offlineCredentials = new OfflineCredentials.Builder(oAuth2Helper)
      .forApi(OfflineCredentials.Api.AD_MANAGER)
      .withClientSecrets("clientId", "clientSecret")
      .withRefreshToken("refreshToken")
      .withHttpTransport(httpTransport)
      .build();

  when(oAuth2Helper.callRefreshToken(Mockito.<Credential>anyObject())).thenReturn(true);

  Credential credential = offlineCredentials.generateCredential();

  assertEquals(
      "clientId",
      ((ClientParametersAuthentication) credential.getClientAuthentication()).getClientId());
  assertEquals(
      "clientSecret",
      ((ClientParametersAuthentication) credential.getClientAuthentication()).getClientSecret());
  assertEquals("refreshToken", credential.getRefreshToken());
  assertSame(httpTransport, credential.getTransport());
}
 
Example #23
Source Project: appengine-gcs-client   Author: GoogleCloudPlatform   File: URLFetchUtilsTest.java    License: Apache License 2.0 6 votes vote down vote up
@Test
public void testDescribeRequestAndResponseForApiClient() throws Exception {
  HttpRequestInitializer initializer = mock(HttpRequestInitializer.class);
  NetHttpTransport transport = new NetHttpTransport();
  Storage storage = new Storage.Builder(transport, new JacksonFactory(), initializer)
      .setApplicationName("bla").build();
  HttpRequest request = storage.objects().delete("bucket", "object").buildHttpRequest();
  request.getHeaders().clear();
  request.getHeaders().put("k1", "v1");
  request.getHeaders().put("k2", "v2");
  HttpResponseException exception = null;
  try {
    request.execute();
  } catch (HttpResponseException ex) {
    exception = ex;
  }
  String expected = "Request: DELETE " + Storage.DEFAULT_BASE_URL + "b/bucket/o/object\n"
      + "k1: v1\nk2: v2\n\nno content\n\nResponse: 40";
  String result =
      URLFetchUtils.describeRequestAndResponse(new HTTPRequestInfo(request), exception);
  assertTrue(expected + "\nis not a prefix of:\n" + result, result.startsWith(expected));
}
 
Example #24
Source Project: apigee-android-sdk   Author: apigee   File: ApigeeDataClient.java    License: Apache License 2.0 6 votes vote down vote up
/**
 * Used to get an OAuth 2 access_token using the password grant_type synchronously.
 *
 * @param accessTokenURL The accessTokenURL
 * @param username The username of the user to login
 * @param password The password of the user to login
 * @param clientId The clientId
 * @return The TokenResponse object if we successfully gathered the token or null if the attempt was not successful.
 */
public TokenResponse oauth2AccessToken(String accessTokenURL, String username, String password, String clientId) {
    validateNonEmptyParam(accessTokenURL, "accessTokenURL");
    validateNonEmptyParam(username, "username");
    validateNonEmptyParam(password, "password");

    TokenResponse tokenResponse = null;

    // Make sure clientId is just non-null.  Otherwise we will possibly crash or get an unneeded exception.
    if( clientId == null ) {
        clientId = "";
    }

    try {
        AuthorizationRequestUrl authorizationRequestUrl = new AuthorizationRequestUrl(accessTokenURL, clientId, Collections.singleton("token"));
        PasswordTokenRequest passwordTokenRequest = new PasswordTokenRequest(new NetHttpTransport(), new JacksonFactory(), authorizationRequestUrl, username, password);
        tokenResponse = passwordTokenRequest.execute();
    } catch (Exception exception) {
    }

    return tokenResponse;
}
 
Example #25
Source Project: che   Author: eclipse   File: OAuthAuthenticator.java    License: Eclipse Public License 2.0 6 votes vote down vote up
protected OAuthAuthenticator(
    String clientId,
    String requestTokenUri,
    String accessTokenUri,
    String authorizeTokenUri,
    String redirectUri,
    @Nullable String clientSecret,
    @Nullable String privateKey) {
  this.clientId = clientId;
  this.clientSecret = clientSecret;
  this.privateKey = privateKey;
  this.requestTokenUri = requestTokenUri;
  this.accessTokenUri = accessTokenUri;
  this.authorizeTokenUri = authorizeTokenUri;
  this.redirectUri = redirectUri;
  this.httpTransport = new NetHttpTransport();
  this.credentialsStore = new HashMap<>();
  this.credentialsStoreLock = new ReentrantLock();
  this.sharedTokenSecrets = new HashMap<>();
}
 
Example #26
Source Project: googleads-java-lib   Author: googleads   File: AdHocReportDownloadHelperTest.java    License: Apache License 2.0 6 votes vote down vote up
@Before
public void setUp() throws Exception {
  MockitoAnnotations.initMocks(this);

  Enum<?> downloadFormat = TestDownloadFormat.CSV;
  Mockito.<Enum<?>>when(reportRequest.getDownloadFormat()).thenReturn(downloadFormat);

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

  helper =
      new GenericAdWordsServices()
          .getBootstrapper()
          .getInstanceOf(session, AdHocReportDownloadHelper.class);
  exceptionBuilder = DetailedReportDownloadResponseException::new;
}
 
Example #27
Source Project: jdrivesync   Author: siom79   File: DriveFactory.java    License: Apache License 2.0 5 votes vote down vote up
public Drive getDrive(Credential credential) {
    if(drive == null) {
        HttpTransport httpTransport = new NetHttpTransport();
        drive = new Drive.Builder(httpTransport, getJsonFactory(), credential).setApplicationName("JDriveSync").build();
    }
    return drive;
}
 
Example #28
Source Project: mutual-tls-ssl   Author: Hakky54   File: ClientConfig.java    License: 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 #29
Source Project: java-specialagent   Author: opentracing-contrib   File: GoogleHttpClientTest.java    License: Apache License 2.0 5 votes vote down vote up
@Test
public void asyncRequest(final MockTracer tracer) throws Exception {
  final HttpRequestFactory requestFactory = new NetHttpTransport().createRequestFactory();
  final HttpRequest request = requestFactory.buildGetRequest(new GenericUrl("http://www.google.com"));
  final int statusCode = request.executeAsync().get(15, TimeUnit.SECONDS).getStatusCode();
  assertEquals(200, statusCode);

  final List<MockSpan> spans = tracer.finishedSpans();
  assertEquals(1, spans.size());
  assertEquals(GoogleHttpClientAgentIntercept.COMPONENT_NAME, spans.get(0).tags().get(Tags.COMPONENT.getKey()));
}
 
Example #30
Source Project: java-specialagent   Author: opentracing-contrib   File: GoogleHttpClientITest.java    License: Apache License 2.0 5 votes vote down vote up
public static void main(final String[] args) throws Exception {
  final HttpRequestFactory requestFactory = new NetHttpTransport().createRequestFactory();
  final HttpRequest request = requestFactory.buildGetRequest(new GenericUrl("https://www.google.com"));
  final int statusCode = request.execute().getStatusCode();
  if (200 != statusCode)
    throw new AssertionError("ERROR: response: " + statusCode);

  TestUtil.checkSpan(new ComponentSpanCount("google-http-client", 1));
}