com.google.api.client.json.jackson2.JacksonFactory Java Examples

The following examples show how to use com.google.api.client.json.jackson2.JacksonFactory. 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: IndexingServiceTest.java    From connector-sdk with Apache License 2.0 6 votes vote down vote up
@Test
public void testBuilderWithServices() throws IOException, GeneralSecurityException {
  CredentialFactory credentialFactory =
      scopes ->
          new MockGoogleCredential.Builder()
              .setTransport(new MockHttpTransport())
              .setJsonFactory(JacksonFactory.getDefaultInstance())
              .build();
  assertNotNull(
      new IndexingServiceImpl.Builder()
          .setSourceId(SOURCE_ID)
          .setIdentitySourceId(IDENTITY_SOURCE_ID)
          .setService(cloudSearch)
          .setBatchingIndexingService(batchingService)
          .setCredentialFactory(credentialFactory)
          .setBatchPolicy(new BatchPolicy.Builder().build())
          .setRetryPolicy(new RetryPolicy.Builder().build())
          .setConnectorId("unitTest")
          .build());
}
 
Example #2
Source File: IndexingServiceTest.java    From connector-sdk with Apache License 2.0 6 votes vote down vote up
@Test
public void testBuilderWithConfigurationAndCredentialFactory()
    throws IOException, GeneralSecurityException {
  CredentialFactory credentialFactory =
      scopes ->
          new MockGoogleCredential.Builder()
              .setTransport(new MockHttpTransport())
              .setJsonFactory(JacksonFactory.getDefaultInstance())
              .build();
  Properties config = new Properties();
  config.put(IndexingServiceImpl.SOURCE_ID, "sourceId");
  config.put(IndexingServiceImpl.IDENTITY_SOURCE_ID, "identitySourceId");
  setupConfig.initConfig(config);
  IndexingServiceImpl.Builder.fromConfiguration(Optional.of(credentialFactory), "unitTest")
      .build();
}
 
Example #3
Source File: DisableServiceAccount.java    From java-docs-samples with Apache License 2.0 6 votes vote down vote up
private static Iam initService() throws GeneralSecurityException, IOException {
  // Use the Application Default Credentials strategy for authentication. For more info, see:
  // https://cloud.google.com/docs/authentication/production#finding_credentials_automatically
  GoogleCredentials credential =
      GoogleCredentials.getApplicationDefault()
          .createScoped(Collections.singleton(IamScopes.CLOUD_PLATFORM));
  // Initialize the IAM service, which can be used to send requests to the IAM API.
  Iam service =
      new Iam.Builder(
              GoogleNetHttpTransport.newTrustedTransport(),
              JacksonFactory.getDefaultInstance(),
              new HttpCredentialsAdapter(credential))
          .setApplicationName("service-accounts")
          .build();
  return service;
}
 
Example #4
Source File: LocalFileCredentialFactory.java    From connector-sdk with Apache License 2.0 6 votes vote down vote up
/**
 * Gets {@link GoogleCredential} instance constructed for service account.
 */
@Override
public GoogleCredential getCredential(Collection<String> scopes)
    throws GeneralSecurityException, IOException {

  JsonFactory jsonFactory = JacksonFactory.getDefaultInstance();

  HttpTransport transport = proxy.getHttpTransport();
  if (!isJsonKey) {
    return credentialHelper.getP12Credential(
        serviceAccountId,
        serviceAccountKeyFilePath,
        transport,
        jsonFactory,
        proxy.getHttpRequestInitializer(),
        scopes);
  }
  return credentialHelper.getJsonCredential(
      serviceAccountKeyFilePath,
      transport,
      jsonFactory,
      proxy.getHttpRequestInitializer(),
      scopes);
}
 
Example #5
Source File: TestUtils.java    From connector-sdk with Apache License 2.0 6 votes vote down vote up
/**
 * Asserts that the expected and the actual items match. Tests tend to use this by
 * passing in an Item constructed in the test class to compare with an Item from the
 * server. Tests have an option of setting the name to a fully-qualified name
 * (datasources/id/items/name) or just the name. This comparison compares the item
 * names, ignoring any prefixes.
 *
 * @throws AssertionError - if the items don't match.
 */
