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


Thank you for visiting the BlackBerry Support Community Forums.

BlackBerry will be closing the BlackBerry Support Community Forums Device Forums on April 1st (Developers, see below)

BlackBerry remains committed to providing excellent customer support to our customers. We are delighted to direct you to the CrackBerry Forums, a well-established and thorough support channel, for continued BlackBerry support. Please visit http://forums.crackberry.com or http://crackberry.com/ask. You can also continue to visit BlackBerry Support or the BlackBerry Knowledge Base for official support options available for your BlackBerry Smartphone.

"When we launched CrackBerry.com 10 years ago, we set out to make it a fun and useful destination where BlackBerry Smartphone owners could share their excitement and learn to unleash the full potential of their BlackBerry. A decade later, the CrackBerry community is as active and passionate as ever and I know our knowledgeable members and volunteers will be excited to welcome and assist more BlackBerry owners with their questions."

- Kevin Michaluk, Founder, CrackBerry.com

Developers, for more information about the BlackBerry Developer Community please review Join the Conversation on the BlackBerry Developer Community Forums found on Inside BlackBerry.


Reply
Developer
Posts: 528
Registered: ‎10-06-2009
My Device: 9800,BB Dev Alpha,z10 limited edition
My Carrier: Vodafone

Cookies in browserfield

Hi,

I am making an application which shows some link on browserfield(custom browser). When I try to show tht link it shows error that "Your browser should be cookie enabled".

I have implemented all the code of cookie handling in the browserfield(found from the forum) but still its not working.can anyone help me with this?

Rujuta Trivedi
Developer
Posts: 905
Registered: ‎02-07-2009
My Device: BlackBerry Torch 9800
My Carrier: Globe Telecom

Re: Cookies in browserfield

Hi trivedirujuta,

 

can you post some code snippet? 

 

 

cheers! Smiley Happy

Developer
Posts: 528
Registered: ‎10-06-2009
My Device: 9800,BB Dev Alpha,z10 limited edition
My Carrier: Vodafone

Re: Cookies in browserfield

Hi,


I have used below code for handling browserscreen n cookies

 

 

 


