com.google.api.client.util.store.DataStoreFactory Java Examples

The following examples show how to use com.google.api.client.util.store.DataStoreFactory. 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: AdvancedCreateCredentialFromScratch.java    From googleads-java-lib with Apache License 2.0 6 votes vote down vote up
private static AdWordsSession createAdWordsSession(String userId, DataStoreFactory storeFactory)
    throws IOException, ValidationException, ConfigurationLoadException {
  // Create a GoogleCredential with minimal information.
  GoogleAuthorizationCodeFlow authorizationFlow = new GoogleAuthorizationCodeFlow.Builder(
      new NetHttpTransport(),
      new JacksonFactory(),
      CLIENT_ID,
      CLIENT_SECRET,
      Arrays.asList(SCOPE))
      .setDataStoreFactory(storeFactory)
      .build();

  // Load the credential.
  Credential credential = authorizationFlow.loadCredential(userId);

  // Construct an AdWordsSession using the default ads.properties file to set the session's
  // developer token, client customer ID, etc., but use the credentials created above.
  return new AdWordsSession.Builder()
      .fromFile()
      .withOAuth2Credential(credential)
      .build();
}
 
Example #2
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.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();

  // Store the credential for the user.
  authorizationFlow.createAndStoreCredential(tokenResponse, userId);
}
 
Example #3
Source File: AdvancedCreateCredentialFromScratch.java    From googleads-java-lib with Apache License 2.0 6 votes vote down vote up
public static void main(String[] args) throws Exception {
  if (CLIENT_ID.equals("INSERT_CLIENT_ID_HERE")
      || CLIENT_SECRET.equals("INSERT_CLIENT_SECRET_HERE")) {
    throw new IllegalArgumentException(
        "Please input your client IDs or secret. "
            + "See https://console.developers.google.com/project");
  }

  // It is highly recommended that you use a credential store in your
  // application to store a per-user Credential.
  // See:
  // https://developers.google.com/api-client-library/java/google-api-java-client/oauth2#data_store
  DataStoreFactory storeFactory = new MemoryDataStoreFactory();

  // Authorize and store your credential.
  authorize(storeFactory, USER_ID);

  // Create a AdManagerSession from the credential store. You will typically do this
  // in a servlet interceptor for a web application or per separate thread
  // of your offline application.
  AdManagerSession adManagerSession = createDfpSession(storeFactory, USER_ID);

  AdManagerServices adManagerServices = new AdManagerServices();

  runExample(adManagerServices, adManagerSession);
}
 
Example #4
Source File: AdvancedCreateCredentialFromScratch.java    From googleads-java-lib with Apache License 2.0 6 votes vote down vote up
private static AdManagerSession createDfpSession(DataStoreFactory storeFactory, String userId)
    throws IOException, ValidationException, ConfigurationLoadException {

  // Create a GoogleCredential with minimal information.
  GoogleAuthorizationCodeFlow authorizationFlow =
      new GoogleAuthorizationCodeFlow.Builder(
              new NetHttpTransport(),
              new JacksonFactory(),
              CLIENT_ID,
              CLIENT_SECRET,
              Arrays.asList(SCOPE))
          .setDataStoreFactory(storeFactory)
          .build();

  // Load the credential.
  Credential credential = authorizationFlow.loadCredential(userId);

  // Construct a AdManagerSession.
  return new AdManagerSession.Builder().fromFile().withOAuth2Credential(credential).build();
}
 
Example #5
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 #6
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 #7
Source File: AppEngineDataStoreFactoryTest.java    From google-http-java-client with Apache License 2.0 5 votes vote down vote up
@Override
protected DataStoreFactory newDataStoreFactory() {
  return AppEngineDataStoreFactory.getDefaultInstance();
}
 
