@ReactMethod public void getAuthCredentials( ReadableMap args, Callback successCallback, Callback errorCallback) { ClientManager clientManager = new ClientManager( getReactApplicationContext(), SalesforceSDKManager.getInstance().getAccountType(), SalesforceSDKManager.getInstance().getLoginOptions(), SalesforceSDKManager.getInstance().shouldLogoutWhenTokenRevoked()); RestClient client = clientManager.peekRestClient(); RestClient.ClientInfo clientInfo = client.getClientInfo(); try { JSONObject data = new JSONObject(); data.put(ACCESS_TOKEN, client.getAuthToken()); data.put(REFRESH_TOKEN, client.getRefreshToken()); data.put(USER_ID, clientInfo.userId); data.put(ORG_ID, clientInfo.orgId); data.put(CLIENT_ID, clientInfo.clientId); data.put(LOGIN_URL, clientInfo.loginUrl.toString()); data.put(IDENTITY_URL, clientInfo.identityUrl.toString()); data.put(INSTANCE_URL, clientInfo.instanceUrl.toString()); data.put(COMMUNITY_ID, clientInfo.communityId); data.put(COMMUNITY_URL, clientInfo.communityUrl); ReactBridgeHelper.invokeSuccess(successCallback, data); } catch (JSONException e) { Log.e("OauthReactBridge", "getAuthCredentials", e); errorCallback.invoke(e.toString()); } }
@Override protected Map<String, List<String>> doInBackground(List<FormField>... params) { String attUrl = client .getClientInfo() .resolveUrl("/services/apexrest/MobilePickListValuesWebService?fieldId=") .toString(); for (FormField fieldId : params[0]) { HttpClient tempClient = new DefaultHttpClient(); URI theUrl = null; try { theUrl = new URI(attUrl + fieldId.getId()); HttpGet getRequest = new HttpGet(); getRequest.setURI(theUrl); getRequest.setHeader("Authorization", "Bearer " + client.getAuthToken()); BasicHttpParams param = new BasicHttpParams(); // param.setParameter("fieldId", fieldId); getRequest.setParams(param); HttpResponse httpResponse = null; try { httpResponse = tempClient.execute(getRequest); StatusLine statusLine = httpResponse.getStatusLine(); if (statusLine.getStatusCode() == HttpStatus.SC_OK) { HttpEntity httpEntity = httpResponse.getEntity(); if (httpEntity != null) { result = EntityUtils.toString(httpEntity); JSONObject jo = null; try { jo = new JSONObject(result); } catch (JSONException e) { e.printStackTrace(); } JSONArray ja = null; try { ja = jo.getJSONArray(parameters.get("auth")); fieldId.setPicklistEntries(convertJsonStringToString(ja)); } catch (JSONException e) { e.printStackTrace(); } } } else { httpResponse.getEntity().getContent().close(); throw new IOException(statusLine.getReasonPhrase()); } } catch (IOException e) { e.printStackTrace(); } } catch (URISyntaxException e) { e.printStackTrace(); } } return null; }
/** @return credentials as JSONObject */ private static JSONObject getJSONCredentials(RestClient client) { ClientInfo clientInfo = client.getClientInfo(); Map<String, String> data = new HashMap<String, String>(); data.put(ACCESS_TOKEN, client.getAuthToken()); data.put(REFRESH_TOKEN, client.getRefreshToken()); data.put(USER_ID, clientInfo.userId); data.put(ORG_ID, clientInfo.orgId); data.put(CLIENT_ID, clientInfo.clientId); data.put(LOGIN_URL, clientInfo.loginUrl.toString()); data.put(INSTANCE_URL, clientInfo.instanceUrl.toString()); data.put(USER_AGENT, ForceApp.APP.getUserAgent()); return new JSONObject(data); }
/** * Send restRequest using RestClient's sendAsync method. Note: Synchronous calls are not allowed * from code running on the UI thread. * * @param restRequest */ private void sendFromUIThread(RestRequest restRequest) { client.sendAsync( restRequest, new AsyncRequestCallback() { private long start = System.nanoTime(); @Override public void onSuccess(RestRequest request, RestResponse result) { try { long duration = System.nanoTime() - start; println(result); int size = result.asString().length(); int statusCode = result.getStatusCode(); printRequestInfo(duration, size, statusCode); extractIdsFromResponse(result.asString()); } catch (Exception e) { printException(e); } EventsObservable.get().notifyEvent(EventType.RenditionComplete); } @Override public void onError(Exception exception) { printException(exception); EventsObservable.get().notifyEvent(EventType.RenditionComplete); } }); }
/** * If auto-refresh is enabled, this method will be called when the app resumes, and automatically * refresh the user's OAuth credentials in the app, ensuring a valid session. * * @param webView The WebView running the application. * @param ctx The main activity/context for the app. */ public static void autoRefreshIfNeeded( final WebView webView, final SalesforceDroidGapActivity ctx) { Log.i("SalesforceOAuthPlugin.autoRefreshIfNeeded", "Checking if auto refresh needed"); if (shouldAutoRefresh()) { Log.i("SalesforceOAuthPlugin.autoRefreshIfNeeded", "Starting auto-refresh"); clientManager.invalidateToken(client.getAuthToken()); clientManager.getRestClient( ctx, new RestClientCallback() { @Override public void authenticatedRestClient(RestClient c) { if (c == null) { Log.w( "SalesforceOAuthPlugin.autoRefreshIfNeeded", "Auto-refresh failed - logging out"); logout(ctx); } else { Log.i("SalesforceOAuthPlugin.autoRefreshIfNeeded", "Auto-refresh succeeded"); updateRefreshTime(); SalesforceOAuthPlugin.client = c; setSidCookies(webView, SalesforceOAuthPlugin.client); Log.i( "SalesforceOAuthPlugin.autoRefreshIfNeeded", "Firing salesforceSessionRefresh event"); ctx.sendJavascript( "PhoneGap.fireDocumentEvent('salesforceSessionRefresh'," + getJSONCredentials(SalesforceOAuthPlugin.client).toString() + ");"); } } }); } }
/** * Delete records specified in idToNames * * @param ids * @throws Exception */ protected void deleteRecordsOnServer(Set<String> ids, String objectType) throws Exception { for (String id : ids) { RestRequest request = RestRequest.getRequestForDelete( ApiVersionStrings.getVersionNumber(targetContext), objectType, id); restClient.sendSync(request); } }
/** * Method called from bridge to get auth credentials * * @param successCallback * @param errorCallback */ public void getAuthCredentials(Callback successCallback, Callback errorCallback) { Log.i(TAG, "getAuthCredentials called"); if (client != null) { if (successCallback != null) { ReactBridgeHelper.invokeSuccess(successCallback, client.getJSONCredentials()); } } else { if (errorCallback != null) { errorCallback.invoke("Not authenticated"); } } }
/** * Sends a REST request. * * @param soql SOQL query. * @param obj Object being queried. */ private void sendRequest(String soql, final String obj) throws UnsupportedEncodingException { final RestRequest restRequest = RestRequest.getRequestForQuery(getString(R.string.api_version), soql); client.sendAsync( restRequest, new AsyncRequestCallback() { @Override public void onSuccess(RestRequest request, RestResponse result) { try { final JSONArray records = result.asJSONObject().getJSONArray("records"); if (obj.equals("Account")) { smartStoreIntf.insertAccounts(records); } else if (obj.equals("Opportunity")) { smartStoreIntf.insertOpportunities(records); } else { /* * If the object is not an account or opportunity, * we do nothing. This block can be used to save * other types of records. */ } } catch (Exception e) { onError(e); } finally { progressDialog.dismiss(); Toast.makeText( MainActivity.this, "Records ready for offline access.", Toast.LENGTH_SHORT) .show(); } } @Override public void onError(Exception exception) { Toast.makeText( MainActivity.this, MainActivity.this.getString( SalesforceSDKManagerWithSmartStore.getInstance() .getSalesforceR() .stringGenericError(), exception.toString()), Toast.LENGTH_LONG) .show(); } }); }
private void getAccounts() { try { String accountId = getIntent().getStringExtra("ACCOUNT_ID"); String soql = "select Id, Name from Contact where AccountId = '" + accountId + "'"; RestRequest request = RestRequest.getRequestForQuery(apiVersion, soql); client.sendAsync( request, new AsyncRequestCallback() { public void onSuccess(RestResponse response) { try { if (response == null || response.asJSONObject() == null) return; JSONArray records = response.asJSONObject().getJSONArray("records"); if (records.length() == 0) return; accounts = new String[records.length()]; for (int i = 0; i < records.length(); i++) { JSONObject album = (JSONObject) records.get(i); accounts[i] = (i + 1) + ". " + album.getString("Name"); } ArrayAdapter<String> ad = new ArrayAdapter<String>( ContactListActivity.this, R.layout.list_item, accounts); lv.setAdapter(ad); EventsObservable.get().notifyEvent(EventType.RenditionComplete); } catch (Exception e) { e.printStackTrace(); displayError(e.getMessage()); } } public void onError(Exception exception) { displayError(exception.getMessage()); EventsObservable.get().notifyEvent(EventType.RenditionComplete); } }); } catch (Exception e) { e.printStackTrace(); displayError(e.getMessage()); } }
/** * Set cookies on cookie manager * * @param client */ private static void setSidCookies(WebView webView, RestClient client) { Log.i("SalesforceOAuthPlugin.setSidCookies", "setting cookies"); CookieSyncManager cookieSyncMgr = CookieSyncManager.getInstance(); CookieManager cookieMgr = CookieManager.getInstance(); cookieMgr.setAcceptCookie( true); // Required to set additional cookies that the auth process will return. cookieMgr.removeSessionCookie(); SystemClock.sleep(250); // removeSessionCookies kicks out a thread - let it finish String accessToken = client.getAuthToken(); // Android 3.0+ clients want to use the standard .[domain] format. Earlier clients will only // work // with the [domain] format. Set them both; each platform will leverage its respective format. addSidCookieForDomain(cookieMgr, "salesforce.com", accessToken); addSidCookieForDomain(cookieMgr, ".salesforce.com", accessToken); cookieSyncMgr.sync(); }
/** * Helper methods to create "count" of test records * * @param count * @return map of id to name for the created accounts * @throws Exception */ protected Map<String, String> createRecordsOnServer(int count, String objectType) throws Exception { Map<String, String> idToValues = new HashMap<String, String>(); for (int i = 0; i < count; i++) { // Request. String fieldValue = createRecordName(objectType); Map<String, Object> fields = new HashMap<String, Object>(); // add more object type if need to support to use this API // to create a new record on server switch (objectType) { case Constants.ACCOUNT: fields.put(Constants.NAME, fieldValue); break; case Constants.OPPORTUNITY: fields.put(Constants.NAME, fieldValue); fields.put("StageName", "Prospecting"); DateFormat formatter = new SimpleDateFormat("yyyy-MM-dd"); fields.put("CloseDate", formatter.format(new Date())); break; default: break; } RestRequest request = RestRequest.getRequestForCreate( ApiVersionStrings.getVersionNumber(targetContext), objectType, fields); // Response. RestResponse response = restClient.sendSync(request); assertNotNull("Response should not be null", response); assertTrue("Response status should be success", response.isSuccess()); String id = response.asJSONObject().getString(LID); idToValues.put(id, fieldValue); } return idToValues; }