Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- package app.screen;
- import impl.rim.com.twitterapime.xauth.ui.BrowserContentManagerOAuthDialogWrapper;
- import com.twitterapime.rest.Credential;
- import com.twitterapime.rest.TweetER;
- import com.twitterapime.rest.UserAccountManager;
- import com.twitterapime.search.Tweet;
- import com.twitterapime.xauth.Token;
- import com.twitterapime.xauth.ui.OAuthDialogListener;
- import com.twitterapime.xauth.ui.OAuthDialogWrapper;
- import net.rim.device.api.browser.field.BrowserContentManager;
- import net.rim.device.api.browser.field.RenderingOptions;
- import net.rim.device.api.ui.UiApplication;
- import net.rim.device.api.ui.component.ButtonField;
- import net.rim.device.api.ui.component.Dialog;
- import net.rim.device.api.ui.component.EditField;
- import net.rim.device.api.ui.component.LabelField;
- import net.rim.device.api.ui.container.MainScreen;
- public class TwitterScreen extends MainScreen {
- // ** Información de tu aplicación en Twitter
- private final String CONSUMER_KEY =
- "TU_CONSUMER_KEY";
- private final String CONSUMER_SECRET =
- "TU_CONSUMER_SECRET";
- // ** Colocar el callback autorizado en tu aplicación Twitter
- // ** si no colocas nada, Twitter te pedirá validar con un PIN
- private final String CALLBACK_URL =
- "URL_CALLBACK_AUTORIZADO_DESDE_TWITTER";
- // ** Label simplemente a modo de log
- private LabelField labelLog;
- // ** Componente de la API que hace el trabajo
- private OAuthDialogWrapper pageWrapper = null;
- // ** Inner class que nos levanta la página de Twitter
- ShowAuthBrowser showAuthBrowserScreen;
- /**
- * Constructor
- */
- public TwitterScreen()
- {
- // ** Definimos un título para nuestra ventana
- setTitle("Twitter API ME - OAuth");
- // ** Iniciamos una única vez nuestro browser
- // ** (lo llamaremos 2 veces)
- showAuthBrowserScreen = new ShowAuthBrowser();
- // 1ra vez que invocamos al browser para firmarse
- add ( new ButtonField( "Firmarse" ) {
- protected boolean navigationUnclick(int status, int time) {
- // ** pedimos firmar sin código PIN
- showAuthBrowserScreen.doAuth( null );
- // ** mostramos la pantalla del browser
- UiApplication.getUiApplication().pushScreen(
- showAuthBrowserScreen);
- return true;
- }
- });
- if ( CALLBACK_URL.trim().equals("") )
- {
- // ** edit field para ingresar el PIN que nos provee Twitter
- final EditField editPin = new EditField("Ingresa PIN Twitter: ", "" );
- add( editPin );
- // 2da vez que invocamos al browser para firmarse
- add( new ButtonField( "Validar PIN" ) {
- protected boolean navigationUnclick(int status, int time) {
- if ( editPin.getText() != null &&
- !editPin.getText().trim().equals("") )
- {
- // ** pedimos firmar, ahora con un código PIN
- showAuthBrowserScreen.doAuth( editPin.getText() );
- // ** mostramos nuevamente la pantalla del browser
- UiApplication.getUiApplication().pushScreen(
- showAuthBrowserScreen );
- return true;
- }
- return true;
- }
- });
- }
- }
- /**
- * Inner class para mostrar el browser con Twitter
- * @author Walter A. Rodriguez
- *
- */
- class ShowAuthBrowser extends MainScreen implements OAuthDialogListener
- {
- // ** Browser de la API que nos levanta la página de Twitter
- BrowserContentManager browserMngr = new BrowserContentManager(0);
- RenderingOptions rendOptions = null;
- /**
- * Constructor
- */
- public ShowAuthBrowser()
- {
- // ** definimos algunos valores básicos de renderizado del browser
- rendOptions =
- browserMngr.getRenderingSession().getRenderingOptions();
- rendOptions.setProperty(
- RenderingOptions.CORE_OPTIONS_GUID,
- RenderingOptions.SHOW_IMAGES_IN_HTML,
- false);
- // ** escribimos un log en pantalla
- labelLog = new LabelField( "Cargando Twitter..." );
- add( labelLog );
- // ** agregamos por primera vez el browser en pantalla
- add(browserMngr);
- // ** creamos el objeto que navegará en Twitter
- pageWrapper = new BrowserContentManagerOAuthDialogWrapper(browserMngr);
- // ** y le definimos los valores claves
- pageWrapper.setConsumerKey(CONSUMER_KEY);
- pageWrapper.setConsumerSecret(CONSUMER_SECRET);
- pageWrapper.setCallbackUrl(CALLBACK_URL);
- pageWrapper.setOAuthListener(this);
- }
- /**
- * Método que realiza el login (con y sin PIN)
- * @param pin
- */
- public void doAuth( String pin )
- {
- try
- {
- if ( pin == null )
- {
- // ** si no viene PIN, hacemos el primer login
- pageWrapper.login();
- }
- else
- {
- // ** si viene un PIN, borramos el browser anterior
- // ** y cargamos uno nuevo
- this.deleteAll();
- add(browserMngr);
- // ** volvemos a loguearnos con PIN
- pageWrapper.login( pin );
- }
- }
- catch ( Exception e )
- {
- // ** los errores en el proceso aparecen por aquí
- final String message = "Error loggin Twitter: " + e.getMessage();
- System.out.println( message );
- PowerDialog.displayMessage( message );
- }
- }
- /**
- * Si el login fue correcto...
- */
- public void onAccessDenied(String response ) {
- System.out.println("Access denied! -> " + response );
- updateScreenLog( "Acceso denegado! -> " + response );
- }
- /**
- * Autorización satisfactoria
- */
- public void onAuthorize(Token token) {
- // ** obtenemos el Token desde Twitter
- final Token myToken = token;
- UiApplication.getUiApplication().invokeLater( new Runnable() {
- public void run() {
- // ** ya podemos borrar todo en pantalla
- deleteAll();
- String tweetTest = "Test: " + System.currentTimeMillis();
- // ** hacemos un tweet de prueba
- doTweet( tweetTest, myToken );
- PowerDialog.displayMessage( "Estas autorizado! - " +
- "Se ha enviado el siguiente Tweet de prueba " +
- "a tu cuenta: " + tweetTest );
- // ** cerramos esta ventana
- close();
- }
- });
- }
- /**
- * La autentificación falla
- */
- public void onFail(String arg0, String arg1) {
- System.out.println("Error autentificando usuario! -> " + arg0 + ", " +
- arg1);
- updateScreenLog("Error autentificando usuario! -> " + arg0 + ", " +
- arg1);
- }
- }
- /**
- * Actualiza el mensaje en pantalla
- *
- * @param message Texto a mostrar en pantalla a modo de log.
- */
- private void updateScreenLog( final String message )
- {
- UiApplication.getUiApplication().invokeLater( new Runnable() {
- public void run() {
- labelLog.setText( message );
- }
- });
- }
- /**
- * Método que realiza un tweet de prueba
- *
- * @param message
- * @param token
- */
- public void doTweet( String message, Token token )
- {
- // ** creamos un objeto de credenciales
- Credential c = new Credential(CONSUMER_KEY, CONSUMER_SECRET, token);
- // ** creamos un objeto de administración de cuenta de usuario
- UserAccountManager uam = UserAccountManager.getInstance(c);
- try
- {
- if (uam.verifyCredential())
- {
- TweetER.getInstance(uam).post(new Tweet( message ));
- System.out.println("Tweet posteado!");
- updateScreenLog("Tweet posteado!");
- }
- } catch (Exception e)
- {
- System.out.println("Error by posting tweet.");
- updateScreenLog("Error by posting tweet.");
- }
- }
- /**
- * Una clase auxiliar para mostrar un diálogo en pantalla
- *
- * @author Walter A. Rodriguez
- *
- */
- static class PowerDialog
- {
- public static void displayMessage( final String message )
- {
- UiApplication.getUiApplication().invokeLater( new Runnable() {
- public void run() {
- Dialog.alert( message );
- }
- });
- }
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement