Java 类com.facebook.FacebookRequestError 实例源码

项目:GodotFireBase    文件:FacebookSignIn.java   
public void revokePermission(final String permission) {
    AccessToken token = AccessToken.getCurrentAccessToken();

    String uri = "me/permissions/" + permission;

    GraphRequest graphRequest = GraphRequest.newDeleteObjectRequest(
    token, uri, new GraphRequest.Callback() {
        @Override
        public void onCompleted(GraphResponse response) {
            FacebookRequestError error = response.getError();
            if (error == null) {
                Utils.d("FB:Revoke:Response:" + response.toString());
                getPermissions();
            }
        }
    });

    graphRequest.executeAsync();
}
项目:GodotFireBase    文件:FacebookSignIn.java   
/** GraphRequest **/

    public void revokeAccess() {
        mAuth.signOut();

        AccessToken token = AccessToken.getCurrentAccessToken();
        GraphRequest graphRequest = GraphRequest.newDeleteObjectRequest(
        token, "me/permissions", new GraphRequest.Callback() {
            @Override
            public void onCompleted(GraphResponse response) {
                FacebookRequestError error = response.getError();
                if (error == null) {
                    Utils.d("FB:Delete:Access" + response.toString());
                }
            }
        });

        graphRequest.executeAsync();
    }
