Network Connections

Overview

This category contains the packages you can use to manage input and output (I/O) data streams for Java applications on a BlackBerry™ device. The APIs in this category provide a wide range of functionality. You can use them to connect and work with everything from a MicroSD form factor smart card to an enterprise LDAP service. This category includes the implementation of the Generic Connection Framework (GCF). It also includes the Network API, which builds upon the GCF to make it easier to determine which transport types are available and to establish network connections over those transport types.

Generic Connection Framework (GCF)

Packages: javax.microedition.io, java.io

The GCF is an easy-to-use, extensible framework that lets you create connections and perform input and output operations. Although the GCF was originally created because the standard Java connection libraries were too large to implement on mobile devices, it's simplicity has made it a popular choice for I/O tasks on non-mobile devices. In fact, JSR 197 describes its implementation in J2SE.

Every connection you make using the GCF starts with the connection factory, which is implemented by the Connector class. You call Connector.open() to create any type of supported connection. The first parameter to Connector.open() is a URI (as described in RFC 2396) that specifies the type of connection to make, the endpoint to connect to and optional connection configuration details. When the connection is established, a connection interface that corresponds to the type of connection that was created is returned from the call to Connector.open(). You cast the returned connection interface to the appropriate connection subtype according to the URI you specified.

The URI's used by the GCF are comprised of three parts:


(scheme) : (hierarchical location information) ; (additional information)

The (scheme) indicates the protocol to use to establish the connection. The (hierarchical location information) describes the endpoint of the connection. And the (additional information) is used to provide additional configuration details if they are needed.

For example, in the following code snippet, the http protocol is specified along with an IP address to indicate the connection endpoint. Then interface=wifi is included to specify that the WiFi radio should be used to initiate the connection. Because the http protocol was specified, you can cast the returned connection to an HTTPConnection interface.

HTTPConnection conn = (HTTPConnection) Connector.open("http://127.0.0.1;interface=wifi");

Important: Many of the operations you can perform with the connections provided by the GCF can block. Do not attempt to work with these connections on the event thread. If you do, your application will lock. Create a non-event thread to work over these connections. To learn how to create a non-event thread and how to update the UI from such a thread, refer to the User Interface API category overview.

The following table lists the type of connections you can make using the GCF, the scheme to use in the URI and the type of Connection interface that is returned by Connector.open().

Type of connectionURI schemeConnection interface returned
Network
HTTPhttp HttpConnection or HttpServerConnection
Secure HTTPshttpHttpsConnection
UDPdatagramUDPDatagramConnection
SocketsocketSocketConnection
Server SocketsocketserverServerSocketConnection
Secure Socketssl, tlsSecureConnection
File
Filefile FileConnection or ExtendedFileConnection
Bluetooth
Bluetooth Serial Port Profile (BTSPP)btspp SocketConnection or ServerSocketConnection
L2CAPbtl2capL2CAPConnection
Messages
Short Messaging Service (SMS)smsMessageConnection
Multimedia Messaging Service (MMS)mmsMessageConnection
Serial Port
Logical Serial PortcommCommConnection
Java Card
Java Card RMIjcrmiJavaCardRMIConnection
Smart Card Applications
Application Protocol Data Unit (APDU)apduAPDUConnection

After you use Connector.open() to retrieve the connection interface for the connection you want to work with, you use methods on the interface to create an input or output stream class to enable you to send or receive data over the connection. The stream classes are defined in the java.io package.

In some cases, you can cast a returned connection interface to a super interface of the ones listed in the table above. Typically, that will result in an interface with less features. For examples of this, see the samples in the HttpConnection reference topic.

Network

Although the GCF provides a uniform, simple syntax for establishing connections, it does not abstract away the fact that there are many ways a BlackBerry device can make a network connection. Many devices have a WiFi radio as well as a cellular radio and connections can be made directly or through BES, BIS or WAP proxies. The (Additional Information) component of the connection URI is used to specify which of these many transport possibilites should be used to establish a connection. The large number of transport possibilities help ensure that BlackBerry connectivity is robust for end users. But because the capabilities and operating environment of each BlackBerry device is potentially different, you must first probe those device capabilities and environmental factors before you can construct an appropriate connection URI. This can be a challenging task.

The following table lists parameters that can be specified in the (additional information) component of network-related connection URIs.

