Search in sources :

Example 6 with RestResponse

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

the class AILTNPublisher method publishLogLines.

public boolean publishLogLines(JSONArray logLines) {
    final JSONObject body = new JSONObject();
    try {
        body.put(LOG_LINES, logLines);
    } catch (JSONException e) {
        SalesforceSDKLogger.e(TAG, "Exception thrown while constructing event payload", e);
        return false;
    }
    RestResponse restResponse = null;
    try {
        final String apiPath = String.format(API_PATH, ApiVersionStrings.getVersionNumber(SalesforceSDKManager.getInstance().getAppContext()));
        final RestClient restClient = SalesforceSDKManager.getInstance().getClientManager().peekRestClient();
        /*
             * Since the publisher is invoked from a Service, it could use an instance
             * of RestClient from memory that has no backing OkHttpClient that's ready.
             */
        if (restClient.getOkHttpClient() == null) {
            return false;
        }
        /*
             * There's no easy way to get content length using GZIP interceptors. Some trickery is
             * required to achieve this by adding an additional interceptor to determine content length.
             * See this post for more details: https://github.com/square/okhttp/issues/350#issuecomment-123105641.
             */
        final RequestBody requestBody = setContentLength(gzipCompressedBody(RequestBody.create(RestRequest.MEDIA_TYPE_JSON, body.toString())));
        final Map<String, String> requestHeaders = new HashMap<>();
        requestHeaders.put(CONTENT_ENCODING, GZIP);
        requestHeaders.put(CONTENT_LENGTH, Long.toString(requestBody.contentLength()));
        final RestRequest restRequest = new RestRequest(RestRequest.RestMethod.POST, apiPath, requestBody, requestHeaders);
        restResponse = restClient.sendSync(restRequest);
    } catch (ClientManager.AccountInfoNotFoundException e) {
        SalesforceSDKLogger.e(TAG, "Exception thrown while constructing rest client", e);
    } catch (IOException e) {
        SalesforceSDKLogger.e(TAG, "Exception thrown while making network request", e);
    }
    if (restResponse != null && restResponse.isSuccess()) {
        return true;
    }
    return false;
}
Also used : RestRequest(com.salesforce.androidsdk.rest.RestRequest) JSONObject(org.json.JSONObject) HashMap(java.util.HashMap) RestResponse(com.salesforce.androidsdk.rest.RestResponse) ClientManager(com.salesforce.androidsdk.rest.ClientManager) RestClient(com.salesforce.androidsdk.rest.RestClient) JSONException(org.json.JSONException) IOException(java.io.IOException) RequestBody(okhttp3.RequestBody)

Example 7 with RestResponse

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

the class SalesforceNetReactBridge method sendRequest.