项目:GDFacebook    文件:FacebookSDK.java   
public void loadRequests() {
    AccessToken token = AccessToken.getCurrentAccessToken();

    GraphRequest myRequests = GraphRequest.newGraphPathRequest(
    token, "/me/apprequests", new GraphRequest.Callback() {
        @Override
        public void onCompleted(GraphResponse response) {
            FacebookRequestError error = response.getError();

            if (error == null) {
                JSONObject graphObject = response.getJSONObject();
                JSONArray data = graphObject.optJSONArray("data");

                Utils.callScriptFunc("pendingRequest", data.toString());
            } else { Utils.d("Response Error: " + error.toString()); }
        }
    });

    myRequests.executeAsync();
}
项目:GDFacebook    文件:FacebookSDK.java   
public static void deleteRequest (String requestId) {
    // delete Requets here GraphAPI.
    Utils.d("Deleting:Request:" + requestId);

    AccessToken token = AccessToken.getCurrentAccessToken();
    GraphRequest graphRequest = GraphRequest.newDeleteObjectRequest(
    token, requestId, new GraphRequest.Callback() {
        @Override
        public void onCompleted(GraphResponse response) {
            FacebookRequestError error = response.getError();
            if (error == null) { Utils.d("OnDelete:Req:" + response.toString()); }
        }
    });

    graphRequest.executeAsync();
}
项目:GDFacebook    文件:FacebookSDK.java   
public static void getUserDataFromRequest (String requestId) {
    // Grah Api to get user data from request.

    AccessToken token = AccessToken.getCurrentAccessToken();
    GraphRequest graphRequest = GraphRequest.newGraphPathRequest(
    token, requestId, new GraphRequest.Callback() {
        @Override
        public void onCompleted(GraphResponse response) {
            FacebookRequestError error = response.getError();

            if (error == null) { Utils.d("Response: " + response.toString()); }
            else { Utils.d("Error: " + response.toString()); }
        }
    });

    graphRequest.executeAsync();
}
项目:EmbeddedSocial-Android-SDK    文件:FacebookFriendlistLoader.java   
@Override
public List<String> getThirdPartyFriendIds() throws SocialNetworkException {
    if (!isAuthorizedToSocialNetwork()) {
        throw new NotAuthorizedToSocialNetworkException();
    }
    GraphResponse response = new GraphRequest(
        facebookTokenHolder.getToken(),
        FACEBOOK_FRIENDS_GRAPH_PATH,
        Bundle.EMPTY,
        HttpMethod.GET
    ).executeAndWait();

    facebookTokenHolder.clearToken();

    FacebookRequestError responseError = response.getError();
    if (responseError != null) {
        throw new SocialNetworkException("Internal facebook failure: "
            + responseError.getErrorMessage() + " [" + responseError.getErrorCode() + "]");
    }

    return extractFacebookFriendIds(response);
}
项目:ReactiveFB    文件:RequestAction.java   
@Override
public void onCompleted(GraphResponse response) {
    FacebookRequestError error = response.getError();
    if (error != null) {
        Logger.logError(RequestAction.class,
                "Failed to get what you have requested", error.getException());

        if (mSingleEmitter != null) {
            mSingleEmitter.onError(error.getException());
        }
    } else {
        if (response.getRawResponse() == null) {
            Logger.logError(RequestAction.class, "The response GraphObject " +
                    "has null value. Response=" + response.toString(), null);
            mSingleEmitter.onError(new FacebookGraphResponseException(response,
                    "The response has null value"));
        } else {
            if (mSingleEmitter != null) {
                mSingleEmitter.onSuccess(response);
            }
        }
    }
}
项目:yelo-android    文件:GraphObjectPagingLoader.java   
private void requestCompleted(Response response) {
    Request request = response.getRequest();
    if (request != currentRequest) {
        return;
    }

    loading = false;
    currentRequest = null;

    FacebookRequestError requestError = response.getError();
    FacebookException exception = (requestError == null) ? null : requestError.getException();
    if (response.getGraphObject() == null && exception == null) {
        exception = new FacebookException("GraphObjectPagingLoader received neither a result nor an error.");
    }

    if (exception != null) {
        nextRequest = null;

        if (onErrorListener != null) {
            onErrorListener.onError(exception, this);
        }
    } else {
        addResults(response);
    }
}
项目:TP-Formation-Android    文件:TestFacebookActivity.java   
private void showPublishResult(String message, GraphObject result, FacebookRequestError error) {
    String title = null;
    String alertMessage = null;
    if (error == null) {
        title = getString(R.string.success);
        alertMessage = getString(R.string.successfully_posted_post, message);
    } else {
        title = getString(R.string.error);
        alertMessage = error.getErrorMessage();
    }

    new AlertDialog.Builder(this)
            .setTitle(title)
            .setMessage(alertMessage)
            .setPositiveButton(R.string.ok, null)
            .show();
}
项目:QuizUpWinner    文件:GraphObjectPagingLoader.java   
private void requestCompleted(Response paramResponse)
{
  if (paramResponse.getRequest() != this.currentRequest)
    return;
  this.loading = false;
  this.currentRequest = null;
  FacebookRequestError localFacebookRequestError = paramResponse.getError();
  FacebookException localFacebookException;
  if (localFacebookRequestError == null)
    localFacebookException = null;
  else
    localFacebookException = localFacebookRequestError.getException();
  if ((paramResponse.getGraphObject() == null) && (localFacebookException == null))
    localFacebookException = new FacebookException("GraphObjectPagingLoader received neither a result nor an error.");
  if (localFacebookException != null)
  {
    this.nextRequest = null;
    if (this.onErrorListener != null)
      this.onErrorListener.onError(localFacebookException, this);
  }
  else
  {
    addResults(paramResponse);
  }
}
项目:p2psafety    文件:GraphObjectPagingLoader.java   
private void requestCompleted(Response response) {
    Request request = response.getRequest();
    if (request != currentRequest) {
        return;
    }

    loading = false;
    currentRequest = null;

    FacebookRequestError requestError = response.getError();
    FacebookException exception = (requestError == null) ? null : requestError.getException();
    if (response.getGraphObject() == null && exception == null) {
        exception = new FacebookException("GraphObjectPagingLoader received neither a result nor an error.");
    }

    if (exception != null) {
        nextRequest = null;

        if (onErrorListener != null) {
            onErrorListener.onError(exception, this);
        }
    } else {
        addResults(response);
    }
}
项目:HereAStory-Android    文件:LoginActivity.java   
private void saveFacebookInfo() {       
    Request request = Request.newMeRequest(ParseFacebookUtils.getSession(), new Request.GraphUserCallback() {
        @Override
        public void onCompleted(GraphUser graphUser, Response response) {
            if (graphUser != null) {
                new DownloadProfilePictureTask().execute(new String[] { graphUser.getId(), graphUser.getName() });
            } else if (response.getError() != null) {
                if ((response.getError().getCategory() == FacebookRequestError.Category.AUTHENTICATION_RETRY)
                        || (response.getError().getCategory() == FacebookRequestError.Category.AUTHENTICATION_REOPEN_SESSION)) {
                    Log.d(LOG_TAG, "The facebook session was invalidated.");
                } else {
                    Log.e(LOG_TAG, "Some other error: " + response.getError().getErrorMessage());
                }
            }
        }

    });
    request.executeAsync();
}
项目:kognitivo    文件:ShareInternalUtility.java   
public static void invokeCallbackWithResults(
        FacebookCallback<Sharer.Result> callback,
        final String postId,
        final GraphResponse graphResponse) {
    FacebookRequestError requestError = graphResponse.getError();
    if (requestError != null) {
        String errorMessage = requestError.getErrorMessage();
        if (Utility.isNullOrEmpty(errorMessage)) {
            errorMessage = "Unexpected error sharing.";
        }
        invokeOnErrorCallback(callback, graphResponse, errorMessage);
    } else {
        invokeOnSuccessCallback(callback, postId);
    }
}
项目:kognitivo    文件:VideoUploader.java   
protected void executeGraphRequestSynchronously(Bundle parameters) {
    GraphRequest request = new GraphRequest(
            uploadContext.accessToken,
            String.format(Locale.ROOT, "%s/videos", uploadContext.graphNode),
            parameters,
            HttpMethod.POST,
            null);
    GraphResponse response = request.executeAndWait();

    if (response != null) {
        FacebookRequestError error = response.getError();
        JSONObject responseJSON = response.getJSONObject();
        if (error != null) {
            if (!attemptRetry(error.getSubErrorCode())) {
                handleError(new FacebookGraphResponseException(response, ERROR_UPLOAD));
            }
        } else if (responseJSON != null) {
            try {
                handleSuccess(responseJSON);
            } catch (JSONException e) {
                endUploadWithFailure(new FacebookException(ERROR_BAD_SERVER_RESPONSE, e));
            }
        } else {
            handleError(new FacebookException(ERROR_BAD_SERVER_RESPONSE));
        }
    } else {
        handleError(new FacebookException(ERROR_BAD_SERVER_RESPONSE));
    }
}
项目:kognitivo    文件:FacebookRequestErrorClassification.java   
public String getRecoveryMessage(FacebookRequestError.Category category) {
    switch (category) {
        case OTHER:
            return otherRecoveryMessage;
        case LOGIN_RECOVERABLE:
            return loginRecoverableRecoveryMessage;
        case TRANSIENT:
            return transientRecoveryMessage;
        default:
            return null;
    }
}
项目:CustomAndroidOneSheeld    文件:FacebookShield.java   
private void publishStory(final String message) {

        if (AccessToken.getCurrentAccessToken() != null) {

            Bundle postParams = new Bundle();
            postParams.putString("message", message);
            GraphRequest.Callback callback = new GraphRequest.Callback() {
                @Override
                public void onCompleted(GraphResponse graphResponse) {
                    FacebookRequestError error = graphResponse.getError();
                    if (error != null) {
                        if (eventHandler != null) {
                            Log.sysOut("$#$#$ " + error);
                            eventHandler.stopProgress();
                            eventHandler.onFacebookError(error
                                    .getErrorMessage());
                        }
                        return;
                    }
                    if (eventHandler != null) {
                        eventHandler.stopProgress();
                        eventHandler.onRecievePost(message);
                    }
                }
            };

            GraphRequest request = new GraphRequest(AccessToken.getCurrentAccessToken(), "feed", postParams,
                    HttpMethod.POST, callback);

            request.executeAsync();
        } else if (eventHandler != null) eventHandler.onFacebookError(activity.getString(R.string.facebook_you_must_login_first_toast));

    }