private void assertItemsMatch(Item expected, Item actual) {
  logger.log(Level.INFO, "Comparing item \n{0} \nto \n{1}", new Object[] {expected, actual});

  // TODO(lchandramouli): verify all applicable meta data
  assertEquals("ACCEPTED", actual.getStatus().getCode());
  assertEquals("name", getItemName(expected.getName()), getItemName(actual.getName()));
  assertEquals("item type", expected.getItemType(), actual.getItemType());

  ItemMetadata expectedMetadata = expected.getMetadata();
  ItemMetadata actualMetadata = actual.getMetadata();
  expectedMetadata.setContainerName(getItemName(expectedMetadata.getContainerName()));
  actualMetadata.setContainerName(getItemName(actualMetadata.getContainerName()));
  if (!expectedMetadata.equals(actualMetadata)) {
    // toString() produces different output (expected does not contain quotes, actual
    // does), so set a JSON factory here so assertEquals can highlight the differences.
    expectedMetadata.setFactory(JacksonFactory.getDefaultInstance());
    assertEquals(expectedMetadata.toString(), actualMetadata.toString());
  }
}
 
Example #6
Source File: CloudiotPubsubExampleServer.java    From java-docs-samples with Apache License 2.0 6 votes vote down vote up
/** Delete this registry from Cloud IoT. */
public static void deleteRegistry(String cloudRegion, String projectId, String registryName)
    throws GeneralSecurityException, IOException {
  GoogleCredentials credential =
      GoogleCredentials.getApplicationDefault().createScoped(CloudIotScopes.all());
  JsonFactory jsonFactory = JacksonFactory.getDefaultInstance();
  HttpRequestInitializer init = new HttpCredentialsAdapter(credential);
  final CloudIot service =
      new CloudIot.Builder(GoogleNetHttpTransport.newTrustedTransport(), jsonFactory, init)
          .setApplicationName(APP_NAME)
          .build();

  final String registryPath =
      String.format(
          "projects/%s/locations/%s/registries/%s", projectId, cloudRegion, registryName);

  System.out.println("Deleting: " + registryPath);
  service.projects().locations().registries().delete(registryPath).execute();
}
 
Example #7
Source File: GoogleWriteableProfileRegistry.java    From halyard with Apache License 2.0 6 votes vote down vote up
GoogleWriteableProfileRegistry(WriteableProfileRegistryProperties properties) {
  HttpTransport httpTransport = GoogleCredentials.buildHttpTransport();
  JsonFactory jsonFactory = JacksonFactory.getDefaultInstance();
  com.google.auth.oauth2.GoogleCredentials credentials;
  try {
    credentials = loadCredentials(properties.getJsonPath());
  } catch (IOException e) {
    throw new RuntimeException("Failed to load json credential", e);
  }

  this.storage =
      new Storage.Builder(
              httpTransport, jsonFactory, GoogleCredentials.setHttpTimeout(credentials))
          .setApplicationName("halyard")
          .build();
  this.properties = properties;
}
 
Example #8
Source File: CloudIotManager.java    From daq with Apache License 2.0 6 votes vote down vote up
private void initializeCloudIoT() {
  projectPath = "projects/" + projectId + "/locations/" + cloudRegion;
  try {
    System.err.println("Initializing with default credentials...");
    GoogleCredentials credential =
        GoogleCredentials.getApplicationDefault().createScoped(CloudIotScopes.all());
    JsonFactory jsonFactory = JacksonFactory.getDefaultInstance();
    HttpRequestInitializer init = new HttpCredentialsAdapter(credential);
    cloudIotService =
        new CloudIot.Builder(GoogleNetHttpTransport.newTrustedTransport(), jsonFactory, init)
            .setApplicationName("com.google.iot.bos")
            .build();
    cloudIotRegistries = cloudIotService.projects().locations().registries();
    System.err.println("Created service for project " + projectPath);
  } catch (Exception e) {
    throw new RuntimeException("While initializing Cloud IoT project " + projectPath, e);
  }
}
 
Example #9
Source File: GooglePhotosInterface.java    From data-transfer-project with Apache License 2.0 6 votes vote down vote up
MediaItemSearchResponse listMediaItems(Optional<String> albumId, Optional<String> pageToken)
    throws IOException, InvalidTokenException, PermissionDeniedException {
  Map<String, Object> params = new LinkedHashMap<>();
  params.put(PAGE_SIZE_KEY, String.valueOf(MEDIA_PAGE_SIZE));
  if (albumId.isPresent()) {
    params.put(ALBUM_ID_KEY, albumId.get());
  } else {
    params.put(FILTERS_KEY, ImmutableMap.of(INCLUDE_ARCHIVED_KEY, String.valueOf(true)));
  }
  if (pageToken.isPresent()) {
    params.put(TOKEN_KEY, pageToken.get());
  }
  HttpContent content = new JsonHttpContent(new JacksonFactory(), params);
  return makePostRequest(
      BASE_URL + "mediaItems:search", Optional.empty(), content, MediaItemSearchResponse.class);
}
 