@ReactMethod
public void sendRequest(ReadableMap args, final Callback successCallback, final Callback errorCallback) {
    try {
        // Prepare request
        final RestRequest request = prepareRestRequest(args);
        final boolean returnBinary = args.hasKey(RETURN_BINARY) && args.getBoolean(RETURN_BINARY);
        final boolean doesNotRequireAuth = args.hasKey(DOES_NOT_REQUIRE_AUTHENTICATION) && args.getBoolean(DOES_NOT_REQUIRE_AUTHENTICATION);
        // Sending request
        final RestClient restClient = getRestClient(doesNotRequireAuth);
        if (restClient == null) {
            // we are detached - do nothing
            return;
        }
        restClient.sendAsync(request, new RestClient.AsyncRequestCallback() {

            @Override
            public void onSuccess(RestRequest request, RestResponse response) {
                try {
                    // Not a 2xx status
                    if (!response.isSuccess()) {
                        final JSONObject responseObject = new JSONObject();
                        responseObject.put("headers", new JSONObject(response.getAllHeaders()));
                        responseObject.put("statusCode", response.getStatusCode());
                        responseObject.put("body", parsedResponse(response));
                        final JSONObject errorObject = new JSONObject();
                        errorObject.put("response", responseObject);
                        errorCallback.invoke(errorObject.toString());
                    } else // Binary response
                    if (returnBinary) {
                        JSONObject result = new JSONObject();
                        result.put(CONTENT_TYPE, response.getContentType());
                        result.put(ENCODED_BODY, Base64.encodeToString(response.asBytes(), Base64.DEFAULT));
                        successCallback.invoke(result.toString());
                    } else // Other cases
                    {
                        successCallback.invoke(response.asString());
                    }
                } catch (Exception e) {
                    SalesforceReactLogger.e(TAG, "sendRequest failed", e);
                    onError(e);
                }
            }

            @Override
            public void onError(Exception exception) {
                final JSONObject errorObject = new JSONObject();
                try {
                    errorObject.put("error", exception.getMessage());
                } catch (JSONException jsonException) {
                    SalesforceReactLogger.e(TAG, "Error creating error object", jsonException);
                }
                errorCallback.invoke(errorObject.toString());
            }
        });
    } catch (Exception exception) {
        final JSONObject errorObject = new JSONObject();
        try {
            errorObject.put("error", exception.getMessage());
        } catch (JSONException jsonException) {
            SalesforceReactLogger.e(TAG, "Error creating error object", jsonException);
        }
        errorCallback.invoke(errorObject.toString());
    }
}
Also used : RestRequest(com.salesforce.androidsdk.rest.RestRequest) JSONObject(org.json.JSONObject) RestResponse(com.salesforce.androidsdk.rest.RestResponse) RestClient(com.salesforce.androidsdk.rest.RestClient) JSONException(org.json.JSONException) URISyntaxException(java.net.URISyntaxException) JSONException(org.json.JSONException) IOException(java.io.IOException) UnsupportedEncodingException(java.io.UnsupportedEncodingException) ReactMethod(com.facebook.react.bridge.ReactMethod)

Example 8 with RestResponse

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

the class SalesforceDroidGapActivity method refresh.

/**
 * If an action causes a redirect to the login page, this method will be called.
 * It causes the session to be refreshed and reloads url through the front door.
 *
 * @param url the page to load once the session has been refreshed.
 */
public void refresh(final String url) {
    SalesforceHybridLogger.i(TAG, "refresh called");
    /*
         * If client is null at this point, authentication hasn't been performed yet.
         * We need to trigger authentication, and recreate the webview in the
         * callback, to load the page correctly. This handles some corner cases
         * involving hitting the back button when authentication is in progress.
         */
    if (client == null) {
        clientManager.getRestClient(this, new RestClientCallback() {

            @Override
            public void authenticatedRestClient(RestClient client) {
                recreate();
            }
        });
        return;
    }
    client.sendAsync(RestRequest.getRequestForUserInfo(), new AsyncRequestCallback() {

        @Override
        public void onSuccess(RestRequest request, RestResponse response) {
            SalesforceHybridLogger.i(TAG, "refresh callback - refresh succeeded");
            runOnUiThread(new Runnable() {

                @Override
                public void run() {
                    /*
                         * The client instance being used here needs to be refreshed, to ensure we
                         * use the new access token. However, if the refresh token was revoked
                         * when the app was in the background, we need to catch that exception
                         * and trigger a proper logout to reset the state of this class.
                         */
                    try {
                        SalesforceDroidGapActivity.this.client = SalesforceDroidGapActivity.this.clientManager.peekRestClient();
                        final String frontDoorUrl = getFrontDoorUrl(url, BootConfig.isAbsoluteUrl(url));
                        loadUrl(frontDoorUrl);
                    } catch (AccountInfoNotFoundException e) {
                        SalesforceHybridLogger.i(TAG, "User has been logged out.");
                        logout(null);
                    }
                }
            });
        }

        @Override
        public void onError(Exception exception) {
            SalesforceHybridLogger.w(TAG, "refresh callback - refresh failed", exception);
            // Only logout if we are NOT offline
            if (!(exception instanceof NoNetworkException)) {
                logout(null);
            }
        }
    });
}
Also used : AsyncRequestCallback(com.salesforce.androidsdk.rest.RestClient.AsyncRequestCallback) RestRequest(com.salesforce.androidsdk.rest.RestRequest) NoNetworkException(com.salesforce.androidsdk.auth.HttpAccess.NoNetworkException) RestResponse(com.salesforce.androidsdk.rest.RestResponse) RestClientCallback(com.salesforce.androidsdk.rest.ClientManager.RestClientCallback) RestClient(com.salesforce.androidsdk.rest.RestClient) AccountInfoNotFoundException(com.salesforce.androidsdk.rest.ClientManager.AccountInfoNotFoundException) AccountInfoNotFoundException(com.salesforce.androidsdk.rest.ClientManager.AccountInfoNotFoundException) NoNetworkException(com.salesforce.androidsdk.auth.HttpAccess.NoNetworkException)