项目:Popdeem-SDK-Android    文件:PDUITagFriendsFragment.java   
private void makeTaggableFriendsRequest() {
        Bundle parameters = new Bundle();
        parameters.putString("limit", "5000");
        GraphRequest taggableFriendsRequest = GraphRequest.newGraphPathRequest(AccessToken.getCurrentAccessToken(),
                "/me/taggable_friends",
                new GraphRequest.Callback() {
                    @Override
                    public void onCompleted(GraphResponse graphResponse) {
                        FacebookRequestError error = graphResponse.getError();
                        if (error != null) {
//                            DialogUtils.showBasicDialog(ClaimActivity.this, error.getErrorUserTitle(), error.getErrorUserMessage(),
//                                    android.R.string.ok, 0, null, null);
                        } else {
                            JsonParser parser = new JsonParser();
                            JsonElement json = parser.parse(graphResponse.getJSONObject().toString());
                            if (json.getAsJsonObject().has("data")) {
                                Type type = new TypeToken<ArrayList<PDSocialMediaFriend>>() {
                                }.getType();

                                Gson gson = new GsonBuilder()
                                        .registerTypeAdapter(type, new PDSocialMediaFriendsDeserializer())
                                        .create();

                                ArrayList<PDSocialMediaFriend> friends = gson.fromJson(json, type);
                                updateTaggableFriends(friends);
                            }
                            PDLog.d(PDUITagFriendsFragment.class, "friends: " + json.toString());
                        }
                    }
                });
        taggableFriendsRequest.setParameters(parameters);
        taggableFriendsRequest.executeAsync();
    }
项目:1Sheeld-Android-App    文件:FacebookShield.java   
private void publishStory(final String message) {

        if (AccessToken.getCurrentAccessToken() != null) {

            Bundle postParams = new Bundle();
            postParams.putString("message", message);
            GraphRequest.Callback callback = new GraphRequest.Callback() {
                @Override
                public void onCompleted(GraphResponse graphResponse) {
                    FacebookRequestError error = graphResponse.getError();
                    if (error != null) {
                        if (eventHandler != null) {
                            Log.sysOut("$#$#$ " + error);
                            eventHandler.stopProgress();
                            eventHandler.onFacebookError(error
                                    .getErrorMessage());
                        }
                        return;
                    }
                    if (eventHandler != null) {
                        eventHandler.stopProgress();
                        eventHandler.onRecievePost(message);
                    }
                }
            };

            GraphRequest request = new GraphRequest(AccessToken.getCurrentAccessToken(), "feed", postParams,
                    HttpMethod.POST, callback);

            request.executeAsync();
        } else if (eventHandler != null) eventHandler.onFacebookError(activity.getString(R.string.facebook_you_must_login_first_toast));

    }
项目:Move-Alarm_ORCA    文件:ShareInternalUtility.java   
public static void invokeCallbackWithResults(
        FacebookCallback<Sharer.Result> callback,
        final String postId,
        final GraphResponse graphResponse) {
    FacebookRequestError requestError = graphResponse.getError();
    if (requestError != null) {
        String errorMessage = requestError.getErrorMessage();
        if (Utility.isNullOrEmpty(errorMessage)) {
            errorMessage = "Unexpected error sharing.";
        }
        invokeOnErrorCallback(callback, graphResponse, errorMessage);
    } else {
        invokeOnSuccessCallback(callback, postId);
    }
}
项目:Move-Alarm_ORCA    文件:FacebookRequestErrorClassification.java   
public String getRecoveryMessage(FacebookRequestError.Category category) {
    switch (category) {
        case OTHER:
            return otherRecoveryMessage;
        case LOGIN_RECOVERABLE:
            return loginRecoverableRecoveryMessage;
        case TRANSIENT:
            return transientRecoveryMessage;
        default:
            return null;
    }
}
项目:edx-app-android    文件:FacebookProvider.java   
/**
 * returns true if there was an error. The callback will be notified
 */
