Skip to content

HTTPS clone URL

Subversion checkout URL

You can clone with
or
.
Download ZIP
Browse files

Updated code sample to improve logging and timestamps

  • Loading branch information...
commit 9790d347774c56acae61dac965f56c2de981f808 1 parent 5ab62b1
@MCacciacarro MCacciacarro authored
View
157 CS_SampleBwsClient.Console.txt
@@ -1,70 +1,87 @@
-Initializing web services...
-Entering Setup()
-Entering GetAuthenticator()
-Calling bwsUtilService.getAuthenticators()...
-...bwsUtilService.getAuthenticators() returned "SUCCESS"
-Exiting GetAuthenticator() with Authenticator object (Name "BlackBerry Administration Service")
-Entering GetEncodedUserName()
-Calling bwsUtilService.getEncodedUsername()...
-...bwsUtilService.getEncodedUsername() returned "SUCCESS"
-Exiting GetEncodedUserName() with value "5,0,0,1,1,0;admin00"
-Exiting Setup() with value "True"
-Getting system information...
-Entering GetSystemInfo()
-Calling bwsService.getSystemInfo()...
-...bwsService.getSystemInfo() returned "SUCCESS"
-bwsService.getSystemInfo() Execution Time: 0.0524 seconds
-bwsService.getSystemInfo() Request UID: a7295aad-8946-42cc-8165-9fd527bc4d30
-bwsService.getSystemInfo() returned the following properties:
-BWS Version: 6.0.0.262
-BAS Version: 6.0.0.265
-Mail Platform: Unknown
-Authenticated User Uid: 1
-Supports PlayBook: Yes
-Exiting GetSystemInfo() with value "True"
-Creating a user...
-Entering CreateUser()
-Creating a user with email address ""user01@example.net""
-Calling bwsService.createUsers()...
-...bwsService.createUsers() returned "SUCCESS"
-User created with UID "7" using Email Address ""user01@example.net""
-Exiting CreateUser() with value "True"
-Displaying a user's details...
-Entering DisplayUserDetails()
-Entering GetUser()
-Calling bwsService.getUsers()...
-...bwsService.getUsers() returned "SUCCESS"
-Exiting GetUser() with User object (UID "2")
-Displaying details for user with email address ""user01@example.net""
-Calling bwsService.getUsersDetail()...
-...bwsService.getUsersDetail() returned "SUCCESS"
-User details:
-Display Name: User 01
-User UID: 2
-Last Login Time: 03/19/2012 18:03:58
-Indirect IT policy names: Default
-User's device details:
-Device 1 data
----------------
-PIN: 12G34H56
-Model: PB 16GB WIFI
-Phone Number:
-Active Carrier:
-Network: Wi-Fi
-Serial Number: 0
-State: RUNNING
-IT Policy Name: Default
-Platform Version: 2.0.0.190 (Platform 2.0.0.190)
-Total Messages Expired: 0
-Total Messages Filtered: 0
-Total Messages Forwarded: 0
-Total Messages Pending: 0
-Total Messages Sent: 0
----------------
-User's account details:
-Account 1 data
----------------
-Email Address: user01@example.net
----------------
-Exiting DisplayUserDetails() with value "True"
-Press Enter to exit
+00:00.002 Initializing web services...
+00:00.007 Entering Setup()
+00:00.008 Initializing BWS web service stub
+00:01.297 BWS web service stub initialized
+00:01.297 Initializing BWSUtil web service stub
+00:01.469 BWSUtil web service stub initialized
+00:01.471 Entering GetAuthenticator()
+00:01.472 Calling bwsUtilService.getAuthenticators()...
+00:01.709 ...bwsUtilService.getAuthenticators() returned "SUCCESS"
+00:01.709 Execution Time: 0.0259 seconds
+00:01.710 Request UID: 02cf09fb-748f-4953-b952-9036982bffb3
+00:01.710 Exiting GetAuthenticator() with Authenticator object (Name "BlackBerry Administration Service")
+00:01.712 Entering GetEncodedUserName()
+00:01.713 Calling bwsUtilService.getEncodedUsername()...
+00:01.747 ...bwsUtilService.getEncodedUsername() returned "SUCCESS"
+00:01.747 Execution Time: 0.0000 seconds
+00:01.748 Request UID: e51b6ea2-9221-4a31-a111-507f74d48599
+00:01.748 Exiting GetEncodedUserName() with value "5,0,0,1,1,0;admin00"
+00:01.753 Exiting Setup() with value "True"
+00:01.753 Getting system information...
+00:01.755 Entering GetSystemInfo()
+00:01.756 Calling bwsService.getSystemInfo()...
+00:02.727 ...bwsService.getSystemInfo() returned "SUCCESS"
+00:02.727 Execution Time: 0.1046 seconds
+00:02.727 Request UID: c3f6cdfb-0aaf-488a-9544-c51ee41b4cf2
+00:02.728 bwsService.getSystemInfo() returned the following properties:
+BWS Version: 5.0.2
+BAS Version: 6.2.0.366
+Mail Platform: Unknown
+Authenticated User Uid: 1
+Supports PlayBook: Yes
+Email Address Is Mandatory: No
+Email Address Is Unique: No
+External User Uid Is Searchable: Yes
+00:02.729 Exiting GetSystemInfo() with value "True"
+00:02.729 Creating a user...
+00:02.732 Entering CreateUser()
+00:02.733 Creating a user with email address ""BRKTest0003@core.sqm.testnet.rim.net""
+00:02.734 Calling bwsService.createUsers()...
+00:04.397 ...bwsService.createUsers() returned "SUCCESS"
+00:04.398 Execution Time: 1.6135 seconds
+00:04.398 Request UID: 379c4c12-95b7-4d6a-a27a-8fe827448775
+User created with UID "16" using Email Address ""BRKTest0003@core.sqm.testnet.rim.net""
+00:04.399 Exiting CreateUser() with value "True"
+00:04.399 Displaying a user's details...
+00:04.406 Entering DisplayUserDetails()
+00:04.406 Displaying details for user with email address ""BRKTest0001@core.sqm.testnet.rim.net""
+00:04.408 Entering GetUser()
+00:04.410 Calling bwsService.getUsers()...
+00:04.654 ...bwsService.getUsers() returned "SUCCESS"
+00:04.654 Execution Time: 0.0853 seconds
+00:04.655 Request UID: b2163ef4-8a76-4f1b-af34-2b68f7016318
+00:04.655 Exiting GetUser() with User object (UID "2")
+00:04.656 Calling bwsService.getUsersDetail()...
+00:05.461 ...bwsService.getUsersDetail() returned "SUCCESS"
+00:05.461 Execution Time: 0.3601 seconds
+00:05.461 Request UID: fcb55dbf-3b0e-4623-aa88-e32eb99d91cc
+User details:
+Display Name: BRKTest0001 BRKTest0001
+User UID: 2
+Last Login Time: 10/26/2012 18:32:42
+Indirect IT policy names: Default
+User's device details:
+Device 1 data
+---------------
+PIN: 332DBC0D
+Model: BlackBerry� PlayBook� tablet 16GB
+Phone Number:
+Active Carrier:
+Network: CDMA,GSM,LTE,HSPA+,Wi-Fi,Bluetooth
+Serial Number: 990001240049197
+State: RUNNING
+IT Policy Name: Default
+Platform Version: 10.0.9.785
+Total Messages Expired: 0
+Total Messages Filtered: 0
+Total Messages Forwarded: 0
+Total Messages Pending: 0
+Total Messages Sent: 0
+---------------
+User's account details:
+Account 1 data
+---------------
+Email Address: BRKTest0001@core.sqm.testnet.rim.net
+---------------
+00:05.496 Exiting DisplayUserDetails() with value "True"
+Press Enter to exit
View
166 Java_SampleBwsClient.Console.txt
@@ -1,75 +1,91 @@
-Initializing web services...
-Entering setup()
-Mar 21, 2012 2:21:11 PM org.apache.cxf.service.factory.ReflectionServiceFactoryBean buildServiceFromClass
-INFO: Creating Service {http://ws.rim.com/enterprise/admin}BWSService from class com.rim.ws.enterprise.admin.BWS
-Mar 21, 2012 2:21:15 PM org.apache.cxf.service.factory.ReflectionServiceFactoryBean buildServiceFromClass
-INFO: Creating Service {http://ws.rim.com/enterprise/admin}BWSUtilService from class com.rim.ws.enterprise.admin.BWSUtil
-Entering getAuthenticator()
-Calling _bwsUtil.getAuthenticators()...
-..._bwsUtil.getAuthenticators() returned "SUCCESS"
-Exiting getAuthenticator() with Authenticator object (Name "BlackBerry Administration Service")
-Entering getEncodedUserName()
-Calling _bwsUtil.getEncodedUsername()...
-..._bwsUtil.getEncodedUsername() returned "SUCCESS"
-Exiting getEncodedUserName() with value "5,0,0,1,1,0;admin00"
-Exiting setup() with value "true"
-Getting system information...
-Entering getSystemInfo()
-Calling _bws.getSystemInfo()...
-..._bws.getSystemInfo() returned "SUCCESS"
-_bws.getSystemInfo() Execution Time: 0.1356 seconds
-_bws.getSystemInfo() Request UID: bf7dce44-2e25-47ea-9078-5c41a9cb8fed
-_bws.getSystemInfo() returned the following properties:
-BWS Version: 6.0.0.262
-BAS Version: 6.0.0.265
-Mail Platform: Unknown
-Authenticated User Uid: 1
-Supports PlayBook: Yes
-Exiting getSystemInfo() with value "true"
-Creating a user...
-Entering createUser()
-Creating a user with email address ""user01@example.net""
-Calling _bws.createUsers()...
-..._bws.createUsers() returned "SUCCESS"
-User created with UID "5" using Email Address ""user01@example.net""
-Exiting createUser() with value "true"
-Displaying a user's details...
-Entering displayUserDetails()
-Displaying details for user with email address ""user01@example.net""
-Entering getUser()
-Calling _bws.getUsers()...
-..._bws.getUsers() returned "SUCCESS"
-Exiting getUser() with User object (UID "2")
-Calling _bws.getUsersDetail()...
-..._bws.getUsersDetail() returned "SUCCESS"
-User details:
-Display Name: User 01
-User UID: 2
-Last Login Time: 03/19/2012 18:03:58
-Indirect IT policy names: Default
-User's device details:
-Device 1 data
----------------
-PIN: 12G34H56
-Model: PB 16GB WIFI
-Phone Number:
-Active Carrier:
-Network: Wi-Fi
-Serial Number: 0
-State: RUNNING
-IT Policy Name: Default
-Platform Version: 2.0.0.190 (Platform 2.0.0.190)
-Total Messages Expired: 0
-Total Messages Filtered: 0
-Total Messages Forwarded: 0
-Total Messages Pending: 0
-Total Messages Sent: 0
----------------
-User's account details:
-Account 1 data
----------------
-Email Address: user01@example.net
----------------
-Exiting displayUserDetails() with value "true"
-Press Enter to exit
-
+00:00.025 Initializing web services...
+00:00.030 Entering setup()
+00:00.032 Initializing BWS web service stub
+Oct 30, 2012 10:45:55 AM org.apache.cxf.service.factory.ReflectionServiceFactoryBean buildServiceFromClass
+INFO: Creating Service {http://ws.rim.com/enterprise/admin}BWSService from class com.rim.ws.enterprise.admin.BWS
+00:03.615 BWS web service stub initialized
+00:03.615 Initializing BWSUtil web service stub
+Oct 30, 2012 10:45:58 AM org.apache.cxf.service.factory.ReflectionServiceFactoryBean buildServiceFromClass
+INFO: Creating Service {http://ws.rim.com/enterprise/admin}BWSUtilService from class com.rim.ws.enterprise.admin.BWSUtil
+00:04.657 BWSUtil web service stub initialized
+00:04.699 Entering getAuthenticator()
+00:04.699 Calling _bwsUtil.getAuthenticators()...
+00:05.406 ..._bwsUtil.getAuthenticators() returned "SUCCESS"
+00:05.406 Execution Time: 0.0219 seconds
+00:05.409 Request UID: 85a06f84-b7d7-407a-8493-0bacffaa9a68
+00:05.410 Exiting getAuthenticator() with Authenticator object (Name "BlackBerry Administration Service")
+00:05.410 Entering getEncodedUserName()
+00:05.410 Calling _bwsUtil.getEncodedUsername()...
+00:05.423 ..._bwsUtil.getEncodedUsername() returned "SUCCESS"
+00:05.423 Execution Time: 0.0000 seconds
+00:05.424 Request UID: bea76c60-c53b-45e5-8c90-f0cc737b2132
+00:05.424 Exiting getEncodedUserName() with value "5,0,0,1,1,0;admin00"
+00:05.424 Exiting setup() with value "true"
+00:05.424 Getting system information...
+00:05.425 Entering getSystemInfo()
+00:05.425 Calling _bws.getSystemInfo()...
+00:05.592 ..._bws.getSystemInfo() returned "SUCCESS"
+00:05.593 Execution Time: 0.1075 seconds
+00:05.593 Request UID: 4a9655de-7839-40c1-81a8-ded6c06ea75e
+00:05.593 _bws.getSystemInfo() returned the following properties:
+BWS Version: 5.0.2
+BAS Version: 6.2.0.366
+Mail Platform: Unknown
+Authenticated User Uid: 1
+Supports PlayBook: Yes
+Email Address Is Mandatory: No
+Email Address Is Unique: No
+External User Uid Is Searchable: Yes
+00:05.594 Exiting getSystemInfo() with value "true"
+00:05.594 Creating a user...
+00:05.594 Entering createUser()
+00:05.595 Creating a user with email address ""BRKTest0003@core.sqm.testnet.rim.net""
+00:05.595 Calling _bws.createUsers()...
+00:07.264 ..._bws.createUsers() returned "SUCCESS"
+00:07.265 Execution Time: 1.6499 seconds
+00:07.265 Request UID: 75ce6161-c263-475f-877c-4f57ede0e5f3
+User created with UID "15" using Email Address ""BRKTest0003@core.sqm.testnet.rim.net""
+00:07.265 Exiting createUser() with value "true"
+00:07.265 Displaying a user's details...
+00:07.266 Entering displayUserDetails()
+00:07.266 Displaying details for user with email address ""BRKTest0001@core.sqm.testnet.rim.net ""
+00:07.266 Entering getUser()
+00:07.266 Calling _bws.getUsers()...
+00:07.369 ..._bws.getUsers() returned "SUCCESS"
+00:07.369 Execution Time: 0.0829 seconds
+00:07.369 Request UID: b2916a4a-250c-448f-a201-9b4d07a0de65
+00:07.370 Exiting getUser() with User object (UID "2")
+00:07.370 Calling _bws.getUsersDetail()...
+00:07.783 ..._bws.getUsersDetail() returned "SUCCESS"
+00:07.783 Execution Time: 0.3707 seconds
+00:07.784 Request UID: 56365229-4e86-4f59-bbcc-1ea134c9be4c
+User details:
+Display Name: BRKTest0001 BRKTest0001
+User UID: 2
+Last Login Time: 10/26/2012 18:32:42
+Indirect IT policy names: Default
+User's device details:
+Device 1 data
+---------------
+PIN: 332DBC0D
+Model: BlackBerry� PlayBook� tablet 16GB
+Phone Number:
+Active Carrier:
+Network: CDMA,GSM,LTE,HSPA+,Wi-Fi,Bluetooth
+Serial Number: 990001240049197
+State: RUNNING
+IT Policy Name: Default
+Platform Version: 10.0.9.785
+Total Messages Expired: 0
+Total Messages Filtered: 0
+Total Messages Forwarded: 0
+Total Messages Pending: 0
+Total Messages Sent: 0
+---------------
+User's account details:
+Account 1 data
+---------------
+Email Address: BRKTest0001@core.sqm.testnet.rim.net
+---------------
+00:07.786 Exiting displayUserDetails() with value "true"
+Press Enter to exit
View
1,556 SampleBwsClient.cs
@@ -1,717 +1,841 @@
- /*
- * Copyright (c) 2012 Research In Motion Limited.
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-using System;
-using System.Net;
-using System.IO;
-using System.Collections.Generic;
-using System.Text;
-
-/*
- * SampleBwsClient.cs
- *
- * A program that demonstrates BlackBerry Web Services (BWS) for Enterprise Administration APIs.
- *
- * This sample program demonstrates how to get system information to make an authenticated API call. If successful, the
- * program then optionally creates a user and optionally displays the user's details. If the authenticated API is not
- * successful, the program displays a message indicating that the failure has occurred.
- *
- * This program was tested against the BlackBerry Device Service version 6.0.0.
- */
-
-
-namespace Rim.Bws.Samples
-{
- class SampleBwsClient
- {
- private static BWSService bwsService;
- private static BWSUtilService bwsUtilService;
-
- // The request Metadata information.
- // This is the version of the WSDL used to generate the proxy, not the version of the server.
- private const string ClientVersion = "6.0.0";
-
- /*
- * To use a different locale, call getLocales() in the BWSUtilService web service
- * to see which locales are supported.
- */
- private const string Locale = "en_US";
- private const string OrgUid = "0";
- private static readonly RequestMetadata Metadata = new RequestMetadata();
-
- // Authentication type name.
- private const string AuthenticatorName = "BlackBerry Administration Service";
-
- // Hostname to use when connecting to web service.
- private const string BWSHostName = "<BWSHostName>"; // e.g. BWSHostName = "server01.yourcompany.net".
- private const string Username = "<username>"; // e.g. Username = "admin".
- private const string Password = "<password>"; // e.g. Password = "password".
-
- /*
- * Note about exact String Searching: To use an email address as the search criteria for an exact string match
- * search, it must be enclosed in double-quotes e.g. \"user01@example.net\". Enclosing search criteria in
- * double-quotes causes an exact string match search to be performed.
- *
- * Failing to enclose the email search criteria in double-quotes e.g. user01@example.net (no double-quotes)
- * will result in a substring match search being performed. A substring match search in this case would return
- * multiple undesired search results because searching with user01@example.net (no double-quotes) would
- * not only match on the value user01@example.net, but would also match on the value
- * someuser01@example.net and someotheruser01@example.net due to the fact that the substring
- * user01@example.net satisfies the search criteria in all of these cases.
- *
- * String searches are not case-sensitive. Wildcards and prefix or suffix matching is supported.
- */
-
- // Email address used to create a new user with the createUsers() API call.
- private const string CreateNewUserEmail = "\"user01@example.net\"";
-
- // Email address used to identify the user to find with the getUsersDetail() API call.
- private const string DisplayUserDetailsEmail = "\"user01@example.net\"";
-
- /// <summary>
- /// Initialize the BWS and BWSUtil services.
- /// </summary>
- /// <returns>Returns true when the setup is successful, and false otherwise.</returns>
- private static bool Setup()
- {
- const string methodName = "Setup()";
- Console.Error.WriteLine("Entering {0}", methodName);
- bool returnValue = false;
-
- Metadata.clientVersion = ClientVersion;
- Metadata.locale = Locale;
- Metadata.organizationUid = OrgUid;
-
- bwsService = new BWSService();
- bwsUtilService = new BWSUtilService();
- // URLs for the web services. This URL points to the main web service page.
- bwsService.Url = "https://" + BWSHostName + "/enterprise/admin/ws";
- bwsUtilService.Url = "https://" + BWSHostName + "/enterprise/admin/util/ws";
-
- // Set the connection timeout to 60 seconds.
- bwsService.Timeout = 60000;
- bwsUtilService.Timeout = 60000;
-
- Authenticator authenticator = GetAuthenticator(AuthenticatorName);
- if (authenticator != null)
- {
- string encodedUsername = GetEncodedUserName(Username, authenticator);
- if (!string.IsNullOrEmpty(encodedUsername))
- {
- /*
- * Set the HTTP basic authentication on the BWS service.
- * BWSUtilService is a utility web service that does not require
- * authentication.
- */
- bwsService.Credentials = new NetworkCredential(encodedUsername, Password);
-
- /*
- * Send an HTTP Authorization header with requests after authentication
- * has taken place.
- */
- bwsService.PreAuthenticate = true;
- returnValue = true;
- }
- else
- {
- Console.Error.WriteLine("'encodedUsername' is null or empty");
- }
- }
- else
- {
- Console.Error.WriteLine("'authenticator' is null");
- }
-
- Console.Error.WriteLine("Exiting {0} with value \"{1}\"", methodName, returnValue);
- return returnValue;
- }
-
- /// <summary>
- /// Get the authenticator object for the authenticator name.
- /// </summary>
- /// <param name="authenticatorName">A string containing the name of the desired authenticator.</param>
- /// <returns>Returns the requested authenticator if it is found, and null otherwise.</returns>
- public static Authenticator GetAuthenticator(string authenticatorName)
- {
- const string methodName = "GetAuthenticator()";
- const string bwsApiName = "bwsUtilService.getAuthenticators()";
- Console.Error.WriteLine("Entering {0}", methodName);
- Authenticator returnValue = null;
-
- GetAuthenticatorsRequest request = new GetAuthenticatorsRequest();
- request.metadata = Metadata;
-
- Console.Error.WriteLine("Calling {0}...", bwsApiName);
- GetAuthenticatorsResponse response = bwsUtilService.getAuthenticators(request);
- Console.Error.WriteLine("...{0} returned \"{1}\"", bwsApiName, response.returnStatus.code);
-
- if (response.returnStatus.code.Equals("SUCCESS"))
- {
- if (response.authenticators != null && response.authenticators.Length > 0)
- {
- foreach (Authenticator authenticator in response.authenticators)
- {
- if (authenticator.name.Equals(authenticatorName, StringComparison.CurrentCultureIgnoreCase))
- {
- returnValue = authenticator;
- break;
- }
- }
-
- if (returnValue == null)
- {
- Console.Error.WriteLine("Could not find \"{0}\" in GetAuthenticatorsResponse",
- authenticatorName);
- }
- }
- else
- {
- Console.Error.WriteLine("No authenticators in GetAuthenticatorsResponse");
- }
- }
- else
- {
- Console.Error.WriteLine("Error: Code: \"{0}\", Message: \"{1}\"", response.returnStatus.code,
- response.returnStatus.message);
- }
-
- Console.Error.WriteLine("Exiting {0} with {1}", methodName, returnValue == null ? "\"null\"" :
- "Authenticator object (Name \"" + returnValue.name + "\")");
- return returnValue;
- }
-
- /// <summary>
- /// Get the encoded username required to authenticate user to BWS.
- /// </summary>
- /// <param name="username">A string containing the username to encode.</param>
- /// <param name="authenticator">The authenticator.</param>
- /// <returns>Returns a string containing the encoded username if successful, and a null message string
- /// otherwise.</returns>
- public static string GetEncodedUserName(string username, Authenticator authenticator)
- {
- const string methodName = "GetEncodedUserName()";
- const string bwsApiName = "bwsUtilService.getEncodedUsername()";
- Console.Error.WriteLine("Entering {0}", methodName);
- string returnValue = null;
-
- GetEncodedUsernameRequest request = new GetEncodedUsernameRequest();
- request.metadata = Metadata;
- request.username = username;
- request.orgUid = Metadata.organizationUid;
- request.authenticator = authenticator;
-
- CredentialType credentialType = new CredentialType();
- credentialType.PASSWORD = true;
- credentialType.value = "PASSWORD";
- request.credentialType = credentialType;
-
- Console.Error.WriteLine("Calling {0}...", bwsApiName);
- GetEncodedUsernameResponse response = bwsUtilService.getEncodedUsername(request);
- Console.Error.WriteLine("...{0} returned \"{1}\"", bwsApiName, response.returnStatus.code);
-
- if (response.returnStatus.code.Equals("SUCCESS"))
- {
- returnValue = response.encodedUsername;
- }
- else
- {
- Console.Error.WriteLine("Error: Code: \"{0}\", Message: \"{1}\"", response.returnStatus.code,
- response.returnStatus.message);
- }
-
- Console.Error.WriteLine("Exiting {0} with value \"{1}\"", methodName, returnValue == null ? "null" :
- returnValue);
- return returnValue;
- }
-
- /// <summary>
- /// Retrieves a single user using an email address. If more or less than one result is found, that is treated
- /// as an error.
- /// </summary>
- /// <returns>Returns a User object if user is found, and null otherwise.</returns>
- public static User GetUser()
- {
- const string methodName = "GetUser()";
- const string bwsApiName = "bwsService.getUsers()";
- Console.Error.WriteLine("Entering {0}", methodName);
- User returnValue = null;
-
- GetUsersRequest request = new GetUsersRequest();
- request.metadata = Metadata;
-
- GetUsersSearchCriteria searchCriteria = new GetUsersSearchCriteria();
-
-
- // Note: Email searches are not case-sensitive. Wildcards and prefix or suffix matching are supported.
-
- /*
- * Check if the value of the variable "DisplayUserDetailsEmail" is enclosed in double-quotes, and if it's
- * not, then display a message. If the variable "DisplayUserDetailsEmail" is not enclosed in double-quotes,
- * then a substring match search will be performed.
- */
- if (!DisplayUserDetailsEmail.StartsWith("\"") || !DisplayUserDetailsEmail.EndsWith("\""))
- {
- Console.Error.WriteLine("Warning: Email Address \"{0}\" is not enclosed in double-quotes",
- DisplayUserDetailsEmail);
- }
- searchCriteria.emailAddress = DisplayUserDetailsEmail;
- request.searchCriteria = searchCriteria;
-
- /*
- * The pageSize value of 2 is used to help determine if exactly 1 unique user was found. Using a pageSize value
- * of 2 avoids the overhead of retrieving more than 2 search results.
- */
- request.pageSize = 2;
-
- GetUsersSortBy sortBy = new GetUsersSortBy();
- sortBy.EMAIL_ADDRESS = true;
- sortBy.value = "EMAIL_ADDRESS";
- request.sortBy = sortBy;
-
- Console.Error.WriteLine("Calling {0}...", bwsApiName);
- GetUsersResponse response = bwsService.getUsers(request);
- Console.Error.WriteLine("...{0} returned \"{1}\"", bwsApiName, response.returnStatus.code);
-
- if (response.returnStatus.code.Equals("SUCCESS"))
- {
- if (response.users != null && response.users.Length == 1)
- {
- // Returns the first user object in the users array.
- returnValue = response.users [0];
- }
- else if (response.users != null && response.users.Length > 1)
- {
- Console.Error.WriteLine("More than one user was found with email address \"{0}\"",
- DisplayUserDetailsEmail);
- }
- else
- {
- Console.Error.WriteLine("No user was found with email address \"{0}\"", DisplayUserDetailsEmail);
- }
- }
- else
- {
- Console.Error.WriteLine("Error: Code: \"{0}\", Message: \"{1}\"", response.returnStatus.code,
- response.returnStatus.message);
- }
-
- Console.Error.WriteLine("Exiting {0} with {1}", methodName, returnValue == null ? "\"null\"" :
- "User object (UID \"" + returnValue.uid + "\")");
- return returnValue;
- }
-
- /// <summary>
- /// Retrieve and display some user details.
- /// <returns>Returns true if getUsersDetail is successful, and false otherwise.</returns>
- /// </summary>
- public static bool DisplayUserDetails()
- {
- const string methodName = "DisplayUserDetails()";
- const string bwsApiName = "bwsService.getUsersDetail()";
- Console.Error.WriteLine("Entering {0}", methodName);
- bool returnValue = false;
-
- // Getting the user object.
- User user = GetUser();
- Console.Error.WriteLine("Displaying details for user with email address \"{0}\"",
- DisplayUserDetailsEmail);
-
- if (user == null)
- {
- Console.Error.WriteLine("'user' is null");
- Console.Error.WriteLine("Exiting {0} with value \"{1}\"", methodName, returnValue);
- return returnValue;
- }
-
- List<User> users = new List<User>();
- users.Add(user);
-
- GetUsersDetailRequest request = new GetUsersDetailRequest();
- request.metadata = Metadata;
-
- /*
- * To help improve API performance, load only the required details.
- * By default all load flags are set to false.
- */
- request.loadAccounts = true;
- request.loadDevices = true;
- request.loadITPolicies = true;
- request.users = users.ToArray();
-
- Console.Error.WriteLine("Calling {0}...", bwsApiName);
- GetUsersDetailResponse response = bwsService.getUsersDetail(request);
- Console.Error.WriteLine("...{0} returned \"{1}\"", bwsApiName, response.returnStatus.code);
-
- if (response.returnStatus.code.Equals("SUCCESS"))
- {
- if (response.individualResponses != null && response.individualResponses.Length == 1)
- {
- foreach (GetUsersDetailIndividualResponse individualResponse in response.individualResponses)
- {
- UserDetail userDetail = individualResponse.userDetail;
-
- Console.WriteLine("User details:");
-
- Console.WriteLine("Display Name: {0}", userDetail.displayName);
- Console.WriteLine("User UID: {0}", individualResponse.userUid);
-
- // Displays time in UTC format.
- Console.WriteLine("Last Login Time: {0}", userDetail.lastLoginTime);
- if (userDetail.indirectITPolicies != null && userDetail.indirectITPolicies.Length > 0)
- {
- Console.Write("Indirect IT policy names: ");
- StringBuilder policyString = new StringBuilder();
- foreach (IndirectITPolicy indirectITPolicy in userDetail.indirectITPolicies)
- {
- if (policyString.Length > 0)
- {
- policyString.Append(", ");
- }
- policyString.Append(indirectITPolicy.itPolicy.policy.name);
- }
- Console.WriteLine(policyString);
- }
-
- if (userDetail.directITPolicy != null && userDetail.directITPolicy.policy != null)
- {
- Console.WriteLine("Direct IT policy name: {0}", userDetail.directITPolicy.policy.name);
- }
-
- /*
- * The BWS object model supports multiple accounts and devices. However, BES 5.0.3 will only
- * return at most one object in the userDetail.devices array, and at most one object in the
- * userDetail.accounts array.
- */
- if (userDetail.devices != null && userDetail.devices.Length > 0)
- {
- Console.WriteLine("User's device details:");
-
- int deviceIndex = 1;
- foreach (Device device in userDetail.devices)
- {
- Console.WriteLine("Device {0} data", (deviceIndex++));
- Console.WriteLine("---------------");
- Console.WriteLine("PIN: {0}", device.pin);
- Console.WriteLine("Model: {0}", device.model);
- Console.WriteLine("Phone Number: {0}", device.phoneNumber);
- Console.WriteLine("Active Carrier: {0}", device.activeCarrier);
- Console.WriteLine("Network: {0}", device.network);
- Console.WriteLine("Serial Number: {0}", device.serialNumber);
- Console.WriteLine("State: {0}", device.state.value);
- Console.WriteLine("IT Policy Name: {0}", device.itPolicyName);
- Console.WriteLine("Platform Version: {0}", device.platformVersion);
- Console.WriteLine("Total Messages Expired: {0}", device.totalMessagesExpired);
- Console.WriteLine("Total Messages Filtered: {0}", device.totalMessagesFiltered);
- Console.WriteLine("Total Messages Forwarded: {0}", device.totalMessagesForwarded);
- Console.WriteLine("Total Messages Pending: {0}", device.totalMessagesPending);
- Console.WriteLine("Total Messages Sent: {0}", device.totalMessagesSent);
- Console.WriteLine("---------------");
- }
- }
-
- if (userDetail.accounts != null && userDetail.accounts.Length > 0)
- {
- Console.WriteLine("User's account details:");
-
- int accountIndex = 1;
- foreach (Account account in userDetail.accounts)
- {
- Console.WriteLine("Account {0} data", (accountIndex++));
- Console.WriteLine("---------------");
- Console.WriteLine("Email Address: {0}", account.emailAddress);
- Console.WriteLine("---------------");
- }
- }
- }
-
- returnValue = true;
- }
- else if (response.individualResponses != null && response.individualResponses.Length > 1)
- {
- Console.Error.WriteLine("More than one user was found with userUid \"{0}\"",
- user.uid);
- }
- else
- {
- Console.Error.WriteLine("No user was found with userUid \"{0}\"", user.uid);
- }
- }
- else
- {
- Console.Error.WriteLine("Error: Code: \"{0}\", Message: \"{1}\"", response.returnStatus.code,
- response.returnStatus.message);
- if (response.individualResponses != null)
- {
- foreach (GetUsersDetailIndividualResponse individualResponse in response.individualResponses)
- {
- Console.Error.WriteLine("User UID: \"{0}\"", individualResponse.userUid);
- Console.Error.WriteLine("Individual Response - Code: \"{0}\", Message: \"{1}\"",
- individualResponse.returnStatus.code, individualResponse.returnStatus.message);
- }
- }
- }
-
- Console.Error.WriteLine("Exiting {0} with value \"{1}\"", methodName, returnValue);
- return returnValue;
- }
-
- /// <summary>
- /// Creates a user using an email address.
- /// <returns>Returns true if createUsers is successful, and false otherwise.</returns>
- /// </summary>
- public static bool CreateUser()
- {
- const string methodName = "CreateUser()";
- const string bwsApiName = "bwsService.createUsers()";
- Console.Error.WriteLine("Entering {0}", methodName);
- bool returnValue = false;
-
- // Create the request object.
- CreateUsersRequest createUsersRequest = new CreateUsersRequest();
- createUsersRequest.metadata = Metadata;
-
- NewUser newUser = new NewUser();
-
- // To create an administrator user, create and set the "UserAttributes".
- AccountAttributes accountAttributes = new AccountAttributes();
-
- /*
- * Check if value of the variable "CreateNewUserEmail" is enclosed in double-quotes,
- * otherwise the string would infer a substring match search.
- */
- if (!CreateNewUserEmail.StartsWith("\"") || !CreateNewUserEmail.EndsWith("\""))
- {
- Console.Error.WriteLine("Warning: Email Address \"{0}\" is not enclosed in double-quotes",
- CreateNewUserEmail);
- }
- // Value of the variable "CreateNewUserEmail" is used to create a BlackBerry-enabled user.
- Console.Error.WriteLine("Creating a user with email address \"{0}\"", CreateNewUserEmail);
- accountAttributes.emailAddress = CreateNewUserEmail;
-
- newUser.accountAttributes = accountAttributes;
- // Randomly select a BlackBerry Enterprise Server on which to create the user.
- newUser.server = null;
-
- List<NewUser> newUsers = new List<NewUser>();
- newUsers.Add(newUser);
- createUsersRequest.newUsers = newUsers.ToArray();
-
- Console.Error.WriteLine("Calling {0}...", bwsApiName);
- CreateUsersResponse response = bwsService.createUsers(createUsersRequest);
- Console.Error.WriteLine("...{0} returned \"{1}\"", bwsApiName, response.returnStatus.code);
-
- if (response.returnStatus.code.Equals("SUCCESS"))
- {
- if (response.individualResponses != null)
- {
- foreach (IndividualResponse individualResponse in response.individualResponses)
- {
- Console.WriteLine("User created with UID \"{0}\" using Email Address \"{1}\"",
- individualResponse.uid, CreateNewUserEmail);
- }
-
- returnValue = true;
- }
- }
- else
- {
- Console.Error.WriteLine("Error: Code: \"{0}\", Message: \"{1}\"", response.returnStatus.code,
- response.returnStatus.message);
- if (response.individualResponses != null)
- {
- foreach (IndividualResponse individualResponse in response.individualResponses)
- {
- Console.Error.WriteLine("Individual Response - Code: \"{0}\", Message: \"{1}\"",
- individualResponse.returnStatus.code, individualResponse.returnStatus.message);
- }
- }
- }
-
- Console.Error.WriteLine("Exiting {0} with value \"{1}\"", methodName, returnValue);
- return returnValue;
- }
-
- /// <summary>
- /// Call bwsService.getSystemInfo() and display the returned properties.
- /// <returns>Returns true if getSystemInfo is successful, and false otherwise.</returns>
- /// </summary>
- public static bool GetSystemInfo()
- {
- const string methodName = "GetSystemInfo()";
- const string bwsApiName = "bwsService.getSystemInfo()";
- Console.Error.WriteLine("Entering {0}", methodName);
- bool returnValue = false;
-
- GetSystemInfoRequest request = new GetSystemInfoRequest();
-
- /*
- * Setting the value of loadAuthenticatedUserProperties to true will cause the API to return additional
- * properties about the current user, like the Authenticated User Uid property. The Authenticated User Uid
- * property is often used to make self-service calls to APIs like getUsersDetail(), setUsersAutoSignature()
- * and others.
- */
- request.loadAuthenticatedUserProperties = true;
- request.metadata = Metadata;
-
- GetSystemInfoResponse response = null;
-
- /*
- * The try catch block here is used to illustrate how to handle a specific type of exception.
- * For example, in this case we check to see if the error was caused by invalid credentials.
- */
- try
- {
- Console.Error.WriteLine("Calling {0}...", bwsApiName);
- response = bwsService.getSystemInfo(request);
- Console.Error.WriteLine("...{0} returned \"{1}\"", bwsApiName, response.returnStatus.code);
- }
- catch (WebException e)
- {
- HttpWebResponse webResponse = e.Response as HttpWebResponse;
- // Handle authentication failure.
- if (webResponse != null && webResponse.StatusCode == HttpStatusCode.Unauthorized)
- {
- Console.Error.WriteLine("Failed to authenticate with the BWS web service");
- Console.Error.WriteLine("Exiting {0} with value \"{1}\"", methodName, returnValue);
- return returnValue;
- }
- else
- {
- // Re-throw other exceptions.
- throw e;
- }
- }
-
- if (response.metadata != null)
- {
- /*
- * Converting response.metadata.executionTime (which is in nano-seconds) into seconds by
- * multiplying it by 10^-9.
- */
- Console.Error.WriteLine("{0} Execution Time: {1:0.0000} seconds", bwsApiName,
- (response.metadata.executionTime * Math.Pow(10, -9)));
- Console.Error.WriteLine("{0} Request UID: {1}", bwsApiName, response.metadata.requestUid);
- }
-
- if (response.returnStatus.code.Equals("SUCCESS"))
- {
- if (response.properties != null && response.properties.Length > 0)
- {
- Console.Error.WriteLine("{0} returned the following properties:", bwsApiName);
- foreach (Property property in response.properties)
- {
- Console.WriteLine("{0}: {1}", property.name, property.value);
- }
-
- returnValue = true;
- }
- else
- {
- Console.Error.WriteLine("No properties in response");
- }
- }
- else
- {
- Console.Error.WriteLine("Error: Code: \"{0}\", Message: \"{1}\"", response.returnStatus.code,
- response.returnStatus.message);
- }
-
- Console.Error.WriteLine("Exiting {0} with value \"{1}\"", methodName, returnValue);
- return returnValue;
- }
-
- /// <summary>
- /// The Main function.
- /// </summary>
- static int Main(string [] args)
- {
- // Return codes.
- const int success = 0;
- const int failure = 1;
- int returnCode = success;
-
- /*
- * Flags that are used to determine whether or not
- * CreateUser() and DisplayUserDetails() gets called.
- */
- bool createNewUser = true;
- bool displayUserDetails = true;
-
- /*
- * BWS Host certificate must be installed on the client machine before running this sample code, otherwise
- * a SSL/TLS secure channel error will be thrown. For more information, see the BlackBerry Web Services for
- * Enterprise Administration For Microsoft .NET Developers Getting Started Guide.
- */
- try
- {
- Console.Error.WriteLine("Initializing web services...");
- if (Setup())
- {
- /*
- * Demonstrate call to bwsService.getSystemInfo().
- * This is also the first authenticated call in the client application.
- */
- Console.Error.WriteLine("Getting system information...");
- if (GetSystemInfo())
- {
- if (createNewUser)
- {
- Console.Error.WriteLine("Creating a user...");
-
- // Demonstrate call to bwsService.createUsers() API.
- if (!CreateUser())
- {
- Console.Error.WriteLine("Error: CreateUser() failed");
- returnCode = failure;
- }
- }
-
- if (displayUserDetails)
- {
- Console.Error.WriteLine("Displaying a user's details...");
-
- // Demonstrate call to bwsService.getUsers() and bwsService.getUsersDetail() APIs.
- if (!DisplayUserDetails())
- {
- Console.Error.WriteLine("Error: DisplayUserDetails() failed");
- returnCode = failure;
- }
- }
- }
- else
- {
- Console.Error.WriteLine("Error: GetSystemInfo() failed");
- returnCode = failure;
- }
- }
- else
- {
- Console.Error.WriteLine("Error: Setup() failed");
- returnCode = failure;
- }
- }
- catch (Exception e)
- {
- Console.Error.WriteLine("Exception: \"{0}\"", e.Message);
- returnCode = failure;
- }
-
- Console.Error.WriteLine("Press Enter to exit");
- Console.ReadKey();
-
- return returnCode;
- }
- }
+/*
+* Copyright (c) 2012 Research In Motion Limited.
+*
+* Licensed under the Apache License, Version 2.0 (the "License");
+* you may not use this file except in compliance with the License.
+* You may obtain a copy of the License at
+*
+* http://www.apache.org/licenses/LICENSE-2.0
+*
+* Unless required by applicable law or agreed to in writing, software
+* distributed under the License is distributed on an "AS IS" BASIS,
+* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+* See the License for the specific language governing permissions and
+* limitations under the License.
+*/
+using System;
+using System.Net;
+using System.IO;
+using System.Collections.Generic;
+using System.Text;
+using System.Diagnostics;
+/*
+ * SampleBwsClient.cs
+ *
+ * A program that demonstrates BlackBerry Web Services (BWS) for Enterprise Administration APIs.
+ *
+ * This sample program demonstrates how to get system information to make an authenticated API call. If successful, the
+ * program then optionally creates a user and optionally displays the user's details. If the authenticated API is not
+ * successful, the program displays a message indicating that the failure has occurred.
+ *
+ * This program was tested against the BlackBerry Device Service version 6.0.0.
+ */
+
+
+namespace Rim.Bws.Samples
+{
+ class SampleBwsClient
+ {
+ // Web service stubs.
+ private static BWSService bwsService;
+ private static BWSUtilService bwsUtilService;
+
+ // Timer used by logging.
+ private static Stopwatch startTime = new Stopwatch();
+ // The request Metadata information.
+ // This is the version of the WSDL used to generate the proxy, not the version of the server.
+ private const string ClientVersion = "6.0.0";
+
+ /*
+ * To use a different locale, call getLocales() in the BWSUtilService web service
+ * to see which locales are supported.
+ */
+ private const string Locale = "en_US";
+ private const string OrgUid = "0";
+ private static readonly RequestMetadata Metadata = new RequestMetadata();
+
+ // Authentication type name.
+ private const string AuthenticatorName = "BlackBerry Administration Service";
+
+ // Hostname to use when connecting to web service.
+ private static string BWSHostName = null; // e.g. BWSHostName = "server01.yourcompany.net".
+ private static string Username = null; // e.g. Username = "admin".
+ private static string Password = null; // e.g. Password = "password".
+
+ /*
+ * Note about exact String Searching: To use an email address as the search criteria for an exact string match
+ * search, it must be enclosed in double-quotes e.g. \"user01@example.net\". Enclosing search criteria in
+ * double-quotes causes an exact string match search to be performed.
+ *
+ * Failing to enclose the email search criteria in double-quotes e.g. user01@example.net (no double-quotes)
+ * will result in a substring match search being performed. A substring match search in this case would return
+ * multiple undesired search results because searching with user01@example.net (no double-quotes) would
+ * not only match on the value user01@example.net, but would also match on the value
+ * someuser01@example.net and someotheruser01@example.net due to the fact that the substring
+ * user01@example.net satisfies the search criteria in all of these cases.
+ *
+ * String searches are not case-sensitive. Wildcards and prefix or suffix matching is supported.
+ */
+
+ // Email address used to create a new user with the createUsers() API call.
+ private static string CreateNewUserEmail = null;
+
+ // Email address used to identify the user to find with the getUsersDetail() API call.
+ private static string DisplayUserDetailsEmail = null;
+
+ /// <summary>
+ /// Initialize the BWS and BWSUtil services.
+ /// </summary>
+ /// <returns>Returns true when the setup is successful, and false otherwise.</returns>
+ private static bool Setup()
+ {
+ const string methodName = "Setup()";
+ logMessage("Entering {0}", methodName);
+ bool returnValue = false;
+
+ Metadata.clientVersion = ClientVersion;
+ Metadata.locale = Locale;
+ Metadata.organizationUid = OrgUid;
+
+ logMessage("Initializing BWS web service stub");
+ bwsService = new BWSService();
+ logMessage("BWS web service stub initialized");
+ logMessage("Initializing BWSUtil web service stub");
+ bwsUtilService = new BWSUtilService();
+ logMessage("BWSUtil web service stub initialized");
+ // These are the URLs that point to the web services used for all calls.
+ bwsService.Url = "https://" + BWSHostName + "/enterprise/admin/ws";
+ bwsUtilService.Url = "https://" + BWSHostName + "/enterprise/admin/util/ws";
+
+ // Set the connection timeout to 60 seconds.
+ bwsService.Timeout = 60000;
+ bwsUtilService.Timeout = 60000;
+
+ Authenticator authenticator = GetAuthenticator(AuthenticatorName);
+ if (authenticator != null)
+ {
+ string encodedUsername = GetEncodedUserName(Username, authenticator);
+ if (!string.IsNullOrEmpty(encodedUsername))
+ {
+ /*
+ * Set the HTTP basic authentication on the BWS service.
+ * BWSUtilService is a utility web service that does not require
+ * authentication.
+ */
+ bwsService.Credentials = new NetworkCredential(encodedUsername, Password);
+
+ /*
+ * Send an HTTP Authorization header with requests after authentication
+ * has taken place.
+ */
+ bwsService.PreAuthenticate = true;
+ returnValue = true;
+ }
+ else
+ {
+ logMessage("'encodedUsername' is null or empty");
+ }
+ }
+ else
+ {
+ logMessage("'authenticator' is null");
+ }
+
+ logMessage("Exiting {0} with value \"{1}\"", methodName, returnValue);
+ return returnValue;
+ }
+
+ /// <summary>
+ /// Get the authenticator object for the authenticator name.
+ /// </summary>
+ /// <param name="authenticatorName">A string containing the name of the desired authenticator.</param>
+ /// <returns>Returns the requested authenticator if it is found, and null otherwise.</returns>
+ public static Authenticator GetAuthenticator(string authenticatorName)
+ {
+ const string methodName = "GetAuthenticator()";
+ const string bwsApiName = "bwsUtilService.getAuthenticators()";
+ logMessage("Entering {0}", methodName);
+ Authenticator returnValue = null;
+
+ GetAuthenticatorsRequest request = new GetAuthenticatorsRequest();
+ request.metadata = Metadata;
+
+ GetAuthenticatorsResponse response = null;
+
+ try
+ {
+ logRequest(bwsApiName);
+ response = bwsUtilService.getAuthenticators(request);
+ logResponse(bwsApiName, response.returnStatus.code, response.metadata);
+ }
+ catch (WebException e)
+ {
+ // Log and re-throw exception.
+ logMessage("Exiting {0} with exception \"{1}\"", methodName, e.Message);
+ throw e;
+ }
+
+ if (response.returnStatus.code.Equals("SUCCESS"))
+ {
+ if (response.authenticators != null && response.authenticators.Length > 0)
+ {
+ foreach (Authenticator authenticator in response.authenticators)
+ {
+ if (authenticator.name.Equals(authenticatorName, StringComparison.CurrentCultureIgnoreCase))
+ {
+ returnValue = authenticator;
+ break;
+ }
+ }
+
+ if (returnValue == null)
+ {
+ logMessage("Could not find \"{0}\" in GetAuthenticatorsResponse",
+ authenticatorName);
+ }
+ }
+ else
+ {
+ logMessage("No authenticators in GetAuthenticatorsResponse");
+ }
+ }
+ else
+ {
+ logMessage("Error Message: \"{0}\"", response.returnStatus.message);
+ }
+
+ logMessage("Exiting {0} with {1}", methodName, returnValue == null ? "\"null\"" :
+ "Authenticator object (Name \"" + returnValue.name + "\")");
+ return returnValue;
+ }
+
+ /// <summary>
+ /// Get the encoded username required to authenticate user to BWS.
+ /// </summary>
+ /// <param name="username">A string containing the username to encode.</param>
+ /// <param name="authenticator">The authenticator.</param>
+ /// <returns>Returns a string containing the encoded username if successful, and a null message string
+ /// otherwise.</returns>
+ public static string GetEncodedUserName(string username, Authenticator authenticator)
+ {
+ const string methodName = "GetEncodedUserName()";
+ const string bwsApiName = "bwsUtilService.getEncodedUsername()";
+ logMessage("Entering {0}", methodName);
+ string returnValue = null;
+
+ GetEncodedUsernameRequest request = new GetEncodedUsernameRequest();
+ request.metadata = Metadata;
+ request.username = username;
+ request.orgUid = Metadata.organizationUid;
+ request.authenticator = authenticator;
+
+ CredentialType credentialType = new CredentialType();
+ credentialType.PASSWORD = true;
+ credentialType.value = "PASSWORD";
+ request.credentialType = credentialType;
+
+ GetEncodedUsernameResponse response = null;
+
+ try
+ {
+ logRequest(bwsApiName);
+ response = bwsUtilService.getEncodedUsername(request);
+ logResponse(bwsApiName, response.returnStatus.code, response.metadata);
+ }
+ catch (WebException e)
+ {
+ // Log and re-throw exception.
+ logMessage("Exiting {0} with exception \"{1}\"", methodName, e.Message);
+ throw e;
+ }
+
+ if (response.returnStatus.code.Equals("SUCCESS"))
+ {
+ returnValue = response.encodedUsername;
+ }
+ else
+ {
+ logMessage("Error Message: \"{0}\"", response.returnStatus.message);
+ }
+
+ logMessage("Exiting {0} with value \"{1}\"", methodName, returnValue == null ? "null" :
+ returnValue);
+ return returnValue;
+ }
+
+ /// <summary>
+ /// Retrieves a single user using an email address. If more or less than one result is found, that is treated
+ /// as an error.
+ /// </summary>
+ /// <returns>Returns a User object if user is found, and null otherwise.</returns>
+ public static User GetUser()
+ {
+ const string methodName = "GetUser()";
+ const string bwsApiName = "bwsService.getUsers()";
+ logMessage("Entering {0}", methodName);
+ User returnValue = null;
+
+ GetUsersRequest request = new GetUsersRequest();
+ request.metadata = Metadata;
+
+ GetUsersSearchCriteria searchCriteria = new GetUsersSearchCriteria();
+
+
+ // Note: Email searches are not case-sensitive. Wildcards and prefix or suffix matching are supported.
+
+ /*
+ * Check if the value of the variable "DisplayUserDetailsEmail" is enclosed in double-quotes, and if it's
+ * not, then display a message. If the variable "DisplayUserDetailsEmail" is not enclosed in double-quotes,
+ * then a substring match search will be performed.
+ */
+ if (!DisplayUserDetailsEmail.StartsWith("\"") || !DisplayUserDetailsEmail.EndsWith("\""))
+ {
+ logMessage("Warning: Email Address \"{0}\" is not enclosed in double-quotes",
+ DisplayUserDetailsEmail);
+ }
+ searchCriteria.emailAddress = DisplayUserDetailsEmail;
+ request.searchCriteria = searchCriteria;
+
+ /*
+ * The pageSize value of 2 is used to help determine if exactly 1 unique user was found. Using a pageSize value
+ * of 2 avoids the overhead of retrieving more than 2 search results.
+ */
+ request.pageSize = 2;
+
+ GetUsersSortBy sortBy = new GetUsersSortBy();
+ sortBy.EMAIL_ADDRESS = true;
+ sortBy.value = "EMAIL_ADDRESS";
+ request.sortBy = sortBy;
+
+ GetUsersResponse response = null;
+
+ try
+ {
+ logRequest(bwsApiName);
+ response = bwsService.getUsers(request);
+ logResponse(bwsApiName, response.returnStatus.code, response.metadata);
+ }
+ catch (WebException e)
+ {
+ // Log and re-throw exception.
+ logMessage("Exiting {0} with exception \"{1}\"", methodName, e.Message);
+ throw e;
+ }
+
+ if (response.returnStatus.code.Equals("SUCCESS"))
+ {
+ if (response.users != null && response.users.Length == 1)
+ {
+ // Returns the first user object in the users array.
+ returnValue = response.users[0];
+ }
+ else if (response.users != null && response.users.Length > 1)
+ {
+ logMessage("More than one user was found with email address \"{0}\"",
+ DisplayUserDetailsEmail);
+ }
+ else
+ {
+ logMessage("No user was found with email address \"{0}\"", DisplayUserDetailsEmail);
+ }
+ }
+ else
+ {
+ logMessage("Error Message: \"{0}\"", response.returnStatus.message);
+ }
+
+ logMessage("Exiting {0} with {1}", methodName, returnValue == null ? "\"null\"" :
+ "User object (UID \"" + returnValue.uid + "\")");
+ return returnValue;
+ }
+
+ /// <summary>
+ /// Retrieve and display some user details.
+ /// <returns>Returns true if getUsersDetail is successful, and false otherwise.</returns>
+ /// </summary>
+ public static bool DisplayUserDetails()
+ {
+ const string methodName = "DisplayUserDetails()";
+ const string bwsApiName = "bwsService.getUsersDetail()";
+ logMessage("Entering {0}", methodName);
+ bool returnValue = false;
+
+ logMessage("Displaying details for user with email address \"{0}\"",
+ DisplayUserDetailsEmail);
+
+ // Getting the user object.
+ User user = GetUser();
+
+ if (user == null)
+ {
+ logMessage("'user' is null");
+ logMessage("Exiting {0} with value \"{1}\"", methodName, returnValue);
+ return returnValue;
+ }
+
+ List<User> users = new List<User>();
+ users.Add(user);
+
+ GetUsersDetailRequest request = new GetUsersDetailRequest();
+ request.metadata = Metadata;
+
+ /*
+ * To help improve API performance, load only the required details.
+ * By default all load flags are set to false.
+ */
+ request.loadAccounts = true;
+ request.loadDevices = true;
+ request.loadITPolicies = true;
+ request.users = users.ToArray();
+
+ GetUsersDetailResponse response = null;
+ try
+ {
+ logRequest(bwsApiName);
+ response = bwsService.getUsersDetail(request);
+ logResponse(bwsApiName, response.returnStatus.code, response.metadata);
+ }
+ catch (WebException e)
+ {
+ // Log and re-throw exception.
+ logMessage("Exiting {0} with exception \"{1}\"", methodName, e.Message);
+ throw e;
+ }
+
+ if (response.returnStatus.code.Equals("SUCCESS"))
+ {
+ if (response.individualResponses != null && response.individualResponses.Length == 1)
+ {
+ foreach (GetUsersDetailIndividualResponse individualResponse in response.individualResponses)
+ {
+ UserDetail userDetail = individualResponse.userDetail;
+
+ displayResult("User details:");
+
+ displayResult("Display Name: {0}", userDetail.displayName);
+ displayResult("User UID: {0}", individualResponse.userUid);
+
+ // Displays time in UTC format.
+ displayResult("Last Login Time: {0}", userDetail.lastLoginTime);
+ if (userDetail.indirectITPolicies != null && userDetail.indirectITPolicies.Length > 0)
+ {
+ StringBuilder policyString = new StringBuilder();
+ foreach (IndirectITPolicy indirectITPolicy in userDetail.indirectITPolicies)
+ {
+ if (policyString.Length > 0)
+ {
+ policyString.Append(", ");
+ }
+ policyString.Append(indirectITPolicy.itPolicy.policy.name);
+ }
+ displayResult("Indirect IT policy names: {0}", policyString.ToString());
+ }
+
+ if (userDetail.directITPolicy != null && userDetail.directITPolicy.policy != null)
+ {
+ displayResult("Direct IT policy name: {0}", userDetail.directITPolicy.policy.name);
+ }
+
+ /*
+ * The BWS object model supports multiple accounts and devices. However, BlackBerry Enterprise
+ * Server 5.0.3 or later will only return at most one object in the userDetail.devices array, and
+ * at most one object in the userDetail.accounts array.
+ */
+ if (userDetail.devices != null && userDetail.devices.Length > 0)
+ {
+ displayResult("User's device details:");
+
+ int deviceIndex = 1;
+ foreach (Device device in userDetail.devices)
+ {
+ displayResult("Device {0} data", (deviceIndex++));
+ displayResult("---------------");
+ displayResult("PIN: {0}", device.pin);
+ displayResult("Model: {0}", device.model);
+ displayResult("Phone Number: {0}", device.phoneNumber);
+ displayResult("Active Carrier: {0}", device.activeCarrier);
+ displayResult("Network: {0}", device.network);
+ displayResult("Serial Number: {0}", device.serialNumber);
+ displayResult("State: {0}", device.state.value);
+ displayResult("IT Policy Name: {0}", device.itPolicyName);
+ displayResult("Platform Version: {0}", device.platformVersion);
+ displayResult("Total Messages Expired: {0}", device.totalMessagesExpired);
+ displayResult("Total Messages Filtered: {0}", device.totalMessagesFiltered);
+ displayResult("Total Messages Forwarded: {0}", device.totalMessagesForwarded);
+ displayResult("Total Messages Pending: {0}", device.totalMessagesPending);
+ displayResult("Total Messages Sent: {0}", device.totalMessagesSent);
+ displayResult("---------------");
+ }
+ }
+
+ if (userDetail.accounts != null && userDetail.accounts.Length > 0)
+ {
+ displayResult("User's account details:");
+
+ int accountIndex = 1;
+ foreach (Account account in userDetail.accounts)
+ {
+ displayResult("Account {0} data", (accountIndex++));
+ displayResult("---------------");
+ displayResult("Email Address: {0}", account.emailAddress);
+ displayResult("---------------");
+ }
+ }
+ }
+
+ returnValue = true;
+ }
+ else if (response.individualResponses != null && response.individualResponses.Length > 1)
+ {
+ logMessage("More than one user was found with userUid \"{0}\"",
+ user.uid);
+ }
+ else
+ {
+ logMessage("No user was found with userUid \"{0}\"", user.uid);
+ }
+ }
+ else
+ {
+ logMessage("Error Message: \"{0}\"", response.returnStatus.message);
+ if (response.individualResponses != null)
+ {
+ foreach (GetUsersDetailIndividualResponse individualResponse in response.individualResponses)
+ {
+ logMessage("User UID: \"{0}\"", individualResponse.userUid);
+ logMessage("Individual Response - Code: \"{0}\", Message: \"{1}\"",
+ individualResponse.returnStatus.code, individualResponse.returnStatus.message);
+ }
+ }
+ }
+
+ logMessage("Exiting {0} with value \"{1}\"", methodName, returnValue);
+ return returnValue;
+ }
+
+ /// <summary>
+ /// Creates a user using an email address.
+ /// <returns>Returns true if createUsers is successful, and false otherwise.</returns>
+ /// </summary>
+ public static bool CreateUser()
+ {
+ const string methodName = "CreateUser()";
+ const string bwsApiName = "bwsService.createUsers()";
+ logMessage("Entering {0}", methodName);
+ bool returnValue = false;
+
+ // Create the request object.
+ CreateUsersRequest createUsersRequest = new CreateUsersRequest();
+ createUsersRequest.metadata = Metadata;
+
+ NewUser newUser = new NewUser();
+
+ // To create an administrator user, create and set the "UserAttributes".
+ AccountAttributes accountAttributes = new AccountAttributes();
+
+ /*
+ * Check if value of the variable "CreateNewUserEmail" is enclosed in double-quotes,
+ * otherwise the string would infer a substring match search.
+ */
+ if (!CreateNewUserEmail.StartsWith("\"") || !CreateNewUserEmail.EndsWith("\""))
+ {
+ logMessage("Warning: Email Address \"{0}\" is not enclosed in double-quotes",
+ CreateNewUserEmail);
+ }
+ // Value of the variable "CreateNewUserEmail" is used to create a BlackBerry-enabled user.
+ logMessage("Creating a user with email address \"{0}\"", CreateNewUserEmail);
+ accountAttributes.emailAddress = CreateNewUserEmail;
+
+ newUser.accountAttributes = accountAttributes;
+ // Randomly select a BlackBerry Enterprise Server on which to create the user.
+ newUser.server = null;
+
+ List<NewUser> newUsers = new List<NewUser>();
+ newUsers.Add(newUser);
+ createUsersRequest.newUsers = newUsers.ToArray();
+
+ CreateUsersResponse response = null;
+
+ try
+ {
+ logRequest(bwsApiName);
+ response = bwsService.createUsers(createUsersRequest);
+ logResponse(bwsApiName, response.returnStatus.code, response.metadata);
+ }
+ catch (WebException e)
+ {
+ // Log and re-throw exception.
+ logMessage("Exiting {0} with exception \"{1}\"", methodName, e.Message);
+ throw e;
+ }
+
+ if (response.returnStatus.code.Equals("SUCCESS"))
+ {
+ if (response.individualResponses != null)
+ {
+ foreach (IndividualResponse individualResponse in response.individualResponses)
+ {
+ displayResult("User created with UID \"{0}\" using Email Address \"{1}\"",
+ individualResponse.uid, accountAttributes.emailAddress);
+ }
+
+ returnValue = true;
+ }
+ }
+ else
+ {
+ logMessage("Error Message: \"{0}\"", response.returnStatus.message);
+ if (response.individualResponses != null)
+ {
+ foreach (IndividualResponse individualResponse in response.individualResponses)
+ {
+ logMessage("Individual Response - Code: \"{0}\", Message: \"{1}\"",
+ individualResponse.returnStatus.code, individualResponse.returnStatus.message);
+ }
+ }
+ }
+
+ logMessage("Exiting {0} with value \"{1}\"", methodName, returnValue);
+ return returnValue;
+ }
+
+ /// <summary>
+ /// Call bwsService.getSystemInfo() and display the returned properties.
+ /// <returns>Returns true if getSystemInfo is successful, and false otherwise.</returns>
+ /// </summary>
+ public static bool GetSystemInfo()
+ {
+ const string methodName = "GetSystemInfo()";
+ const string bwsApiName = "bwsService.getSystemInfo()";
+ logMessage("Entering {0}", methodName);
+ bool returnValue = false;
+
+ GetSystemInfoRequest request = new GetSystemInfoRequest();
+
+ /*
+ * Setting the value of loadAuthenticatedUserProperties to true will cause the API to return additional
+ * properties about the current user, like the Authenticated User Uid property. The Authenticated User Uid
+ * property is often used to make self-service calls to APIs like getUsersDetail(), setUsersAutoSignature()
+ * and others.
+ */
+ request.loadAuthenticatedUserProperties = true;
+ request.metadata = Metadata;
+
+ GetSystemInfoResponse response = null;
+
+ /*
+ * The try catch block here is used to illustrate how to handle a specific type of exception.
+ * For example, in this case we check to see if the error was caused by invalid credentials.
+ */
+ try
+ {
+ logRequest(bwsApiName);
+ response = bwsService.getSystemInfo(request);
+ logResponse(bwsApiName, response.returnStatus.code, response.metadata);
+ }
+ catch (WebException e)
+ {
+ HttpWebResponse webResponse = e.Response as HttpWebResponse;
+ // Handle authentication failure.
+ if (webResponse != null && webResponse.StatusCode == HttpStatusCode.Unauthorized)
+ {
+ logMessage("Failed to authenticate with the BWS web service");
+ logMessage("Exiting {0} with value \"{1}\"", methodName, returnValue);
+ return returnValue;
+ }
+ // Log and re-throw exception.
+ logMessage("Exiting {0} with exception \"{1}\"", methodName, e.Message);
+ throw e;
+
+ }
+
+ if (response.returnStatus.code.Equals("SUCCESS"))
+ {
+ if (response.properties != null && response.properties.Length > 0)
+ {
+ logMessage("{0} returned the following properties:", bwsApiName);
+ foreach (Property property in response.properties)
+ {
+ displayResult("{0}: {1}", property.name, property.value);
+ }
+
+ returnValue = true;
+ }
+ else
+ {
+ logMessage("No properties in response");
+ }
+ }
+ else
+ {
+ logMessage("Error Message: \"{0}\"", response.returnStatus.message);
+ }
+
+ logMessage("Exiting {0} with value \"{1}\"", methodName, returnValue);
+ return returnValue;
+ }
+
+ /// <summary>
+ /// Creates a string containing the elapsed time since the program started.
+ /// The execution time will be reset to 00:00.000 if the execution time exceeds an hour.
+ /// <returns>Returns the elapsed time from start of program.</returns>
+ /// </summary>
+ public static String logTime()
+ {
+ String time = startTime.Elapsed.ToString();
+ // trim decimals to 3 digits for seconds
+ time = time.Substring(0, time.IndexOf('.') + 4);
+ // get rid of HH:
+ time = time.Substring(3);
+ return time;
+ }
+
+ /// <summary>
+ /// Prints a log message to stderr.
+ /// Appends the message to a string containing the elapsed time of the program.
+ /// <param name="format">A string which formats how args will be displayed in the message.</param>
+ /// <param name="args">Array of objects to be displayed in the message.</param>
+ /// </summary>
+ public static void logMessage(String format, params Object[] args)
+ { //Change output stream if desired
+ TextWriter logStream = Console.Error;
+ Console.OutputEncoding = System.Text.Encoding.UTF8;
+ logStream.WriteLine(logTime() + " " + format, args);
+ }
+
+ /// <summary>
+ /// Prints results to stderr.
+ /// <param name="format">A string which formats how args will be displayed in the message.</param>
+ /// <param name="args">Array of objects to be displayed in the message.</param>
+ /// </summary>
+ public static void displayResult(String format, params Object[] args)
+ { //Change output stream if desired
+ TextWriter resultStream = Console.Error;
+ Console.OutputEncoding = System.Text.Encoding.UTF8;
+ resultStream.WriteLine(format, args);
+ }
+
+ /// <summary>
+ /// Logs the calling of an API.
+ /// <param name="bwsApiName">A string of the API called.</param>
+ /// </summary>
+ public static void logRequest(String bwsApiName)
+ {
+ logMessage("Calling {0}...", bwsApiName);
+ }
+
+ /// <summary>
+ /// Logs various information about an API response.
+ /// <param name="bwsApiName">A string of the API called.</param>
+ /// <param name="code">The return code from the API called.</param>
+ /// <param name="metadata">The metadata contained in the response object returned from the API called.</param>
+ /// </summary>
+ public static void logResponse(String bwsApiName, String code, ResponseMetadata metadata)
+ {
+ logMessage("...{0} returned \"{1}\"", bwsApiName, code);
+ if (metadata != null)
+ {
+ /*
+ * Converting response.metadata.executionTime (which is in nano-seconds) into seconds by
+ * multiplying it by 10^-9.
+ */
+ logMessage("Execution Time: {0:0.0000} seconds", (metadata.executionTime * Math.Pow(10, -9)));
+ logMessage("Request UID: {0}", metadata.requestUid);
+ }
+ }
+
+ /// <summary>
+ /// The Main function.
+ /// </summary>
+ static int Main(string[] args)
+ {
+ startTime.Start();
+ // Return codes.
+ const int success = 0;
+ const int failure = 1;
+ int returnCode = success;
+
+ /*
+ * Flags that are used to determine whether or not
+ * CreateUser() and DisplayUserDetails() get called.
+ */
+ bool createNewUser = false;
+ bool displayUserDetails = true;
+
+ // Hostname to use when connecting to web service.
+ BWSHostName = "<BWSHostName>"; // e.g. BWSHostName = "server01.yourcompany.net".
+ Username = "<username>"; // e.g. Username = "admin".
+ Password = "<password>"; // e.g. Password = "password".
+
+ // Email address used to create a new user with the createUsers() API call.
+ CreateNewUserEmail = "\"user01@example.net\"";
+
+ // Email address used to identify the user to find with the getUsersDetail() API call.
+ DisplayUserDetailsEmail = "\"user01@example.net\"";
+
+ /*
+ * BWS Host certificate must be installed on the client machine before running this sample code, otherwise
+ * a SSL/TLS secure channel error will be thrown. For more information, see the BlackBerry Web Services for
+ * Enterprise Administration For Microsoft .NET Developers Getting Started Guide.
+ */
+ try
+ {
+ logMessage("Initializing web services...");
+ if (Setup())
+ {
+ /*
+ * Demonstrate call to bwsService.getSystemInfo().
+ * This is also the first authenticated call in the client application.
+ */
+ logMessage("Getting system information...");
+ if (GetSystemInfo())
+ {
+ if (createNewUser)
+ {
+ logMessage("Creating a user...");
+
+ // Demonstrate call to bwsService.createUsers() API.
+ if (!CreateUser())
+ {
+ logMessage("Error: CreateUser() failed");
+ returnCode = failure;
+ }
+ }
+
+ if (displayUserDetails)
+ {
+ logMessage("Displaying a user's details...");
+
+ // Demonstrate call to bwsService.getUsers() and bwsService.getUsersDetail() APIs.
+ if (!DisplayUserDetails())
+ {
+ logMessage("Error: DisplayUserDetails() failed");
+ returnCode = failure;
+ }
+ }
+ }
+ else
+ {
+ logMessage("Error: GetSystemInfo() failed");
+ returnCode = failure;
+ }
+ }
+ else
+ {
+ logMessage("Error: Setup() failed");
+ returnCode = failure;
+ }
+ }
+ catch (Exception e)
+ {
+ Console.Error.WriteLine("Exception: \"{0}\"", e.Message);
+ returnCode = failure;
+ }
+
+ Console.Error.WriteLine("Press Enter to exit");
+ Console.ReadKey();
+
+ return returnCode;
+ }
+ }
}
View
444 SampleBwsClient.java
@@ -16,12 +16,15 @@
* It is a best practice to use Apache CXF 2.1.10 or later
*/
import com.rim.ws.enterprise.admin.*;
-import java.io.FileOutputStream;
+
import java.io.IOException;
import java.io.PrintStream;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
+import java.text.DateFormat;
+import java.text.SimpleDateFormat;
+
import javax.xml.ws.BindingProvider;
import javax.xml.ws.WebServiceException;
import javax.xml.namespace.QName;
@@ -42,16 +45,22 @@
* successful, the program displays a message indicating that the failure has occurred.
*
*
-* This program was tested against the BlackBerry Device Service version 6.0.0, and the BlackBerry Enterprise Server version 5.0.3 MR5.
+* This program was tested against the BlackBerry Device Service version 6.0.0, and the BlackBerry Enterprise Server
+* version 5.0.3 MR5.
*/
public class SampleBwsClient
{
+ // Values used in log messages.
+ final private static long NANOSECONDS_IN_A_MILLISECOND = 1000000L;
+ private static long startTime = System.nanoTime();
+
+ // Web service stubs.
private static BWSService _bwsService;
private static BWS _bws;
private static BWSUtilService _bwsUtilService;
- private static BWSUtil _bwsUtil;
-
+ private static BWSUtil _bwsUtil;
+
// The request Metadata information.
// This is the version of the WSDL used to generate the proxy, not the version of the server.
private final static String CLIENT_VERSION = "6.0.0";
@@ -68,9 +77,9 @@
private final static String AUTHENTICATOR_NAME = "BlackBerry Administration Service";
// Hostname to use when connecting to web service.
- private final static String BWS_HOST_NAME = "<BWSHostName>"; // e.g. BWS_HOST_NAME = "server01.yourcompany.net".
- private final static String USERNAME = "<username>"; // e.g. USERNAME = "admin".
- private final static String PASSWORD = "<password>"; // e.g. PASSWORD = "password".
+ private static String BWS_HOST_NAME = null; // e.g. BWS_HOST_NAME = "server01.yourcompany.net".
+ private static String USERNAME = null; // e.g. USERNAME = "admin".
+ private static String PASSWORD = null; // e.g. PASSWORD = "password".
/*
@@ -87,12 +96,12 @@
*
* String searches are not case-sensitive. Wildcards and prefix or suffix matching is supported.
*/
-
+
// Email address used to create a new user with the createUsers() API call.
- private final static String CREATE_NEW_USER_EMAIL = "\"user01@example.net\"";
+ private static String CREATE_NEW_USER_EMAIL = null;
// Email address used to identify the user to find with the getUsersDetail() API call.
- private final static String DISPLAY_USER_DETAIL_EMAIL = "\"user01@example.net\"";
+ private static String DISPLAY_USER_DETAIL_EMAIL = null;
/*******************************************************************************************************************
*
@@ -105,7 +114,7 @@
private static boolean setup()
{
final String METHOD_NAME = "setup()";
- System.err.format("Entering %s%n", METHOD_NAME);
+ logMessage("Entering %s", METHOD_NAME);
boolean returnValue = false;
REQUEST_METADATA.setClientVersion(CLIENT_VERSION);
REQUEST_METADATA.setLocale(LOCALE);
@@ -123,24 +132,27 @@ private static boolean setup()
catch (MalformedURLException e)
{
- System.err.format("Cannot initialize wsdl urls%n");
- System.err.format("Exiting %s with value \"%s\"%n", METHOD_NAME, returnValue);
+ logMessage("Cannot initialize web service URLs");
+ logMessage("Exiting %s with value \"%s\"", METHOD_NAME, returnValue);
return returnValue;
}
-
+
// Initialize the BWS web service stubs that will be used for all calls.
+ logMessage("Initializing BWS web service stub");
QName serviceBWS = new QName("http://ws.rim.com/enterprise/admin", "BWSService");
QName portBWS = new QName("http://ws.rim.com/enterprise/admin", "BWS");
_bwsService = new BWSService(null, serviceBWS);
_bwsService.addPort(portBWS, "http://schemas.xmlsoap.org/soap/", bwsServiceUrl.toString());
_bws = _bwsService.getPort(portBWS,BWS.class);
-
+ logMessage("BWS web service stub initialized");
+
+ logMessage("Initializing BWSUtil web service stub");
QName serviceUtil = new QName("http://ws.rim.com/enterprise/admin", "BWSUtilService");
QName portUtil = new QName("http://ws.rim.com/enterprise/admin", "BWSUtil");
_bwsUtilService = new BWSUtilService(null, serviceUtil);
_bwsUtilService.addPort(portUtil, "http://schemas.xmlsoap.org/soap/", bwsUtilServiceUrl.toString());
_bwsUtil = _bwsUtilService.getPort(portUtil, BWSUtil.class);
-
+ logMessage("BWSUtil web service stub initialized");
// Set the connection timeout to 60 seconds.
HTTPClientPolicy httpClientPolicy = new HTTPClientPolicy();
httpClientPolicy.setConnectionTimeout(60000);
@@ -175,15 +187,15 @@ private static boolean setup()
}
else
{
- System.err.format("'encodedUsername' is null or empty%n");
+ logMessage("'encodedUsername' is null or empty");
}
}
else
{
- System.err.format("'authenticator' is null%n");
+ logMessage("'authenticator' is null");
}
- System.err.format("Exiting %s with value \"%s\"%n", METHOD_NAME, returnValue);
+ logMessage("Exiting %s with value \"%s\"", METHOD_NAME, returnValue);
return returnValue;
}
@@ -201,16 +213,26 @@ public static Authenticator getAuthenticator(String authenticatorName)
{
final String METHOD_NAME = "getAuthenticator()";
final String BWS_API_NAME = "_bwsUtil.getAuthenticators()";
- System.err.format("Entering %s%n", METHOD_NAME);
+ logMessage("Entering %s", METHOD_NAME);
Authenticator returnValue = null;
GetAuthenticatorsRequest request = new GetAuthenticatorsRequest();
request.setMetadata(REQUEST_METADATA);
- System.err.format("Calling %s...%n", BWS_API_NAME);
- GetAuthenticatorsResponse response = _bwsUtil.getAuthenticators(request);
- System.err.format("...%s returned \"%s\"%n", BWS_API_NAME, response.getReturnStatus().getCode());
-
+ GetAuthenticatorsResponse response=null;
+ try
+ {
+ logRequest(BWS_API_NAME);
+ response = _bwsUtil.getAuthenticators(request);
+ logResponse(BWS_API_NAME, response.getReturnStatus().getCode(), response.getMetadata());
+ }
+ catch (WebServiceException e)
+ {
+ // Log and re-throw exception.
+ logMessage("Exiting %s with exception \"%s\"", METHOD_NAME, e.getMessage());
+ throw e;
+ }
+
if (response.getReturnStatus().getCode().equals("SUCCESS"))
{
if (response.getAuthenticators() != null && !response.getAuthenticators().isEmpty())
@@ -226,21 +248,20 @@ public static Authenticator getAuthenticator(String authenticatorName)
if (returnValue == null)
{
- System.err.format("Could not find \"%s\" in GetAuthenticatorsResponse%n", authenticatorName);
+ logMessage("Could not find \"%s\" in GetAuthenticatorsResponse", authenticatorName);
}
}
else
{
- System.err.format("No authenticators in GetAuthenticatorsResponse%n");
+ logMessage("No authenticators in GetAuthenticatorsResponse");
}
}
else
{
- System.err.format( "Error: Code: \"%s\", Message: \"%s\"%n", response.getReturnStatus().getCode(),
- response.getReturnStatus().getMessage());
+ logMessage( "Error Message: \"%s\"", response.getReturnStatus().getMessage());
}
- System.err.format("Exiting %s with %s%n", METHOD_NAME, returnValue == null ? "\"null\""
+ logMessage("Exiting %s with %s", METHOD_NAME, returnValue == null ? "\"null\""
: "Authenticator object (Name \"" + returnValue.getName() + "\")");
return returnValue;
}
@@ -261,7 +282,7 @@ public static String getEncodedUserName(String username, Authenticator authentic
{
final String METHOD_NAME = "getEncodedUserName()";
final String BWS_API_NAME = "_bwsUtil.getEncodedUsername()";
- System.err.format("Entering %s%n", METHOD_NAME);
+ logMessage("Entering %s", METHOD_NAME);
String returnValue = null;
GetEncodedUsernameRequest request = new GetEncodedUsernameRequest();
@@ -275,21 +296,30 @@ public static String getEncodedUserName(String username, Authenticator authentic
credentialType.setValue("PASSWORD");
request.setCredentialType(credentialType);
- System.err.format("Calling %s...%n", BWS_API_NAME);
- GetEncodedUsernameResponse response = _bwsUtil.getEncodedUsername(request);
- System.err.format("...%s returned \"%s\"%n", BWS_API_NAME, response.getReturnStatus().getCode());
-
+ GetEncodedUsernameResponse response=null;
+ try
+ {
+ logRequest(BWS_API_NAME);
+ response = _bwsUtil.getEncodedUsername(request);
+ logResponse(BWS_API_NAME, response.getReturnStatus().getCode(), response.getMetadata());
+ }
+ catch (WebServiceException e)
+ {
+ // Log and re-throw exception.
+ logMessage("Exiting %s with exception \"%s\"", METHOD_NAME, e.getMessage());
+ throw e;
+ }
+
if (response.getReturnStatus().getCode().equals("SUCCESS"))
{
returnValue = response.getEncodedUsername();
}
else
{
- System.err.format( "Error: Code: \"%s\", Message: \"%s\"%n", response.getReturnStatus().getCode(),
- response.getReturnStatus().getMessage());
+ logMessage( "Error Message: \"%s\"", response.getReturnStatus().getMessage());
}
- System.err.format("Exiting %s with value \"%s\"%n", METHOD_NAME, returnValue == null ? "null" : returnValue);
+ logMessage("Exiting %s with value \"%s\"", METHOD_NAME, returnValue == null ? "null" : returnValue);
return returnValue;
}
@@ -306,7 +336,7 @@ public static User getUser()
{
final String METHOD_NAME = "getUser()";
final String BWS_API_NAME = "_bws.getUsers()";
- System.err.format("Entering %s%n", METHOD_NAME);
+ logMessage("Entering %s", METHOD_NAME);
User returnValue = null;
GetUsersRequest request = new GetUsersRequest();
@@ -323,7 +353,7 @@ public static User getUser()
*/
if (!DISPLAY_USER_DETAIL_EMAIL.startsWith("\"") || !DISPLAY_USER_DETAIL_EMAIL.endsWith("\""))
{
- System.err.format( "Warning: Email Address \"%s\" is not enclosed in double-quotes%n",
+ logMessage( "Warning: Email Address \"%s\" is not enclosed in double-quotes",
DISPLAY_USER_DETAIL_EMAIL);
}
searchCriteria.setEmailAddress(DISPLAY_USER_DETAIL_EMAIL);
@@ -340,10 +370,20 @@ public static User getUser()
sortBy.setValue("EMAIL_ADDRESS");
request.setSortBy(sortBy);
- System.err.format("Calling %s...%n", BWS_API_NAME);
- GetUsersResponse response = _bws.getUsers(request);
- System.err.format("...%s returned \"%s\"%n", BWS_API_NAME, response.getReturnStatus().getCode());
-
+ GetUsersResponse response=null;
+ try
+ {
+ logRequest(BWS_API_NAME);
+ response = _bws.getUsers(request);
+ logResponse(BWS_API_NAME, response.getReturnStatus().getCode(), response.getMetadata());
+ }
+ catch (WebServiceException e)
+ {
+ // Log and re-throw exception.
+ logMessage("Exiting %s with exception \"%s\"", METHOD_NAME, e.getMessage());
+ throw e;
+ }
+
if (response.getReturnStatus().getCode().equals("SUCCESS"))
{
if (response.getUsers() != null && response.getUsers().size() == 1)
@@ -353,21 +393,20 @@ public static User getUser()
}
else if (response.getUsers() != null && response.getUsers().size() > 1)
{
- System.err.format("More than one user was found with email address \"%s\"%n",
+ logMessage("More than one user was found with email address \"%s\"",
DISPLAY_USER_DETAIL_EMAIL);
}
else
{
- System.err.format("No user was found with email address \"%s\"%n", DISPLAY_USER_DETAIL_EMAIL);
+ logMessage("No user was found with email address \"%s\"", DISPLAY_USER_DETAIL_EMAIL);
}
}
else
{
- System.err.format( "Error: Code: \"%s\", Message: \"%s\"%n", response.getReturnStatus().getCode(),
- response.getReturnStatus().getMessage());
+ logMessage( "Error Message: \"%s\"", response.getReturnStatus().getMessage());
}
- System.err.format("Exiting %s with %s%n", METHOD_NAME, returnValue == null ? "\"null\"" : "User object (UID \""
+ logMessage("Exiting %s with %s", METHOD_NAME, returnValue == null ? "\"null\"" : "User object (UID \""
+ returnValue.getUid() + "\")");
return returnValue;
}
@@ -384,18 +423,18 @@ public static boolean displayUserDetails()
{
final String METHOD_NAME = "displayUserDetails()";
final String BWS_API_NAME = "_bws.getUsersDetail()";
- System.err.format("Entering %s%n", METHOD_NAME);
+ logMessage("Entering %s", METHOD_NAME);
boolean returnValue = false;
- System.err.format("Displaying details for user with email address \"%s\"%n", DISPLAY_USER_DETAIL_EMAIL);
+ logMessage("Displaying details for user with email address \"%s\"", DISPLAY_USER_DETAIL_EMAIL);
// Getting the user object.
User user = getUser();
if (user == null)
{
- System.err.format("'user' is null%n");
- System.err.format("Exiting %s with value \"%s\"%n", METHOD_NAME, returnValue);
+ logMessage("'user' is null");
+ logMessage("Exiting %s with value \"%s\"", METHOD_NAME, returnValue);
return returnValue;
}
@@ -411,10 +450,19 @@ public static boolean displayUserDetails()
request.setLoadITPolicies(true);
request.getUsers().add(user);
- System.err.format("Calling %s...%n", BWS_API_NAME);
- GetUsersDetailResponse response = _bws.getUsersDetail(request);
- System.err.format("...%s returned \"%s\"%n", BWS_API_NAME, response.getReturnStatus().getCode());
-
+ GetUsersDetailResponse response=null;
+ try{
+ logRequest(BWS_API_NAME);
+ response = _bws.getUsersDetail(request);
+ logResponse(BWS_API_NAME, response.getReturnStatus().getCode(), response.getMetadata());
+ }
+ catch (WebServiceException e)
+ {
+ // Log and re-throw exception.
+ logMessage("Exiting %s with exception \"%s\"", METHOD_NAME, e.getMessage());
+ throw e;
+ }
+
if (response.getReturnStatus().getCode().equals("SUCCESS"))
{
if (response.getIndividualResponses() != null && response.getIndividualResponses().size() == 1)
@@ -423,15 +471,14 @@ public static boolean displayUserDetails()
{
UserDetail userDetail = individualResponse.getUserDetail();
- System.out.format("User details:%n");
+ displayResult("User details:");
// The values of the fields, and whether they will be populated or not, depends on the device type.
- System.out.format("Display Name: %s%n", userDetail.getDisplayName());
- System.out.format("User UID: %s%n", individualResponse.getUserUid());
+ displayResult("Display Name: %s", userDetail.getDisplayName());
+ displayResult("User UID: %s", individualResponse.getUserUid());
// Displays time in UTC format.
- System.out.format("Last Login Time: %s%n", userDetail.getLastLoginTime());
+ displayResult("Last Login Time: %s", userDetail.getLastLoginTime());
if (userDetail.getIndirectITPolicies() != null && !userDetail.getIndirectITPolicies().isEmpty())
{
- System.out.format("Indirect IT policy names: ");
StringBuilder policyString = new StringBuilder();
for (IndirectITPolicy indirectITPolicy : userDetail.getIndirectITPolicies())
{
@@ -441,63 +488,63 @@ public static boolean displayUserDetails()
}
policyString.append(indirectITPolicy.getItPolicy().getPolicy().getName());
}
- System.out.format("%s%n", policyString);
+ displayResult("Indirect IT policy names: %s", policyString);
}
if (userDetail.getDirectITPolicy() != null && userDetail.getDirectITPolicy().getPolicy() != null)
{
- System.out.format("Direct IT policy name: %s%n", userDetail.getDirectITPolicy().getPolicy().getName());
+ displayResult("Direct IT policy name: %s", userDetail.getDirectITPolicy().getPolicy().getName());
}
/*
- * The BWS object model supports multiple accounts and devices. However, BES 5.0.3 will only return
- * at most one object in the userDetail.getDevices() list, and at most one object in the
+ * The BWS object model supports multiple accounts and devices. However, BlackBerry Enterprise Server 5.0.3 or
+ * later will only return at most one object in the userDetail.getDevices() list, and at most one object in the
* userDetail.getAccounts() list.
*/
if (userDetail.getDevices() != null && !userDetail.getDevices().isEmpty())
{
- System.out.format("User's device details:%n");
+ displayResult("User's device details:");
int deviceIndex = 1;
for (Device device : userDetail.getDevices())
{
- System.out.format("Device %d data%n", (deviceIndex++));
- System.out.format("---------------%n");
- System.out.format("PIN: %s%n", device.getPin());
- System.out.format("Model: %s%n", device.getModel());
- System.out.format("Phone Number: %s%n", device.getPhoneNumber());
-
+ displayResult("Device %d data", (deviceIndex++));
+ displayResult("---------------");
+ displayResult("PIN: %s", device.getPin());
+ displayResult("Model: %s", device.getModel());
+ displayResult("Phone Number: %s", device.getPhoneNumber());
+
/*The following 3 lines are valid for BlackBerry Enterprise Server 5.0.3 MR5 or later*/
- System.out.format("Active Carrier: %s%n", device.getActiveCarrier());
- System.out.format("Network: %s%n", device.getNetwork());
- System.out.format("Serial Number: %s%n", device.getSerialNumber());
-
- System.out.format("State: %s%n", device.getState().getValue());
- System.out.format("IT Policy Name: %s%n", device.getItPolicyName());
-
+ displayResult("Active Carrier: %s", device.getActiveCarrier());
+ displayResult("Network: %s", device.getNetwork());
+ displayResult("Serial Number: %s", device.getSerialNumber());
+
+ displayResult("State: %s", device.getState().getValue());
+ displayResult("IT Policy Name: %s", device.getItPolicyName());
+
/*The following 6 lines are valid for BlackBerry Enterprise Server 5.0.3 MR5 or later*/
- System.out.format("Platform Version: %s%n", device.getPlatformVersion());
- System.out.format("Total Messages Expired: %s%n", device.getTotalMessagesExpired());
- System.out.format("Total Messages Filtered: %s%n", device.getTotalMessagesFiltered());
- System.out.format("Total Messages Forwarded: %s%n", device.getTotalMessagesForwarded());
- System.out.format("Total Messages Pending: %s%n", device.getTotalMessagesPending());
- System.out.format("Total Messages Sent: %s%n", device.getTotalMessagesSent());
-
- System.out.format("---------------%n");
+ displayResult("Platform Version: %s", device.getPlatformVersion());
+ displayResult("Total Messages Expired: %s", device.getTotalMessagesExpired());
+ displayResult("Total Messages Filtered: %s", device.getTotalMessagesFiltered());
+ displayResult("Total Messages Forwarded: %s", device.getTotalMessagesForwarded());
+ displayResult("Total Messages Pending: %s", device.getTotalMessagesPending());
+ displayResult("Total Messages Sent: %s", device.getTotalMessagesSent());
+
+ displayResult("---------------");
}
}
if (userDetail.getAccounts() != null && !userDetail.getAccounts().isEmpty())
{
- System.out.format("User's account details:%n");
+ displayResult("User's account details:");
int accountIndex = 1;
for (Account account : userDetail.getAccounts())
{
- System.out.format("Account %d data%n", (accountIndex++));
- System.out.format("---------------%n");
- System.out.format("Email Address: %s%n", account.getEmailAddress());
- System.out.format("---------------%n");
+ displayResult("Account %d data", (accountIndex++));
+ displayResult("---------------");
+ displayResult("Email Address: %s", account.getEmailAddress());
+ displayResult("---------------");
}
}
}
@@ -506,30 +553,29 @@ public static boolean displayUserDetails()
}
else if (response.getIndividualResponses() != null && response.getIndividualResponses().size() > 1)
{
- System.err.format("More than one user was found with userUid \"%s\"%n", user.getUid());
+ logMessage("More than one user was found with userUid \"%s\"", user.ge