Skip to content
Browse files

my initial commit message

  • Loading branch information...
0 parents commit 1325a749be7b432a406c1d8532fc4c32ad1395e7 George Grosso committed Apr 2, 2012
Showing with 1,739 additions and 0 deletions.
  1. +201 −0 LICENSE.txt
  2. +27 −0 README.md
  3. +717 −0 SampleBwsClient.cs
  4. +794 −0 SampleBwsClient.java
201 LICENSE.txt
@@ -0,0 +1,201 @@
+ Apache License
+ Version 2.0, January 2004
+ http://www.apache.org/licenses/
+
+ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
+
+ 1. Definitions.
+
+ "License" shall mean the terms and conditions for use, reproduction,
+ and distribution as defined by Sections 1 through 9 of this document.
+
+ "Licensor" shall mean the copyright owner or entity authorized by
+ the copyright owner that is granting the License.
+
+ "Legal Entity" shall mean the union of the acting entity and all
+ other entities that control, are controlled by, or are under common
+ control with that entity. For the purposes of this definition,
+ "control" means (i) the power, direct or indirect, to cause the
+ direction or management of such entity, whether by contract or
+ otherwise, or (ii) ownership of fifty percent (50%) or more of the
+ outstanding shares, or (iii) beneficial ownership of such entity.
+
+ "You" (or "Your") shall mean an individual or Legal Entity
+ exercising permissions granted by this License.
+
+ "Source" form shall mean the preferred form for making modifications,
+ including but not limited to software source code, documentation
+ source, and configuration files.
+
+ "Object" form shall mean any form resulting from mechanical
+ transformation or translation of a Source form, including but
+ not limited to compiled object code, generated documentation,
+ and conversions to other media types.
+
+ "Work" shall mean the work of authorship, whether in Source or
+ Object form, made available under the License, as indicated by a
+ copyright notice that is included in or attached to the work
+ (an example is provided in the Appendix below).
+
+ "Derivative Works" shall mean any work, whether in Source or Object
+ form, that is based on (or derived from) the Work and for which the
+ editorial revisions, annotations, elaborations, or other modifications
+ represent, as a whole, an original work of authorship. For the purposes
+ of this License, Derivative Works shall not include works that remain
+ separable from, or merely link (or bind by name) to the interfaces of,
+ the Work and Derivative Works thereof.
+
+ "Contribution" shall mean any work of authorship, including
+ the original version of the Work and any modifications or additions
+ to that Work or Derivative Works thereof, that is intentionally
+ submitted to Licensor for inclusion in the Work by the copyright owner
+ or by an individual or Legal Entity authorized to submit on behalf of
+ the copyright owner. For the purposes of this definition, "submitted"
+ means any form of electronic, verbal, or written communication sent
+ to the Licensor or its representatives, including but not limited to
+ communication on electronic mailing lists, source code control systems,
+ and issue tracking systems that are managed by, or on behalf of, the
+ Licensor for the purpose of discussing and improving the Work, but
+ excluding communication that is conspicuously marked or otherwise
+ designated in writing by the copyright owner as "Not a Contribution."
+
+ "Contributor" shall mean Licensor and any individual or Legal Entity
+ on behalf of whom a Contribution has been received by Licensor and
+ subsequently incorporated within the Work.
+
+ 2. Grant of Copyright License. Subject to the terms and conditions of
+ this License, each Contributor hereby grants to You a perpetual,
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
+ copyright license to reproduce, prepare Derivative Works of,
+ publicly display, publicly perform, sublicense, and distribute the
+ Work and such Derivative Works in Source or Object form.
+
+ 3. Grant of Patent License. Subject to the terms and conditions of
+ this License, each Contributor hereby grants to You a perpetual,
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
+ (except as stated in this section) patent license to make, have made,
+ use, offer to sell, sell, import, and otherwise transfer the Work,
+ where such license applies only to those patent claims licensable
+ by such Contributor that are necessarily infringed by their
+ Contribution(s) alone or by combination of their Contribution(s)
+ with the Work to which such Contribution(s) was submitted. If You
+ institute patent litigation against any entity (including a
+ cross-claim or counterclaim in a lawsuit) alleging that the Work
+ or a Contribution incorporated within the Work constitutes direct
+ or contributory patent infringement, then any patent licenses
+ granted to You under this License for that Work shall terminate
+ as of the date such litigation is filed.
+
+ 4. Redistribution. You may reproduce and distribute copies of the
+ Work or Derivative Works thereof in any medium, with or without
+ modifications, and in Source or Object form, provided that You
+ meet the following conditions:
+
+ (a) You must give any other recipients of the Work or
+ Derivative Works a copy of this License; and
+
+ (b) You must cause any modified files to carry prominent notices
+ stating that You changed the files; and
+
+ (c) You must retain, in the Source form of any Derivative Works
+ that You distribute, all copyright, patent, trademark, and
+ attribution notices from the Source form of the Work,
+ excluding those notices that do not pertain to any part of
+ the Derivative Works; and
+
+ (d) If the Work includes a "NOTICE" text file as part of its
+ distribution, then any Derivative Works that You distribute must
+ include a readable copy of the attribution notices contained
+ within such NOTICE file, excluding those notices that do not
+ pertain to any part of the Derivative Works, in at least one
+ of the following places: within a NOTICE text file distributed
+ as part of the Derivative Works; within the Source form or
+ documentation, if provided along with the Derivative Works; or,
+ within a display generated by the Derivative Works, if and
+ wherever such third-party notices normally appear. The contents
+ of the NOTICE file are for informational purposes only and
+ do not modify the License. You may add Your own attribution
+ notices within Derivative Works that You distribute, alongside
+ or as an addendum to the NOTICE text from the Work, provided
+ that such additional attribution notices cannot be construed
+ as modifying the License.
+
+ You may add Your own copyright statement to Your modifications and
+ may provide additional or different license terms and conditions
+ for use, reproduction, or distribution of Your modifications, or
+ for any such Derivative Works as a whole, provided Your use,
+ reproduction, and distribution of the Work otherwise complies with
+ the conditions stated in this License.
+
+ 5. Submission of Contributions. Unless You explicitly state otherwise,
+ any Contribution intentionally submitted for inclusion in the Work
+ by You to the Licensor shall be under the terms and conditions of
+ this License, without any additional terms or conditions.
+ Notwithstanding the above, nothing herein shall supersede or modify
+ the terms of any separate license agreement you may have executed
+ with Licensor regarding such Contributions.
+
+ 6. Trademarks. This License does not grant permission to use the trade
+ names, trademarks, service marks, or product names of the Licensor,
+ except as required for reasonable and customary use in describing the
+ origin of the Work and reproducing the content of the NOTICE file.
+
+ 7. Disclaimer of Warranty. Unless required by applicable law or
+ agreed to in writing, Licensor provides the Work (and each
+ Contributor provides its Contributions) on an "AS IS" BASIS,
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
+ implied, including, without limitation, any warranties or conditions
+ of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
+ PARTICULAR PURPOSE. You are solely responsible for determining the
+ appropriateness of using or redistributing the Work and assume any
+ risks associated with Your exercise of permissions under this License.
+
+ 8. Limitation of Liability. In no event and under no legal theory,
+ whether in tort (including negligence), contract, or otherwise,
+ unless required by applicable law (such as deliberate and grossly
+ negligent acts) or agreed to in writing, shall any Contributor be
+ liable to You for damages, including any direct, indirect, special,
+ incidental, or consequential damages of any character arising as a
+ result of this License or out of the use or inability to use the
+ Work (including but not limited to damages for loss of goodwill,
+ work stoppage, computer failure or malfunction, or any and all
+ other commercial damages or losses), even if such Contributor
+ has been advised of the possibility of such damages.
+
+ 9. Accepting Warranty or Additional Liability. While redistributing
+ the Work or Derivative Works thereof, You may choose to offer,
+ and charge a fee for, acceptance of support, warranty, indemnity,
+ or other liability obligations and/or rights consistent with this
+ License. However, in accepting such obligations, You may act only
+ on Your own behalf and on Your sole responsibility, not on behalf
+ of any other Contributor, and only if You agree to indemnify,
+ defend, and hold each Contributor harmless for any liability
+ incurred by, or claims asserted against, such Contributor by reason
+ of your accepting any such warranty or additional liability.
+
+ END OF TERMS AND CONDITIONS
+
+ APPENDIX: How to apply the Apache License to your work.
+
+ To apply the Apache License to your work, attach the following
+ boilerplate notice, with the fields enclosed by brackets "[]"
+ replaced with your own identifying information. (Don't include
+ the brackets!) The text should be enclosed in the appropriate
+ comment syntax for the file format. We also recommend that a
+ file or class name and description of purpose be included on the
+ same "printed page" as the copyright notice for easier
+ identification within third-party archives.
+
+ Copyright [yyyy] [name of copyright owner]
+
+ 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.
27 README.md
@@ -0,0 +1,27 @@
+# BWS Code Samples Repository
+
+The _**BWS-CodeSamples**_ repository holds code samples that demonstrate how to use the BlackBerry Web Services for Enterprise Administration API.
+
+All APIs shared in this repository are Open Source under the [Apache 2.0 License](http://www.apache.org/licenses/LICENSE-2.0.html)
+
+**To contribute code to this repository you must be signed up as an [official contributor](http://blackberry.github.com/howToContribute.html).**
+
+
+## Code Organization
+
+Each sample added to the repository is available in both Java and C#.
+
+
+**Repository Committers**
+
+* [George Grosso](https://github.com/ggrosso)
+
+
+## Bug Reporting and Feature Requests
+
+If you find a bug in a sample, or have an enhancement request, simply file an [Issue](http://github.rim.net/ggrosso/BWS-CodeSamples/issues) for the sample and send a message (via github messages) to the sample Author(s) to let them know that you have filed an [Issue](http://github.rim.net/ggrosso/BWS-CodeSamples/issues).
+
+## Disclaimer
+
+THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
+
717 SampleBwsClient.cs
@@ -0,0 +1,717 @@
+ /*
+ * 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;
+ }
+ }
+}
794 SampleBwsClient.java
@@ -0,0 +1,794 @@
+/*
+ * 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.
+ */
+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 javax.xml.ws.BindingProvider;
+import javax.xml.ws.WebServiceException;
+
+import org.apache.cxf.endpoint.Client;
+import org.apache.cxf.frontend.ClientProxy;
+import org.apache.cxf.transport.http.HTTPConduit;
+import org.apache.cxf.transport.http.HTTPException;
+import org.apache.cxf.transports.http.configuration.HTTPClientPolicy;
+
+/*
+ * SampleBwsClient.java
+ *
+ * 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.
+ */
+
+public class SampleBwsClient
+{
+ private static BWSService _bwsService;
+ private static BWS _bws;
+ private static BWSUtilService _bwsUtilService;
+ 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";
+
+ /*
+ * To use a different locale, call getLocales() in the BWSUtilService web service
+ * to see which locales are supported.
+ */
+ private final static String LOCALE = "en_US";
+ private final static String ORG_UID = "0";
+ private final static RequestMetadata REQUEST_METADATA = new RequestMetadata();
+
+ // Authentication type name.
+ 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".
+
+
+ /*
+ * 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 final static String CREATE_NEW_USER_EMAIL = "\"user01@example.net\"";
+
+ // 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\"";
+
+ /*******************************************************************************************************************
+ *
+ * Initialize the BWS and BWSUtil services.
+ *
+ * @return Returns true when the setup is successful, and false otherwise.
+ *
+ *******************************************************************************************************************
+ */
+ private static boolean setup()
+ {
+ final String METHOD_NAME = "setup()";
+ System.err.format("Entering %s%n", METHOD_NAME);
+ boolean returnValue = false;
+ REQUEST_METADATA.setClientVersion(CLIENT_VERSION);
+ REQUEST_METADATA.setLocale(LOCALE);
+ REQUEST_METADATA.setOrganizationUid(ORG_UID);
+
+ URL bwsServiceUrl = null;
+ URL bwsUtilServiceUrl = null;
+
+ try
+ {
+ // These are the URLs that point to the web services used for all calls.
+ bwsServiceUrl = new URL("https://" + BWS_HOST_NAME + "/enterprise/admin/ws");
+ bwsUtilServiceUrl = new URL("https://" + BWS_HOST_NAME + "/enterprise/admin/util/ws");
+ }
+ catch (MalformedURLException e)
+ {
+
+ System.err.format("Cannot initialize wsdl urls%n");
+ System.err.format("Exiting %s with value \"%s\"%n", METHOD_NAME, returnValue);
+ return returnValue;
+ }
+
+ // Initialize the BWS web service stubs that will be used for all calls.
+ 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);
+
+ 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);
+
+ // Set the connection timeout to 60 seconds.
+ HTTPClientPolicy httpClientPolicy = new HTTPClientPolicy();
+ httpClientPolicy.setConnectionTimeout(60000);
+
+ httpClientPolicy.setAllowChunking(false);
+ httpClientPolicy.setReceiveTimeout(60000);
+
+ Client client = ClientProxy.getClient(_bws);
+ HTTPConduit http = (HTTPConduit) client.getConduit();
+ http.setClient(httpClientPolicy);
+
+ client = ClientProxy.getClient(_bwsUtil);
+ http = (HTTPConduit) client.getConduit();
+ http.setClient(httpClientPolicy);
+
+ Authenticator authenticator = getAuthenticator(AUTHENTICATOR_NAME);
+ if (authenticator != null)
+ {
+ String encodedUsername = getEncodedUserName(USERNAME, authenticator);
+ if (encodedUsername != null && !encodedUsername.isEmpty())
+ {
+ /*
+ * Set the HTTP basic authentication on the BWS service.
+ * BWSUtilService is a utility web service that does not require
+ * authentication.
+ */
+ BindingProvider bp = (BindingProvider) _bws;
+ bp.getRequestContext().put(BindingProvider.USERNAME_PROPERTY, encodedUsername);
+ bp.getRequestContext().put(BindingProvider.PASSWORD_PROPERTY, PASSWORD);
+
+ returnValue = true;
+ }
+ else
+ {
+ System.err.format("'encodedUsername' is null or empty%n");
+ }
+ }
+ else
+ {
+ System.err.format("'authenticator' is null%n");
+ }
+
+ System.err.format("Exiting %s with value \"%s\"%n", METHOD_NAME, returnValue);
+ return returnValue;
+ }
+
+ /*******************************************************************************************************************
+ *
+ * Get the authenticator object for the authenticator name.
+ *
+ * @param authenticatorName
+ * A string containing the name of the desired authenticator.
+ * @return Returns the requested authenticator if it is found, null otherwise.
+ *
+ *******************************************************************************************************************
+ */
+ 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);
+ 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());
+
+ if (response.getReturnStatus().getCode().equals("SUCCESS"))
+ {
+ if (response.getAuthenticators() != null && !response.getAuthenticators().isEmpty())
+ {
+ for (Authenticator authenticator : response.getAuthenticators())
+ {
+ if (authenticator.getName().equalsIgnoreCase(authenticatorName))
+ {
+ returnValue = authenticator;
+ break;
+ }
+ }
+
+ if (returnValue == null)
+ {
+ System.err.format("Could not find \"%s\" in GetAuthenticatorsResponse%n", authenticatorName);
+ }
+ }
+ else
+ {
+ System.err.format("No authenticators in GetAuthenticatorsResponse%n");
+ }
+ }
+ else
+ {
+ System.err.format( "Error: Code: \"%s\", Message: \"%s\"%n", response.getReturnStatus().getCode(),
+ response.getReturnStatus().getMessage());
+ }
+
+ System.err.format("Exiting %s with %s%n", METHOD_NAME, returnValue == null ? "\"null\""
+ : "Authenticator object (Name \"" + returnValue.getName() + "\")");
+ return returnValue;
+ }
+
+ /*******************************************************************************************************************
+ *
+ * Get the encoded username required to authenticate user to BWS.
+ *
+ * @param username
+ * A string containing the username to encode.
+ * @param authenticator
+ * The authenticator.
+ * @return Returns a string containing the encoded username if successful, and a null message string otherwise.
+ *
+ *******************************************************************************************************************
+ */
+ public static String getEncodedUserName(String username, Authenticator authenticator)
+ {
+ final String METHOD_NAME = "getEncodedUserName()";
+ final String BWS_API_NAME = "_bwsUtil.getEncodedUsername()";
+ System.err.format("Entering %s%n", METHOD_NAME);
+ String returnValue = null;
+
+ GetEncodedUsernameRequest request = new GetEncodedUsernameRequest();
+ request.setMetadata(REQUEST_METADATA);
+ request.setUsername(username);
+ request.setOrgUid(REQUEST_METADATA.getOrganizationUid());
+ request.setAuthenticator(authenticator);
+
+ CredentialType credentialType = new CredentialType();
+ credentialType.setPASSWORD(true);
+ 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());
+
+ 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());
+ }
+
+ System.err.format("Exiting %s with value \"%s\"%n", METHOD_NAME, returnValue == null ? "null" : returnValue);
+ return returnValue;
+ }
+
+ /*******************************************************************************************************************
+ *
+ * Retrieves a single user using an email address. If more or less than one result is found, that is treated as an
+ * error.
+ *
+ * @return Returns a User object if user is found, and null otherwise.
+ *
+ *******************************************************************************************************************
+ */
+ public static User getUser()
+ {
+ final String METHOD_NAME = "getUser()";
+ final String BWS_API_NAME = "_bws.getUsers()";
+ System.err.format("Entering %s%n", METHOD_NAME);
+ User returnValue = null;
+
+ GetUsersRequest request = new GetUsersRequest();
+ request.setMetadata(REQUEST_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 "DISPLAY_USER_DETAIL_EMAIL" is enclosed in double-quotes, and if it's not,
+ * then display a message. If the variable "DISPLAY_USER_DETAIL_EMAIL" is not enclosed in double-quotes, then a
+ * substring match search will be performed.
+ */
+ 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",
+ DISPLAY_USER_DETAIL_EMAIL);
+ }
+ searchCriteria.setEmailAddress(DISPLAY_USER_DETAIL_EMAIL);
+ request.setSearchCriteria(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.setPageSize(2);
+
+ GetUsersSortBy sortBy = new GetUsersSortBy();
+ sortBy.setEMAILADDRESS(true);
+ 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());
+
+ if (response.getReturnStatus().getCode().equals("SUCCESS"))
+ {
+ if (response.getUsers() != null && response.getUsers().size() == 1)
+ {
+ // Returns the first user object in the users list.
+ returnValue = response.getUsers().get(0);
+ }
+ else if (response.getUsers() != null && response.getUsers().size() > 1)
+ {
+ System.err.format("More than one user was found with email address \"%s\"%n",
+ DISPLAY_USER_DETAIL_EMAIL);
+ }
+ else
+ {
+ System.err.format("No user was found with email address \"%s\"%n", DISPLAY_USER_DETAIL_EMAIL);
+ }
+ }
+ else
+ {
+ System.err.format( "Error: Code: \"%s\", Message: \"%s\"%n", response.getReturnStatus().getCode(),
+ response.getReturnStatus().getMessage());
+ }
+
+ System.err.format("Exiting %s with %s%n", METHOD_NAME, returnValue == null ? "\"null\"" : "User object (UID \""
+ + returnValue.getUid() + "\")");
+ return returnValue;
+ }
+
+ /*******************************************************************************************************************
+ *
+ * Retrieve and display some user details.
+ *
+ * @return Returns true if getUsersDetail is successful, and false otherwise.
+ *
+ *******************************************************************************************************************
+ */
+ public static boolean displayUserDetails()
+ {
+ final String METHOD_NAME = "displayUserDetails()";
+ final String BWS_API_NAME = "_bws.getUsersDetail()";
+ System.err.format("Entering %s%n", METHOD_NAME);
+ boolean returnValue = false;
+
+ System.err.format("Displaying details for user with email address \"%s\"%n", 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);
+ return returnValue;
+ }
+
+ GetUsersDetailRequest request = new GetUsersDetailRequest();
+ request.setMetadata(REQUEST_METADATA);
+
+ /*
+ * To help improve API performance, load only the required details.
+ * By default all load flags are set to false.
+ */
+ request.setLoadAccounts(true);
+ request.setLoadDevices(true);
+ 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());
+
+ if (response.getReturnStatus().getCode().equals("SUCCESS"))
+ {
+ if (response.getIndividualResponses() != null && response.getIndividualResponses().size() == 1)
+ {
+ for (GetUsersDetailIndividualResponse individualResponse : response.getIndividualResponses())
+ {
+ UserDetail userDetail = individualResponse.getUserDetail();
+
+ System.out.format("User details:%n");
+ // 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());
+ // Displays time in UTC format.
+ System.out.format("Last Login Time: %s%n", 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())
+ {
+ if (policyString.length() > 0)
+ {
+ policyString.append(", ");
+ }
+ policyString.append(indirectITPolicy.getItPolicy().getPolicy().getName());
+ }
+ System.out.format("%s%n", policyString);
+ }
+
+ if (userDetail.getDirectITPolicy() != null && userDetail.getDirectITPolicy().getPolicy() != null)
+ {
+ System.out.format("Direct IT policy name: %s%n", 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
+ * userDetail.getAccounts() list.
+ */
+ if (userDetail.getDevices() != null && !userDetail.getDevices().isEmpty())
+ {
+ System.out.format("User's device details:%n");
+
+ 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());
+ 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());
+ 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");
+ }
+ }
+
+ if (userDetail.getAccounts() != null && !userDetail.getAccounts().isEmpty())
+ {
+ System.out.format("User's account details:%n");
+
+ 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");
+ }
+ }
+ }
+
+ returnValue = true;
+ }
+ else if (response.getIndividualResponses() != null && response.getIndividualResponses().size() > 1)
+ {
+ System.err.format("More than one user was found with userUid \"%s\"%n", user.getUid());
+ }
+ else
+ {
+ System.err.format("No user was found with userUid \"%s\"%n", user.getUid());
+ }
+ }
+ else
+ {
+ System.err.format( "Error: Code: \"%s\", Message: \"%s\"%n", response.getReturnStatus().getCode(),
+ response.getReturnStatus().getMessage());
+ if (response.getIndividualResponses() != null)
+ {
+ for (GetUsersDetailIndividualResponse individualResponse : response.getIndividualResponses())
+ {
+ System.err.format("User UID: \"%s\"%n", individualResponse.getUserUid());
+ System.err.format( "Individual Response - Code: \"%s\", Message: \"%s\"%n",
+ individualResponse.getReturnStatus().getCode(),
+ individualResponse.getReturnStatus().getMessage());
+ }
+ }
+ }
+
+ System.err.format("Exiting %s with value \"%s\"%n", METHOD_NAME, returnValue);
+ return returnValue;
+ }
+
+ /*******************************************************************************************************************
+ *
+ * Creates a user using an email address.
+ *
+ * @return Returns true if createUsers is successful, and false otherwise.
+ *
+ *******************************************************************************************************************
+ */
+ public static boolean createUser()
+ {
+ final String METHOD_NAME = "createUser()";
+ final String BWS_API_NAME = "_bws.createUsers()";
+ System.err.format("Entering %s%n", METHOD_NAME);
+ boolean returnValue = false;
+
+ // Create the request object.
+ CreateUsersRequest createUsersRequest = new CreateUsersRequest();
+ createUsersRequest.setMetadata(REQUEST_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 "CREATE_NEW_USER_EMAIL" is enclosed in double-quotes, otherwise the string
+ * would infer a substring match search.
+ */
+ if (!CREATE_NEW_USER_EMAIL.startsWith("\"") || !CREATE_NEW_USER_EMAIL.endsWith("\""))
+ {
+ System.err.format("Warning: Email Address \"%s\" is not enclosed in double-quotes%n",
+ CREATE_NEW_USER_EMAIL);
+ }
+ // Value of the variable "CREATE_NEW_USER_EMAIL" is used to create a BlackBerry-enabled user.
+ System.err.format("Creating a user with email address \"%s\"%n", CREATE_NEW_USER_EMAIL);
+ accountAttributes.setEmailAddress(CREATE_NEW_USER_EMAIL);
+
+ newUser.setAccountAttributes(accountAttributes);
+ // Randomly select a BlackBerry Enterprise Server on which to create the user.
+ newUser.setServer(null);
+
+ createUsersRequest.getNewUsers().add(newUser);
+
+ System.err.format("Calling %s...%n", BWS_API_NAME);
+ CreateUsersResponse response = _bws.createUsers(createUsersRequest);
+ System.err.format("...%s returned \"%s\"%n", BWS_API_NAME, response.getReturnStatus().getCode());
+
+ if (response.getReturnStatus().getCode().equals("SUCCESS"))
+ {
+ if (response.getIndividualResponses() != null)
+ {
+ for (IndividualResponse individualResponse : response.getIndividualResponses())
+ {
+ System.out.format( "User created with UID \"%s\" using Email Address \"%s\"%n",
+ individualResponse.getUid(), CREATE_NEW_USER_EMAIL);
+ }
+
+ returnValue = true;
+ }
+ }
+ else
+ {
+ System.err.format( "Error: Code: \"%s\", Message: \"%s\"%n", response.getReturnStatus().getCode(),
+ response.getReturnStatus().getMessage());
+ if (response.getIndividualResponses() != null)
+ {
+ for (IndividualResponse individualResponse : response.getIndividualResponses())
+ {
+ System.err.format( "Individual Response - Code: \"%s\", Message: \"%s\"%n",
+ individualResponse.getReturnStatus().getCode(),
+ individualResponse.getReturnStatus().getMessage());
+ }
+ }
+ }
+
+ System.err.format("Exiting %s with value \"%s\"%n", METHOD_NAME, returnValue);
+ return returnValue;
+ }
+
+ /*******************************************************************************************************************
+ *
+ * Call _bwsService.getSystemInfo() and display the returned properties.
+ *
+ * @return Returns true if getSystemInfo is successful, and false otherwise.
+ *
+ *******************************************************************************************************************
+ */
+ public static boolean getSystemInfo()
+ {
+ final String METHOD_NAME = "getSystemInfo()";
+ final String BWS_API_NAME = "_bws.getSystemInfo()";
+ System.err.format("Entering %s%n", METHOD_NAME);
+ boolean 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.setLoadAuthenticatedUserProperties(true);
+ request.setMetadata(REQUEST_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
+ {
+ System.err.format(String.format("Calling %s...%n", BWS_API_NAME));
+ response = _bws.getSystemInfo(request);
+ System.err.format(String.format("...%s returned \"%s\"%n", BWS_API_NAME, response.getReturnStatus()
+ .getCode()));
+ }
+ catch (WebServiceException e)
+ {
+ if (e.getCause() instanceof HTTPException)
+ {
+ HTTPException httpException = (HTTPException) e.getCause();
+ // Handle authentication failure.
+ if (httpException != null && httpException.getResponseCode() == HttpURLConnection.HTTP_UNAUTHORIZED)
+ {
+ System.err.format("Failed to authenticate with the BWS web service%n");
+ System.err.format("Exiting %s with value \"%s\"%n", METHOD_NAME, returnValue);
+ return returnValue;
+ }
+ }
+ else
+ {
+ // Re-throw other exceptions.
+ throw e;
+ }
+ }
+
+ if (response.getMetadata() != null)
+ {
+ /*
+ * Converting response.getMetadata().getExecutionTime() (which is in nano-seconds) into seconds by
+ * multiplying it by 10^-9.
+ */
+ System.err.format( "%s Execution Time: %.4f seconds%n", BWS_API_NAME,
+ (response.getMetadata().getExecutionTime() * Math.pow(10, -9)));
+ System.err.format("%s Request UID: %s%n", BWS_API_NAME, response.getMetadata().getRequestUid());
+ }
+
+ if (response.getReturnStatus().getCode().equals("SUCCESS"))
+ {
+ if (response.getProperties() != null && !response.getProperties().isEmpty())
+ {
+ System.err.format("%s returned the following properties:%n", BWS_API_NAME);
+ for (Property property : response.getProperties())
+ {
+ System.out.format("%s: %s%n", property.getName(), property.getValue());
+ }
+
+ returnValue = true;
+ }
+ else
+ {
+ System.err.format("No properties in response%n");
+ }
+ }
+ else
+ {
+ System.err.format( "Error: Code: \"%s\", Message: \"%s\"%n", response.getReturnStatus().getCode(),
+ response.getReturnStatus().getMessage());
+ }
+
+ System.err.format("Exiting %s with value \"%s\"%n", METHOD_NAME, returnValue);
+ return returnValue;
+ }
+
+ /*******************************************************************************************************************
+ *
+ * The main method.
+ *
+ * @param args
+ * not used.
+ * @throws IOException
+ * if it fails to create log files.
+ *
+ *******************************************************************************************************************
+ */
+ public static void main(String[] args) throws IOException
+ {
+ // Return codes
+ final int SUCCESS = 0;
+ final int FAILURE = 1;
+ int returnCode = SUCCESS;
+
+ /*
+ * Flags that are used to determine whether or not
+ * createUser() and displayUserDetails() gets called.
+ */
+ boolean createNewUser = false;
+ boolean displayUserDetails = true;
+
+ // Write standard output / error streams to text files.
+ System.setErr(System.out);
+
+ /*
+ * 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 Java Developers Getting Started Guide.
+ */
+ try
+ {
+ System.err.format("Initializing web services...%n");
+ if (setup())
+ {
+ /*
+ * Demonstrate call to _bws.getSystemInfo() API.
+ * This is also the first authenticated call in the client application.
+ */
+ System.err.format("Getting system information...%n");
+ if (getSystemInfo())
+ {
+ if (createNewUser)
+ {
+ // Demonstrate call to _bws.createUsers() API.
+ System.err.format("Creating a user...%n");
+ if (!createUser())
+ {
+ System.err.format("Error: createUser() failed%n");
+ returnCode = FAILURE;
+ }
+ }
+
+ if (displayUserDetails)
+ {
+ // Demonstrate call to _bws.getUsers() and _bws.getUsersDetail() APIs.
+ System.err.format("Displaying a user's details...%n");
+ if (!displayUserDetails())
+ {
+ System.err.format("Error: displayUserDetails() failed%n");
+ returnCode = FAILURE;
+ }
+ }
+ }
+ else
+ {
+ System.err.format("Error: getSystemInfo() failed%n");
+ returnCode = FAILURE;
+ }
+ }
+ else
+ {
+ System.err.format("Error: setup() failed%n");
+ returnCode = FAILURE;
+ }
+ }
+ catch (Exception e)
+ {
+ System.err.format(String.format("Exception: \"%s\"%n", e.getMessage()));
+ returnCode = FAILURE;
+ }
+
+ System.err.format("Press Enter to exit%n");
+ System.in.read();
+
+ System.exit(returnCode);
+ }
+}

0 comments on commit 1325a74

Please sign in to comment.
Something went wrong with that request. Please try again.