private boolean notifyIfError(Response response, Callback callback) {
    if (response.getError() != null) {
        FacebookRequestError error = response.getError();
        callback.onError(new SocialError(error.getException()));
        return true;
    }
    return false;
}
项目:SocioBlood    文件:ShareInternalUtility.java   
public static void invokeCallbackWithResults(
        FacebookCallback<Sharer.Result> callback,
        final String postId,
        final GraphResponse graphResponse) {
    FacebookRequestError requestError = graphResponse.getError();
    if (requestError != null) {
        String errorMessage = requestError.getErrorMessage();
        if (Utility.isNullOrEmpty(errorMessage)) {
            errorMessage = "Unexpected error sharing.";
        }
        invokeOnErrorCallback(callback, graphResponse, errorMessage);
    } else {
        invokeOnSuccessCallback(callback, postId);
    }
}
项目:SocioBlood    文件:VideoUploader.java   
protected void executeGraphRequestSynchronously(Bundle parameters) {
    GraphRequest request = new GraphRequest(
            uploadContext.accessToken,
            String.format(Locale.ROOT, "%s/videos", uploadContext.targetId),
            parameters,
            HttpMethod.POST,
            null);
    GraphResponse response = request.executeAndWait();

    if (response != null) {
        FacebookRequestError error = response.getError();
        JSONObject responseJSON = response.getJSONObject();
        if (error != null) {
            if (!attemptRetry(error.getSubErrorCode())) {
                handleError(new FacebookGraphResponseException(response, ERROR_UPLOAD));
            }
        } else if (responseJSON != null) {
            try {
                handleSuccess(responseJSON);
            } catch (JSONException e) {
                endUploadWithFailure(new FacebookException(ERROR_BAD_SERVER_RESPONSE, e));
            }
        } else {
            handleError(new FacebookException(ERROR_BAD_SERVER_RESPONSE));
        }
    } else {
        handleError(new FacebookException(ERROR_BAD_SERVER_RESPONSE));
    }
}
项目:SocioBlood    文件:FacebookRequestErrorClassification.java   
public String getRecoveryMessage(FacebookRequestError.Category category) {
    switch (category) {
        case OTHER:
            return otherRecoveryMessage;
        case LOGIN_RECOVERABLE:
            return loginRecoverableRecoveryMessage;
        case TRANSIENT:
            return transientRecoveryMessage;
        default:
            return null;
    }
}
项目:vocefiscal-android    文件:FiscalizacaoConcluidaActivity.java   
private void publishStory(Session session) 
{
    Bundle postParams = new Bundle();
    postParams.putString("name", "Você Fiscal");

    // Receber os dados da eleição!!!
    postParams.putString("message", "Eu fiscalizei a seção: "+ this.secao +"\nNa zona eleitoral: " + this.zonaEleitoral + "\nNo município de: " + this.municipio);          
    postParams.putString("description", "Obrigado por contribuir com a democracia!");
    postParams.putString("link", "http://www.vocefiscal.org/");
    postParams.putString("picture", "http://imagizer.imageshack.us/v2/150x100q90/913/bAwPgx.png");

    Request.Callback callback= new Request.Callback() 
    {
        public void onCompleted(Response response) 
        {
            JSONObject graphResponse = response.getGraphObject().getInnerJSONObject();
            String postId = "Compartilhado com sucesso!";
            try 
            {
                postId = graphResponse.getString("Compartilhado com sucesso!");
            } catch (JSONException e) 
            {
            }
            FacebookRequestError error = response.getError();
            if (error != null) 
            {
                Toast.makeText(FiscalizacaoConcluidaActivity.this.getApplicationContext(),error.getErrorMessage(),Toast.LENGTH_SHORT).show();
            } else 
            {
                Toast.makeText(FiscalizacaoConcluidaActivity.this.getApplicationContext(),  postId, Toast.LENGTH_LONG).show();
            }
        }
    };

    Request request = new Request(session, "me/feed", postParams, HttpMethod.POST, callback);

    RequestAsyncTask task = new RequestAsyncTask(request);
    task.execute();
}
项目:openkit-android    文件:OKSocialLeaderboardFragment.java   
private void getSocialScoresFromOpenKit()
{
    if(FacebookUtilities.isFBSessionOpen())
    {
        startedSocialRequest();

        FacebookUtilities.GetFBFriends(new GetFBFriendsRequestHandler() {

            @Override
            public void onSuccess(ArrayList<Long> friendsArray) {
                currentLeaderboard.getFacebookFriendsScoresWithFacebookFriends(friendsArray, new OKScoresResponseHandler() {

                    @Override
                    public void onSuccess(List<OKScore> scoresList) {
                        OKLog.v("Got %d social scores!", scoresList.size());
                        addScoresToSocialScoresListAdapater(scoresList);
                        stoppedSocialRequest();
                    }

                    @Override
                    public void onFailure(Throwable e, JSONObject errorResponse) {
                        OKLog.v("Failed to get social scores from OpenKit: " + e);
                        stoppedSocialRequest();
                    }
                });
            }

            @Override
            public void onFail(FacebookRequestError error) {
                OKLog.v("Failed to get Facebook friends");
                stoppedSocialRequest();
            }
        });
    }
}
项目:openkit-android    文件:UnityPlugin.java   
public static void getFacebookFriendsList(final String gameObjectName)
{
    OKBridgeLog("getFBFriends");

    UnityPlayer.currentActivity.runOnUiThread(new Runnable() {
        @Override
        public void run() {

            FacebookUtilities.GetFBFriends(new FacebookUtilities.GetFBFriendsRequestHandler() {
                @Override
                public void onSuccess(ArrayList<Long> friendsArray) {
                    OKBridgeLog("getFBFriends success");
                    String friendsList = FacebookUtilities.getSerializedListOfFBFriends(friendsArray);
                    UnityPlayer.UnitySendMessage(gameObjectName, ASYNC_CALL_SUCCEEDED, friendsList);
                }

                @Override
                public void onFail(FacebookRequestError error) {
                    OKBridgeLog("getFBFriends fail");
                    if(error != null){
                        UnityPlayer.UnitySendMessage(gameObjectName, ASYNC_CALL_FAILED, error.getErrorMessage());
                    } else {
                        UnityPlayer.UnitySendMessage(gameObjectName, ASYNC_CALL_FAILED, "Unknown error when trying to get friends from Android native");
                    }
                }
            });

        }
    });
}
项目:openkit-android    文件:ScoreCreator.java   
public static void CreateFriendsScores(int aNumScores, int aLeaderboardID, int maxScoreValue)
{
    final int numScores = aNumScores;
    final int leaderboardID = aLeaderboardID;

    OKLog.d("Getting list of FB friends");

    Session session = Session.getActiveSession();

    if(session != null && session.isOpened())
    {
        Request friendsRequest = Request.newMyFriendsRequest(session, new GraphUserListCallback() {

            @Override
            public void onCompleted(List<GraphUser> users, Response response) {
                FacebookRequestError error = response.getError();

                if(error != null) {
                    OKLog.d("Error getting Facebook friends");
                } else {
                    OKLog.d("Got %d facebook friends", users.size());


                    Random generator = new Random();

                    for(int x = 0; x < numScores; x++) {

                        int friendIndex = generator.nextInt(users.size());
                        CreateFriendScore(users.get(friendIndex), leaderboardID, x);
                    }

                }
            }
        });

        friendsRequest.executeAsync();
    } else {
        OKLog.v("FB session not open");
    }
}
项目:kognitivo    文件:WebViewLoginMethodHandler.java   
void onWebDialogComplete(LoginClient.Request request, Bundle values,
        FacebookException error) {
    LoginClient.Result outcome;
    if (values != null) {
        // Actual e2e we got from the dialog should be used for logging.
        if (values.containsKey(ServerProtocol.DIALOG_PARAM_E2E)) {
            e2e = values.getString(ServerProtocol.DIALOG_PARAM_E2E);
        }

        try {
            AccessToken token = createAccessTokenFromWebBundle(
                    request.getPermissions(),
                    values,
                    AccessTokenSource.WEB_VIEW,
                    request.getApplicationId());
            outcome = LoginClient.Result.createTokenResult(
                    loginClient.getPendingRequest(),
                    token);

            // Ensure any cookies set by the dialog are saved
            // This is to work around a bug where CookieManager may fail to instantiate if
            // CookieSyncManager has never been created.
            CookieSyncManager syncManager =
                    CookieSyncManager.createInstance(loginClient.getActivity());
            syncManager.sync();
            saveCookieToken(token.getToken());
        } catch (FacebookException ex) {
            outcome = LoginClient.Result.createErrorResult(
                    loginClient.getPendingRequest(),
                    null,
                    ex.getMessage());
        }
    } else {
        if (error instanceof FacebookOperationCanceledException) {
            outcome = LoginClient.Result.createCancelResult(loginClient.getPendingRequest(),
                    "User canceled log in.");
        } else {
            // Something went wrong, don't log a completion event since it will skew timing
            // results.
            e2e = null;

            String errorCode = null;
            String errorMessage = error.getMessage();
            if (error instanceof FacebookServiceException) {
                FacebookRequestError requestError =
                        ((FacebookServiceException)error).getRequestError();
                errorCode = String.format(Locale.ROOT, "%d", requestError.getErrorCode());
                errorMessage = requestError.toString();
            }
            outcome = LoginClient.Result.createErrorResult(loginClient.getPendingRequest(),
                    null, errorMessage, errorCode);
        }
    }

    if (!Utility.isNullOrEmpty(e2e)) {
        logWebLoginCompleted(e2e);
    }

    loginClient.completeAndValidate(outcome);
}
项目:kognitivo    文件:AppEventsLogger.java   
private static void handleResponse(
        AccessTokenAppIdPair accessTokenAppId,
        GraphRequest request,
        GraphResponse response,
        SessionEventsState sessionEventsState,
        FlushStatistics flushState) {
    FacebookRequestError error = response.getError();
    String resultDescription = "Success";

    FlushResult flushResult = FlushResult.SUCCESS;

    if (error != null) {
        final int NO_CONNECTIVITY_ERROR_CODE = -1;
        if (error.getErrorCode() == NO_CONNECTIVITY_ERROR_CODE) {
            resultDescription = "Failed: No Connectivity";
            flushResult = FlushResult.NO_CONNECTIVITY;
        } else {
            resultDescription = String.format("Failed:\n  Response: %s\n  Error %s",
                    response.toString(),
                    error.toString());
            flushResult = FlushResult.SERVER_ERROR;
        }
    }

    if (FacebookSdk.isLoggingBehaviorEnabled(LoggingBehavior.APP_EVENTS)) {
        String eventsJsonString = (String) request.getTag();
        String prettyPrintedEvents;

        try {
            JSONArray jsonArray = new JSONArray(eventsJsonString);
            prettyPrintedEvents = jsonArray.toString(2);
        } catch (JSONException exc) {
            prettyPrintedEvents = "<Can't encode events for debug logging>";
        }

        Logger.log(LoggingBehavior.APP_EVENTS, TAG,
                "Flush completed\nParams: %s\n  Result: %s\n  Events JSON: %s",
                request.getGraphObject().toString(),
                resultDescription,
                prettyPrintedEvents);
    }

    sessionEventsState.clearInFlightAndStats(error != null);

    if (flushResult == FlushResult.NO_CONNECTIVITY) {
        // We may call this for multiple requests in a batch, which is slightly inefficient
        // since in principle we could call it once for all failed requests, but the impact is
        // likely to be minimal. We don't call this for other server errors, because if an event
        // failed because it was malformed, etc., continually retrying it will cause subsequent
        // events to not be logged either.
        PersistedEvents.persistEvents(applicationContext, accessTokenAppId, sessionEventsState);
    }

    if (flushResult != FlushResult.SUCCESS) {
        // We assume that connectivity issues are more significant to report than server issues.
        if (flushState.result != FlushResult.NO_CONNECTIVITY) {
            flushState.result = flushResult;
        }
    }
}
项目:AndroidBackendlessChat    文件:BFacebookManager.java   
/** Does not work if your app dosent have facebook game app privileges.*/
public static Promise<List<JSONObject>, BError, Void> getInvitableFriendsList(){

    final Deferred<List<JSONObject>, BError, Void> deferred = new DeferredObject<>();

    final Session session = Session.getActiveSession();
    if (session != null && session.isOpened()) {

        // Get a list of friends who have _not installed_ the game.
        Request invitableFriendsRequest = Request.newGraphPathRequest(session,
                "/me/invitable_friends", new Request.Callback() {

                    @Override
                    public void onCompleted(Response response) {

                        FacebookRequestError error = response.getError();
                        if (error != null) {
                            if (DEBUG) Timber.e(error.toString());
                            deferred.reject(new BError(BError.Code.TAGGED, "Error while fetching invitable friends.", error));
                        } else if (session == Session.getActiveSession()) {
                            if (response != null) {
                                // Get the result
                                GraphObject graphObject = response.getGraphObject();
                                JSONArray dataArray = (JSONArray)graphObject.getProperty("data");

                                List<JSONObject> invitableFriends = new ArrayList<JSONObject>();
                                if (dataArray.length() > 0) {
                                    // Ensure the user has at least one friend ...

                                    for (int i=0; i<dataArray.length(); i++) {
                                        invitableFriends.add(dataArray.optJSONObject(i));
                                    }
                                }
                                deferred.resolve(invitableFriends);
                            }
                        }
                    }

                });

        Bundle invitableParams = new Bundle();
        invitableParams.putString("fields", "id,first_name,picture");
        invitableFriendsRequest.setParameters(invitableParams);
        invitableFriendsRequest.executeAsync();
    }
    else
    {
        if (DEBUG) Timber.d("Session is closed");
        deferred.reject(new BError(BError.Code.SESSION_CLOSED));
    }

    return deferred.promise();

}
项目:GDFacebook    文件:FacebookSDK.java   
public void loadTopScore() {
        AccessToken token = AccessToken.getCurrentAccessToken();

        GraphRequest graphRequest = GraphRequest.newGraphPathRequest(
        token, "/" + APP_ID + "/scores?fields=score&limit=20",
        new GraphRequest.Callback() {
            @Override
            public void onCompleted(GraphResponse response) {
                FacebookRequestError error = response.getError();

                Utils.d("Resonce:Top:Scores: " + response.toString());

                if (error == null) {
                    JSONArray ret = new JSONArray();
                    JSONArray data = response.getJSONObject().optJSONArray("data");
                    for (int i = 0; i < data.length(); i++) {
                        JSONObject jobj = data.optJSONObject(i);
                        JSONObject user = jobj.optJSONObject("user");

                        Utils.d("USER:Data:" + user.toString());

                        int score = jobj.optInt("score");
                        String userName = user.optString("name");

                        JSONObject retObj = new JSONObject();
                        try {
                            retObj.put("score", score);
                            retObj.put("name", userName);
                        } catch(JSONException e) {
                            Utils.d("Loading:Scores:exception");
                        }

                        Utils.d("Adding:User:" + userName);
                        ret.put(retObj);
                    }

                    Utils.callScriptFunc("topScoresList", ret.toString());
                }
            }
        });

//      Bundle params = graphRequest.getParameters();
//      params.putString(PARAM_FIELDS, "name,first_name,score");
//      graphRequest.setParameters(params);

        graphRequest.executeAsync();
    }