Example #10
Source File: GoogleBloggerProxy.java    From petscii-bbs with Mozilla Public License 2.0 6 votes vote down vote up
public void init() throws IOException {
    try {
        originalBlogUrl = blogUrl;
        cls();
        write(GREY3);
        waitOn();

        this.credential = GoogleCredential
                .fromStream(new FileInputStream(CRED_FILE_PATH))
                .createScoped(Arrays.asList(BloggerScopes.BLOGGER));

        this.blogger = new Blogger.Builder(new NetHttpTransport(), new JacksonFactory(), credential)
                .setApplicationName("PETSCII BBS Builder - Blogger Proxy - " + this.getClass().getSimpleName())
                .build();

        changeBlogIdByUrl(this.blogUrl);
        pageTokens.reset();
        waitOff();
    } catch (IOException e) {
        exitWithError();
    }
}
 
Example #11
Source File: ListServiceAccountKeys.java    From java-docs-samples with Apache License 2.0 6 votes vote down vote up
private static Iam initService() throws GeneralSecurityException, IOException {
  // Use the Application Default Credentials strategy for authentication. For more info, see:
  // https://cloud.google.com/docs/authentication/production#finding_credentials_automatically
  GoogleCredentials credential =
      GoogleCredentials.getApplicationDefault()
          .createScoped(Collections.singleton(IamScopes.CLOUD_PLATFORM));
  // Initialize the IAM service, which can be used to send requests to the IAM API.
  Iam service =
      new Iam.Builder(
              GoogleNetHttpTransport.newTrustedTransport(),
              JacksonFactory.getDefaultInstance(),
              new HttpCredentialsAdapter(credential))
          .setApplicationName("service-account-keys")
          .build();
  return service;
}
 
Example #12
Source File: DeviceRegistryExample.java    From java-docs-samples with Apache License 2.0 6 votes vote down vote up
/** Retrieves registry metadata from a project. * */
protected static DeviceRegistry getRegistry(
    String projectId, String cloudRegion, String registryName)
    throws GeneralSecurityException, IOException {
  GoogleCredentials credential =
      GoogleCredentials.getApplicationDefault().createScoped(CloudIotScopes.all());
  JsonFactory jsonFactory = JacksonFactory.getDefaultInstance();
  HttpRequestInitializer init = new HttpCredentialsAdapter(credential);
  final CloudIot service =
      new CloudIot.Builder(GoogleNetHttpTransport.newTrustedTransport(), jsonFactory, init)
          .setApplicationName(APP_NAME)
          .build();

  final String registryPath =
      String.format(
          "projects/%s/locations/%s/registries/%s", projectId, cloudRegion, registryName);

  return service.projects().locations().registries().get(registryPath).execute();
}
 
Example #13
Source File: GuiMain.java    From google-sites-liberation with Apache License 2.0 6 votes vote down vote up
/**
 * Retrieve OAuth 2.0 credentials.
 * 
 * @return OAuth 2.0 Credential instance.
 * @throws IOException
 */
private Credential getCredentials() throws IOException {
  String code = tokenField.getText();
  HttpTransport transport = new NetHttpTransport();
  JacksonFactory jsonFactory = new JacksonFactory();
  String CLIENT_SECRET = "EPME5fbwiNLCcMsnj3jVoXeY";

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

  // Build a new GoogleCredential instance and return it.
  return new GoogleCredential.Builder()
      .setClientSecrets(CLIENT_ID, CLIENT_SECRET)
      .setJsonFactory(jsonFactory).setTransport(transport).build()
      .setAccessToken(response.getAccessToken())
      .setRefreshToken(response.getRefreshToken());
}
 
