DEVELOPERS BLOG

Integrate BEMS Directory Lookup Service into Your Application

Image by ArnoldReinhold (Own work) [GFDL , CC-BY-SA-3.0 or CC BY 2.5], via Wikimedia Commons

In an earlier blog post – Does Your App Need Storage Options? Integrate BEMS Docs Service into Your Application – I demonstrated how you could use the BlackBerry Enterprise Mobility Server (BEMS) Docs service to access remote storage repositories.  The Docs service is one of many services BEMS provides.  I’m going to discuss how to use another BEMS service today, the Directory Lookup Service.

BEMS Directory Lookup Service Development Resources

The Directory Service allows you to perform searches against both the user’s remote contact list (on Exchange or any other LDAP system) as well as the organizations global address list (GAL).  The Directory Service accepts a search string and searches for matches against the Last Name, Display Name, Full Name, Alias and Email fields and returns contacts that match with the following detail.  You can specify which fields are returned when you make your search request.

  • Full Name
  • Display Name
  • Given Name
  • Surname
  • Email Address
  • Alternative Email Address
  • Physical Addresses
  • Phone Numbers
  • Department
  • Job Title
  • Company Name
  • Office Location
  • Has Photo
  • Photo
  • Alias
  • SMIME Certificate
  • Manager Display Name
  • Manager Email Address
  • Direct Reports

Let’s look at how the Android sample BEMSDirectoryLookupSample makes use of this service.  If you have read the previous blog article on using the BEMS Docs Service, you’ll notice that the code for service discovery is re-used from that sample.

Discovering the Docs Service

BEMS is discoverable by BlackBerry Dynamics applications using BlackBerry Dynamics service discovery.  This isn’t specific to BEMS, but is a method any local or remote service can use to advertise itself.  UEM administrators have the capability to enable and disable these services for their users.  The first few steps use service discovery to determine if the user’s BlackBerry Dynamics environment has an active BEMS Directory Lookup service that they are entitled to use.  We query for this using the getServiceProvidersFor method.

Vector<GDServiceProvider> providers =
        GDAndroid.getInstance().getServiceProvidersFor(
            "com.good.gdservice.enterprise.directory",
            "1.0.0.0", GDServiceProviderType.GDSERVICEPROVIDERSERVER);

This call returns a Vector containing GDServiceProvider.  From that Vector, we can filter the services that support the BEMS Directory Lookup service and get their server name, port and priority.  Priority can be used to choose from a pool of BEMS servers and is configured by the UEM administrator.  The parseServiceDetails method in the MainActivity class of the Android sample extracts and stores that information.

Constructing the Header

BEMS identifies and authenticates the user using a BD Authentication Token.  The application requests a token using the destination BEMS server address.  When the BEMS server receives the requests, it connects to the BlackBerry Control server to verify the token is valid.  The token is requested using the GDUtility.getGDAuthToken(final String challenge, final String serverName, final GDAuthTokenCallback callback) method.  The sample application makes this request in its onGetAuthToken method of the DirectorySearch class.

The BD Authentication Token is received by the application in the onGDAuthTokenSuccess callback method of the DirectorySearch  class in the sample app.  Now that it has the token, the app can add it to the HTTP requests made to the BEMS servers as a header like this:

ArrayList<BasicHeader> headers = new ArrayList<>();
headers.add(new BasicHeader("X-Good-GD-AuthToken", gdAuthToken));

In addition to the authentication token being added as a header, the following headers are added to describe the content we are sending (JSON) and type of content we expect back.

headers.add(new BasicHeader("Content-Type", "application/json"));
headers.add(new BasicHeader("Accept", "application/json"));

Constructing the JSON Search String

The search criteria are sent in a JSON string, which looks something like this:

{
"Account":"testuser@example.com",
"SearchKey":"Tom",
"MaxNumber":10,
"SearchContacts":"True"
"UserShape":[attribute1, attribute2, attribute3, etc…]
}

Account refers to the source account we are using to look up.  This is the current user doing the search.  The email address was obtained using the BlackBerry Dynamics application configuration.

Map<String, Object> config = GDAndroid.getInstance().getApplicationConfig();
usersEmail = (String)config.get("userId");

SearchKey is the string the string that will be used to find a match.

MaxNumber is the maximum number of contacts to return in the response.

