es.davy.ai

Preguntas y respuestas de programación confiables

¿Tienes una pregunta?

Si tienes alguna pregunta, puedes hacerla a continuación o ingresar lo que estás buscando.

¿Cómo implementar una fábrica de DataStore personalizada para su uso con las API de Google utilizando OAuth2?

Estoy tratando de implementar una DataStoreFactory personalizada según se menciona en la documentación aquí para poder autenticarme con las APIs de Google y almacenar mis tokens de acceso / actualización en mi base de datos, pero no puedo encontrar ninguna documentación o ejemplos de una implementación personalizada por ejemplo:

// Construir el flujo e iniciar la solicitud de autorización del usuario.
GoogleAuthorizationCodeFlow flow = new GoogleAuthorizationCodeFlow.Builder(
        HTTP_TRANSPORT, JSON_FACTORY, clientSecrets, SCOPES)
             .setDataStoreFactory(new MyCustomDatastoreFactory() )
             .setAccessType("offline")
             .build();

Si implemento la interfaz DataStoreFactory, me da un método para implementar:

import java.io.IOException;
import java.io.Serializable;

import com.google.api.client.util.store.DataStore;
import com.google.api.client.util.store.DataStoreFactory;

public class MyCustomDatastoreFactory implements DataStoreFactory {

    @Override
    public <V extends Serializable> DataStore<V> getDataStore(String arg0) throws IOException {
        ...
    }

}

El objeto DataStore tiene varios métodos que deben ser implementados, pero no estoy seguro de dónde y cómo exactamente necesito usar esto para recuperar y almacenar mis credenciales:

new DataStore<Serializable>() {

    @Override
    public DataStore<Serializable> clear() throws IOException {
        // TODO Auto-generated method stub
        return null;
    }

    @Override
    public boolean containsKey(String arg0) throws IOException {
        // TODO Auto-generated method stub
        return false;
    }

    @Override
    public boolean containsValue(Serializable arg0) throws IOException {
        // TODO Auto-generated method stub
        return false;
    }

    @Override
    public DataStore<Serializable> delete(String arg0) throws IOException {
        // TODO Auto-generated method stub
        return null;
    }

    @Override
    public Serializable get(String arg0) throws IOException {
        // TODO Auto-generated method stub
        return null;
    }

    @Override
    public DataStoreFactory getDataStoreFactory() {
        // TODO Auto-generated method stub
        return null;
    }

    @Override
    public String getId() {
        // TODO Auto-generated method stub
        return null;
    }

    @Override
    public boolean isEmpty() throws IOException {
        // TODO Auto-generated method stub
        return false;
    }

    @Override
    public Set<String> keySet() throws IOException {
        // TODO Auto-generated method stub
        return null;
    }

    @Override
    public DataStore<Serializable> set(String arg0, Serializable arg1) throws IOException {
        // TODO Auto-generated method stub
        return null;
    }

    @Override
    public int size() throws IOException {
        // TODO Auto-generated method stub
        return 0;
    }

    @Override
    public Collection<Serializable> values() throws IOException {
        // TODO Auto-generated method stub
        return null;
    }
};

También hay una clase DataStoreCredentialRefreshListener, ¿pero necesito implementar eso y asociarlo con mi DataStoreFactory o DataStore para que actualice automáticamente mi base de datos con nuevos tokens?

Tags:  , ,

