Search in sources :

Example 1 with RestResponse

use of com.salesforce.androidsdk.rest.RestResponse in project SalesforceMobileSDK-Android by forcedotcom.

the class SyncManager method sendSyncWithMobileSyncUserAgent.

/**
 * Send request after adding user-agent header that says MobileSync.
 * @param restRequest
 * @return
 * @throws IOException
 */
public RestResponse sendSyncWithMobileSyncUserAgent(RestRequest restRequest) throws IOException {
    MobileSyncLogger.d(TAG, "sendSyncWithMobileSyncUserAgent called with request: ", restRequest);
    RestResponse restResponse = restClient.sendSync(restRequest, new HttpAccess.UserAgentInterceptor(SalesforceSDKManager.getInstance().getUserAgent(MOBILE_SYNC)));
    return restResponse;
}
Also used : HttpAccess(com.salesforce.androidsdk.auth.HttpAccess) RestResponse(com.salesforce.androidsdk.rest.RestResponse)

Example 2 with RestResponse

use of com.salesforce.androidsdk.rest.RestResponse in project SalesforceMobileSDK-Android by forcedotcom.

the class ParentChildrenSyncTestCase method createAccountsAndContactsOnServer.

protected void createAccountsAndContactsOnServer(int numberAccounts, int numberContactsPerAccount) throws Exception {
    accountIdToFields = new HashMap<>();
    accountIdContactIdToFields = new HashMap<>();
    Map<String, Map<String, Object>> refIdToFields = new HashMap<>();
    List<RestRequest.SObjectTree> accountTrees = new ArrayList<>();
    List<Map<String, Object>> listAccountFields = buildFieldsMapForRecords(numberAccounts, Constants.ACCOUNT, null);
    for (int i = 0; i < listAccountFields.size(); i++) {
        List<Map<String, Object>> listContactFields = buildFieldsMapForRecords(numberContactsPerAccount, Constants.CONTACT, null);
        String refIdAccount = "refAccount_" + i;
        Map<String, Object> accountFields = listAccountFields.get(i);
        refIdToFields.put(refIdAccount, accountFields);
        List<RestRequest.SObjectTree> contactTrees = new ArrayList<>();
        for (int j = 0; j < listContactFields.size(); j++) {
            String refIdContact = refIdAccount + ":refContact_" + j;
            Map<String, Object> contactFields = listContactFields.get(j);
            refIdToFields.put(refIdContact, contactFields);
            contactTrees.add(new RestRequest.SObjectTree(Constants.CONTACT, Constants.CONTACTS, refIdContact, contactFields, null));
        }
        accountTrees.add(new RestRequest.SObjectTree(Constants.ACCOUNT, null, refIdAccount, accountFields, contactTrees));
    }
    RestRequest request = RestRequest.getRequestForSObjectTree(apiVersion, Constants.ACCOUNT, accountTrees);
    // Send request
    RestResponse response = restClient.sendSync(request);
    // Parse response
    Map<String, String> refIdToId = new HashMap<>();
    JSONArray results = response.asJSONObject().getJSONArray("results");
    for (int i = 0; i < results.length(); i++) {
        JSONObject result = results.getJSONObject(i);
        String refId = result.getString(RestRequest.REFERENCE_ID);
        String id = result.getString(Constants.LID);
        refIdToId.put(refId, id);
    }
    // Populate accountIdToFields and accountIdContactIdToFields
    for (String refId : refIdToId.keySet()) {
        Map<String, Object> fields = refIdToFields.get(refId);
        String[] parts = refId.split(":");
        String accountId = refIdToId.get(parts[0]);
        String contactId = parts.length > 1 ? refIdToId.get(refId) : null;
        if (contactId == null) {
            accountIdToFields.put(accountId, fields);
        } else {
            if (!accountIdContactIdToFields.containsKey(accountId))
                accountIdContactIdToFields.put(accountId, new HashMap<String, Map<String, Object>>());
            accountIdContactIdToFields.get(accountId).put(contactId, fields);
        }
    }
}
Also used : HashMap(java.util.HashMap) RestResponse(com.salesforce.androidsdk.rest.RestResponse) ArrayList(java.util.ArrayList) JSONArray(org.json.JSONArray) RestRequest(com.salesforce.androidsdk.rest.RestRequest) JSONObject(org.json.JSONObject) JSONObject(org.json.JSONObject) HashMap(java.util.HashMap) Map(java.util.Map)

Example 3 with RestResponse

use of com.salesforce.androidsdk.rest.RestResponse in project SalesforceMobileSDK-Android by forcedotcom.

the class SyncManagerTestCase method checkServerDeleted.

/**
 * Check that records were deleted from server
 * @param ids
 * @param sObjectType
 * @throws IOException
 */
protected void checkServerDeleted(String[] ids, String sObjectType) throws IOException, JSONException {
    String soql = String.format("SELECT %s FROM %s WHERE %s IN %s", Constants.ID, sObjectType, Constants.ID, makeInClause(ids));
    RestRequest request = RestRequest.getRequestForQuery(ApiVersionStrings.getVersionNumber(targetContext), soql);
    RestResponse response = restClient.sendSync(request);
    JSONArray records = response.asJSONObject().getJSONArray(RECORDS);
    Assert.assertEquals("No accounts should have been returned from server", 0, records.length());
}
Also used : RestRequest(com.salesforce.androidsdk.rest.RestRequest) RestResponse(com.salesforce.androidsdk.rest.RestResponse) JSONArray(org.json.JSONArray)