SearchContacts can be set to true or false, depending on whether we want include the user’s personal address book in the search.  Note this is their personal address book on their Exchange (or equivalent LDAP) server, not the local address book on their mobile device.

UserShape is used to choose the fields we want returned from the Directory Lookup Service.

In the BEMSDirectoryLookupSample, the following code is used to create the JSON.

JSONObject searchJson = new JSONObject();

try
{
    searchJson.put(AppConstants.TAG_ACCOUNT, usersEmail);
    searchJson.put(AppConstants.TAG_SEARCH_KEY, searchText.getText());
    searchJson.put(AppConstants.TAG_MAX_NUMBER_RESULTS, 10);

    if (includePersonalCheckBox.isChecked())
    {
        searchJson.put(AppConstants.TAG_SEARCH_PERSONAL_CONTACTS, true);
    }
    else
    {
        searchJson.put(AppConstants.TAG_SEARCH_PERSONAL_CONTACTS, false);
    }

    ArrayList<String> shape = new ArrayList<String>();

    shape.add("FullName");
    shape.add("EmailAddress");

    searchJson.put(AppConstants.TAG_USER_SHAPE, new JSONArray(shape));

}
catch (Exception jsonex)
{
    logOutput("Exception generating JSON: " + jsonex);
}

The JSON is now ready to be sent to the BEMS Directory Lookup Service.

Parsing the JSON Response

After performing the search, the BEMS Directory Lookup Service returns JSON containing search results with the fields we specified.  In the BEMSDirectoryLookupSample, FullName and EmailAddress were requested.  Here’s an example of what that JSON might look like:

[{"Alias":"MarkSohm","EmailAddress":"MarkSohm@bbtestlab.com","FullName":"Mark Sohm"},
{"Alias":"MarkSohm1","EmailAddress":"MarkSohm1@bbtestlab.com","FullName":"Mark Sohm1"},
{"Alias":"MarkSohm2","EmailAddress":"MarkSohm2@bbtestlab.com","FullName":"Mark Sohm2"},
{"Alias":"MarkSohm3","EmailAddress":"MarkSohm3@bbtestlab.com","FullName":"Mark Sohm3"}]

The BEMSDirectoryLookupSample parses the JSON response and loads it into a ListView using the following code.

try {
    //Get a JSONArray of all contacts.
    JSONArray contacts = new JSONArray(result);

    int numContacts = contacts.length();

    //Iterate through each contact.
    for (int count = 0; count < numContacts; count++)
    {
        //Extract the individual contact.
        JSONObject contact = contacts.getJSONObject(count);

        //Extract the contact name and email address.
        String fullName = contact.getString(AppConstants.TAG_FULL_NAME);
        String email = contact.getString(AppConstants.TAG_EMAIL_ADDRESS);

        //Create a HashMap to store the individual contact.
        HashMap<String, String> c = new HashMap<>();
        c.put(AppConstants.TAG_FULL_NAME, fullName);
        c.put(AppConstants.TAG_EMAIL_ADDRESS, email);

        //Add the contact to the list.
        contactList.add(c);
    }
}
catch (Exception ex)
{
    logOutput("Exception parsing result: " + ex.toString());
}

//Update parsed JSON data into ListView
ListAdapter adapter = new SimpleAdapter(
        this, contactList,
        R.layout.dir_list_item, new String[]{AppConstants.TAG_FULL_NAME,
        AppConstants.TAG_EMAIL_ADDRESS},
        new int[]{R.id.name, R.id.email});

resultsListView.setAdapter(adapter);

These basic steps should get you started with integrating the BEMS Directory Lookup Service into your application.  Have a look at the Directory Lookup REST API Documentation and explore the other features of these samples.

For more developer resources or to get started on any of our platforms, please visit the BlackBerry Developer Community website.

Mark Sohm

About Mark Sohm

Senior Technical Solutions Manager on the Solution Architects team.

Mark Sohm joined BlackBerry in 2003 and currently works as a Senior Technical Solutions Manager on the Solutions Architects team. Mark Sohm has been helping developers create applications using BlackBerry technologies for over 15 years, starting way back with the very first BlackBerry JDK on BlackBerry OS 3.6 through to BlackBerry 10 and now Android with BlackBerry Dynamics and Android Enterprise.