Welcome!

Welcome to the official BlackBerry Support Community Forums.

This is your resource to discuss support topics with your peers, and learn from each other.

inside custom component

Java Development

Reply
Developer
Posts: 178
Registered: ‎04-16-2011
My Device: torch 9800
My Carrier: verizon

BrowserContent attempt

[ Edited ]

Hi all, I have been looking at a few samples avilable to display web content on a field/screen. I am hoping to login to youtube/google using oauth 2.

 

Here is my attempt - My problem is that I get the first login screen but when i enter my credentials and press login I get the same page again but as if it has been loaded again.  I am hoping to get a permissions screen next.

 

Can anyone see a mistake with my code - i have had to edit it a lot compared to samples as the address for login is https.

 

import java.io.IOException;
import java.util.Vector;
import javax.microedition.io.Connector;
import javax.microedition.io.HttpConnection;
import javax.microedition.io.HttpsConnection;


import net.rim.device.api.browser.field.BrowserContent;
import net.rim.device.api.browser.field.BrowserContentChangedEvent;
import net.rim.device.api.browser.field.Event;
import net.rim.device.api.browser.field.RedirectEvent;
import net.rim.device.api.browser.field.RenderingApplication;
import net.rim.device.api.browser.field.RenderingException;
import net.rim.device.api.browser.field.RenderingSession;
import net.rim.device.api.browser.field.RequestedResource;
import net.rim.device.api.browser.field.UrlRequestedEvent;
import net.rim.device.api.io.http.HttpHeaders;
import net.rim.device.api.servicebook.ServiceBook;
import net.rim.device.api.servicebook.ServiceRecord;
import net.rim.device.api.system.CoverageInfo;
import net.rim.device.api.system.DeviceInfo;
import net.rim.device.api.system.RadioInfo;
import net.rim.device.api.ui.Field;
import net.rim.device.api.ui.Graphics;

import net.rim.device.api.ui.container.MainScreen;


