Advertisement
warodri

BlackBerry Twiiter

Dec 28th, 2011
162
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Java 7.75 KB | None | 0 0
  1. package app.screen;
  2.  
  3. import impl.rim.com.twitterapime.xauth.ui.BrowserContentManagerOAuthDialogWrapper;
  4.  
  5. import com.twitterapime.rest.Credential;
  6. import com.twitterapime.rest.TweetER;
  7. import com.twitterapime.rest.UserAccountManager;
  8. import com.twitterapime.search.Tweet;
  9. import com.twitterapime.xauth.Token;
  10. import com.twitterapime.xauth.ui.OAuthDialogListener;
  11. import com.twitterapime.xauth.ui.OAuthDialogWrapper;
  12. import net.rim.device.api.browser.field.BrowserContentManager;
  13. import net.rim.device.api.browser.field.RenderingOptions;
  14. import net.rim.device.api.ui.UiApplication;
  15. import net.rim.device.api.ui.component.ButtonField;
  16. import net.rim.device.api.ui.component.Dialog;
  17. import net.rim.device.api.ui.component.EditField;
  18. import net.rim.device.api.ui.component.LabelField;
  19. import net.rim.device.api.ui.container.MainScreen;
  20.  
  21. public class TwitterScreen extends MainScreen  {
  22.    
  23.     // ** Información de tu aplicación en Twitter
  24.     private final String CONSUMER_KEY =
  25.         "TU_CONSUMER_KEY";
  26.     private final String CONSUMER_SECRET =
  27.         "TU_CONSUMER_SECRET";
  28.    
  29.     // ** Colocar el callback autorizado en tu aplicación Twitter
  30.     // ** si no colocas nada, Twitter te pedirá validar con un PIN
  31.     private final String CALLBACK_URL =
  32.         "URL_CALLBACK_AUTORIZADO_DESDE_TWITTER";
  33.    
  34.     // ** Label simplemente a modo de log
  35.     private LabelField labelLog;
  36.    
  37.     // ** Componente de la API que hace el trabajo
  38.     private OAuthDialogWrapper pageWrapper = null;
  39.    
  40.     // ** Inner class que nos levanta la página de Twitter
  41.     ShowAuthBrowser showAuthBrowserScreen;
  42.    
  43.    
  44.     /**
  45.      * Constructor
  46.      */
  47.     public TwitterScreen()
  48.     {
  49.         // ** Definimos un título para nuestra ventana
  50.         setTitle("Twitter API ME - OAuth");
  51.        
  52.         // ** Iniciamos una única vez nuestro browser
  53.         // ** (lo llamaremos 2 veces)
  54.         showAuthBrowserScreen = new ShowAuthBrowser();
  55.        
  56.         // 1ra vez que invocamos al browser para firmarse
  57.         add ( new ButtonField( "Firmarse" ) {
  58.             protected boolean navigationUnclick(int status, int time) {
  59.                
  60.                 // ** pedimos firmar sin código PIN
  61.                 showAuthBrowserScreen.doAuth( null );
  62.                
  63.                 // ** mostramos la pantalla del browser
  64.                 UiApplication.getUiApplication().pushScreen(
  65.                         showAuthBrowserScreen);
  66.                
  67.                 return true;
  68.             }
  69.         });
  70.        
  71.         if ( CALLBACK_URL.trim().equals("") )
  72.         {      
  73.             // ** edit field para ingresar el PIN que nos provee Twitter
  74.             final EditField editPin = new EditField("Ingresa PIN Twitter: ", "" );
  75.             add( editPin );
  76.            
  77.             // 2da vez que invocamos al browser para firmarse
  78.             add( new ButtonField( "Validar PIN" ) {
  79.                 protected boolean navigationUnclick(int status, int time) {
  80.                     if ( editPin.getText() != null &&
  81.                             !editPin.getText().trim().equals("") )
  82.                     {
  83.                         // ** pedimos firmar, ahora con un código PIN
  84.                         showAuthBrowserScreen.doAuth( editPin.getText() );
  85.                        
  86.                         // ** mostramos nuevamente la pantalla del browser
  87.                         UiApplication.getUiApplication().pushScreen(
  88.                                 showAuthBrowserScreen );
  89.                        
  90.                         return true;
  91.                     }
  92.                     return true;
  93.                 }
  94.             });
  95.         }
  96.        
  97.     }
  98.    
  99.    
  100.     /**
  101.      * Inner class para mostrar el browser con Twitter
  102.      * @author Walter A. Rodriguez
  103.      *
  104.      */
  105.     class ShowAuthBrowser extends MainScreen implements OAuthDialogListener
  106.     {
  107.         // ** Browser de la API que nos levanta la página de Twitter
  108.         BrowserContentManager browserMngr = new BrowserContentManager(0);
  109.         RenderingOptions rendOptions = null;
  110.        
  111.         /**
  112.          * Constructor
  113.          */
  114.         public ShowAuthBrowser()
  115.         {
  116.             // ** definimos algunos valores básicos de renderizado del browser
  117.             rendOptions =
  118.                 browserMngr.getRenderingSession().getRenderingOptions();
  119.             rendOptions.setProperty(
  120.                 RenderingOptions.CORE_OPTIONS_GUID,
  121.                 RenderingOptions.SHOW_IMAGES_IN_HTML,
  122.                 false);
  123.            
  124.             // ** escribimos un log en pantalla
  125.             labelLog = new LabelField( "Cargando Twitter..." );
  126.             add( labelLog );
  127.            
  128.             // ** agregamos por primera vez el browser en pantalla
  129.             add(browserMngr);
  130.            
  131.             // ** creamos el objeto que navegará en Twitter
  132.             pageWrapper = new BrowserContentManagerOAuthDialogWrapper(browserMngr);
  133.            
  134.             // ** y le definimos los valores claves
  135.             pageWrapper.setConsumerKey(CONSUMER_KEY);
  136.             pageWrapper.setConsumerSecret(CONSUMER_SECRET);
  137.             pageWrapper.setCallbackUrl(CALLBACK_URL);
  138.             pageWrapper.setOAuthListener(this);
  139.            
  140.         }
  141.        
  142.         /**
  143.          * Método que realiza el login (con y sin PIN)
  144.          * @param pin
  145.          */
  146.         public void doAuth( String pin )
  147.         {
  148.             try
  149.             {
  150.                 if ( pin == null )
  151.                 {
  152.                     // ** si no viene PIN, hacemos el primer login
  153.                     pageWrapper.login();
  154.                    
  155.                 }
  156.                 else
  157.                 {
  158.                     // ** si viene un PIN, borramos el browser anterior
  159.                     // ** y cargamos uno nuevo
  160.                     this.deleteAll();
  161.                     add(browserMngr);
  162.                    
  163.                     // ** volvemos a loguearnos con PIN
  164.                     pageWrapper.login( pin );
  165.                 }
  166.                
  167.             }
  168.             catch ( Exception e )
  169.             {
  170.                 // ** los errores en el proceso aparecen por aquí
  171.                 final String message = "Error loggin Twitter: " + e.getMessage();
  172.                 System.out.println( message );
  173.                 PowerDialog.displayMessage( message );
  174.             }          
  175.         }
  176.        
  177.         /**
  178.          * Si el login fue correcto...
  179.          */
  180.         public void onAccessDenied(String response ) {
  181.  
  182.             System.out.println("Access denied! -> " + response );
  183.             updateScreenLog( "Acceso denegado! -> " + response );
  184.            
  185.         }
  186.  
  187.         /**
  188.          * Autorización satisfactoria
  189.          */
  190.         public void onAuthorize(Token token) {
  191.            
  192.             // ** obtenemos el Token desde Twitter
  193.             final Token myToken = token;
  194.            
  195.             UiApplication.getUiApplication().invokeLater( new Runnable() {
  196.                
  197.                 public void run() {
  198.                    
  199.                     // ** ya podemos borrar todo en pantalla
  200.                     deleteAll();
  201.                    
  202.                     String tweetTest = "Test: " + System.currentTimeMillis();
  203.                    
  204.                     // ** hacemos un tweet de prueba
  205.                     doTweet( tweetTest, myToken );
  206.                    
  207.                     PowerDialog.displayMessage( "Estas autorizado! - " +
  208.                             "Se ha enviado el siguiente Tweet de prueba " +
  209.                             "a tu cuenta: " + tweetTest );
  210.                    
  211.                     // ** cerramos esta ventana
  212.                     close();
  213.                    
  214.                 }
  215.             });
  216.            
  217.         }
  218.        
  219.         /**
  220.          * La autentificación falla
  221.          */
  222.         public void onFail(String arg0, String arg1) {
  223.  
  224.             System.out.println("Error autentificando usuario! -> " + arg0 + ", " +
  225.                     arg1);
  226.             updateScreenLog("Error autentificando usuario! -> " + arg0 + ", " +
  227.                     arg1);
  228.            
  229.         }
  230.     }
  231.    
  232.    
  233.     /**
  234.      * Actualiza el mensaje en pantalla
  235.      *
  236.      * @param message Texto a mostrar en pantalla a modo de log.
  237.      */
  238.     private void updateScreenLog( final String message )
  239.     {
  240.         UiApplication.getUiApplication().invokeLater( new Runnable() {
  241.            
  242.             public void run() {
  243.                 labelLog.setText( message );               
  244.             }
  245.         });
  246.     }
  247.    
  248.     /**
  249.      * Método que realiza un tweet de prueba
  250.      *
  251.      * @param message
  252.      * @param token
  253.      */
  254.     public void doTweet( String message, Token token )
  255.     {
  256.         // ** creamos un objeto de credenciales
  257.         Credential c = new Credential(CONSUMER_KEY, CONSUMER_SECRET, token);
  258.        
  259.         // ** creamos un objeto de administración de cuenta de usuario
  260.         UserAccountManager uam = UserAccountManager.getInstance(c);
  261.        
  262.         try
  263.         {
  264.             if (uam.verifyCredential())
  265.             {
  266.                 TweetER.getInstance(uam).post(new Tweet( message ));
  267.                
  268.                 System.out.println("Tweet posteado!");
  269.                 updateScreenLog("Tweet posteado!");
  270.             }
  271.         } catch (Exception e)
  272.         {
  273.             System.out.println("Error by posting tweet.");
  274.             updateScreenLog("Error by posting tweet.");
  275.         }
  276.        
  277.     }
  278.  
  279.     /**
  280.      * Una clase auxiliar para mostrar un diálogo en pantalla
  281.      *
  282.      * @author Walter A. Rodriguez
  283.      *
  284.      */
  285.     static class PowerDialog
  286.     {
  287.         public static void displayMessage( final String message )
  288.         {
  289.             UiApplication.getUiApplication().invokeLater( new Runnable() {
  290.                
  291.                 public void run() {
  292.                     Dialog.alert( message );               
  293.                 }
  294.             });
  295.         }
  296.        
  297.     }
  298. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement