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;
}
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;
}
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);
}
}
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;
}
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());
}
}
Aggregations