Search in sources :

Example 6 with RestClient

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

the class SalesforceReactActivity method login.

protected void login() {
    SalesforceReactLogger.i(TAG, "login called");
    clientManager.getRestClient(this, new RestClientCallback() {

        @Override
        public void authenticatedRestClient(RestClient client) {
            if (client == null) {
                SalesforceReactLogger.i(TAG, "login callback triggered with null client");
                logout(null);
            } else {
                SalesforceReactLogger.i(TAG, "login callback triggered with actual client");
                SalesforceReactActivity.this.restartReactNativeApp();
            }
        }
    });
}
Also used : RestClientCallback(com.salesforce.androidsdk.rest.ClientManager.RestClientCallback) RestClient(com.salesforce.androidsdk.rest.RestClient)

Example 7 with RestClient

use of com.salesforce.androidsdk.rest.RestClient 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 8 with RestClient

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

the class SalesforceNetworkPlugin method sendRequest.

/**
 * Native implementation for "sendRequest" action.
 *
 * @param callbackContext Used when calling back into Javascript.
 */
protected void sendRequest(JSONArray args, final CallbackContext callbackContext) {
    try {
        final RestRequest request = prepareRestRequest(args);
        final boolean returnBinary = ((JSONObject) args.get(0)).optBoolean(RETURN_BINARY, false);
        final boolean doesNotRequireAuth = ((JSONObject) args.get(0)).optBoolean(DOES_NOT_REQUIRE_AUTHENTICATION, false);
        // Sends the request.
        final RestClient restClient = getRestClient(doesNotRequireAuth);
        if (restClient == null) {
            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);
                        callbackContext.error(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));
                        callbackContext.success(result);
                    } else // Some response
                    if (response.asBytes().length > 0) {
                        final Object parsedResponse = parsedResponse(response);
                        if (parsedResponse instanceof JSONObject) {
                            callbackContext.success((JSONObject) parsedResponse);
                        } else if (parsedResponse instanceof JSONArray) {
                            callbackContext.success((JSONArray) parsedResponse);
                        } else {
                            callbackContext.success((String) parsedResponse);
                        }
                    } else // No response
                    {
                        callbackContext.success();
                    }
                } catch (Exception e) {
                    SalesforceHybridLogger.e(TAG, "Error while parsing response", e);
                    onError(e);
                }
            }

            @Override
            public void onError(Exception exception) {
                final JSONObject errorObject = new JSONObject();
                try {
                    errorObject.put("error", exception.getMessage());
                } catch (JSONException jsonException) {
                    SalesforceHybridLogger.e(TAG, "Error creating error object", jsonException);
                }
                callbackContext.error(errorObject.toString());
            }
        });
    } catch (Exception exception) {
        final JSONObject errorObject = new JSONObject();
        try {
            errorObject.put("error", exception.getMessage());
        } catch (JSONException jsonException) {
            SalesforceHybridLogger.e(TAG, "Error creating error object", jsonException);
        }
        callbackContext.error(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) JSONArray(org.json.JSONArray) JSONException(org.json.JSONException) JSONObject(org.json.JSONObject) URISyntaxException(java.net.URISyntaxException) IOException(java.io.IOException) JSONException(org.json.JSONException) UnsupportedEncodingException(java.io.UnsupportedEncodingException)

Example 9 with RestClient

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

the class SalesforceActivityDelegate method onResume.

/**
 * Brings up ScreenLock if needed
 * Build RestClient if requested and then calls activity.onResume(restClient)
 * Otherwise calls activity.onResume(null)
 *
 * @param buildRestClient
 */
public void onResume(boolean buildRestClient) {
    // Brings up the ScreenLock if needed.
    if (buildRestClient) {
        // Gets login options.
        final String accountType = SalesforceSDKManager.getInstance().getAccountType();
        final ClientManager.LoginOptions loginOptions = SalesforceSDKManager.getInstance().getLoginOptions();
        // Gets a rest client.
        new ClientManager(SalesforceSDKManager.getInstance().getAppContext(), accountType, loginOptions, SalesforceSDKManager.getInstance().shouldLogoutWhenTokenRevoked()).getRestClient(activity, new ClientManager.RestClientCallback() {

            @Override
            public void authenticatedRestClient(RestClient client) {
                if (client == null) {
                    SalesforceSDKManager.getInstance().logout(activity);
                    return;
                }
                ((SalesforceActivityInterface) activity).onResume(client);
                // Lets observers know that rendition is complete.
                EventsObservable.get().notifyEvent(EventsObservable.EventType.RenditionComplete);
            }
        });
    } else {
        ((SalesforceActivityInterface) activity).onResume(null);
    }
}
Also used : ClientManager(com.salesforce.androidsdk.rest.ClientManager) RestClient(com.salesforce.androidsdk.rest.RestClient)

Example 10 with RestClient

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

the class SyncManager method getInstance.

/**
 * Returns the instance of this class associated with this user, community and smartstore.
 *
 * @param account     User account. Pass null to user current user.
 * @param communityId Community ID. Pass null if not applicable
 * @param smartStore  SmartStore instance. Pass null to use current user default smartstore.
 * @return Instance of this class.
 */
public static synchronized SyncManager getInstance(UserAccount account, String communityId, SmartStore smartStore) {
    if (account == null) {
        account = MobileSyncSDKManager.getInstance().getUserAccountManager().getCachedCurrentUser();
    }
    if (smartStore == null) {
        smartStore = MobileSyncSDKManager.getInstance().getSmartStore(account, communityId);
    }
    String uniqueId = (account != null ? account.getUserId() : "") + ":" + smartStore.getDatabase().getPath();
    SyncManager instance = INSTANCES.get(uniqueId);
    if (instance == null) {
        RestClient restClient = null;
        /*
             * If account is still null, there is no user logged in, which means, the default
             * RestClient should be set to the unauthenticated RestClient instance.
             */
        if (account == null) {
            restClient = SalesforceSDKManager.getInstance().getClientManager().peekUnauthenticatedRestClient();
        } else {
            restClient = SalesforceSDKManager.getInstance().getClientManager().peekRestClient(account);
        }
        instance = new SyncManager(smartStore, restClient);
        INSTANCES.put(uniqueId, instance);
    }
    SalesforceSDKManager.getInstance().registerUsedAppFeature(Features.FEATURE_MOBILE_SYNC);
    return instance;
}
Also used : RestClient(com.salesforce.androidsdk.rest.RestClient)

Aggregations

RestClient (com.salesforce.androidsdk.rest.RestClient)13 RestResponse (com.salesforce.androidsdk.rest.RestResponse)6 IOException (java.io.IOException)6 RestRequest (com.salesforce.androidsdk.rest.RestRequest)5 RestClientCallback (com.salesforce.androidsdk.rest.ClientManager.RestClientCallback)4 JSONObject (org.json.JSONObject)4 ClientManager (com.salesforce.androidsdk.rest.ClientManager)3 JSONException (org.json.JSONException)3 NoNetworkException (com.salesforce.androidsdk.auth.HttpAccess.NoNetworkException)2 AccountInfoNotFoundException (com.salesforce.androidsdk.rest.ClientManager.AccountInfoNotFoundException)2 AsyncRequestCallback (com.salesforce.androidsdk.rest.RestClient.AsyncRequestCallback)2 ClientInfo (com.salesforce.androidsdk.rest.RestClient.ClientInfo)2 UnsupportedEncodingException (java.io.UnsupportedEncodingException)2 URI (java.net.URI)2 URISyntaxException (java.net.URISyntaxException)2 HashMap (java.util.HashMap)2 ReactMethod (com.facebook.react.bridge.ReactMethod)1 HttpAccess (com.salesforce.androidsdk.auth.HttpAccess)1 TokenEndpointResponse (com.salesforce.androidsdk.auth.OAuth2.TokenEndpointResponse)1 AccMgrAuthTokenProvider (com.salesforce.androidsdk.rest.ClientManager.AccMgrAuthTokenProvider)1