Example #8
Source File: GoogleDriveServiceImpl.java    From sakai with Educational Community License v2.0 5 votes vote down vote up
public void init() {
	log.debug("GoogleDriveServiceImpl init");
	OBJECT_MAPPER.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);
	
	clientId = serverConfigurationService.getString(GOOGLEDRIVE_PREFIX + GOOGLEDRIVE_CLIENT_ID, null);
	clientSecret = serverConfigurationService.getString(GOOGLEDRIVE_PREFIX + GOOGLEDRIVE_CLIENT_SECRET, null);
	redirectUri = serverConfigurationService.getString(GOOGLEDRIVE_PREFIX + GOOGLEDRIVE_REDIRECT_URI, "http://localhost:8080/sakai-googledrive-tool");

	try {
		JsonNode rootNode = OBJECT_MAPPER.createObjectNode();
		JsonNode webInfo = OBJECT_MAPPER.createObjectNode();
		((ObjectNode) webInfo).put("client_id", clientId);
		//((ObjectNode) webInfo).put("project_id", "algebraic-creek-243007");
		((ObjectNode) webInfo).put("auth_uri", ENDPOINT_AUTH);
		((ObjectNode) webInfo).put("token_uri", ENDPOINT_TOKEN);
		((ObjectNode) webInfo).put("auth_provider_x509_cert_url", ENDPOINT_CERTS);
		((ObjectNode) webInfo).put("client_secret", clientSecret);
		((ObjectNode) rootNode).set("web", webInfo);
		InputStream isJson = IOUtils.toInputStream(rootNode.toString());
		isJson.close();//?

		httpTransport = GoogleNetHttpTransport.newTrustedTransport();
		jsonFactory = JacksonFactory.getDefaultInstance();
		clientSecrets = GoogleClientSecrets.load(jsonFactory, new InputStreamReader(isJson));

		DataStoreFactory dataStore = new JPADataStoreFactory(googledriveRepo);			
		flow = new GoogleAuthorizationCodeFlow.Builder(httpTransport, jsonFactory, clientSecrets, Collections.singleton(DriveScopes.DRIVE))
				.setDataStoreFactory(dataStore)
				.setApprovalPrompt("force")
				.setAccessType("offline")
				.build();
	} catch(Exception e) {
		log.error("Error while trying to init Google Drive configuration");
	}

	driveRootItemsCache = memoryService.<String, List<GoogleDriveItem>>getCache("org.sakaiproject.googledrive.service.driveRootItemsCache");
	driveChildrenItemsCache = memoryService.<String, List<GoogleDriveItem>>getCache("org.sakaiproject.googledrive.service.driveChildrenItemsCache");
	googledriveUserCache = memoryService.<String, Drive>getCache("org.sakaiproject.googledrive.service.googledriveUserCache");
	driveItemsCache = memoryService.<String, GoogleDriveItem>getCache("org.sakaiproject.googledrive.service.driveItemsCache");
}
 