Example #14
Source File: CloudiotPubsubExampleServer.java    From java-docs-samples with Apache License 2.0 6 votes vote down vote up
/** Delete this device from Cloud IoT. */
public static void deleteDevice(
    String deviceId, String projectId, String cloudRegion, String registryName)
    throws GeneralSecurityException, IOException {
  GoogleCredentials credential =
      GoogleCredentials.getApplicationDefault().createScoped(CloudIotScopes.all());
  JsonFactory jsonFactory = JacksonFactory.getDefaultInstance();
  HttpRequestInitializer init = new HttpCredentialsAdapter(credential);
  final CloudIot service =
      new CloudIot.Builder(GoogleNetHttpTransport.newTrustedTransport(), jsonFactory, init)
          .setApplicationName(APP_NAME)
          .build();

  final String devicePath =
      String.format(
          "projects/%s/locations/%s/registries/%s/devices/%s",
          projectId, cloudRegion, registryName, deviceId);

  System.out.println("Deleting device " + devicePath);
  service.projects().locations().registries().devices().delete(devicePath).execute();
}
 
Example #15
Source File: DirectoryGroupsConnectionTest.java    From nomulus with Apache License 2.0 6 votes vote down vote up
/** Returns a valid GoogleJsonResponseException for the given status code and error message.  */
private GoogleJsonResponseException makeResponseException(
    final int statusCode,
    final String message) throws Exception {
  HttpTransport transport = new MockHttpTransport() {
    @Override
    public LowLevelHttpRequest buildRequest(String method, String url) {
      return new MockLowLevelHttpRequest() {
        @Override
        public LowLevelHttpResponse execute() {
          MockLowLevelHttpResponse response = new MockLowLevelHttpResponse();
          response.setStatusCode(statusCode);
          response.setContentType(Json.MEDIA_TYPE);
          response.setContent(String.format(
              "{\"error\":{\"code\":%d,\"message\":\"%s\",\"domain\":\"global\","
              + "\"reason\":\"duplicate\"}}",
              statusCode,
              message));
          return response;
        }};
    }};
  HttpRequest request = transport.createRequestFactory()
      .buildGetRequest(HttpTesting.SIMPLE_GENERIC_URL)
      .setThrowExceptionOnExecuteError(false);
  return GoogleJsonResponseException.from(new JacksonFactory(), request.execute());
}
 
Example #16
Source File: SetPolicy.java    From java-docs-samples with Apache License 2.0 6 votes vote down vote up
public static CloudResourceManager createCloudResourceManagerService()
    throws IOException, GeneralSecurityException {
  // Use the Application Default Credentials strategy for authentication. For more info, see:
  // https://cloud.google.com/docs/authentication/production#finding_credentials_automatically
  GoogleCredentials credential =
      GoogleCredentials.getApplicationDefault()
          .createScoped(Collections.singleton(IamScopes.CLOUD_PLATFORM));

  CloudResourceManager service =
      new CloudResourceManager.Builder(
              GoogleNetHttpTransport.newTrustedTransport(),
              JacksonFactory.getDefaultInstance(),
              new HttpCredentialsAdapter(credential))
          .setApplicationName("service-accounts")
          .build();
  return service;
}
 
Example #17
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 #18
Source File: GCPProject.java    From policyscanner with Apache License 2.0 6 votes vote down vote up
/**
 * Return the Projects api object used for accessing the Cloud Resource Manager Projects API.
 * @return Projects api object used for accessing the Cloud Resource Manager Projects API
 * @throws GeneralSecurityException Thrown if there's a permissions error.
 * @throws IOException Thrown if there's an IO error initializing the API object.
 */
public static synchronized Projects getProjectsApiStub()
    throws GeneralSecurityException, IOException {
  if (projectApiStub != null) {
    return projectApiStub;
  }
  HttpTransport transport;
  GoogleCredential credential;
  JsonFactory jsonFactory = JacksonFactory.getDefaultInstance();
  transport = GoogleNetHttpTransport.newTrustedTransport();
  credential = GoogleCredential.getApplicationDefault(transport, jsonFactory);
  if (credential.createScopedRequired()) {
    Collection<String> scopes = CloudResourceManagerScopes.all();
    credential = credential.createScoped(scopes);
  }
  projectApiStub = new CloudResourceManager
      .Builder(transport, jsonFactory, credential)
      .build()
      .projects();
  return projectApiStub;
}
 