/**
 *
 */
 public class YouTubeLogin implements RenderingApplication {
public YouTubeLogin dis;
PrimaryResourceFetchThread thread;
    private static final String REFERER = "referer";
public SecondaryResourceFetchThread2 sf;
    private RenderingSession _renderingSession;
BrowserContent browserContent;
    private MainScreen _mainScreen;

    private HttpConnection  _currentConnection;
String url = "https://accounts.google.com/o/oauth2/auth?"+"redirect_uri=urn:ietf:wg:oauth:2.0:oob&"+
  "client_id="+"1087788870733.apps.googleusercontent.com"+"&"+
  
  "scope=https://gdata.youtube.com&"+
 "response_type=code&"+
  "access_type=offline";
   public UploadApplication app;
  String clientId ="1087788870733.apps.googleusercontent.com";
    public YouTubeLogin(UploadApplication app2) {
       app = app2;
       dis = this;
        _mainScreen = new MainScreen();
        synchronized(app.getEventLock())
        {
            app.pushScreen(_mainScreen);
        }
        
        _renderingSession = RenderingSession.getNewInstance();


       browse();

    }


                        public void browse() {
                if (url != null) {

                        requestURL(url, url);
                }
        }

      private void requestURL(String url, String referrer) {

                //Set the referrer header if it exists.
                //  note in some cases, the referrer header should not be included in the request and will be null.
                HttpHeaders requestHeaders = null;
                //prevUrl = getUrl();
     Log.info("requesting  " + url);
                if (referrer != null) {
                        requestHeaders = new HttpHeaders();
                        requestHeaders.setProperty("referer", referrer);
                }
                if(url.indexOf("code=") == -1)
                {
                 thread = new PrimaryResourceFetchThread(url, requestHeaders, null, null);
                thread.start();
                }
 else
                {
         Log.info("code is present");
 }
        }
    public void processConnection(HttpConnection connection, Event e) {

        // cancel previous request
        Log.info("processconnection");
        if (_currentConnection != null) {
            try {
                _currentConnection.close();
            } catch (IOException e1) {
            }
        }

        _currentConnection = connection;

         browserContent = null;

        try {
             Log.info("processconnection2");
            browserContent = _renderingSession.getBrowserContent(connection, this, e);
             Log.info("processconnection3");
            if (browserContent != null) {

                Field field = browserContent.getDisplayableContent();
                 Log.info("processconnection4");
                if (field != null) {
                    synchronized (app.getEventLock()) {
                        _mainScreen.deleteAll();
                        _mainScreen.add(field);
                         Log.info("processconnection5");

                         try
                         {
                          browserContent.finishLoading();
                        }
                         catch(Exception mm)
                         {
                             Log.info("finishloading error "+mm);
                         }
                    }
                }
                Log.info("after finished loading");
              
            }

        } catch (RenderingException re) {

        } finally {

              if(sf == null)
              {
                  sf = new SecondaryResourceFetchThread2();
              }
            try
            {
            sf.doneAddingImages();
            }
            catch(Exception hh)
            {
                
            }
        }

    }

    /**
     * @see net.rim.device.api.browser.RenderingApplication#eventOccurred(net.rim.device.api.browser.Event)
     */
    public Object eventOccurred(Event event) {

        int eventId = event.getUID();

        switch (eventId) {

            case Event.EVENT_URL_REQUESTED : {
Log.info("eventoccurred urlrequest");
                UrlRequestedEvent urlRequestedEvent = (UrlRequestedEvent) event;
                String absoluteUrl = urlRequestedEvent.getURL();

                HttpConnection conn = null;
                 thread = new PrimaryResourceFetchThread(absoluteUrl,null, null, null     );
                thread.start();

                break;

            } case Event.EVENT_BROWSER_CONTENT_CHANGED: {
Log.info("eventoccurred changed content"+event.getSourceURL());
                // browser field title might have changed update title
                BrowserContentChangedEvent browserContentChangedEvent = (BrowserContentChangedEvent) event;

                if (browserContentChangedEvent.getSource() instanceof BrowserContent) {
                     browserContent = (BrowserContent) browserContentChangedEvent.getSource();
                    String newTitle = browserContent.getTitle();
                    if (newTitle != null) {
                        Log.info("newtitle"+newTitle);
                       // _mainScreen.setTitle(newTitle);
                    }
                }

                break;

            } case Event.EVENT_REDIRECT : {
Log.info("eventoccurred reddirect");
                    RedirectEvent e = (RedirectEvent) event;
                    String referrer = e.getSourceURL();
Log.info("eventoccurred reddirect"+referrer);
                    switch (e.getType()) {

                        case RedirectEvent.TYPE_SINGLE_FRAME_REDIRECT :
                            // show redirect message
                          
                                   Log.info("You are being redirected to a different page...");
                               

                            break;

                        case RedirectEvent.TYPE_JAVASCRIPT :
                            break;
                        case RedirectEvent.TYPE_META :
                            // MSIE and Mozilla don't send a Referer for META Refresh.
                            referrer = null;
                            break;
                        case RedirectEvent.TYPE_300_REDIRECT :
                            // MSIE, Mozilla, and Opera all send the original
                            // request's Referer as the Referer for the new
                            // request.
                            Object eventSource = e.getSource();
                            if (eventSource instanceof HttpsConnection) {
                                referrer = ((HttpsConnection)eventSource).getRequestProperty(REFERER);
                            }
                            break;

                    }

                    HttpHeaders requestHeaders = new HttpHeaders();
                    requestHeaders.setProperty(REFERER, referrer);
                     thread = new PrimaryResourceFetchThread(e.getLocation(), requestHeaders,null, null);
Log.info("eventoccurred primary"+e.getLocation());
                    thread.start();
                    break;

            } case Event.EVENT_CLOSE :
                Log.info("eventoccurred close");
                // TODO: close the appication
                break;

            case Event.EVENT_SET_HEADER :        // no cache support
            case Event.EVENT_SET_HTTP_COOKIE :   // no cookie support
            case Event.EVENT_HISTORY :           // no history support
            case Event.EVENT_EXECUTING_SCRIPT :  // no progress bar is supported
            case Event.EVENT_FULL_WINDOW :       // no full window support
            case Event.EVENT_STOP :              // no stop loading support
            default :
        }

        return null;
    }

    /**
     * @see net.rim.device.api.browser.RenderingApplication#getAvailableHeight(net.rim.device.api.browser.BrowserContent)

     */
    public int getAvailableHeight(BrowserContent browserField) {
        // field has full screen
        return Graphics.getScreenHeight();
    }

    /**
     * @see net.rim.device.api.browser.RenderingApplication#getAvailableWidth(net.rim.device.api.browser.BrowserContent)

     */
    public int getAvailableWidth(BrowserContent browserField) {
        // field has full screen
        return Graphics.getScreenWidth();
    }

    /**
     * @see net.rim.device.api.browser.RenderingApplication#getHistoryPosition(net.rim.device.api.browser.BrowserContent)

     */
    public int getHistoryPosition(BrowserContent browserField) {
        // no history support
        return 0;
    }

    /**
     * @see net.rim.device.api.browser.RenderingApplication#getHTTPCookie(java.lang.String)
     */
    public String getHTTPCookie(String url) {
        // no cookie support
        return null;
    }

    /**
     * @see net.rim.device.api.browser.RenderingApplication#getResource(net.rim.device.api.browser.RequestedResource,
     *      net.rim.device.api.browser.BrowserContent)
     */
    public HttpConnection getResource( RequestedResource resource, BrowserContent referrer) {
 Log.info("getresource0");
        if (resource == null) {
            return null;
        }

        // check if this is cache-only request
        if (resource.isCacheOnly()) {
            // no cache support
            return null;
        }

        String url = resource.getUrl();

        if (url == null) {
            return null;
        } Log.info("getresource1");
        // if referrer is null we must return the connection
        if (referrer == null) {
               try
        {
       HttpsConnection connection = (HttpsConnection)Connector.open(resource.getUrl()+getConnectionProfileSocket());
                             resource.setHttpConnection(connection);
                              return connection;
        }
        catch(Exception gg)
        {
            Log.info("error "+gg);
        }
           

        } else {
            try
        {
       HttpsConnection connection = (HttpsConnection)Connector.open(resource.getUrl()+getConnectionProfileSocket());
                             resource.setHttpConnection(connection);
        }
        catch(Exception gg)
        {
            Log.info("error "+gg);
        }
            // if referrer is provided we can set up the connection on a separate thread

              if(sf == null)
              {
                  sf = new SecondaryResourceFetchThread2();
              }
            sf.enqueue(resource, referrer);

        }

        return null;
    }

    /**
     * @see net.rim.device.api.browser.RenderingApplication#invokeRunnable(java.lang.Runnable)
     */
    public void invokeRunnable(Runnable runnable) {
        (new Thread(runnable)).run();
    }



class PrimaryResourceFetchThread extends Thread {


    private Event _event;

    private byte[] _postData;

    private HttpHeaders _requestHeaders;

    private String _url;
 HttpConnectionFactory factory;
    PrimaryResourceFetchThread(String url, HttpHeaders requestHeaders, byte[] postData,
                                  Event event) {

        _url = url;
        _requestHeaders = requestHeaders;
        _postData = postData;

        _event = event;
    }

    public void run() {
        try
        {

       HttpsConnection connection = (HttpsConnection)Connector.open(_url+getConnectionProfileSocket());//factory.getHttpConnection(_url, _requestHeaders);
                                Log.info("primary resource thread run "+_url);
                                processConnection(connection, _event);
        }
        catch(Exception gg)
        {
            Log.info("error "+gg);
        }
    }


}

class SecondaryResourceFetchThread2 extends Thread {

        /**
         * Callback browser field.
         */
        private BrowserContent browserField;

        /**
         * Connection headers.
         */
        private HttpHeaders headers;

        private HttpConnectionFactory factory;

        /**
         * Images to retrieve.
         */
        private Vector imageQueue;

        /**
         * True is all images have been enqueued.
         */
        private boolean done;

        /**
         * Sync object.
         */
        private  Object syncObject = new Object();

        /**
         * Singleton
         */
        private  SecondaryResourceFetchThread2 instance;

        /**
         * Enqueues secondary resource for a browser field.
         *
         * @param resource
         *            - resource to retrieve.
         * @param referrer
         *            - call back browsr field.
         */
        public  void enqueue(RequestedResource resource, BrowserContent referrer){//, HttpHeaders requestHeaders, HttpConnectionFactory pFactory) {
                if (resource == null) {
                        return;
                }

                synchronized (syncObject) {
                        // Create new thread.
                        if (instance == null) {
                                instance = new SecondaryResourceFetchThread2();
                                instance.start();
                                //instance.headers = requestHeaders;
                                //instance.factory = factory;//pFactory;
                        } else {
                                // If thread already is running, check that we are adding images for the same browser field.
                                if (referrer != instance.browserField) {
                                        synchronized (instance.imageQueue) {
                                                // If the request is for a different browser field clear old elements.
                                                instance.imageQueue.removeAllElements();
                                        }
                                }
                        }

                        synchronized (instance.imageQueue) {
                                instance.imageQueue.addElement(resource);
                        }

                        instance.browserField = referrer;
                }
        }

        /**
         * Default Constructor.
         *
         */
        private SecondaryResourceFetchThread2() {
                imageQueue = new Vector();
        }

        /**
         * Indicate that all images have been enqueued for this browser field.
         *
         */
         void doneAddingImages() {
                synchronized (syncObject) {
                        if (instance != null) {
                                instance.done = true;
                        }
                }
        }

        public void run() {
                while (true) {
                        if (done) {
                                // Check if we are done requesting images.
                                synchronized (syncObject) {
                                        synchronized (imageQueue) {
                                                if (imageQueue.size() == 0) {
                                                        instance = null;
                                                        break;
                                                }
                                        }
                                }
                        }

                        RequestedResource resource = null;

                        // Request next image.
                        synchronized (imageQueue) {
                                if (imageQueue.size() > 0) {
                                        resource = (RequestedResource) imageQueue.elementAt(0);
                                        imageQueue.removeElementAt(0);
                                }
                        }

                        if (resource != null) {
                            HttpsConnection connection = null;
                                //pass headers to secondary resource request:
                                if (headers == null) {
                                        headers = new HttpHeaders();
                                }

                                headers.setProperties(resource.getRequestHeaders());

                                try {
                                         connection = (HttpsConnection)Connector.open(resource.getUrl());//factory.getHttpConnection(resource.getUrl(), headers);
                                        resource.setHttpConnection(connection);
                                } catch (Exception e) {
                                    Log.info(resource.getUrl()+"second error "+e);
                                }

                                // Signal to the browser field that resource is ready.
                                if (browserField != null) {
                                        browserField.resourceReady(resource);
                                }
                                   try
                {
                    connection.close();
                }
                catch (Exception e1)
                {
                    Log.info("connectioncloseerror " + e1);
                }
                        }
                }
        }
     }
}

 

 

Developer
Posts: 729
Registered: ‎05-04-2011
My Device: 9700

Re: BrowserContent attempt

Hi,

 

I think you should do a couple things as the first step:

 

1. Encode your URL. The URL contains illegal URL characters, You can use the URLEncodedPostData class for that.

http://www.blackberry.com/developers/docs/5.0.0api/net/rim/blackberry/api/browser/URLEncodedPostData...

 

2. Add logs to your code. This way you would easily know what is the response and have more info on the problem.

 

Hope that helps,

 

E.