Example #9
Source File: GoogleDriveServiceImpl.java    From sakai with Educational Community License v2.0 5 votes vote down vote up
public void init() {
	log.debug("GoogleDriveServiceImpl init");
	OBJECT_MAPPER.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);
	
	clientId = serverConfigurationService.getString(GOOGLEDRIVE_PREFIX + GOOGLEDRIVE_CLIENT_ID, null);
	clientSecret = serverConfigurationService.getString(GOOGLEDRIVE_PREFIX + GOOGLEDRIVE_CLIENT_SECRET, null);
	redirectUri = serverConfigurationService.getString(GOOGLEDRIVE_PREFIX + GOOGLEDRIVE_REDIRECT_URI, "http://localhost:8080/sakai-googledrive-tool");

	try {
		JsonNode rootNode = OBJECT_MAPPER.createObjectNode();
		JsonNode webInfo = OBJECT_MAPPER.createObjectNode();
		((ObjectNode) webInfo).put("client_id", clientId);
		//((ObjectNode) webInfo).put("project_id", "algebraic-creek-243007");
		((ObjectNode) webInfo).put("auth_uri", ENDPOINT_AUTH);
		((ObjectNode) webInfo).put("token_uri", ENDPOINT_TOKEN);
		((ObjectNode) webInfo).put("auth_provider_x509_cert_url", ENDPOINT_CERTS);
		((ObjectNode) webInfo).put("client_secret", clientSecret);
		((ObjectNode) rootNode).set("web", webInfo);
		InputStream isJson = IOUtils.toInputStream(rootNode.toString());
		isJson.close();//?

		httpTransport = GoogleNetHttpTransport.newTrustedTransport();
		jsonFactory = JacksonFactory.getDefaultInstance();
		clientSecrets = GoogleClientSecrets.load(jsonFactory, new InputStreamReader(isJson));

		DataStoreFactory dataStore = new JPADataStoreFactory(googledriveRepo);			
		flow = new GoogleAuthorizationCodeFlow.Builder(httpTransport, jsonFactory, clientSecrets, Collections.singleton(DriveScopes.DRIVE))
				.setDataStoreFactory(dataStore)
				.setApprovalPrompt("force")
				.setAccessType("offline")
				.build();
	} catch(Exception e) {
		log.error("Error while trying to init Google Drive configuration");
	}

	driveRootItemsCache = memoryService.<String, List<GoogleDriveItem>>getCache("org.sakaiproject.googledrive.service.driveRootItemsCache");
	driveChildrenItemsCache = memoryService.<String, List<GoogleDriveItem>>getCache("org.sakaiproject.googledrive.service.driveChildrenItemsCache");
	googledriveUserCache = memoryService.<String, Drive>getCache("org.sakaiproject.googledrive.service.googledriveUserCache");
	driveItemsCache = memoryService.<String, GoogleDriveItem>getCache("org.sakaiproject.googledrive.service.driveItemsCache");
}
 
Example #10
Source File: GoogleAuthorizationCodeFlow.java    From google-api-java-client with Apache License 2.0 4 votes vote down vote up
@Override
public Builder setDataStoreFactory(DataStoreFactory dataStore) throws IOException {
  return (Builder) super.setDataStoreFactory(dataStore);
}
 
Example #11
Source File: Utils.java    From java-samples with Apache License 2.0 4 votes vote down vote up
/** Gets the datastore factory used in these samples. */
public static DataStoreFactory getDataStoreFactory() {
  return dataStoreFactory;
}
 
Example #12
Source File: MemoryDataStoreFactoryTest.java    From google-http-java-client with Apache License 2.0 4 votes vote down vote up
@Override
protected DataStoreFactory newDataStoreFactory() {
  return MemoryDataStoreFactory.getDefaultInstance();
}
 
Example #13
Source File: AbstractDataStoreFactoryTest.java    From google-http-java-client with Apache License 2.0 4 votes vote down vote up
/** Returns a new instance of the data store factory to test. */
protected abstract DataStoreFactory newDataStoreFactory() throws Exception;
 
Example #14
Source File: AppEngineNoMemcacheDataStoreFactoryTest.java    From google-http-java-client with Apache License 2.0 4 votes vote down vote up
@Override
protected DataStoreFactory newDataStoreFactory() {
  return new AppEngineDataStoreFactory.Builder().setDisableMemcache(true).build();
}
 
Example #15
Source File: StoredChannel.java    From google-api-java-client with Apache License 2.0 2 votes vote down vote up
/**
 * Returns the stored channel data store using the ID {@link #DEFAULT_DATA_STORE_ID}.
 *
 * @param dataStoreFactory data store factory
 * @return stored channel data store
 */
public static DataStore<StoredChannel> getDefaultDataStore(DataStoreFactory dataStoreFactory)
    throws IOException {
  return dataStoreFactory.getDataStore(DEFAULT_DATA_STORE_ID);
}
 