ParameterDescription
devicesideSpecifies whether the connection should be made directly (true) or through a proxy (false)
interfaceCan be set to WiFi to force a connection to use a WiFi radio
ConnectionUIDThe UID of the service record for the WAP 2.0 gateway through which to connect. WPTCP is the CID of this service record. You can use the ServiceBook class to search for it by its CID. Useful only if a direct TCP connection is made by specifying deviceside=true.
WapGatewayAPNWAP Gateway Access Point Name
WapGatewayIPWAP Gateway IP address
WapGatewayPortWAP Gateway port
WapSourceIPWAP Source IP address
WapSourcePortWAP Source port
WapEnableWTLSOverrides the default use of WTLS on the device. If this parameter is not specified, then the WAP HTTP stack will determine whether to load WTLS based on the WAP gateway port number. Port 9203 is the secure port number of WAP gateways. If this parameter set to true then WTLS is used. If the parameter is set to false then WTLS is not used.
TunnelAuthUsernameUser name for APN session
TunnelAuthPasswordPassword for APN session

To learn more about how to use these parameters, see the Connector interface reference topic and the developer videos referred to below.

Although you have the option of writing probing code and constructing the connection URI yourself, if you are working with http, https, socket, ssl or tls network connections, you can use the Network API which makes it easy to probe for available transports and looks after the details of establishing an appropriate connection.

To learn more about the various transports available to BlackBerry devices and how to construct corresponding connection URIs, watch the following developer library videos: Network Transports and Network Transports II.

File

Unlike other GCF connection types, if you create a file Connection interface using Connector.open(), it can refer to a non-existant endpoint. If the specified endpoint doesn't exist, you can use FileConnection.create() to create the file. The endpoint can also refer to and allow you to manage directories. You cannot use this mechanism to connect to files that are considered private, like system files for example.

If you want to prevent a file from being read on another device, you can enable Digital Rights Management (DRM) by casting the interface returned by Connector.open() to an ExtendedFileConnection interface. This will let you call the ExtendedFileConnection.enableDRMForwardLock() to enable DRM. The ExtendedFileConnection also lets you encrypt files using a CodeSigningKey.

There is no (additional information) to specify in a FileConnection URI. However, the (hierarchical location information) is BlackBerry device specific. Use the following strings for the (hierarchical location information) component of the URI:

DescriptionLocation information
MicroSD card///SDCard
Device Memory///store

Be sure to including a trailing slash ('/') when specifying a FileConnection URI that refers to a directory. Otherwise, the API interpret that the URI is referring to a non-existent file.

Serial Port

The CommConnection interface represents a logical serial interface. This does not necessarily correspond to a physical RS-232 serial port. The following (additional information) can be provided in the connection URI as a series of name=value pairs, separated by apersands (&).

ParameterDefaultDescription
baudratedevice dependentThe speed of the port
bitsperchar8The number bits per character(7 or 8).
stopbits1The number of stop bits per char(1 or 2)
paritynoneThe parity can be odd, even, or none.
blockingonIf on, wait for a full buffer when reading.
autoctson If on, wait for the CTS line to be on before writing.
autortsonIf on, turn on the RTS line when the input buffer is not full. If off, the RTS line is always on.

The Network API

Package: net.rim.device.api.io.transport

The Network API is designed to make it easy to create http, https, socket, ssl and tls connections. As described above, you have to perform two tasks to create a network connection on a BlackBerry device: probe and connect. The Network API includes classes that correspond to each of these tasks. The TransportInfo class helps you probe and the ConnectionFactory helps you create connections.

You can use the TransportInfo.getAvailableTransportTypes() method to determine which transport types are supported by a device. Then you can use the TransportInfo.isTransportAvailable() method to determine whether the device is currently capable of using the supplied transport type. Finally, you can test the coverage of the transport type by using TransportInfo.hasSufficientCoverage(). After that sequence of probing calls, you know what transports are available and whether the device is in coverage for your transport of choice.

The following table lists the transport types for which you can probe.

Transport typeStatic integer constant
BlackBerry Internet Service (BIS)TransportInfo.TRANSPORT_BIS_B
Mobile Data System (MDS)TransportInfo.TRANSPORT_MDS
TCP CellularTransportInfo.TRANSPORT_TCP_CELLULAR
WiFiTransportInfo.TRANSPORT_WIFI
WAP 1.0/1.1TransportInfo.TRANSPORT_WAP
WAP 2.0TransportInfo.TRANSPORT_WAP2

Important: The Network API does not make connection creation thread safe. You must not call ConnectionFactory.getConnection() on the event thread. If you do, your application will lock. Create a non-event thread when calling this method to create a connection. To learn how to create a non-event thread and how to update the UI from such a thread, refer to the User Interface API category overview.

The simplest way to use the ConnectionFactory class to create a connection is to call the ConnectionFactory.getConnection() method, specifying only the URL to connect to. The method will return a ConnectionDescriptor object from which you can call ConnectionDescriptor.getConnection() to retrieve a Connection object which you can cast to an appropriate subobject.

If you take this approach, the Connection object returned by ConnectionDescriptor corresponds to the first transport type that was available on the device. You can instead provide preferred transport types by using the ConnectionFactory.setPreferredTransportTypes() method. You can also use the ConnectionFactory.setDisallowedTransportTypes() method to prohibit the factory from considering specified transport types.

