Java tutorial
/* Copyright (C) 2012 cloudbase.io This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License, version 2, as published by the Free Software Foundation. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program; see the file COPYING. If not, write to the Free Software Foundation, 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. */ package com.cloudbase; import java.util.Enumeration; import java.util.Vector; import java.util.Hashtable; import org.json.me.JSONArray; import org.json.me.JSONException; import org.json.me.JSONObject; import com.cloudbase.datacommands.CBDataAggregationCommand; import com.cloudbase.datacommands.CBSearchCondition; import net.rim.device.api.gps.BlackBerryLocation; import net.rim.device.api.i18n.Locale; import net.rim.device.api.system.DeviceInfo; import net.rim.device.api.ui.UiApplication; /*! \mainpage cloudbase.io BlackBerry JDK Helper Class Reference * * \section intro_sec Introduction * * This program is free software; you can redistribute it and/or modify it under * the terms of the GNU General Public License, version 2, as published by * the Free Software Foundation.<br/><br/> * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY * or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License * for more details.<br/><br/> * You should have received a copy of the GNU General Public License * along with this program; see the file COPYING. If not, write to the Free * Software Foundation, 59 Temple Place - Suite 330, Boston, MA * 02111-1307, USA.<br/><br/> * * \section install_sec Getting Started * * The cloudbase.io helper class BlackBerry JDK compiles to .jar library. It can also be included as a "project" inside * another project<br/><br/> * Make sure the library is included in your project:<br/> * 1. Right click on the project once you have imported it in the workspace and click properties<br/> * 2. Next in the "Java Build Path" section you can either add it as a library: * a. select the "Libraries" tab. There press "Add Jar", the first button on the right and select the jar generated by the CBHelper project in your workspace.<br/> * b. In the Projects tab as the CBHelper project should be available in your workspace * This full reference is a companion to <a href="/documentation/blackberry-java/get-started" target="_blank"> * the tutorial on the cloudbase.io website<a/> */ /** * The main CBHelper class. All of the methods interacting with the cloudbase.io APIs are part of this class. * <br/> * This class requires the <strong>appCode</strong>, <strong>appSecret</strong> and <strong>password</strong> * properties set. appCode and appSecret are handed to the class in the constructor and the password can be * set using the <strong>setPassword</strong> setter. * <br/> * This library depends on the Gson library by google. This is used to serialise and de-serialise objects to be * sent to the APIs. This library was built on top of the Gson 2.2.1. Make sure the jar file is available in your * classpath * @author Stefano Buliani */ public class CBHelper implements CBHelperResponder { // application settings to connect to cloudbase.io private String appCode; private String appSecret; private String password; // whether to use the https apis. This should be set to "true" by default. private boolean https; // whether the APIs require user authentication. and the current application // username and password private boolean userAuthentication; private String authUsername; private String authPassword; // The current location variable to be attached to requests to the CloudBase apis private boolean useLocation; private BlackBerryLocation currentLocation; // Device information used for the analytics private String deviceUniqueIdentifier; private String deviceName; private String deviceModel; private String language; private String country; private String sessionId; private UiApplication applicationRefernce; // this is used when downloading attachments from the CloudBase - temporary files // are saved in the application files folder and handed back to the application private String temporaryFilesPath; private String apiURL = "api.cloudbase.io"; private static final String defaultLogCategory = "DEFAULT"; private boolean deviceRegistered; /** * Creates a new instance of CBHelper and initializes the main properties to their default values. * @param code The application code generated by cloudbase.io when the application is registered (test-application) * @param uniq The unique code generated by cloudbase.io when the application is registered (8a159fe6e4493d4b9a56d4aa580953a2) * @param activity The main activity from the application. This is used to get Context variables, specifically the Cache directory */ public CBHelper(String code, String uniq) { this.appCode = code; this.appSecret = uniq; this.deviceName = DeviceInfo.getDeviceName(); //Build.MANUFACTURER + " - " + Build.PRODUCT; this.deviceModel = DeviceInfo.getSoftwareVersion(); this.deviceUniqueIdentifier = "" + DeviceInfo.getDeviceId(); this.userAuthentication = false; this.https = true; this.language = Locale.getDefaultForSystem().getLanguage(); this.country = Locale.getDefaultForSystem().getCountry(); this.deviceRegistered = false; //this.temporaryFilesPath = activity.getCacheDir().getAbsolutePath(); //Log.d(logTag, "CBHelper initialized"); } /** * Logs an event to the cloudbase.io application log * @param logLine The content of the line to be logged */ public void logEvent(String logLine) { this.log(logLine, CBLogLevel.EVENT, null, null); } /** * Logs an event to the cloudbase.io application log * @param logLine The content of the line to be Logged * @param category The category of the log line. This is a free text string and can be used to separate different * sections of the application and events */ public void logEvent(String logLine, String category) { this.log(logLine, CBLogLevel.EVENT, category, null); } /** * Logs an event to the cloudbase.io application log * @param logLine The content of the line to be Logged * @param category The category of the log line. This is a free text string and can be used to separate different * sections of the application and events * @param responder A responder to handle the return value from the cloudbase.io APIs. This is an optional parameter * and can be sent as null */ public void logEvent(String logLine, String category, CBHelperResponder responder) { this.log(logLine, CBLogLevel.EVENT, category, responder); } /** * Logs a fatal exception to the cloudbase.io application log * @param logLine The content of the line to be logged */ public void logFatal(String logLine) { this.log(logLine, CBLogLevel.FATAL, null, null); } /** * Logs a fatal exception to the cloudbase.io application log * @param logLine The content of the line to be logged * @param category The category of the log line. This is a free text string and can be used to separate different * sections of the application and events */ public void logFatal(String logLine, String category) { this.log(logLine, CBLogLevel.FATAL, category, null); } /** * Logs a fatal exception to the cloudbase.io application log * @param logLine The content of the line to be logged * @param category The category of the log line. This is a free text string and can be used to separate different * sections of the application and events * @param responder A responder to handle the return value from the cloudbase.io APIs. This is an optional parameter * and can be sent as null */ public void logFatal(String logLine, String category, CBHelperResponder responder) { this.log(logLine, CBLogLevel.FATAL, category, responder); } /** * Logs an error to the cloudbase.io application log * @param logLine The content of the line to be logged */ public void logError(String logLine) { this.log(logLine, CBLogLevel.ERROR, null, null); } /** * Logs an error to the cloudbase.io application log * @param logLine The content of the line to be logged * @param category The category of the log line. This is a free text string and can be used to separate different * sections of the application and events */ public void logError(String logLine, String category) { this.log(logLine, CBLogLevel.ERROR, category, null); } /** * Logs an error to the cloudbase.io application log * @param logLine The content of the line to be logged * @param category The category of the log line. This is a free text string and can be used to separate different * sections of the application and events * @param responder A responder to handle the return value from the cloudbase.io APIs. This is an optional parameter * and can be sent as null */ public void logError(String logLine, String category, CBHelperResponder responder) { this.log(logLine, CBLogLevel.ERROR, category, responder); } /** * Logs a warning to the cloudbase.io application log * @param logLine The content of the line to be logged */ public void logWarning(String logLine) { this.log(logLine, CBLogLevel.WARNING, null, null); } /** * Logs a warning to the cloudbase.io application log * @param logLine The content of the line to be logged * @param category The category of the log line. This is a free text string and can be used to separate different * sections of the application and events */ public void logWarning(String logLine, String category) { this.log(logLine, CBLogLevel.WARNING, category, null); } /** * Logs a warning to the cloudbase.io application log * @param logLine The content of the line to be logged * @param category The category of the log line. This is a free text string and can be used to separate different * sections of the application and events * @param responder A responder to handle the return value from the cloudbase.io APIs. This is an optional parameter * and can be sent as null */ public void logWarning(String logLine, String category, CBHelperResponder responder) { this.log(logLine, CBLogLevel.WARNING, category, responder); } /** * Logs an information message to the cloudbase.io application log * @param logLine The content of the line to be logged */ public void logInfo(String logLine) { this.log(logLine, CBLogLevel.INFO, null, null); } /** * Logs an information message to the cloudbase.io application log * @param logLine The content of the line to be logged * @param category The category of the log line. This is a free text string and can be used to separate different * sections of the application and events */ public void logInfo(String logLine, String category) { this.log(logLine, CBLogLevel.INFO, category, null); } /** * Logs an information message to the cloudbase.io application log * @param logLine The content of the line to be logged * @param category The category of the log line. This is a free text string and can be used to separate different * sections of the application and events * @param responder A responder to handle the return value from the cloudbase.io APIs. This is an optional parameter * and can be sent as null */ public void logInfo(String logLine, String category, CBHelperResponder responder) { this.log(logLine, CBLogLevel.INFO, category, responder); } /** * Logs a debug message to the cloudbase.io application log * @param logLine The content of the line to be logged */ public void logDebug(String logLine) { this.log(logLine, CBLogLevel.DEBUG, null, null); } /** * Logs a debug message to the cloudbase.io application log * @param logLine The content of the line to be logged * @param category The category of the log line. This is a free text string and can be used to separate different * sections of the application and events */ public void logDebug(String logLine, String category) { this.log(logLine, CBLogLevel.DEBUG, category, null); } /** * Logs a debug message to the cloudbase.io application log * @param logLine The content of the line to be logged * @param category The category of the log line. This is a free text string and can be used to separate different * sections of the application and events * @param responder A responder to handle the return value from the cloudbase.io APIs. This is an optional parameter * and can be sent as null */ public void logDebug(String logLine, String category, CBHelperResponder responder) { this.log(logLine, CBLogLevel.DEBUG, category, responder); } /** * Send a line to the log on the cloudbase.io application log. * * @param logLine The content of the log line * @param level The severity of the log line, a <strong>CBLogLevel</strong> value * @param category The category of the log line. This is a free text string and can be used to separate different * sections of the application and events */ public void log(String logLine, String level, String category) { this.log(logLine, level, category, null); } /** * Send a line to the log on the cloudbase.io application log. * * @param logLine The content of the log line * @param level The severity of the log line, a <strong>CBLogLevel</strong> value * @param category The category of the log line. This is a free text string and can be used to separate different * sections of the application and events * @param responder A responder to handle the return value from the cloudbase.io APIs. This is an optional parameter * and can be sent as null */ public void log(String logLine, String level, String category, CBHelperResponder responder) { String url = this.getUrl() + this.appCode + "/log"; // Create the log object Hashtable logData = new Hashtable(); logData.put("category", (category == null ? CBHelper.defaultLogCategory : category)); logData.put("level", level.toString()); logData.put("device_name", this.deviceName); logData.put("device_model", this.deviceModel); logData.put("log_line", logLine); Hashtable preparedPost = this.preparePostParams(new JSONObject(logData), null); CBHelperRequest req = new CBHelperRequest(url, "log"); req.setPostData(preparedPost); // set the responder if we have one and run give the CBHttpRequest object a Handler // to be able to return data to the main UI thread if (responder != null) { req.setResponder(responder); } // Start the call in a separate thread this.getApplicationRefernce().invokeLater(req); } /** * Sends cloudbase.io the name of the newly opened screen. This data is used to then generate the usage * flow analytics and show how people interact with your application * @param screenName The unique name assigned to the opened view */ public void logNavigation(String screenName) { String url = this.getUrl() + this.appCode + "/lognavigation"; Hashtable logData = new Hashtable(); logData.put("session_id", this.sessionId); logData.put("screen_name", screenName); Hashtable preparedPost = this.preparePostParams(new JSONObject(logData), null); CBHelperRequest req = new CBHelperRequest(url, "log"); req.setPostData(preparedPost); this.getApplicationRefernce().invokeLater(req); } /** * Inserts the given object in a cloudbase.io collection. If the collection does not exist it is automatically created. * Similarly if the data structure of the given object is different from documents already present in the collection * the structure is automatically altered to accommodate the new object. * The system will automatically try to serialize any object sent to this function. However, we recommend you use * the simplest possible objects to hold data if not a Map or Array directly. * Once the call to the APIs is completed the responder is called. * @param document The object to be inserted * @param collection The name of the collection the document should be inserted into * @throws JSONException */ public void insertDocument(CBHelperSerializable document, String collection) throws JSONException { insertDocument(document, collection, null, null); } /** * Inserts the given object in a cloudbase.io collection. If the collection does not exist it is automatically created. * Similarly if the data structure of the given object is different from documents already present in the collection * the structure is automatically altered to accommodate the new object. * The system will automatically try to serialize any object sent to this function. However, we recommend you use * the simplest possible objects to hold data if not a Map or Array directly. * Once the call to the APIs is completed the responder is called. * @param document The object to be inserted * @param collection The name of the collection the document should be inserted into * @param responder The CBHelperResponder object to handle the response from the cloudbase.io APIs * @throws JSONException */ public void insertDocument(CBHelperSerializable document, String collection, CBHelperResponder responder) throws JSONException { insertDocument(document, collection, null, responder); } /** * Inserts the given object in a cloudbase.io collection. If the collection does not exist it is automatically created. * Similarly if the data structure of the given object is different from documents already present in the collection * the structure is automatically altered to accommodate the new object. * The system will automatically try to serialize any object sent to this function. However, we recommend you use * the simplest possible objects to hold data if not a Map or Array directly. * Once the call to the APIs is completed the responder is called. * @param document The object to be inserted * @param collection The name of the collection the document should be inserted into * @param attachments A Vector of CBHelperAttachment objects to include in the document. File IDs will be stored in the additional column * <strong>cb_files</strong> * @param responder The CBHelperResponder object to handle the response from the cloudbase.io APIs * @throws JSONException */ public void insertDocument(CBHelperSerializable document, String collection, Vector attachments, CBHelperResponder responder) throws JSONException { // We need to insert a List as the cloudbase.io APIs expect an array of objects to the // insert APIs - this way we can insert multiple objects at the same time. If it is not a List // then create a new List and insert the given object in it. JSONObject newDoc = document.toJSONObject(); JSONArray documentList = new JSONArray(); documentList.put(newDoc); String url = this.getUrl() + this.appCode + "/" + collection + "/insert"; Hashtable preparedPost = this.preparePostParams(documentList, null); CBHelperRequest req = new CBHelperRequest(url, "data"); req.setPostData(preparedPost); // set the responder if we have one and run give the CBHttpRequest object a Handler // to be able to return data to the main UI thread if (responder != null) { req.setResponder(responder); } // if we have File attachments then add them to the request if (attachments != null) req.setFiles(attachments); this.getApplicationRefernce().invokeLater(req); } /** * Returns all of the documents in the given collection * @param collection The name of the collection to run the search over * @param responder The CBHelperResponder object to manage the data returned from the cloudbase.io APIs */ public void searchDocument(String collection, CBHelperResponder responder) { this.searchDocument(collection, null, responder); } /** * Runs a search over a collection with the given criteria. The documents matching the search criteria are then * returned to the given responder object * @param collection The name of the collection to run the search over * @param cond A CBSearchCondition object containing the criteria for this search. This object can be null, in which case * all of the documents in the collection will be returned * @param responder The CBHelperResponder object to manage the data returned from the cloudbase.io APIs */ public void searchDocument(String collection, CBSearchCondition cond, CBHelperResponder responder) { // if we have no conditions for the request then send an empty Map - the cloudbase.io APIs // will then return all of the objects in the collection JSONObject finalConditions = new JSONObject(); try { finalConditions.put("cb_search_key", cond.toJSONObject()); } catch (Exception e) { e.printStackTrace(); } String url = this.getUrl() + this.appCode + "/" + collection + "/search"; Hashtable preparedPost = this.preparePostParams(finalConditions, null); CBHelperRequest req = new CBHelperRequest(url, "data"); req.setPostData(preparedPost); req.setResponder(responder); this.getApplicationRefernce().invokeLater(req); } /** * Runs a search over a collection and applies the given list of aggregation commands to the output. * @param collection The name of the collection to run the search over * @param aggregateConditions A List of CBDataAggregationCommand objects * @param handler a block of code to be executed once the request is completed */ public void searchDocumentAggregate(String collection, Vector aggregateConditions, CBHelperResponder responder) { JSONArray serializedAggregateConditions = new JSONArray(); try { for (int i = 0; i < aggregateConditions.size(); i++) { CBDataAggregationCommand curComm = (CBDataAggregationCommand) aggregateConditions.elementAt(i); JSONObject curSerializedCondition = new JSONObject(); curSerializedCondition.put(curComm.getCommandType(), curComm.serializeAggregateConditions()); serializedAggregateConditions.put(curSerializedCondition); } String url = this.getUrl() + this.appCode + "/" + collection + "/aggregate"; JSONObject paramsToPrepare = new JSONObject(); paramsToPrepare.put("cb_aggregate_key", serializedAggregateConditions); Hashtable preparedPost = this.preparePostParams(paramsToPrepare, null); CBHelperRequest req = new CBHelperRequest(url, "data"); req.setPostData(preparedPost); req.setResponder(responder); this.getApplicationRefernce().invokeLater(req); } catch (Exception e) { e.printStackTrace(); } } /** * Downloads a file matching the given file id. The file id comes from the cloudbase.io cb_files field on collections * created when documents are inserted with file attachments. * The data is downloaded and a java.io.File object is made available in the CBHelperResponse class called downloadedFile * @param fileId the cloudbase.io generated file id * @param responder The object to handle the response object */ public void downloadFile(String fileId, CBHelperResponder responder) { String url = this.getUrl() + this.appCode + "/file/" + fileId; Hashtable preparedPost = this.preparePostParams(new JSONObject(), null); CBHelperRequest req = new CBHelperRequest(url, "download"); req.setPostData(preparedPost); req.setFileId(fileId); req.setResponder(responder); this.getApplicationRefernce().invokeLater(req); } /** * Subscribes the current device, with the Key received from Google's C2DM to a notification channel. By default all * devices are automatically subscribed to the "All" channel. * @param deviceKey The registration id received from the Google's C2DM * @param channel The name of the channel to subscribe to. If the given channel does not exist then it is automatically * created */ public void notificationSubscribeDevice(String deviceKey, String channel) { notificationSubscribeDevice(deviceKey, channel, null); } /** * Subscribes the current device, with the Key received from Google's C2DM to a notification channel. By default all * devices are automatically subscribed to the "All" channel. * @param deviceKey deviceKey The registration id received from the Google's C2DM * @param channel The name of the channel to subscribe to. If the given channel does not exist then it is automatically * @param responder A CBHelperResponder object to handle the response from the cloudbase.io APIs */ public void notificationSubscribeDevice(String deviceKey, String channel, CBHelperResponder responder) { JSONObject subForm = new JSONObject(); try { subForm.put("action", "subscribe"); subForm.put("device_key", deviceKey); subForm.put("device_network", "bb"); subForm.put("channel", channel); String url = this.getUrl() + this.appCode + "/notifications-register"; Hashtable preparedPost = this.preparePostParams(subForm, null); CBHelperRequest req = new CBHelperRequest(url, "notifications-register"); req.setPostData(preparedPost); req.setResponder(responder); this.getApplicationRefernce().invokeLater(req); } catch (Exception e) { e.printStackTrace(); } } /** * Unsubscribes the current device from the given notification channel * @param deviceKey deviceKey The registration id received from the Google's C2DM * @param channel The name of the channel to subscribe to. If the given channel does not exist then it is automatically */ public void notificationUnsubscribeDevice(String deviceKey, String channel) { notificationUnsubscribeDevice(deviceKey, channel, null); } /** * Unsubscribes the current device from the given notification channel * @param deviceKey deviceKey The registration id received from the Google's C2DM * @param channel The name of the channel to subscribe to. If the given channel does not exist then it is automatically * @param responder A CBHelperResponder object to handle the response from the cloudbase.io server */ public void notificationUnsubscribeDevice(String deviceKey, String channel, CBHelperResponder responder) { JSONObject subForm = new JSONObject(); try { subForm.put("action", "unsubscribe"); subForm.put("device_key", deviceKey); subForm.put("device_network", "bb"); subForm.put("channel", channel); String url = this.getUrl() + this.appCode + "/notifications-register"; Hashtable preparedPost = this.preparePostParams(subForm, null); CBHelperRequest req = new CBHelperRequest(url, "notifications-register"); req.setPostData(preparedPost); req.setResponder(responder); this.getApplicationRefernce().invokeLater(req); } catch (Exception e) { e.printStackTrace(); } } /** * Sends an email to the specified recipient using the given template. * @param templateCode The code of the template created in the control panel on cloudbase.io * @param recipient The email address of the recipient of the email * @param subject The subject of the email * @param vars A Map of variables to fill the template. */ public void sendEmail(String templateCode, String recipient, String subject, Hashtable vars) { JSONObject subForm = new JSONObject(); try { subForm.put("template_code", templateCode); subForm.put("recipient", recipient); subForm.put("subject", subject); subForm.put("variables", new JSONObject(vars)); String url = this.getUrl() + this.appCode + "/email"; Hashtable preparedPost = this.preparePostParams(subForm, null); CBHelperRequest req = new CBHelperRequest(url, "email"); req.setPostData(preparedPost); this.getApplicationRefernce().invokeLater(req); } catch (Exception e) { e.printStackTrace(); } } /** * Executes a CloudFunction on the cloudbase.io servers on demand. Results will be ignored. * @param functionCode The name of the function to be executed */ public void runCloudFunction(String functionCode) { runCloudFunction(functionCode, null, null); } /** * Executes a CloudFunction on the coudbase.io servers on demand. The additional parameters will be accessible * to the function like standard HTTP POST parameters. Results will be ignored. * @param functionCode The name of the function to be executed * @param params The list of parameters to be passed to the function */ public void runCloudFunction(String functionCode, Hashtable params) { runCloudFunction(functionCode, params, null); } /** * Executes a CloudFunction on the coudbase.io servers on demand. The additional parameters will be accessible * to the function like standard HTTP POST parameters. Results and output are parsed and handed to the responder. * @param functionCode The name of the function to be executed * @param params The list of parameters to be passed to the function * @param responder The CBHelperResponder to handle the response value */ public void runCloudFunction(String functionCode, Hashtable params, CBHelperResponder responder) { String url = this.getUrl() + this.appCode + "/cloudfunction/" + functionCode; Hashtable preparedPost = this.preparePostParams(new JSONObject(), params); CBHelperRequest req = new CBHelperRequest(url, "cloudfunction"); req.setPostData(preparedPost); req.setResponder(responder); this.getApplicationRefernce().invokeLater(req); } /** * Executes a cloudbase.io applet on demand. * Results and output are parsed and handed to the responder. * @param appletCode The name of the applet to be executed * @param params The list of parameters to be passed to the applet * @param responder The CBHelperResponder to handle the response value */ public void runApplet(String appletCode, Hashtable params, CBHelperResponder responder) { String url = this.getUrl() + this.appCode + "/applet/" + appletCode; Hashtable preparedPost = this.preparePostParams(new JSONObject(), params); CBHelperRequest req = new CBHelperRequest(url, "applet"); req.setPostData(preparedPost); req.setResponder(responder); this.getApplicationRefernce().invokeLater(req); } /** * Executes a cloudbase.io Shared API on demand. * Results and output are parsed and handed to the responder. * @param apiCode The unique identifier for the shared API * @param password The password for the Shared API if necessary * @param params The list of parameters to be passed to the Shared API * @param responder The CBHelperResponder to handle the response value */ public void runSharedApi(String appletCode, String password, Hashtable params, CBHelperResponder responder) { String url = this.getUrl() + this.appCode + "/shared/" + appletCode; if (password != null) { params.put("cb_shared_password", password); } Hashtable preparedPost = this.preparePostParams(new JSONObject(), params); CBHelperRequest req = new CBHelperRequest(url, "shared-api"); req.setPostData(preparedPost); req.setResponder(responder); this.getApplicationRefernce().invokeLater(req); } /** * Initiates a transaction with PayPal by sending the payment details and retrieving a token * and an express checkout url. The url returned should be then opened in a browser window. * @param purchaseDetails a populated CBPayPalBill object * @param isLiveEnvironment whether we are using the production or sandbox paypal environments * @param responder a responder to handle the returned PayPal token and submission url */ public void preparePayPalPurchase(CBPayPalBill purchaseDetails, boolean isLiveEnvironment, CBHelperResponder responder) { String url = this.getUrl() + this.appCode + "/paypal/prepare"; try { JSONObject postData = new JSONObject(); postData.put("environment", isLiveEnvironment ? "live" : "sandbox"); postData.put("currency", purchaseDetails.getCurrency()); postData.put("type", "purchase"); postData.put("completed_cloudfunction", purchaseDetails.getPaymentCompletedFunction()); postData.put("cancelled_cloudfunction", purchaseDetails.getPaymentCancelledFunction()); postData.put("purchase_details", purchaseDetails.serializePurchase()); if (purchaseDetails.getPaymentCompletedUrl() != null) postData.put("payment_completed_url", purchaseDetails.getPaymentCompletedUrl()); if (purchaseDetails.getPaymentCancelledUrl() != null) postData.put("payment_cancelled_url", purchaseDetails.getPaymentCancelledUrl()); Hashtable preparedPost = this.preparePostParams(postData, null); CBHelperRequest req = new CBHelperRequest(url, "paypal"); req.setPostData(preparedPost); req.setResponder(responder); this.getApplicationRefernce().invokeLater(req); } catch (Exception e) { e.printStackTrace(); } } /** * Once the PayPal purchase is completed this method updates the record in the cloudbase.io database. * The responder can then proceed to close the payment window using the output of the call * @param url The url returned by PayPal once the payment is completed * @param responder The responder to complete the payment in the application */ public void completePayPalPurchase(String url, CBHelperResponder responder) { Hashtable preparedPost = this.preparePostParams(new JSONObject(), null); CBHelperRequest req = new CBHelperRequest(url, "paypal"); req.setPostData(preparedPost); req.setResponder(responder); this.getApplicationRefernce().invokeLater(req); } /** * Returns all of the details of a payment which has been prepared. * @param paymentId The payment_id returned by the cloudbase.io APIs when the payment is prepared * @param responder A responder to handle the details */ public void getPayPalPaymentDetails(String paymentId, CBHelperResponder responder) { String url = this.getUrl() + this.appCode + "/paypal/payment-details"; try { JSONObject postData = new JSONObject(); postData.put("payment_id", paymentId); Hashtable preparedPost = this.preparePostParams(postData, null); CBHelperRequest req = new CBHelperRequest(url, "paypal"); req.setPostData(preparedPost); req.setResponder(responder); this.getApplicationRefernce().invokeLater(req); } catch (Exception e) { e.printStackTrace(); } } // this function is used only by the helper class and it registers the device // with the cloudbase.io APIs. This is used to get a session_id used by the logNavigation // method. To receive the session_id the CBHelper object itself is a responder private void registerDevice() { if (this.deviceRegistered) return; Hashtable device = new Hashtable(); device.put("device_type", "BlackBerry"); device.put("device_name", this.deviceName); device.put("device_model", this.deviceModel); device.put("language", this.language); device.put("country", this.country); String url = this.getUrl() + this.appCode + "/register"; Hashtable preparedPost = this.preparePostParams(new JSONObject(device), null); CBHelperRequest req = new CBHelperRequest(url, "register-device"); req.setPostData(preparedPost); req.setResponder(this); req.start(); } // This function prepares a request for the cloudbase.io APIs adding all the default // parameters needed for a call private Hashtable preparePostParams(JSONArray postData, Hashtable additionalParams) { Hashtable post = this.prepareStandardParams(additionalParams); post.put("post_data", postData.toString()); return post; } private Hashtable preparePostParams(JSONObject postData, Hashtable additionalParams) { Hashtable post = this.prepareStandardParams(additionalParams); post.put("post_data", postData.toString()); return post; } private Hashtable prepareStandardParams(Hashtable additionalParams) { Hashtable post = new Hashtable(); post.put("app_uniq", this.appSecret); post.put("app_pwd", this.password); post.put("device_uniq", this.deviceUniqueIdentifier); // additional parameters are used for the CloudFunction and Applet APIs if (additionalParams != null) { Enumeration keys = additionalParams.keys(); //for (String curKey : keys) while (keys.hasMoreElements()) { String curKey = (String) keys.nextElement(); post.put(curKey, additionalParams.get(curKey)); } } if (this.userAuthentication) { post.put("cb_auth_user", this.authUsername); post.put("cb_auth_password", this.authPassword); } if (this.useLocation && this.currentLocation != null) { JSONObject locData = new JSONObject(); try { locData.put("lat", Double.toString(this.currentLocation.getQualifiedCoordinates().getLatitude())); locData.put("lng", Double.toString(this.currentLocation.getQualifiedCoordinates().getLongitude())); locData.put("alt", Double.toString(this.currentLocation.getQualifiedCoordinates().getAltitude())); } catch (JSONException e) { e.printStackTrace(); } post.put("location_data", locData.toString()); } return post; } private String getUrl() { return (this.https ? "https" : "http") + "://" + CBHelper.apiURL + "/"; } /** * Returns the device unique identifier used by this object * @return A String representing the unique identifier */ public String getDeviceUniqueIdentifier() { return deviceUniqueIdentifier; } /** * Sets the unique identifier. By default this is initialized to the <strong>ANDROID_ID</strong> in the <strong>Secure</strong> * class. * @param deviceUniqueIdentifier The new unique identifier */ public void setDeviceUniqueIdentifier(String deviceUniqueIdentifier) { this.deviceUniqueIdentifier = deviceUniqueIdentifier; } /** * Sets the password for the application to access the APIs. This should be an <strong>md5</strong> encoded string. * @param password The md5 hash of the password */ public void setPassword(String password) { this.password = password; // after the password is set we should have all of the information needed // to connect to cloudbase.io and register the device. this.registerDevice(); this.deviceRegistered = true; } public boolean isHttps() { return https; } public void setHttps(boolean https) { this.https = https; } public boolean isUserAuthentication() { return userAuthentication; } public void setUserAuthentication(boolean userAuthentication) { this.userAuthentication = userAuthentication; } public String getAuthUsername() { return authUsername; } public void setAuthUsername(String authUsername) { this.authUsername = authUsername; } public String getAuthPassword() { return authPassword; } public void setAuthPassword(String authPassword) { this.authPassword = authPassword; } public boolean isUseLocation() { return useLocation; } public void setUseLocation(boolean useLocation) { this.useLocation = useLocation; } public BlackBerryLocation getCurrentLocation() { return currentLocation; } public void setCurrentLocation(BlackBerryLocation currentLocation) { this.currentLocation = currentLocation; } public String getApiURL() { return apiURL; } public void setApiURL(String apiURL) { this.apiURL = apiURL; } // This is the response handler for the registerDevice method. Read the session_id // from cloudbase and save it in the CBHelper global variable public void handleResponse(CBHelperResponse res) throws JSONException { if (res.getFunction().equals("register-device")) { JSONObject data = (JSONObject) res.getData(); if (data.get("sessionid") != null) this.sessionId = (String) data.get("sessionid"); } } public String getTemporaryFilesPath() { return temporaryFilesPath; } public void setTemporaryFilesPath(String temporaryFilesPath) { this.temporaryFilesPath = temporaryFilesPath; } public UiApplication getApplicationRefernce() { return applicationRefernce; } public void setApplicationRefernce(UiApplication applicationRefernce) { this.applicationRefernce = applicationRefernce; } }