Example #16
Source File: WebhookUtils.java    From google-api-java-client with Apache License 2.0 2 votes vote down vote up
/**
 * Utility method to process the webhook notification from {@link HttpServlet#doPost} by finding
 * the notification channel in the given data store factory.
 *
 * <p>
 * It is a wrapper around
 * {@link #processWebhookNotification(HttpServletRequest, HttpServletResponse, DataStore)} that
 * uses the data store from {@link StoredChannel#getDefaultDataStore(DataStoreFactory)}.
 * </p>
 *
 * @param req an {@link HttpServletRequest} object that contains the request the client has made
 *        of the servlet
 * @param resp an {@link HttpServletResponse} object that contains the response the servlet sends
 *        to the client
 * @param dataStoreFactory data store factory
 * @exception IOException if an input or output error is detected when the servlet handles the
 *            request
 * @exception ServletException if the request for the POST could not be handled
 */
public static void processWebhookNotification(
    HttpServletRequest req, HttpServletResponse resp, DataStoreFactory dataStoreFactory)
    throws ServletException, IOException {
  processWebhookNotification(req, resp, StoredChannel.getDefaultDataStore(dataStoreFactory));
}
 
Example #17
Source File: NotificationServlet.java    From google-api-java-client with Apache License 2.0 2 votes vote down vote up
/**
 * Constructor which uses {@link StoredChannel#getDefaultDataStore(DataStoreFactory)} on the given
 * data store factory, which is the normal use case.
 *
 * @param dataStoreFactory data store factory
 */
protected NotificationServlet(DataStoreFactory dataStoreFactory) throws IOException {
  this(StoredChannel.getDefaultDataStore(dataStoreFactory));
}
 
Example #18
Source File: StoredChannel.java    From google-api-java-client with Apache License 2.0 2 votes vote down vote up
/**
 * Stores this notification channel in the notification channel data store, which is derived from
 * {@link #getDefaultDataStore(DataStoreFactory)} on the given data store factory.
 *
 * <p>
 * It is important that this method be called before the watch HTTP request is made in case the
 * notification is received before the watch HTTP response is received.
 * </p>
 *
 * @param dataStoreFactory data store factory
 */
public StoredChannel store(DataStoreFactory dataStoreFactory) throws IOException {
  return store(getDefaultDataStore(dataStoreFactory));
}
 
Example #19
Source File: AuthorizationCodeFlow.java    From google-oauth-java-client with Apache License 2.0 2 votes vote down vote up
/**
 * {@link Beta} <br/>
 * Sets the data store factory or {@code null} for none.
 *
 * <p>
 * Warning: not compatible with {@link #setCredentialStore}, and if it is called before this
 * method is called, this method will throw an {@link IllegalArgumentException}.
 * </p>
 *
 * <p>
 * Overriding is only supported for the purpose of calling the super implementation and changing
 * the return type, but nothing else.
 * </p>
 *
 * @since 1.16
 */
@Beta
public Builder setDataStoreFactory(DataStoreFactory dataStoreFactory) throws IOException {
  return setCredentialDataStore(StoredCredential.getDefaultDataStore(dataStoreFactory));
}
 
Example #20
Source File: StoredCredential.java    From google-oauth-java-client with Apache License 2.0 2 votes vote down vote up
/**
 * Returns the stored credential data store using the ID {@link #DEFAULT_DATA_STORE_ID}.
 *
 * @param dataStoreFactory data store factory
 * @return stored credential data store
 */
public static DataStore<StoredCredential> getDefaultDataStore(DataStoreFactory dataStoreFactory)
    throws IOException {
  return dataStoreFactory.getDataStore(DEFAULT_DATA_STORE_ID);
}
 
Example #21
Source File: DataStoreCredentialRefreshListener.java    From google-oauth-java-client with Apache License 2.0 2 votes vote down vote up
/**
 * Constructor using {@link StoredCredential#getDefaultDataStore(DataStoreFactory)} for the stored
 * credential data store.
 *
 * @param userId user ID whose credential is to be updated
 * @param dataStoreFactory data store factory
 */
public DataStoreCredentialRefreshListener(String userId, DataStoreFactory dataStoreFactory)
    throws IOException {
  this(userId, StoredCredential.getDefaultDataStore(dataStoreFactory));
}