项目:chat-sdk-android-push-firebase    文件:BFacebookManager.java   
/** Does not work if your app dosent have facebook game app privileges.*/
public static Promise<List<JSONObject>, BError, Void> getInvitableFriendsList(){

    final Deferred<List<JSONObject>, BError, Void> deferred = new DeferredObject<>();

    final Session session = Session.getActiveSession();
    if (session != null && session.isOpened()) {

        // Get a list of friends who have _not installed_ the game.
        Request invitableFriendsRequest = Request.newGraphPathRequest(session,
                "/me/invitable_friends", new Request.Callback() {

                    @Override
                    public void onCompleted(Response response) {

                        FacebookRequestError error = response.getError();
                        if (error != null) {
                            if (DEBUG) Timber.e(error.toString());
                            deferred.reject(new BError(BError.Code.TAGGED, "Error while fetching invitable friends.", error));
                        } else if (session == Session.getActiveSession()) {
                            if (response != null) {
                                // Get the result
                                GraphObject graphObject = response.getGraphObject();
                                JSONArray dataArray = (JSONArray)graphObject.getProperty("data");

                                List<JSONObject> invitableFriends = new ArrayList<JSONObject>();
                                if (dataArray.length() > 0) {
                                    // Ensure the user has at least one friend ...

                                    for (int i=0; i<dataArray.length(); i++) {
                                        invitableFriends.add(dataArray.optJSONObject(i));
                                    }
                                }
                                deferred.resolve(invitableFriends);
                            }
                        }
                    }

                });

        Bundle invitableParams = new Bundle();
        invitableParams.putString("fields", "id,first_name,picture");
        invitableFriendsRequest.setParameters(invitableParams);
        invitableFriendsRequest.executeAsync();
    }
    else
    {
        if (DEBUG) Timber.d("Session is closed");
        deferred.reject(new BError(BError.Code.SESSION_CLOSED));
    }

    return deferred.promise();

}
项目:CustomAndroidOneSheeld    文件:FacebookShield.java   
public void uploadImage(final String path, final String msg) {
    new AsyncTask<Void, Void, Void>() {
        byte[] data = null;
        Bitmap bi;

        @Override
        protected Void doInBackground(Void... params) {
            int rotate = ImageUtils.getCameraPhotoOrientation(path);
            bi = ImageUtils.decodeFile(new File(path), 1024);
            Matrix matrix = new Matrix();
            matrix.postRotate(rotate);
            bi = Bitmap.createBitmap(bi, 0, 0, bi.getWidth(),
                    bi.getHeight(), matrix, true);
            return null;
        }

        @Override
        protected void onPostExecute(final Void result1) {

            if (AccessToken.getCurrentAccessToken() != null) {
                ByteArrayOutputStream baos = new ByteArrayOutputStream();
                if (bi != null) {
                    bi.compress(Bitmap.CompressFormat.JPEG, 100, baos);
                    bi.recycle();
                }
                data = baos.toByteArray();
                Bundle postParams = new Bundle();
                postParams.putString("message", msg);
                postParams.putByteArray("source", data);
                GraphRequest.Callback callback = new GraphRequest.Callback() {
                    public void onCompleted(GraphResponse response) {
                        FacebookRequestError error = response.getError();
                        if (error != null) {
                            if (eventHandler != null) {
                                Log.sysOut("$#$#$ " + error);
                                eventHandler.onFacebookError(error
                                        .getErrorMessage());
                                eventHandler.stopProgress();
                            }
                            return;
                        }
                        data = null;
                        if (bi != null)
                            bi.recycle();
                        System.gc();
                        if (eventHandler != null) {
                            eventHandler.stopProgress();
                            Toast.makeText(activity, R.string.facebook_image_uploaded,
                                    Toast.LENGTH_SHORT).show();
                            eventHandler.onRecievePost(msg);
                        }
                    }
                };
                Toast.makeText(activity, R.string.facebook_uploading_your_image,
                        Toast.LENGTH_SHORT).show();
                GraphRequest request = new GraphRequest(AccessToken.getCurrentAccessToken(), "me/photos",
                        postParams, HttpMethod.POST, callback);

                request.executeAsync();
            } else {
                if (bi != null)
                    bi.recycle();
            }
            super.onPostExecute(result1);
        }
    }.execute(null, null);
}
项目:1Sheeld-Android-App    文件:FacebookShield.java   
public void uploadImage(final String path, final String msg) {
    new AsyncTask<Void, Void, Void>() {
        byte[] data = null;
        Bitmap bi;

        @Override
        protected Void doInBackground(Void... params) {
            int rotate = ImageUtils.getCameraPhotoOrientation(path);
            bi = ImageUtils.decodeFile(new File(path), 1024);
            Matrix matrix = new Matrix();
            matrix.postRotate(rotate);
            bi = Bitmap.createBitmap(bi, 0, 0, bi.getWidth(),
                    bi.getHeight(), matrix, true);
            return null;
        }

        @Override
        protected void onPostExecute(final Void result1) {

            if (AccessToken.getCurrentAccessToken() != null) {
                ByteArrayOutputStream baos = new ByteArrayOutputStream();
                if (bi != null) {
                    bi.compress(Bitmap.CompressFormat.JPEG, 100, baos);
                    bi.recycle();
                }
                data = baos.toByteArray();
                Bundle postParams = new Bundle();
                postParams.putString("message", msg);
                postParams.putByteArray("source", data);
                GraphRequest.Callback callback = new GraphRequest.Callback() {
                    public void onCompleted(GraphResponse response) {
                        FacebookRequestError error = response.getError();
                        if (error != null) {
                            if (eventHandler != null) {
                                Log.sysOut("$#$#$ " + error);
                                eventHandler.onFacebookError(error
                                        .getErrorMessage());
                                eventHandler.stopProgress();
                            }
                            return;
                        }
                        data = null;
                        if (bi != null)
                            bi.recycle();
                        System.gc();
                        if (eventHandler != null) {
                            eventHandler.stopProgress();
                            Toast.makeText(activity, R.string.facebook_image_uploaded,
                                    Toast.LENGTH_SHORT).show();
                            eventHandler.onRecievePost(msg);
                        }
                    }
                };
                Toast.makeText(activity, R.string.facebook_uploading_your_image,
                        Toast.LENGTH_SHORT).show();
                GraphRequest request = new GraphRequest(AccessToken.getCurrentAccessToken(), "me/photos",
                        postParams, HttpMethod.POST, callback);

                request.executeAsync();
            } else {
                if (bi != null)
                    bi.recycle();
            }
            super.onPostExecute(result1);
        }
    }.execute(null, null);
}
项目:Move-Alarm_ORCA    文件:WebViewLoginMethodHandler.java   
void onWebDialogComplete(LoginClient.Request request, Bundle values,
        FacebookException error) {
    LoginClient.Result outcome;
    if (values != null) {
        // Actual e2e we got from the dialog should be used for logging.
        if (values.containsKey(ServerProtocol.DIALOG_PARAM_E2E)) {
            e2e = values.getString(ServerProtocol.DIALOG_PARAM_E2E);
        }

        try {
            AccessToken token = createAccessTokenFromWebBundle(
                    request.getPermissions(),
                    values,
                    AccessTokenSource.WEB_VIEW,
                    request.getApplicationId());
            outcome = LoginClient.Result.createTokenResult(
                    loginClient.getPendingRequest(),
                    token);

            // Ensure any cookies set by the dialog are saved
            // This is to work around a bug where CookieManager may fail to instantiate if
            // CookieSyncManager has never been created.
            CookieSyncManager syncManager =
                    CookieSyncManager.createInstance(loginClient.getActivity());
            syncManager.sync();
            saveCookieToken(token.getToken());
        } catch (FacebookException ex) {
            outcome = LoginClient.Result.createErrorResult(
                    loginClient.getPendingRequest(),
                    null,
                    ex.getMessage());
        }
    } else {
        if (error instanceof FacebookOperationCanceledException) {
            outcome = LoginClient.Result.createCancelResult(loginClient.getPendingRequest(),
                    "User canceled log in.");
        } else {
            // Something went wrong, don't log a completion event since it will skew timing
            // results.
            e2e = null;

            String errorCode = null;
            String errorMessage = error.getMessage();
            if (error instanceof FacebookServiceException) {
                FacebookRequestError requestError =
                        ((FacebookServiceException)error).getRequestError();
                errorCode = String.format(Locale.ROOT, "%d", requestError.getErrorCode());
                errorMessage = requestError.toString();
            }
            outcome = LoginClient.Result.createErrorResult(loginClient.getPendingRequest(),
                    null, errorMessage, errorCode);
        }
    }

    if (!Utility.isNullOrEmpty(e2e)) {
        logWebLoginCompleted(e2e);
    }

    loginClient.completeAndValidate(outcome);
}
项目:Move-Alarm_ORCA    文件:AppEventsLogger.java   
private static void handleResponse(
        AccessTokenAppIdPair accessTokenAppId,
        GraphRequest request,
        GraphResponse response,
        SessionEventsState sessionEventsState,
        FlushStatistics flushState) {
    FacebookRequestError error = response.getError();
    String resultDescription = "Success";

    FlushResult flushResult = FlushResult.SUCCESS;

    if (error != null) {
        final int NO_CONNECTIVITY_ERROR_CODE = -1;
        if (error.getErrorCode() == NO_CONNECTIVITY_ERROR_CODE) {
            resultDescription = "Failed: No Connectivity";
            flushResult = FlushResult.NO_CONNECTIVITY;
        } else {
            resultDescription = String.format("Failed:\n  Response: %s\n  Error %s",
                    response.toString(),
                    error.toString());
            flushResult = FlushResult.SERVER_ERROR;
        }
    }

    if (FacebookSdk.isLoggingBehaviorEnabled(LoggingBehavior.APP_EVENTS)) {
        String eventsJsonString = (String) request.getTag();
        String prettyPrintedEvents;

        try {
            JSONArray jsonArray = new JSONArray(eventsJsonString);
            prettyPrintedEvents = jsonArray.toString(2);
        } catch (JSONException exc) {
            prettyPrintedEvents = "<Can't encode events for debug logging>";
        }

        Logger.log(LoggingBehavior.APP_EVENTS, TAG,
                "Flush completed\nParams: %s\n  Result: %s\n  Events JSON: %s",
                request.getGraphObject().toString(),
                resultDescription,
                prettyPrintedEvents);
    }

    sessionEventsState.clearInFlightAndStats(error != null);

    if (flushResult == FlushResult.NO_CONNECTIVITY) {
        // We may call this for multiple requests in a batch, which is slightly inefficient
        // since in principle we could call it once for all failed requests, but the impact is
        // likely to be minimal. We don't call this for other server errors, because if an event
        // failed because it was malformed, etc., continually retrying it will cause subsequent
        // events to not be logged either.
        PersistedEvents.persistEvents(applicationContext, accessTokenAppId, sessionEventsState);
    }

    if (flushResult != FlushResult.SUCCESS) {
        // We assume that connectivity issues are more significant to report than server issues.
        if (flushState.result != FlushResult.NO_CONNECTIVITY) {
            flushState.result = flushResult;
        }
    }
}
项目:yelo-android    文件:WebDialog.java   
@Override
@SuppressWarnings("deprecation")
public boolean shouldOverrideUrlLoading(WebView view, String url) {
    Utility.logd(LOG_TAG, "Redirect URL: " + url);
    if (url.startsWith(WebDialog.REDIRECT_URI)) {
        Bundle values = Util.parseUrl(url);

        String error = values.getString("error");
        if (error == null) {
            error = values.getString("error_type");
        }

        String errorMessage = values.getString("error_msg");
        if (errorMessage == null) {
            errorMessage = values.getString("error_description");
        }
        String errorCodeString = values.getString("error_code");
        int errorCode = FacebookRequestError.INVALID_ERROR_CODE;
        if (!Utility.isNullOrEmpty(errorCodeString)) {
            try {
                errorCode = Integer.parseInt(errorCodeString);
            } catch (NumberFormatException ex) {
                errorCode = FacebookRequestError.INVALID_ERROR_CODE;
            }
        }

        if (Utility.isNullOrEmpty(error) && Utility
                .isNullOrEmpty(errorMessage) && errorCode == FacebookRequestError.INVALID_ERROR_CODE) {
            sendSuccessToListener(values);
        } else if (error != null && (error.equals("access_denied") ||
                error.equals("OAuthAccessDeniedException"))) {
            sendCancelToListener();
        } else {
            FacebookRequestError requestError = new FacebookRequestError(errorCode, error, errorMessage);
            sendErrorToListener(new FacebookServiceException(requestError, errorMessage));
        }

        WebDialog.this.dismiss();
        return true;
    } else if (url.startsWith(WebDialog.CANCEL_URI)) {
        sendCancelToListener();
        WebDialog.this.dismiss();
        return true;
    } else if (url.contains(DISPLAY_TOUCH)) {
        return false;
    }
    // launch non-dialog URLs in a full browser
    getContext().startActivity(
            new Intent(Intent.ACTION_VIEW, Uri.parse(url)));
    return true;
}
项目:Anypic-Android    文件:HomeListActivity.java   
/**
 * Requesting and setting user data. Essentially, this is the User constructor
 */