Answer

  1. Avatar for davy.ai

    Para implementar una fábrica de DataStore personalizada, primero cree una clase que implemente la interfaz DataStoreFactory. Esta clase debe tener un método getDataStore que devuelva un objeto DataStore. Dentro del método getDataStore, puede crear una instancia de su clase DataStore personalizada que implemente los métodos necesarios.

    Por ejemplo:

    public class MyCustomDatastoreFactory implements DataStoreFactory {
    
      @Override
      public <v extends="" serializable=""> DataStore<v> getDataStore(String id) throws IOException {
        // create an instance of your custom DataStore class
        return new MyCustomDatastore<v>();
      }
    
    }
    

    A continuación, cree una clase que implemente la interfaz DataStore. Esta clase debe implementar los métodos necesarios para almacenar y recuperar sus tokens de acceso/actualización.

    Por ejemplo:

    public class MyCustomDatastore<v extends="" serializable=""> implements DataStore<v> {
    
      private Map<string, v=""> store = new HashMap<>();
    
      @Override
      public DataStore<v> clear() throws IOException {
        store.clear();
        return this;
      }
    
      @Override
      public boolean containsKey(String key) throws IOException {
        return store.containsKey(key);
      }
    
      @Override
      public boolean containsValue(V value) throws IOException {
        return store.containsValue(value);
      }
    
      @Override
      public DataStore<v> delete(String key) throws IOException {
        store.remove(key);
        return this;
      }
    
      @Override
      public V get(String key) throws IOException {
        return store.get(key);
      }
    
      @Override
      public DataStoreFactory getDataStoreFactory() {
        return new MyCustomDatastoreFactory();
      }
    
      @Override
      public String getId() {
        return "my-custom-datastore";
      }
    
      @Override
      public boolean isEmpty() throws IOException {
        return store.isEmpty();
      }
    
      @Override
      public Set<string> keySet() throws IOException {
        return store.keySet();
      }
    
      @Override
      public DataStore<v> set(String key, V value) throws IOException {
        store.put(key, value);
        return this;
      }
    
      @Override
      public int size() throws IOException {
        return store.size();
      }
    
      @Override
      public Collection<v> values() throws IOException {
        return store.values();
      }
    
    }
    

    Para usar su fábrica de DataStore personalizada, pase una instancia de ella al método setDataStoreFactory al construir su objeto GoogleAuthorizationCodeFlow. Por ejemplo:

    GoogleAuthorizationCodeFlow flow = new GoogleAuthorizationCodeFlow.Builder(
                HTTP_TRANSPORT, JSON_FACTORY, clientSecrets, SCOPES)
                     .setDataStoreFactory(new MyCustomDatastoreFactory())
                     .setAccessType("offline")
                     .build();
    

    También necesitará implementar la clase DataStoreCredentialRefreshListener y asociarla con su fábrica o DataStore. Este listener es responsable de actualizar automáticamente su base de datos con nuevos tokens cuando se refrescan.

    Por ejemplo:

    public class MyCustomCredentialRefreshListener implements DataStoreCredentialRefreshListener {
    
      private MyCustomDatastore<storedcredential> datastore;
    
      public MyCustomCredentialRefreshListener(MyCustomDatastore<storedcredential> datastore) {
        this.datastore = datastore;
      }
    
      @Override
      public void onCredentialRefreshed(Credential credential) throws IOException {
        StoredCredential storedCredential = new StoredCredential();
        storedCredential.setAccessToken(credential.getAccessToken());
        storedCredential.setRefreshToken(credential.getRefreshToken());
        storedCredential.setExpirationTimeMilliseconds(credential.getExpirationTimeMilliseconds());
        datastore.set(credential.getTransport().getClass().getName(), storedCredential);
      }
    
    }
    

    Luego, al construir su objeto GoogleAuthorizationCodeFlow, pase una instancia de su listener personalizado al método setCredentialDataStore. Por ejemplo:

    java
    MyCustomDatastore<storedcredential> datastore = new MyCustomDatastore<>();
    GoogleAuthorizationCodeFlow flow = new GoogleAuthorizationCodeFlow.Builder(
    HTTP_TRANSPORT, JSON_FACTORY, clientSecrets, SCOPES)
    .setDataStoreFactory(new MyCustomDatastoreFactory())
    .setCredentialDataStore(datastore)
    .setAccessType("offline")
    .addRefreshListener(new MyCustomCredentialRefreshListener(datastore))
    .build();
    </string,>

Comments are closed.