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 File: ClassroomQuickstart.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 = 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 #2
Source File: PeopleQuickstart.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 = 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 #3
Source File: DevelopersSharedModule.java    From HotswapAgentExamples with 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 #4
Source File: URLFetchUtilsTest.java    From appengine-gcs-client with 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 #5
Source File: OfflineCredentialsTest.java    From googleads-java-lib with 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 #6
Source File: AppsScriptQuickstart.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 = 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 #7
Source File: GoogleApiClientSignerTest.java    From oauth1-signer-java with 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 #8
Source File: AdHocReportDownloadHelperTest.java    From googleads-java-lib with 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 #9
Source File: AdvancedCreateCredentialFromScratch.java    From googleads-java-lib with Apache License 2.0 6 votes vote down vote up
private static void authorize(DataStoreFactory storeFactory, String userId) throws Exception {
  // Depending on your application, there may be more appropriate ways of
  // performing the authorization flow (such as on a servlet), see
  // https://developers.google.com/api-client-library/java/google-api-java-client/oauth2#authorization_code_flow
  // for more information.
  GoogleAuthorizationCodeFlow authorizationFlow =
      new GoogleAuthorizationCodeFlow.Builder(
              new NetHttpTransport(),
              new JacksonFactory(),
              CLIENT_ID,
              CLIENT_SECRET,
              Arrays.asList(SCOPE))
          .setDataStoreFactory(storeFactory)
          // Set the access type to offline so that the token can be refreshed.
          // By default, the library will automatically refresh tokens when it
          // can, but this can be turned off by setting
          // api.admanager.refreshOAuth2Token=false in your ads.properties file.
          .setAccessType("offline")
          .build();

  String authorizeUrl =
      authorizationFlow.newAuthorizationUrl().setRedirectUri(CALLBACK_URL).build();
  System.out.printf("Paste this url in your browser:%n%s%n", authorizeUrl);

  // Wait for the authorization code.
  System.out.println("Type the code you received here: ");
  @SuppressWarnings("DefaultCharset") // Reading from stdin, so default charset is appropriate.
  String authorizationCode = new BufferedReader(new InputStreamReader(System.in)).readLine();

  // Authorize the OAuth2 token.
  GoogleAuthorizationCodeTokenRequest tokenRequest =
      authorizationFlow.newTokenRequest(authorizationCode);
  tokenRequest.setRedirectUri(CALLBACK_URL);
  GoogleTokenResponse tokenResponse = tokenRequest.execute();

  // Store the credential for the user.
  authorizationFlow.createAndStoreCredential(tokenResponse, userId);
}
 
Example #10
Source File: OAuthAuthenticator.java    From che with 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 #11
Source File: ApigeeDataClient.java    From apigee-android-sdk with 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 #12
Source File: DriveQuickstart.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 = 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 #13
Source File: GoogleAuth.java    From oncokb with 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 #14
Source File: YouTubeAPI.java    From UTubeTV with 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 #15
Source File: GoogleAuth.java    From liberty-bikes with Eclipse Public License 1.0 6 votes vote down vote up
@GET
public Response getGoogleCallbackURL(@Context HttpServletRequest request) {

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

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

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

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

        // send the user to google to be authenticated.
        return Response.temporaryRedirect(new URI(authorizationUrl)).build();
    } catch (Exception e) {
        e.printStackTrace();
        return Response.status(500).build();
    }
}
 
Example #16
Source File: RequestFactoryModule.java    From nomulus with 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 #17
Source File: SlidesQuickstart.java    From java-samples with 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 #18
Source File: RemoteGoogleDriveConnector.java    From cloudsync with GNU General Public License v2.0 6 votes vote down vote up
public void initService(Handler handler) throws CloudsyncException
{

	if (service != null) return;

	final HttpTransport httpTransport = new NetHttpTransport();
	final JsonFactory jsonFactory = new JacksonFactory();
	service = new Drive.Builder(httpTransport, jsonFactory, null)
		.setApplicationName("Backup")
		.setHttpRequestInitializer(credential)
		.build();
	if (StringUtils.isEmpty(credential.getServiceAccountId())) {
		credential.setExpiresInSeconds(MIN_TOKEN_REFRESH_TIMEOUT);
	}
	try
	{
		refreshCredential();
	}
	catch (IOException e)
	{
		throw new CloudsyncException("couldn't refresh google drive token");
	}
	handler.getRootItem().setRemoteIdentifier(_getBackupFolder().getId());
}
 