private void makeMeRequest() {
    Request request = Request.newMeRequest(ParseFacebookUtils.getSession(),
            new Request.GraphUserCallback() {
                @Override
                public void onCompleted(GraphUser user, Response response) {
                    if (user != null) {
                        // get the relevant data using the GraphAPI
                        // and store them as fields in our ParseUser

                        /*
                         * User Model
                         * 
                         * displayName : String
                         * email : string
                         * profilePictureMedium : File
                         * profilePictureSmall : File
                         * facebookId : String
                         * facebookFriends : Array
                         * channel : String
                         * userAlreadyAutoFollowedFacebookFriends : boolean
                         */
                        ParseUser currentUser = ParseUser
                                .getCurrentUser();
                        currentUser.put("facebookId", user.getId());
                        currentUser.put("displayName", user.getName());
                        currentUser.saveInBackground();

                        // Make another facebook request to auto follow all of
                        // the current user's facebook friends who are using Anypic
                        if( currentUser.get("userAlreadyAutoFollowedFacebookFriends")!=null &&
                                ((Boolean) currentUser.get("userAlreadyAutoFollowedFacebookFriends")) ){
                            // do nothing
                            Log.i(AnypicApplication.TAG, "Already followed facebook friends");
                        } else{
                            autoFollowFacebookFriendsRequest(); 
                        }
                        // Associate the device with a user
                        ParseInstallation installation = ParseInstallation.getCurrentInstallation();
                        installation.put("user", currentUser);
                        installation.saveInBackground();

                        // handle errors accessing data from facebook
                    } else if (response.getError() != null) {
                        if ((response.getError().getCategory() == FacebookRequestError.Category.AUTHENTICATION_RETRY)
                                || (response.getError().getCategory() == FacebookRequestError.Category.AUTHENTICATION_REOPEN_SESSION)) {
                            Log.i(AnypicApplication.TAG,
                                    "The facebook session was invalidated.");
                            onLogoutButtonClicked();
                        } else {
                            Log.i(AnypicApplication.TAG,
                                    "Some other error: "
                                            + response.getError()
                                                    .getErrorMessage());
                        }
                    }
                }
            });
    request.executeAsync();

}
项目:Anypic-Android    文件:HomeListActivity.java   
/**
 * This function performs a request to the Facebook Graph API, which 
 * finds all the friends of the current ParseUser and checks if any 
 * of them currently use Anypic. If so, then it automatically follows 
 * those friends on Anypic, by creating new Activity relationships. 
 */
