Search in sources :

Example 16 with FacebookException

use of com.facebook.FacebookException in project facebook-android-sdk by facebook.

the class ImageDownloader method download.

private static void download(RequestKey key, Context context) {
    HttpURLConnection connection = null;
    InputStream stream = null;
    Exception error = null;
    Bitmap bitmap = null;
    boolean issueResponse = true;
    try {
        URL url = new URL(key.uri.toString());
        connection = (HttpURLConnection) url.openConnection();
        connection.setInstanceFollowRedirects(false);
        switch(connection.getResponseCode()) {
            case HttpURLConnection.HTTP_MOVED_PERM:
            case HttpURLConnection.HTTP_MOVED_TEMP:
                // redirect. So we need to perform further requests
                issueResponse = false;
                String redirectLocation = connection.getHeaderField("location");
                if (!Utility.isNullOrEmpty(redirectLocation)) {
                    Uri redirectUri = Uri.parse(redirectLocation);
                    UrlRedirectCache.cacheUriRedirect(key.uri, redirectUri);
                    // Once the old downloader context is removed, we are thread-safe since this
                    // is the only reference to it
                    DownloaderContext downloaderContext = removePendingRequest(key);
                    if (downloaderContext != null && !downloaderContext.isCancelled) {
                        enqueueCacheRead(downloaderContext.request, new RequestKey(redirectUri, key.tag), false);
                    }
                }
                break;
            case HttpURLConnection.HTTP_OK:
                // image should be available
                stream = ImageResponseCache.interceptAndCacheImageStream(context, connection);
                bitmap = BitmapFactory.decodeStream(stream);
                break;
            default:
                stream = connection.getErrorStream();
                StringBuilder errorMessageBuilder = new StringBuilder();
                if (stream != null) {
                    InputStreamReader reader = new InputStreamReader(stream);
                    char[] buffer = new char[128];
                    int bufferLength;
                    while ((bufferLength = reader.read(buffer, 0, buffer.length)) > 0) {
                        errorMessageBuilder.append(buffer, 0, bufferLength);
                    }
                    Utility.closeQuietly(reader);
                } else {
                    errorMessageBuilder.append(context.getString(R.string.com_facebook_image_download_unknown_error));
                }
                error = new FacebookException(errorMessageBuilder.toString());
                break;
        }
    } catch (IOException e) {
        error = e;
    } finally {
        Utility.closeQuietly(stream);
        Utility.disconnectQuietly(connection);
    }
    if (issueResponse) {
        issueResponse(key, error, bitmap, false);
    }
}
Also used : InputStreamReader(java.io.InputStreamReader) InputStream(java.io.InputStream) IOException(java.io.IOException) Uri(android.net.Uri) FacebookException(com.facebook.FacebookException) IOException(java.io.IOException) URL(java.net.URL) Bitmap(android.graphics.Bitmap) HttpURLConnection(java.net.HttpURLConnection) FacebookException(com.facebook.FacebookException)

Example 17 with FacebookException

use of com.facebook.FacebookException in project facebook-android-sdk by facebook.

the class NativeAppCallAttachmentStore method addAttachments.

public static void addAttachments(Collection<Attachment> attachments) {
    if (attachments == null || attachments.size() == 0) {
        return;
    }
    // If this is the first time we've been instantiated, clean up any existing attachments.
    if (attachmentsDirectory == null) {
        cleanupAllAttachments();
    }
    ensureAttachmentsDirectoryExists();
    List<File> filesToCleanup = new ArrayList<>();
    try {
        for (Attachment attachment : attachments) {
            if (!attachment.shouldCreateFile) {
                continue;
            }
            File file = getAttachmentFile(attachment.callId, attachment.attachmentName, true);
            filesToCleanup.add(file);
            if (attachment.bitmap != null) {
                processAttachmentBitmap(attachment.bitmap, file);
            } else if (attachment.originalUri != null) {
                processAttachmentFile(attachment.originalUri, attachment.isContentUri, file);
            }
        }
    } catch (IOException exception) {
        Log.e(TAG, "Got unexpected exception:" + exception);
        for (File file : filesToCleanup) {
            try {
                file.delete();
            } catch (Exception e) {
            // Always try to delete other files.
            }
        }
        throw new FacebookException(exception);
    }
}
Also used : FacebookException(com.facebook.FacebookException) ArrayList(java.util.ArrayList) FacebookException(com.facebook.FacebookException)

Example 18 with FacebookException

use of com.facebook.FacebookException in project facebook-android-sdk by facebook.

the class DeviceAuthDialog method getPollRequest.

