Search in sources :

Example 1 with RestClient

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

the class PushService method getRestClient.

private RestClient getRestClient(UserAccount account) {
    final ClientManager cm = SalesforceSDKManager.getInstance().getClientManager();
    RestClient client = null;
    /*
    	 * The reason we can't directly call 'peekRestClient()' here is because
    	 * ClientManager does not hand out a rest client when a logout is in
    	 * progress. Hence, we build a rest client here manually, with the
    	 * available data in the 'account' object.
    	 */
    if (cm != null) {
        try {
            final AccMgrAuthTokenProvider authTokenProvider = new AccMgrAuthTokenProvider(cm, account.getInstanceServer(), account.getAuthToken(), account.getRefreshToken());
            final ClientInfo clientInfo = new ClientInfo(new URI(account.getInstanceServer()), new URI(account.getLoginServer()), new URI(account.getIdUrl()), account.getAccountName(), account.getUsername(), account.getUserId(), account.getOrgId(), account.getCommunityId(), account.getCommunityUrl(), account.getFirstName(), account.getLastName(), account.getDisplayName(), account.getEmail(), account.getPhotoUrl(), account.getThumbnailUrl(), account.getAdditionalOauthValues(), account.getLightningDomain(), account.getLightningSid(), account.getVFDomain(), account.getVFSid(), account.getContentDomain(), account.getContentSid(), account.getCSRFToken());
            client = new RestClient(clientInfo, account.getAuthToken(), HttpAccess.DEFAULT, authTokenProvider);
        } catch (Exception e) {
            SalesforceSDKLogger.e(TAG, "Failed to get rest client", e);
        }
    }
    return client;
}
Also used : ClientManager(com.salesforce.androidsdk.rest.ClientManager) RestClient(com.salesforce.androidsdk.rest.RestClient) ClientInfo(com.salesforce.androidsdk.rest.RestClient.ClientInfo) URI(java.net.URI) IOException(java.io.IOException) AccMgrAuthTokenProvider(com.salesforce.androidsdk.rest.ClientManager.AccMgrAuthTokenProvider)

Example 2 with RestClient

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

Example 3 with RestClient

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

the class PushService method unregisterSFDCPushNotification.

private void unregisterSFDCPushNotification(String registeredId, UserAccount account) {
    try {
        final RestClient client = getRestClient(account);
        if (client != null) {
            onSendUnregisterPushNotificationRequest(registeredId, client).consume();
            onPushNotificationRegistrationStatus(UNREGISTRATION_STATUS_SUCCEEDED, account);
        }
    } catch (IOException e) {
        onPushNotificationRegistrationStatus(UNREGISTRATION_STATUS_FAILED, account);
        SalesforceSDKLogger.e(TAG, "Push notification un-registration failed", e);
    }
}
Also used : RestClient(com.salesforce.androidsdk.rest.RestClient) IOException(java.io.IOException)

Example 4 with RestClient

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

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

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