Example #19
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 #20
Source File: OAuthServlet.java    From vpn-over-dns with 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 #21
Source File: AppsScriptQuickstart.java    From java-samples with 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 #22
Source File: AdminSDKResellerQuickstart.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 = 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 #23
Source File: DatastoreFactoryTest.java    From google-cloud-datastore with 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 #24
Source File: AdminSDKReportsQuickstart.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 = 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 #25
Source File: HttpHealthcareApiClient.java    From beam with 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 #26
Source File: OfflineCredentialsTest.java    From googleads-java-lib with 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 #27
Source File: JelectrumDBCloudData.java    From jelectrum with 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 #28
Source File: GetRefreshTokenWithoutPropertiesFile.java    From googleads-java-lib with Apache License 2.0 5 votes vote down vote up
private static Credential getOAuth2Credential(GoogleClientSecrets clientSecrets)
    throws IOException {
  GoogleAuthorizationCodeFlow authorizationFlow = new GoogleAuthorizationCodeFlow.Builder(
      new NetHttpTransport(),
      new JacksonFactory(),
      clientSecrets,
      Arrays.asList(SCOPE))
      // Set the access type to offline so that the token can be refreshed.
      // By default, the library will automatically refresh tokens when it
      // can, but this can be turned off by setting
      // api.adwords.refreshOAuth2Token=false in your ads.properties file.
      .setAccessType("offline").build();

  String authorizeUrl =
      authorizationFlow.newAuthorizationUrl().setRedirectUri(CALLBACK_URL).build();
  System.out.printf("Paste this url in your browser:%n%s%n", authorizeUrl);

  // Wait for the authorization code.
  System.out.println("Type the code you received here: ");
  @SuppressWarnings("DefaultCharset") // Reading from stdin, so default charset is appropriate.
  String authorizationCode = new BufferedReader(new InputStreamReader(System.in)).readLine();

  // Authorize the OAuth2 token.
  GoogleAuthorizationCodeTokenRequest tokenRequest =
      authorizationFlow.newTokenRequest(authorizationCode);
  tokenRequest.setRedirectUri(CALLBACK_URL);
  GoogleTokenResponse tokenResponse = tokenRequest.execute();

  // Create the OAuth2 credential.
  GoogleCredential credential = new GoogleCredential.Builder()
      .setTransport(new NetHttpTransport())
      .setJsonFactory(new JacksonFactory())
      .setClientSecrets(clientSecrets)
      .build();

  // Set authorized credentials.
  credential.setFromTokenResponse(tokenResponse);

  return credential;
}
 
Example #29
Source File: InstalledOAuth2Authenticator.java    From adwords-alerting with Apache License 2.0 5 votes vote down vote up
private GoogleAuthorizationCodeFlow getAuthorizationFlow() {
  GoogleClientSecrets clientSecrets = null;
  try {
    clientSecrets =
        new GoogleClientSecretsBuilder()
            .forApi(Api.ADWORDS)
            .withClientSecrets(clientId, clientSecret)
            .build();
  } catch (ValidationException e) {
    System.err.println(
        "Please input your client ID and secret into your properties file, which is either "
        + "located in your home directory in your java/resources directory, or on your "
        + "classpath. If you do not have a client ID or secret, please create one in the "
        + "API console: https://code.google.com/apis/console#access");
    System.exit(1);
  }

  return new GoogleAuthorizationCodeFlow
      .Builder(
          new NetHttpTransport(),
          new JacksonFactory(),
          clientSecrets,
          Lists.newArrayList(SCOPE))
      // Set the access type to offline so that the token can be refreshed.
      // By default, the library will automatically refresh tokens when it
      // can, but this can be turned off by setting
      // api.adwords.refreshOAuth2Token=false in your ads.properties file.
      .setAccessType("offline")
      .build();
}
 
Example #30
Source File: GceApi.java    From simpleci with MIT License 5 votes vote down vote up
private Compute createApi(GoogleComputeProvider provider) throws IOException, GeneralSecurityException {
    GoogleCredential credential = GoogleCredential
            .fromStream(new ByteArrayInputStream(provider.gcAccount.serviceAccount.getBytes(StandardCharsets.UTF_8)))
            .createScoped(Collections.singleton(ComputeScopes.COMPUTE));

    NetHttpTransport httpTransport = GoogleNetHttpTransport.newTrustedTransport();
    JsonFactory JSON_FACTORY = JacksonFactory.getDefaultInstance();
    return new Compute.Builder(
            httpTransport, JSON_FACTORY, null).setApplicationName(APPLICATION_NAME)
                                              .setHttpRequestInitializer(credential).build();
}