private GraphRequest getPollRequest() {
    Bundle parameters = new Bundle();
    parameters.putString("code", currentRequestState.getRequestCode());
    return new GraphRequest(null, DEVICE_LOGIN_STATUS_ENDPOINT, parameters, HttpMethod.POST, new GraphRequest.Callback() {

        @Override
        public void onCompleted(GraphResponse response) {
            // Check if the request was already cancelled
            if (completed.get()) {
                return;
            }
            FacebookRequestError error = response.getError();
            if (error != null) {
                // message text
                switch(error.getSubErrorCode()) {
                    case LOGIN_ERROR_SUBCODE_AUTHORIZATION_PENDING:
                    case LOGIN_ERROR_SUBCODE_EXCESSIVE_POLLING:
                        {
                            // Keep polling. If we got the slow down message just ignore
                            schedulePoll();
                        }
                        break;
                    case LOGIN_ERROR_SUBCODE_CODE_EXPIRED:
                    case LOGIN_ERROR_SUBCODE_AUTHORIZATION_DECLINED:
                        {
                            onCancel();
                        }
                        break;
                    default:
                        {
                            onError(response.getError().getException());
                        }
                        break;
                }
                return;
            }
            try {
                JSONObject resultObject = response.getJSONObject();
                onSuccess(resultObject.getString("access_token"));
            } catch (JSONException ex) {
                onError(new FacebookException(ex));
            }
        }
    });
}
Also used : GraphRequest(com.facebook.GraphRequest) JSONObject(org.json.JSONObject) GraphResponse(com.facebook.GraphResponse) Bundle(android.os.Bundle) FacebookException(com.facebook.FacebookException) JSONException(org.json.JSONException) FacebookRequestError(com.facebook.FacebookRequestError)

Example 19 with FacebookException

use of com.facebook.FacebookException in project facebook-android-sdk by facebook.

the class DeviceAuthDialog method onSuccess.

private void onSuccess(final String accessToken) {
    Bundle parameters = new Bundle();
    parameters.putString("fields", "id,permissions,name");
    AccessToken temporaryToken = new AccessToken(accessToken, FacebookSdk.getApplicationId(), "0", null, null, null, null, null);
    GraphRequest request = new GraphRequest(temporaryToken, "me", parameters, HttpMethod.GET, new GraphRequest.Callback() {

        @Override
        public void onCompleted(GraphResponse response) {
            if (completed.get()) {
                return;
            }
            if (response.getError() != null) {
                onError(response.getError().getException());
                return;
            }
            String userId;
            Utility.PermissionsPair permissions;
            String name;
            try {
                JSONObject jsonObject = response.getJSONObject();
                userId = jsonObject.getString("id");
                permissions = Utility.handlePermissionResponse(jsonObject);
                name = jsonObject.getString("name");
            } catch (JSONException ex) {
                onError(new FacebookException(ex));
                return;
            }
            DeviceRequestsHelper.cleanUpAdvertisementService(currentRequestState.getUserCode());
            boolean requireConfirm = FetchedAppSettingsManager.getAppSettingsWithoutQuery(FacebookSdk.getApplicationId()).getSmartLoginOptions().contains(SmartLoginOption.RequireConfirm);
            if (requireConfirm && !isRetry) {
                isRetry = true;
                presentConfirmation(userId, permissions, accessToken, name);
                return;
            }
            completeLogin(userId, permissions, accessToken);
        }
    });
    request.executeAsync();
}
Also used : GraphRequest(com.facebook.GraphRequest) JSONObject(org.json.JSONObject) GraphResponse(com.facebook.GraphResponse) Bundle(android.os.Bundle) AccessToken(com.facebook.AccessToken) FacebookException(com.facebook.FacebookException) JSONException(org.json.JSONException)

Example 20 with FacebookException

use of com.facebook.FacebookException in project facebook-android-sdk by facebook.

the class LoginClient method validateSameFbidAndFinish.

void validateSameFbidAndFinish(Result pendingResult) {
    if (pendingResult.token == null) {
        throw new FacebookException("Can't validate without a token");
    }
    AccessToken previousToken = AccessToken.getCurrentAccessToken();
    AccessToken newToken = pendingResult.token;
    try {
        Result result;
        if (previousToken != null && newToken != null && previousToken.getUserId().equals(newToken.getUserId())) {
            result = Result.createTokenResult(pendingRequest, pendingResult.token);
        } else {
            result = Result.createErrorResult(pendingRequest, "User logged in as different Facebook user.", null);
        }
        complete(result);
    } catch (Exception ex) {
        complete(Result.createErrorResult(pendingRequest, "Caught exception", ex.getMessage()));
    }
}
Also used : FacebookException(com.facebook.FacebookException) AccessToken(com.facebook.AccessToken) FacebookException(com.facebook.FacebookException) JSONException(org.json.JSONException)

Aggregations

FacebookException (com.facebook.FacebookException)70 Bundle (android.os.Bundle)24 JSONObject (org.json.JSONObject)24 JSONException (org.json.JSONException)19 Bitmap (android.graphics.Bitmap)13 GraphRequest (com.facebook.GraphRequest)10 JSONArray (org.json.JSONArray)10 Intent (android.content.Intent)9 Uri (android.net.Uri)8 GraphResponse (com.facebook.GraphResponse)8 URISyntaxException (java.net.URISyntaxException)8 AccessToken (com.facebook.AccessToken)7 FacebookOperationCanceledException (com.facebook.FacebookOperationCanceledException)5 FacebookRequestError (com.facebook.FacebookRequestError)5 LoginResult (com.facebook.login.LoginResult)5 IOException (java.io.IOException)5 InputStream (java.io.InputStream)5 InputStreamReader (java.io.InputStreamReader)5 HttpURLConnection (java.net.HttpURLConnection)5 URL (java.net.URL)5