Lightweight Directory Access Protocol (LDAP)

Package: net.rim.device.api.ldap

LDAP is a protocol that lets you interact with directory services. Directory services provide access to information in hierachical databases. One of the key uses of directory services is for storage of data in an enterprise networking environnment. Products like Microsoft Active Directory and Novell Open Enterprise Server store account information in directory databases and provide LDAP directory services to work with that data.

You can create an application on a BlackBerry device that communicates with an LDAP directory service. The API provides an interface to the LDAP component of the Mobile Data Service (MDS).

Click for code sample: Make an LDAP query.

import net.rim.device.api.ui.UiApplication;
import net.rim.device.api.ui.container.MainScreen;
import net.rim.device.api.ldap.*;
import java.util.Enumeration;


public class LDAPClient extends UiApplication 
{
  public static void main(String[] args) 
  {
    LDAPClient app = new LDAPClient();
    app.enterEventDispatcher();
  }
      
  LDAPClient()
  {
    HomeScreen scr = new HomeScreen();
    this.pushScreen(scr);
  }
}

class HomeScreen extends MainScreen
{
    public HomeScreen()
    {
        LDAPQuery query = new LDAPQuery();
        try
        {
          query.setHost("ldap.rim.net",389,"ou=people,o=rim.net");
          query.setScope(LDAPQuery.LDAP_SCOPE_SUB);
          query.addAttribute("mail");
          query.addFilter("givenname","Dean");
          query.start();
          Enumeration results = query.getResults();
          if (query.getErrorCode() != LDAPQuery.LDAP_SUCCESS) 
          {
            // An error occured, so we should report an error
          }
          while (results.hasMoreElements()) 
          {
            LDAPEntry entry = (LDAPEntry)results.nextElement();
            Enumeration attributes = entry.getAttributes();

              while (attributes.hasMoreElements()) 
              {
                LDAPAttribute attribute = (LDAPAttribute)attributes.nextElement();
                Enumeration   values    = attribute.getValues();

                  while (values.hasMoreElements()) 
                  {
                     Object value = values.nextElement();
                     if (value instanceof String) 
                     {
                        // we got a String value.
                     }
                     else 
                     {
                        // we got a byte array
                     }
                  }
              }
           }
        }
        catch(LDAPException e)
        {
            //handle exception
        }
      }
  }

Smart card and smart card reader connections

Smart cards and smart card readers

Packages: net.rim.device.api.smartcard,

You connect to a smart card or smart card reader by creating a smart card session or a smart card reader session. You create these sessions by calling static methods on the corresponding factory classes: SmartCardFactory or SmartCardReaderFactory. Both types of session objects support a sendAPDU() method which sends an APDU and blocks until it receives a response APDU.

Click for code sample: Establish smart card session

import net.rim.device.api.ui.*;
import net.rim.device.api.ui.component.Dialog;
import net.rim.device.api.ui.component.LabelField;
import net.rim.device.api.ui.component.Menu;
import net.rim.device.api.ui.container.MainScreen;
import net.rim.device.api.smartcard.*;


public class SmartCardConnect extends UiApplication 
{
   public static void main(String args[])
   {
      SmartCardConnect app = new SmartCardConnect();
      app.enterEventDispatcher();
   }
   
   public SmartCardConnect()
   {
      HomeScreen hs = new HomeScreen();
      pushScreen(hs);
   }

}

class HomeScreen extends MainScreen
{
   public HomeScreen()
   {   
      add(new LabelField("Smart card connection sample."));
   }
   
   protected void makeMenu(Menu menu,int instance)
   {
      super.makeMenu(menu,instance);
      menu.add(new MenuItem("Log on to smart card",1,1)
      {
         public void run()
         {
            SmartCard sc;
            SmartCardSession session;
            try
            {
               sc = SmartCardFactory.chooseSmartCard();
               session = SmartCardFactory.getSmartCardSession(sc);
               session.loginPrompt(null,SmartCardSession.UNKNOWN_OPERATION);
            }
            catch(Exception e)
            {
               Dialog.alert("Exception:" + e.getMessage());
            }
         
         }
      });
   }
}
Javacards

Packages: javax.microedition.apdu, javax.microedition.jcrmi, javacard.framework, javacard.framework.service, javacard.security

You can use the types in javax.microedition.jcrmi to connect to and communicate with applications running on a virtual machine on a Java Card. All of the implemented types in javacard.framework, javacard.framework.service and javacard.security are exceptions and are made available so you can appropriately handle any exceptions that originate from an application you are communicating with on a Java Card.


Copyright 1999-2011 Research In Motion Limited. 295 Phillip Street, Waterloo, Ontario, Canada, N2L 3W8. All Rights Reserved.
Java is a trademark of Oracle America, Inc. in the US and other countries.


Legal