Example 4 with RestResponse

use of com.salesforce.androidsdk.rest.RestResponse in project SalesforceMobileSDK-Android by forcedotcom.

the class ExplorerActivity method sendFromUIThread.

/**
 * Sends a REST request using RestClient's sendAsync method.
 * Note: Synchronous calls are not allowed from code running on the UI thread.
 *
 * @param restRequest REST request.
 */
private void sendFromUIThread(RestRequest restRequest) {
    client.sendAsync(restRequest, new AsyncRequestCallback() {

        private long start = System.nanoTime();

        @Override
        public void onSuccess(RestRequest request, final RestResponse result) {
            // consume before going back to main thread
            result.consumeQuietly();
            runOnUiThread(new Runnable() {

                @Override
                public void run() {
                    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(final Exception exception) {
            runOnUiThread(new Runnable() {

                @Override
                public void run() {
                    printException(exception);
                    EventsObservable.get().notifyEvent(EventType.RenditionComplete);
                }
            });
        }
    });
}
Also used : AsyncRequestCallback(com.salesforce.androidsdk.rest.RestClient.AsyncRequestCallback) RestRequest(com.salesforce.androidsdk.rest.RestRequest) RestResponse(com.salesforce.androidsdk.rest.RestResponse) UnsupportedEncodingException(java.io.UnsupportedEncodingException)

Example 5 with RestResponse

use of com.salesforce.androidsdk.rest.RestResponse in project SalesforceMobileSDK-Android by forcedotcom.

the class PushService method registerSFDCPushNotification.

private String registerSFDCPushNotification(String registrationId, UserAccount account) {
    try {
        final Map<String, Object> fields = new HashMap<>();
        fields.put(CONNECTION_TOKEN, registrationId);
        fields.put(SERVICE_TYPE, ANDROID_GCM);
        fields.put(APPLICATION_BUNDLE, SalesforceSDKManager.getInstance().getAppContext().getPackageName());
        // Adds community ID to the registration payload to allow scoping of notifications per community.
        final String communityId = UserAccountManager.getInstance().getCurrentUser().getCommunityId();
        if (!TextUtils.isEmpty(communityId)) {
            fields.put(NETWORK_ID, communityId);
        }
        // Adds an RSA public key to the registration payload if available.
        final String rsaPublicKey = getRSAPublicKey();
        if (!TextUtils.isEmpty(rsaPublicKey)) {
            fields.put(RSA_PUBLIC_KEY, rsaPublicKey);
        }
        final RestClient client = getRestClient(account);
        if (client != null) {
            int status = REGISTRATION_STATUS_FAILED;
            final RestResponse res = onSendRegisterPushNotificationRequest(fields, client);
            String id = null;
            /*
            	 * If the push notification device object has been created,
            	 * reads the device registration ID. If the status code
            	 * indicates that the resource is not found, push notifications
            	 * are not enabled for this connected app, which means we
            	 * should not attempt to re-register a few minutes later.
            	 */
            if (res.getStatusCode() == HttpURLConnection.HTTP_CREATED) {
                final JSONObject obj = res.asJSONObject();
                if (obj != null) {
                    id = obj.getString(FIELD_ID);
                    status = REGISTRATION_STATUS_SUCCEEDED;
                }
            } else if (res.getStatusCode() == HttpURLConnection.HTTP_NOT_FOUND) {
                id = NOT_ENABLED;
                status = REGISTRATION_STATUS_FAILED;
            }
            res.consume();
            SalesforceSDKManager.getInstance().registerUsedAppFeature(Features.FEATURE_PUSH_NOTIFICATIONS);
            onPushNotificationRegistrationStatus(status, account);
            return id;
        }
    } catch (Exception e) {
        SalesforceSDKLogger.e(TAG, "Push notification registration failed", e);
    }
    onPushNotificationRegistrationStatus(REGISTRATION_STATUS_FAILED, account);
    return null;
}
Also used : JSONObject(org.json.JSONObject) HashMap(java.util.HashMap) RestResponse(com.salesforce.androidsdk.rest.RestResponse) RestClient(com.salesforce.androidsdk.rest.RestClient) JSONObject(org.json.JSONObject) IOException(java.io.IOException)

Aggregations

RestResponse (com.salesforce.androidsdk.rest.RestResponse)30 RestRequest (com.salesforce.androidsdk.rest.RestRequest)26 JSONArray (org.json.JSONArray)14 JSONObject (org.json.JSONObject)14 RestClient (com.salesforce.androidsdk.rest.RestClient)6 HashMap (java.util.HashMap)6 IOException (java.io.IOException)5 AsyncRequestCallback (com.salesforce.androidsdk.rest.RestClient.AsyncRequestCallback)3 UnsupportedEncodingException (java.io.UnsupportedEncodingException)3 ArrayList (java.util.ArrayList)3 JSONException (org.json.JSONException)3 NoNetworkException (com.salesforce.androidsdk.auth.HttpAccess.NoNetworkException)2 AccountInfoNotFoundException (com.salesforce.androidsdk.rest.ClientManager.AccountInfoNotFoundException)2 RestClientCallback (com.salesforce.androidsdk.rest.ClientManager.RestClientCallback)2 URISyntaxException (java.net.URISyntaxException)2 LinkedHashMap (java.util.LinkedHashMap)2 Map (java.util.Map)2 Context (android.content.Context)1 Intent (android.content.Intent)1 ReactMethod (com.facebook.react.bridge.ReactMethod)1