Example 9 with RestResponse

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

the class ParentChildrenSyncUpTarget method fetchLastModifiedDates.

/**
 * Fetch last modified dates for a given record and its chidlren
 * @param syncManager
 * @param record
 * @return
 */
protected Map<String, String> fetchLastModifiedDates(SyncManager syncManager, JSONObject record) throws JSONException, IOException {
    Map<String, String> idToRemoteTimestamps = new HashMap<>();
    if (!isLocallyCreated(record)) {
        String parentId = record.getString(getIdFieldName());
        RestRequest lastModRequest = getRequestForTimestamps(syncManager.apiVersion, parentId);
        RestResponse lastModResponse = syncManager.sendSyncWithMobileSyncUserAgent(lastModRequest);
        JSONArray rows = lastModResponse.isSuccess() ? lastModResponse.asJSONObject().getJSONArray(Constants.RECORDS) : null;
        if (rows != null && rows.length() > 0) {
            JSONObject row = rows.getJSONObject(0);
            idToRemoteTimestamps.put(row.getString(getIdFieldName()), row.getString(getModificationDateFieldName()));
            if (row.has(childrenInfo.sobjectTypePlural) && !row.isNull(childrenInfo.sobjectTypePlural)) {
                JSONArray childrenRows = row.getJSONObject(childrenInfo.sobjectTypePlural).getJSONArray(Constants.RECORDS);
                for (int i = 0; i < childrenRows.length(); i++) {
                    final JSONObject childRow = childrenRows.getJSONObject(i);
                    idToRemoteTimestamps.put(childRow.getString(childrenInfo.idFieldName), childRow.getString(childrenInfo.modificationDateFieldName));
                }
            }
        }
    }
    return idToRemoteTimestamps;
}
Also used : RestRequest(com.salesforce.androidsdk.rest.RestRequest) JSONObject(org.json.JSONObject) HashMap(java.util.HashMap) LinkedHashMap(java.util.LinkedHashMap) RestResponse(com.salesforce.androidsdk.rest.RestResponse) JSONArray(org.json.JSONArray)

Example 10 with RestResponse

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

the class RefreshSyncDownTarget method fetchFromServer.

private JSONArray fetchFromServer(SyncManager syncManager, List<String> ids, List<String> fieldlist, long maxTimeStamp) throws IOException, JSONException {
    final String whereClause = "" + getIdFieldName() + " IN ('" + TextUtils.join("', '", ids) + "')" + (maxTimeStamp > 0 ? " AND " + getModificationDateFieldName() + " > " + Constants.TIMESTAMP_FORMAT.format(new Date(maxTimeStamp)) : "");
    final String soql = SOQLBuilder.getInstanceWithFields(fieldlist).from(objectType).where(whereClause).build();
    final RestRequest request = RestRequest.getRequestForQuery(syncManager.apiVersion, soql);
    final RestResponse response = syncManager.sendSyncWithMobileSyncUserAgent(request);
    JSONObject responseJson = response.asJSONObject();
    return responseJson.getJSONArray(Constants.RECORDS);
}
Also used : RestRequest(com.salesforce.androidsdk.rest.RestRequest) JSONObject(org.json.JSONObject) RestResponse(com.salesforce.androidsdk.rest.RestResponse) Date(java.util.Date)

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