private void autoFollowFacebookFriendsRequest(){
    Request request = Request.newMyFriendsRequest(ParseFacebookUtils.getSession(), 
            new Request.GraphUserListCallback() {
                @Override
                public void onCompleted(List<GraphUser> friendList, Response response) {
                    if(friendList != null){
                        List<String> ids = toIdsList(friendList);

                        // Select * From Users Where User.facebookID is contained in 
                        // the list of IDs of users returned from the GraphApi
                        ParseQuery<ParseUser> friendsQuery = ParseUser.getQuery();
                        friendsQuery.whereContainedIn("facebookId", ids);
                        friendsQuery.findInBackground(new FindCallback<ParseUser>() {
                            @Override
                            public void done(List<ParseUser> objects, ParseException e) {
                                if(e == null && objects!=null){
                                    // friendsQuery successful, follow these users
                                    ParseUser currentUser = ParseUser.getCurrentUser();
                                    for(ParseUser friend : objects){
                                        com.parse.anypic.Activity followActivity = new com.parse.anypic.Activity();
                                        followActivity.setFromUser(currentUser);
                                        followActivity.setToUser(friend);
                                        followActivity.setType("follow");
                                        followActivity.saveEventually();
                                    }
                                    currentUser.put("userAlreadyAutoFollowedFacebookFriends", true);
                                    currentUser.saveInBackground();
                                } else {
                                    // friendsQuery failed
                                    Log.i(AnypicApplication.TAG, "Query to find facebook friends in Parse failed");
                                }
                            }
                        }); // end findInBackground()


                        // handle errors from facebook
                    } else if (response.getError() != null) {
                        if ((response.getError().getCategory() == FacebookRequestError.Category.AUTHENTICATION_RETRY)
                                || (response.getError().getCategory() == FacebookRequestError.Category.AUTHENTICATION_REOPEN_SESSION)) {
                            Log.i(AnypicApplication.TAG,
                                    "The facebook session was invalidated.");
                            onLogoutButtonClicked();
                        } else {
                            Log.i(AnypicApplication.TAG,
                                    "Some other error: "
                                            + response.getError()
                                                    .getErrorMessage());
                        }
                    }

                }
            });// end GraphUserListCallback
    request.executeAsync();     
}