public  class BrowserScreen extends
MainScreen implements RenderingApplication
{
    
    private static final String REFERER = "referer";   
    
    private RenderingSession _renderingSession;   
    private HttpConnection  _currentConnection;
    String url;
    private Vector cookies = new Vector();
    
    /***************************************************************************
     * Main.
     **************************************************************************/
   
    
    BrowserScreen(String _url)
    {        
        url="https://www.linkedin.com/uas/oauth/authorize?oauth_token="+Const.token;
              
      
        _renderingSession = RenderingSession.getNewInstance();
        
        // Enable javascript.
        //_renderingSession.getRenderingOptions().setProperty(RenderingOptions.CORE_OPTIONS_GUID, RenderingOptions.JAVASCRIPT_ENABLED, true);                        
        
        PrimaryResourceFetchThread thread = new PrimaryResourceFetchThread(url, null, null, null, this);
        thread.start();                       
             
    }
          
    void processConnection(HttpConnection connection, Event e)
    {
        // Cancel previous request.
        if (_currentConnection != null)
        {
            try
            {
                _currentConnection.close();
            }
            catch (IOException e1)
            {
            }
        }
        
        _currentConnection = connection;
        
        BrowserContent browserContent = null;
        
        try
        { if (cookies.size() > 0) {
            try {
                connection.setRequestProperty(HttpProtocolConstants.HEADER_COOKIE, returnCookie());
          } catch (IOException er) {}
   }
            browserContent = _renderingSession.getBrowserContent(connection, this, e);
            try {
                System.out.println("codeeeeeeeeeeeeeeeeeeeeeeeeeeee"+connection.getResponseCode());
            } catch (IOException e2) {
                // TODO Auto-generated catch block
                e2.printStackTrace();
            }
            if (browserContent != null)
            {
                Field field = browserContent.getDisplayableContent();
                
                if (field != null)
                {String key = null;

                try {
                    for (int i = 0; (key = connection.getHeaderFieldKey(i)) != null; i++) {
                        System.out.println("keyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyy"+key);
                        if (key.equalsIgnoreCase("Set-cookie")) {
                            String s=_currentConnection.getHeaderField(key);
                            System.out.println("keyseeeeeeeeeeeeeeeeeeeeeeeeeeee"+s);
                             addCookies(connection.getHeaderField(key));
                        }
                    }
                } catch (IOException e1) {
                    // TODO Auto-generated catch block
                    e1.printStackTrace();
                }
                    synchronized (Application.getEventLock())
                    {
                        deleteAll();
                        add(field);
                    }
                }
                
                browserContent.finishLoading();
            }
                                                         
        }
        catch (RenderingException re)
        {
        }
        finally
        {
            SecondaryResourceFetchThread.doneAddingImages();
        }
        
    }    
    private void addCookies(String line) {
        Cookie[] cs = Cookie.parseCookies(line);
              
              for (int j = 0; j < cs.length; j ++) {
                addCookie(cs[j]);
             }
     }
     
      private void addCookie(Cookie cookie) {
               Enumeration cs = cookies.elements();
          
              while (cs.hasMoreElements()) {
                Cookie c = (Cookie)cs.nextElement();
                  
                      if (c.getJsession().equals(cookie.getJsession())) {
                           cookies.removeElement(c);
                             break;
                }
             }
             
              cookies.addElement(cookie);
   }
     
      private String returnCookie() {
               StringBuffer cookieValues = new StringBuffer();
               Cookie[] cs = new Cookie[cookies.size()];
             cookies.copyInto(cs);
         
              for (int i = 0; i < cs.length; i ++) {
                if (cs[i].getJsession() == null)
                               continue;
                     
                      cookieValues.append(cs[i].getJsession()).append('=').append(cs[i].getVersion()).append(';');
                
                      if (i < cs.length-1)
                          cookieValues.append(" ");
             }
             
      return cookieValues.toString();
       }
    /**
     * @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 :
            {
                UrlRequestedEvent urlRequestedEvent = (UrlRequestedEvent) event;    
                String absoluteUrl = urlRequestedEvent.getURL();
    
                HttpConnection conn = null;
                PrimaryResourceFetchThread thread = new PrimaryResourceFetchThread(urlRequestedEvent.getURL(),
                                                                                         urlRequestedEvent.getHeaders(),
                                                                                         urlRequestedEvent.getPostData(),
                                                                                         event, this);
                thread.start();
    
                break;

            }
            case Event.EVENT_BROWSER_CONTENT_CHANGED:
            {                
                // Browser field title might have changed update title.
                BrowserContentChangedEvent browserContentChangedEvent = (BrowserContentChangedEvent) event;
            
                if (browserContentChangedEvent.getSource() instanceof BrowserContent)
                {
                    BrowserContent browserField = (BrowserContent) browserContentChangedEvent.getSource();
                    String newTitle = browserField.getTitle();
                    if (newTitle != null)
                    {
                        synchronized (Application.getEventLock())
                        {
                            setTitle(newTitle);
                        }                                               
                    }                                       
                }                   

                break;                

            }
            case Event.EVENT_REDIRECT :
            {
                RedirectEvent e = (RedirectEvent) event;
                String referrer = e.getSourceURL();
                
                switch (e.getType())
                {  
                    case RedirectEvent.TYPE_SINGLE_FRAME_REDIRECT :
                        // Show redirect message.
                        Application.getApplication().invokeAndWait(new Runnable()
                        {
                            public void run()
                            {
                                Status.show("You are being redirected to a different page...");
                            }
                        });
                    
                    break;
                    
                    case RedirectEvent.TYPE_JAVASCRIPT &colon;
                        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 HttpConnection)
                        {
                            referrer = ((HttpConnection)eventSource).getRequestProperty(REFERER);
                        }
                        
                        break;
                    }
                    
                    HttpHeaders requestHeaders = new HttpHeaders();
                    requestHeaders.setProperty(REFERER, referrer);
                    PrimaryResourceFetchThread thread = new PrimaryResourceFetchThread(e.getLocation(), requestHeaders,null, event, this);
                    thread.start();
                    break;

            }
            case Event.EVENT_CLOSE :
                // TODO: close the appication
                break;
            
            case Event.EVENT_SET_HEADER :        // No cache support.
            case Event.EVENT_SET_HTTP_COOKIE :
                SetHttpCookieEvent setHttpCookieEvent = (SetHttpCookieEvent) event;
                 addCookies(setHttpCookieEvent.getCookie());
                break;// 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 Display.getHeight();
    }

    /**
     * @see net.rim.device.api.browser.RenderingApplication#getAvailableWidth(net.rim.device.api.browser.BrowserContent)
     */
    public int getAvailableWidth(BrowserContent browserField)
    {
        // Field has full screen.
        return Display.getWidth();
    }

    /**
     * @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)
    {
        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;
        }

        // If referrer is null we must return the connection.
        if (referrer == null)
        {
            HttpConnection connection = Utilities.makeConnection(resource.getUrl(), resource.getRequestHeaders(), null);
            
            return connection;
            
        }
        else
        {
            // If referrer is provided we can set up the connection on a separate thread.
            SecondaryResourceFetchThread.enqueue(resource, referrer);
        }

        return null;
    }

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

class PrimaryResourceFetchThread extends Thread
{
    
    private BrowserScreen _application;
    private Event _event;
    private byte[] _postData;
    private HttpHeaders _requestHeaders;
    private String _url;
    
    PrimaryResourceFetchThread(String url, HttpHeaders requestHeaders, byte[] postData,
                                  Event event, BrowserScreen application)
    {
        _url = url;
        _requestHeaders = requestHeaders;
        _postData = postData;
        _application = application;
        _event = event;
    }

    public void run()
    {
        HttpConnection connection = Utilities.makeConnection(_url, _requestHeaders, _postData);
        _application.processConnection(connection, _event);        
    }
}

Rujuta Trivedi
Developer
Posts: 905
Registered: ‎02-07-2009
My Device: BlackBerry Torch 9800
My Carrier: Globe Telecom

Re: Cookies in browserfield

hi trivedirujuta,

 

i'm not sure you are storing the cookies properly. some sites contains not just one cookie but several cookies in this format cookie1, cookie2, cookie3. I'm not sure if your parsing is correct.

 

and also implement the redirection properly. 

Contributor
Posts: 16
Registered: ‎06-16-2011
My Device: Blackberry Playbook
My Carrier: Software Engineer

Re: Cookies in browserfield

What is the Cookie class?

Contributor
Posts: 16
Registered: ‎06-16-2011
My Device: Blackberry Playbook
My Carrier: Software Engineer

Re: Cookies in browserfield

Can u Show me the Cookie Class ?