Example #19
Source File: GCPServiceAccount.java    From policyscanner with Apache License 2.0 6 votes vote down vote up
/**
 * Get the API stub for accessing the IAM Service Accounts API.
 * @return ServiceAccounts api stub for accessing the IAM Service Accounts API.
 * @throws IOException Thrown if there's an IO error initializing the api connection.
 * @throws GeneralSecurityException Thrown if there's a security error
 * initializing the connection.
 */
public static ServiceAccounts getServiceAccountsApiStub() throws IOException, GeneralSecurityException {
  if (serviceAccountsApiStub == null) {
    HttpTransport transport;
    GoogleCredential credential;
    JsonFactory jsonFactory = JacksonFactory.getDefaultInstance();
    transport = GoogleNetHttpTransport.newTrustedTransport();
    credential = GoogleCredential.getApplicationDefault(transport, jsonFactory);
    if (credential.createScopedRequired()) {
      Collection<String> scopes = IamScopes.all();
      credential = credential.createScoped(scopes);
    }
    serviceAccountsApiStub = new Iam.Builder(transport, jsonFactory, credential)
        .build()
        .projects()
        .serviceAccounts();
  }
  return serviceAccountsApiStub;
}
 
Example #20
Source File: DriveSyncProvider.java    From science-journal with Apache License 2.0 6 votes vote down vote up
private void addServiceForAccount(AppAccount appAccount) {


    HttpTransport transport = AndroidHttp.newCompatibleTransport();
    JsonFactory jsonFactory = JacksonFactory.getDefaultInstance();
    accountMap.put(
        appAccount,
        new DriveSyncManager(
            appAccount,
            AppSingleton.getInstance(applicationContext).getDataController(appAccount),
            transport,
            jsonFactory,
            applicationContext,
            driveSupplier,
            AppSingleton.getInstance(applicationContext)
                .getSensorEnvironment()
                .getDataController(appAccount)));
  }
 
Example #21
Source File: GoogleAuthTest.java    From endpoints-java with Apache License 2.0 6 votes vote down vote up
private HttpRequest constructHttpRequest(final String content, final int statusCode) throws IOException {
  HttpTransport transport = new MockHttpTransport() {
    @Override
    public LowLevelHttpRequest buildRequest(String method, String url) throws IOException {
      return new MockLowLevelHttpRequest() {
        @Override
        public LowLevelHttpResponse execute() throws IOException {
          MockLowLevelHttpResponse result = new MockLowLevelHttpResponse();
          result.setContentType("application/json");
          result.setContent(content);
          result.setStatusCode(statusCode);
          return result;
        }
      };
    }
  };
  HttpRequest httpRequest = transport.createRequestFactory().buildGetRequest(new GenericUrl("https://google.com")).setParser(new JsonObjectParser(new JacksonFactory()));
  GoogleAuth.configureErrorHandling(httpRequest);
  return httpRequest;
}
 
Example #22
Source File: DeleteServiceAccountKey.java    From java-docs-samples with Apache License 2.0 6 votes vote down vote up
private static Iam initService() throws GeneralSecurityException, IOException {
  // Use the Application Default Credentials strategy for authentication. For more info, see:
  // https://cloud.google.com/docs/authentication/production#finding_credentials_automatically
  GoogleCredentials credential =
      GoogleCredentials.getApplicationDefault()
          .createScoped(Collections.singleton(IamScopes.CLOUD_PLATFORM));
  // Initialize the IAM service, which can be used to send requests to the IAM API.
  Iam service =
      new Iam.Builder(
              GoogleNetHttpTransport.newTrustedTransport(),
              JacksonFactory.getDefaultInstance(),
              new HttpCredentialsAdapter(credential))
          .setApplicationName("service-account-keys")
          .build();
  return service;
}
 
Example #23
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 #24
Source File: DeviceRegistryExample.java    From java-docs-samples with Apache License 2.0 6 votes vote down vote up
/** Delete this registry from Cloud IoT. */
protected static void deleteRegistry(String cloudRegion, String projectId, String registryName)
    throws GeneralSecurityException, IOException {
  GoogleCredentials credential =
      GoogleCredentials.getApplicationDefault().createScoped(CloudIotScopes.all());
  JsonFactory jsonFactory = JacksonFactory.getDefaultInstance();
  HttpRequestInitializer init = new HttpCredentialsAdapter(credential);
  final CloudIot service =
      new CloudIot.Builder(GoogleNetHttpTransport.newTrustedTransport(), jsonFactory, init)
          .setApplicationName(APP_NAME)
          .build();

  final String registryPath =
      String.format(
          "projects/%s/locations/%s/registries/%s", projectId, cloudRegion, registryName);

  System.out.println("Deleting: " + registryPath);
  service.projects().locations().registries().delete(registryPath).execute();
}
 
Example #25
Source File: GSpreadFeedProcessor.java    From micro-integrator with Apache License 2.0 5 votes vote down vote up
/**
 * helper method to get the base credential object
 *
 * @return credential
 */
private GoogleCredential getBaseCredential() {
    HttpTransport httpTransport = new NetHttpTransport();
    JacksonFactory jsonFactory = new JacksonFactory();
    GoogleCredential credential = new GoogleCredential.Builder()
            .setClientSecrets(this.clientId, this.clientSecret)
            .setTransport(httpTransport)
            .setJsonFactory(jsonFactory)
            .build();
    return credential;
}
 
Example #26
Source File: GoogleOAuthAuthenticator.java    From codenvy with Eclipse Public License 1.0 5 votes vote down vote up
@Inject
public GoogleOAuthAuthenticator(
    @Nullable @Named("oauth.google.clientid") String clientId,
    @Nullable @Named("oauth.google.clientsecret") String clientSecret,
    @Nullable @Named("oauth.google.redirecturis") String[] redirectUris,
    @Nullable @Named("oauth.google.authuri") String authUri,
    @Nullable @Named("oauth.google.tokenuri") String tokenUri)
    throws IOException {
  if (!isNullOrEmpty(clientId)
      && !isNullOrEmpty(clientSecret)
      && redirectUris != null
      && redirectUris.length != 0) {

    configure(
        new GoogleAuthorizationCodeFlow.Builder(
                new NetHttpTransport(),
                new JacksonFactory(),
                new GoogleClientSecrets()
                    .setWeb(
                        new GoogleClientSecrets.Details()
                            .setClientId(clientId)
                            .setClientSecret(clientSecret)
                            .setRedirectUris(Arrays.asList(redirectUris))
                            .setAuthUri(authUri)
                            .setTokenUri(tokenUri)),
                Arrays.asList(
                    "https://www.googleapis.com/auth/userinfo.email",
                    "https://www.googleapis.com/auth/userinfo.profile"))
            .setDataStoreFactory(new MemoryDataStoreFactory())
            .setApprovalPrompt("auto")
            .setAccessType("online")
            .build(),
        Arrays.asList(redirectUris));
  }
}
 
Example #27
Source File: TestApp.java    From gcpsamples with Apache License 2.0 5 votes vote down vote up
public TestApp() {
	try
	{

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

		GoogleClientSecrets clientSecrets =  new GoogleClientSecrets();
		GoogleClientSecrets.Details det = new GoogleClientSecrets.Details();
		det.setClientId("YOUR_CLIENT_ID");
		det.setClientSecret("YOUR_CLIENT_SECRET");
		det.setRedirectUris(Arrays.asList("urn:ietf:wg:oauth:2.0:oob"));
		clientSecrets.setInstalled(det);

		GoogleAuthorizationCodeFlow flow = new GoogleAuthorizationCodeFlow.Builder(
		    httpTransport, jsonFactory, clientSecrets,
		    Arrays.asList(Oauth2Scopes.USERINFO_EMAIL)).build();
		Credential credential = new AuthorizationCodeInstalledApp(flow,
		    new LocalServerReceiver()).authorize("user");

		Oauth2 service = new Oauth2.Builder(httpTransport, jsonFactory, credential)
		    .setApplicationName("oauth client").build();

		Userinfoplus ui = service.userinfo().get().execute();
		System.out.println(ui.getEmail());
	} 
	catch (Exception ex) {
		System.out.println("Error:  " + ex);
	}
}
 
Example #28
Source File: DeviceRegistryExample.java    From java-docs-samples with Apache License 2.0 5 votes vote down vote up
protected static void unbindDeviceFromGateway(
    String projectId, String cloudRegion, String registryName, String deviceId, String gatewayId)
    throws GeneralSecurityException, IOException {
  // [START iot_unbind_device_from_gateway]
  GoogleCredentials credential =
      GoogleCredentials.getApplicationDefault().createScoped(CloudIotScopes.all());
  JsonFactory jsonFactory = JacksonFactory.getDefaultInstance();
  HttpRequestInitializer init = new HttpCredentialsAdapter(credential);
  final CloudIot service =
      new CloudIot.Builder(GoogleNetHttpTransport.newTrustedTransport(), jsonFactory, init)
          .setApplicationName(APP_NAME)
          .build();

  final String registryPath =
      String.format(
          "projects/%s/locations/%s/registries/%s", projectId, cloudRegion, registryName);

  UnbindDeviceFromGatewayRequest request = new UnbindDeviceFromGatewayRequest();
  request.setDeviceId(deviceId);
  request.setGatewayId(gatewayId);

  UnbindDeviceFromGatewayResponse response =
      service
          .projects()
          .locations()
          .registries()
          .unbindDeviceFromGateway(registryPath, request)
          .execute();

  System.out.println(String.format("Device unbound: %s", response.toPrettyString()));
  // [END iot_unbind_device_from_gateway]
}
 
Example #29
Source File: DirectoryFacade.java    From connector-sdk with Apache License 2.0 5 votes vote down vote up
/**
 * Builder for DirectoryFacade objects.
 *
 * @param serviceKeyStream {@link InputStream} for the JSON file containing the service account
 *   key to authenticate with the Cloud Identity service.
 * @param adminEmail the email of the domain's admin account
 * @param domain the organization's domain
 */

static DirectoryFacade create(
    InputStream serviceKeyStream, String adminEmail, String domain)
    throws IOException, GeneralSecurityException {
  JsonFactory jsonFactory = JacksonFactory.getDefaultInstance();
  HttpTransport httpTransport = GoogleNetHttpTransport.newTrustedTransport();
  GoogleCredential credential = GoogleCredential
      .fromStream(serviceKeyStream)
      .createScoped(ADMIN_SCOPES);
  Credential adminCredential = new GoogleCredential.Builder()
      .setTransport(httpTransport)
      .setJsonFactory(jsonFactory)
      .setServiceAccountId(credential.getServiceAccountId())
      .setServiceAccountPrivateKey(credential.getServiceAccountPrivateKey())
      .setServiceAccountScopes(ADMIN_SCOPES)
      .setServiceAccountUser(adminEmail)
      .build();
  // Google services are rate-limited. The RetryPolicy allows to rety when a
  // 429 HTTP status response (Too Many Requests) is received.
  RetryPolicy retryPolicy = new RetryPolicy.Builder().build();
  RetryRequestInitializer requestInitializer = new RetryRequestInitializer(retryPolicy);
  Directory.Builder directoryBuilder = new Directory.Builder(
      httpTransport, jsonFactory, request -> {
    adminCredential.initialize(request);
    requestInitializer.initialize(request);
  });
  Directory directory = directoryBuilder.build();
  return new DirectoryFacade(directory, domain);
}
 
Example #30
Source File: MendeleyClient.java    From slr-toolkit with Eclipse Public License 1.0 5 votes vote down vote up
/**
 * This Method exchanges the authorization code for an access token. 
 * If successful the Tokens and Expiration Date will be stored.
 * 
 * @param code The authorization code from the user interface response has to be passed
 * @throws IOException
 * @throws TokenMgrException
 * @throws ParseException
 */
public void requestAccessToken(String code) throws IOException, TokenMgrException, ParseException {
 try {
   TokenResponse response =
       new AuthorizationCodeTokenRequest(new NetHttpTransport(), new JacksonFactory(),
           new GenericUrl("https://api.mendeley.com/oauth/token"),code)
           .setRedirectUri("https://localhost")
           .setGrantType("authorization_code")
           .setClientAuthentication(
               new BasicAuthentication("4335", "sSFcbUA38RS9Cpm7")).execute();
   
   this.access_token = response.getAccessToken();
   this.refresh_token = response.getRefreshToken();
   this.expires_at = this.generateExpiresAtFromExpiresIn(response.getExpiresInSeconds().intValue());
   
   updatePreferenceStore();
   refreshTokenIfNecessary();
 } catch (TokenResponseException e) {
   if (e.getDetails() != null) {
     System.err.println("Error: " + e.getDetails().getError());
     if (e.getDetails().getErrorDescription() != null) {
       System.err.println(e.getDetails().getErrorDescription());
     }
     if (e.getDetails().getErrorUri() != null) {
       System.err.println(e.getDetails().getErrorUri());
     }
   } else {
     System.err.println(e.getMessage());
   }
 }
}