com.facebook.internal.Utility Java Examples

The following examples show how to use com.facebook.internal.Utility. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source File: PlacePickerFragment.java    From Abelana-Android with Apache License 2.0 6 votes vote down vote up
/**
 * Sets the search text and reloads the data in the control. This is used to provide search-box
 * functionality where the user may be typing or editing text rapidly. It uses a timer to avoid repeated
 * requerying, preferring to wait until the user pauses typing to refresh the data. Note that this
 * method will NOT update the text in the search box, if any, as it is intended to be called as a result
 * of changes to the search box (and is public to enable applications to provide their own search box
 * UI instead of the default one).
 *
 * @param searchText                 the search text
 * @param forceReloadEventIfSameText if true, will reload even if the search text has not changed; if false,
 *                                   identical search text will not force a reload
 */
public void onSearchBoxTextChanged(String searchText, boolean forceReloadEventIfSameText) {
    if (!forceReloadEventIfSameText && Utility.stringsEqualOrEmpty(this.searchText, searchText)) {
        return;
    }

    if (TextUtils.isEmpty(searchText)) {
        searchText = null;
    }
    this.searchText = searchText;

    // If search text is being set in response to user input, it is wasteful to send a new request
    // with every keystroke. Send a request the first time the search text is set, then set up a 2-second timer
    // and send whatever changes the user has made since then. (If nothing has changed
    // in 2 seconds, we reset so the next change will cause an immediate re-query.)
    hasSearchTextChangedSinceLastQuery = true;
    if (searchTextTimer == null) {
        searchTextTimer = createSearchTextTimer();
    }
}
 
Example #2
Source File: InsightsLogger.java    From HypFacebook with BSD 2-Clause "Simplified" License 6 votes vote down vote up
/**
 * Constructor is private, newLogger() methods should be used to build an instance.
 */
private InsightsLogger(Context context, String clientToken, String applicationId, Session session) {

    Validate.notNull(context, "context");

    // Always ensure the client token is present, even if not needed for this particular logging (because at
    // some point it will be required).  Be harsh by throwing an exception because this is all too easy to miss
    // and things will work with authenticated sessions, but start failing with users that don't have
    // authenticated sessions.
    Validate.notNullOrEmpty(clientToken, "clientToken");

    if (applicationId == null) {
        applicationId = Utility.getMetadataApplicationId(context);
    }

    this.context = context;
    this.clientToken = clientToken;
    this.applicationId = applicationId;
    this.specifiedSession = session;
}
 
Example #3
Source File: PlacePickerFragment.java    From facebook-api-android-maven with Apache License 2.0 6 votes vote down vote up
/**
 * Sets the search text and reloads the data in the control. This is used to provide search-box
 * functionality where the user may be typing or editing text rapidly. It uses a timer to avoid repeated
 * requerying, preferring to wait until the user pauses typing to refresh the data. Note that this
 * method will NOT update the text in the search box, if any, as it is intended to be called as a result
 * of changes to the search box (and is public to enable applications to provide their own search box
 * UI instead of the default one).
 *
 * @param searchText                 the search text
 * @param forceReloadEventIfSameText if true, will reload even if the search text has not changed; if false,
 *                                   identical search text will not force a reload
 */
public void onSearchBoxTextChanged(String searchText, boolean forceReloadEventIfSameText) {
    if (!forceReloadEventIfSameText && Utility.stringsEqualOrEmpty(this.searchText, searchText)) {
        return;
    }

    if (TextUtils.isEmpty(searchText)) {
        searchText = null;
    }
    this.searchText = searchText;

    // If search text is being set in response to user input, it is wasteful to send a new request
    // with every keystroke. Send a request the first time the search text is set, then set up a 2-second timer
    // and send whatever changes the user has made since then. (If nothing has changed
    // in 2 seconds, we reset so the next change will cause an immediate re-query.)
    hasSearchTextChangedSinceLastQuery = true;
    if (searchTextTimer == null) {
        searchTextTimer = createSearchTextTimer();
    }
}
 
Example #4
Source File: AppLinkData.java    From kognitivo with Apache License 2.0 6 votes vote down vote up
/**
 * Asynchronously fetches app link information that might have been stored for use after
 * installation of the app
 *
 * @param context           The context
 * @param applicationId     Facebook application Id. If null, it is taken from the manifest
 * @param completionHandler CompletionHandler to be notified with the AppLinkData object or null
 *                          if none is available.  Must not be null.
 */
public static void fetchDeferredAppLinkData(
        Context context,
        String applicationId,
        final CompletionHandler completionHandler) {
    Validate.notNull(context, "context");
    Validate.notNull(completionHandler, "completionHandler");

    if (applicationId == null) {
        applicationId = Utility.getMetadataApplicationId(context);
    }

    Validate.notNull(applicationId, "applicationId");

    final Context applicationContext = context.getApplicationContext();
    final String applicationIdCopy = applicationId;
    FacebookSdk.getExecutor().execute(new Runnable() {
        @Override
        public void run() {
            fetchDeferredAppLinkFromServer(
                    applicationContext, applicationIdCopy, completionHandler);
        }
    });
}
 
Example #5
Source File: VideoUploader.java    From kognitivo with Apache License 2.0 6 votes vote down vote up
private static void issueResponse(
        final UploadContext uploadContext,
        final FacebookException error,
        final String videoId) {
    // Remove the UploadContext synchronously
    // Once the UploadContext is removed, this is the only reference to it.
    removePendingUpload(uploadContext);

    Utility.closeQuietly(uploadContext.videoStream);

    if (uploadContext.callback != null) {
        if (error != null) {
            ShareInternalUtility.invokeOnErrorCallback(uploadContext.callback, error);
        } else if (uploadContext.isCanceled) {
            ShareInternalUtility.invokeOnCancelCallback(uploadContext.callback);
        } else {
            ShareInternalUtility.invokeOnSuccessCallback(uploadContext.callback, videoId);
        }
    }
}
 
Example #6
Source File: LikeActionController.java    From kognitivo with Apache License 2.0 6 votes vote down vote up
@Override
protected void processSuccess(GraphResponse response) {
    JSONArray dataSet = Utility.tryGetJSONArrayFromResponse(
            response.getJSONObject(),
            "data");
    if (dataSet != null) {
        for (int i = 0; i < dataSet.length(); i++) {
            JSONObject data = dataSet.optJSONObject(i);
            if (data != null) {
                objectIsLiked = true;
                JSONObject appData = data.optJSONObject("application");
                AccessToken accessToken = AccessToken.getCurrentAccessToken();
                if (appData != null &&
                        accessToken != null &&
                        Utility.areObjectsEqual(
                                accessToken.getApplicationId(),
                                appData.optString("id"))) {
                    unlikeToken = data.optString("id");
                }
            }
        }
    }
}
 
Example #7
Source File: AppLinkData.java    From Abelana-Android with Apache License 2.0 6 votes vote down vote up
/**
 * Asynchronously fetches app link information that might have been stored for use
 * after installation of the app
 * @param context The context
 * @param applicationId Facebook application Id. If null, it is taken from the manifest
 * @param completionHandler CompletionHandler to be notified with the AppLinkData object or null if none is
 *                          available.  Must not be null.
 */
public static void fetchDeferredAppLinkData(
        Context context,
        String applicationId,
        final CompletionHandler completionHandler) {
    Validate.notNull(context, "context");
    Validate.notNull(completionHandler, "completionHandler");

    if (applicationId == null) {
        applicationId = Utility.getMetadataApplicationId(context);
    }

    Validate.notNull(applicationId, "applicationId");

    final Context applicationContext = context.getApplicationContext();
    final String applicationIdCopy = applicationId;
    Settings.getExecutor().execute(new Runnable() {
        @Override
        public void run() {
            fetchDeferredAppLinkFromServer(applicationContext, applicationIdCopy, completionHandler);
        }
    });
}
 
Example #8
Source File: Request.java    From barterli_android with Apache License 2.0 6 votes vote down vote up
/**
 * Creates a new Request configured to create a user owned Open Graph object.
 *
 * @param session
 *            the Session to use, or null; if non-null, the session must be in an opened state
 * @param openGraphObject
 *            the Open Graph object to create; must not be null, and must have a non-empty type and title
 * @param callback
 *            a callback that will be called when the request is completed to handle success or error conditions
 * @return a Request that is ready to execute
 */
public static Request newPostOpenGraphObjectRequest(Session session,
        OpenGraphObject openGraphObject, Callback callback) {
    if (openGraphObject == null) {
        throw new FacebookException("openGraphObject cannot be null");
    }
    if (Utility.isNullOrEmpty(openGraphObject.getType())) {
        throw new FacebookException("openGraphObject must have non-null 'type' property");
    }
    if (Utility.isNullOrEmpty(openGraphObject.getTitle())) {
        throw new FacebookException("openGraphObject must have non-null 'title' property");
    }

    String path = String.format(MY_OBJECTS_FORMAT, openGraphObject.getType());
    Bundle bundle = new Bundle();
    bundle.putString(OBJECT_PARAM, openGraphObject.getInnerJSONObject().toString());
    return new Request(session, path, bundle, HttpMethod.POST, callback);
}
 
Example #9
Source File: NativeProtocol.java    From FacebookNewsfeedSample-Android with Apache License 2.0 6 votes vote down vote up
private static ArrayList<String> ensureDefaultPermissions(ArrayList<String> permissions) {
    ArrayList<String> updated;

    // Return if we are doing publish, or if basic_info is already included
    if (Utility.isNullOrEmpty(permissions)) {
        updated = new ArrayList<String>();
    } else {
        for (String permission : permissions) {
            if (Session.isPublishPermission(permission) || BASIC_INFO.equals(permission)) {
                return permissions;
            }
        }
        updated = new ArrayList<String>(permissions);
    }

    updated.add(BASIC_INFO);
    return updated;
}
 
Example #10
Source File: VideoUploader.java    From kognitivo with Apache License 2.0 6 votes vote down vote up
@Override
protected void handleSuccess(JSONObject jsonObject)
        throws JSONException {
    String startOffset = jsonObject.getString(PARAM_START_OFFSET);
    String endOffset = jsonObject.getString(PARAM_END_OFFSET);

    if (Utility.areObjectsEqual(startOffset, endOffset)) {
        enqueueUploadFinish(
                uploadContext,
                0);
    } else {
        enqueueUploadChunk(
                uploadContext,
                startOffset,
                endOffset,
                0);
    }
}
 
Example #11
Source File: NativeDialogParameters.java    From kognitivo with Apache License 2.0 6 votes vote down vote up
private static Bundle createBaseParameters(ShareContent content, boolean dataErrorsFatal) {
    Bundle params = new Bundle();

    Utility.putUri(params, ShareConstants.CONTENT_URL, content.getContentUrl());
    Utility.putNonEmptyString(params, ShareConstants.PLACE_ID, content.getPlaceId());
    Utility.putNonEmptyString(params, ShareConstants.REF, content.getRef());

    params.putBoolean(ShareConstants.DATA_FAILURES_FATAL, dataErrorsFatal);

    List<String> peopleIds = content.getPeopleIds();
    if (!Utility.isNullOrEmpty(peopleIds)) {
        params.putStringArrayList(
                ShareConstants.PEOPLE_IDS,
                new ArrayList<String>(peopleIds));
    }

    return params;
}
 
Example #12
Source File: LoginButton.java    From platform-friends-android with BSD 2-Clause "Simplified" License 6 votes vote down vote up
private boolean initializeActiveSessionWithCachedToken(Context context) {
    if (context == null) {
        return false;
    }

    Session session = Session.getActiveSession();
    if (session != null) {
        return session.isOpened();
    }

    String applicationId = Utility.getMetadataApplicationId(context);
    if (applicationId == null) {
        return false;
    }

    return Session.openActiveSessionFromCache(context) != null;
}
 
Example #13
Source File: LoginButton.java    From Klyph with MIT License 6 votes vote down vote up
private boolean initializeActiveSessionWithCachedToken(Context context) {
    if (context == null) {
        return false;
    }

    Session session = Session.getActiveSession();
    if (session != null) {
        return session.isOpened();
    }

    String applicationId = Utility.getMetadataApplicationId(context);
    if (applicationId == null) {
        return false;
    }

    return Session.openActiveSessionFromCache(context) != null;
}
 
Example #14
Source File: FacebookDialog.java    From FacebookImageShareIntent with MIT License 6 votes vote down vote up
/**
 * Constructor.
 *
 * @param activity            the Activity which is presenting the native Open Graph action publish dialog;
 *                            must not be null
 * @param action              the Open Graph action to be published, which must contain a reference to at least one
 *                            Open Graph object with the property name specified by setPreviewPropertyName; the action
 *                            must have had its type specified via the {@link OpenGraphAction#setType(String)} method
 * @param actionType          the type of the Open Graph action to be published, which should be the namespace-qualified
 *                            name of the action type (e.g., "myappnamespace:myactiontype"); this will override the type
 *                            of the action passed in.
 * @param previewPropertyName the name of a property on the Open Graph action that contains the
 *                            Open Graph object which will be displayed as a preview to the user
 */
@Deprecated
public OpenGraphDialogBuilderBase(Activity activity, OpenGraphAction action, String actionType,
        String previewPropertyName) {
    super(activity);

    Validate.notNull(action, "action");
    Validate.notNullOrEmpty(actionType, "actionType");
    Validate.notNullOrEmpty(previewPropertyName, "previewPropertyName");
    if (action.getProperty(previewPropertyName) == null) {
        throw new IllegalArgumentException(
                "A property named \"" + previewPropertyName + "\" was not found on the action.  The name of " +
                        "the preview property must match the name of an action property.");
    }
    String typeOnAction = action.getType();
    if (!Utility.isNullOrEmpty(typeOnAction) && !typeOnAction.equals(actionType)) {
        throw new IllegalArgumentException("'actionType' must match the type of 'action' if it is specified. " +
                "Consider using OpenGraphDialogBuilderBase(Activity activity, OpenGraphAction action, " +
                "String previewPropertyName) instead.");
    }
    this.action = action;
    this.actionType = actionType;
    this.previewPropertyName = previewPropertyName;
}
 
Example #15
Source File: FacebookDialog.java    From android-skeleton-project with MIT License 6 votes vote down vote up
/**
 * Constructor.
 *
 * @param activity            the Activity which is presenting the native Open Graph action publish dialog;
 *                            must not be null
 * @param action              the Open Graph action to be published, which must contain a reference to at least one
 *                            Open Graph object with the property name specified by setPreviewPropertyName; the action
 *                            must have had its type specified via the {@link OpenGraphAction#setType(String)} method
 * @param actionType          the type of the Open Graph action to be published, which should be the namespace-qualified
 *                            name of the action type (e.g., "myappnamespace:myactiontype"); this will override the type
 *                            of the action passed in.
 * @param previewPropertyName the name of a property on the Open Graph action that contains the
 *                            Open Graph object which will be displayed as a preview to the user
 */
@Deprecated
public OpenGraphDialogBuilderBase(Activity activity, OpenGraphAction action, String actionType,
        String previewPropertyName) {
    super(activity);

    Validate.notNull(action, "action");
    Validate.notNullOrEmpty(actionType, "actionType");
    Validate.notNullOrEmpty(previewPropertyName, "previewPropertyName");
    if (action.getProperty(previewPropertyName) == null) {
        throw new IllegalArgumentException(
                "A property named \"" + previewPropertyName + "\" was not found on the action.  The name of " +
                        "the preview property must match the name of an action property.");
    }
    String typeOnAction = action.getType();
    if (!Utility.isNullOrEmpty(typeOnAction) && !typeOnAction.equals(actionType)) {
        throw new IllegalArgumentException("'actionType' must match the type of 'action' if it is specified. " +
                "Consider using OpenGraphDialogBuilderBase(Activity activity, OpenGraphAction action, " +
                "String previewPropertyName) instead.");
    }
    this.action = action;
    this.actionType = actionType;
    this.previewPropertyName = previewPropertyName;
}
 
Example #16
Source File: Session.java    From KlyphMessenger with MIT License 6 votes vote down vote up
private void validatePermissions(AuthorizationRequest request, SessionAuthorizationType authType) {
    if (request == null || Utility.isNullOrEmpty(request.getPermissions())) {
        if (SessionAuthorizationType.PUBLISH.equals(authType)) {
            throw new FacebookException("Cannot request publish or manage authorization with no permissions.");
        }
        return; // nothing to check
    }
    for (String permission : request.getPermissions()) {
        if (isPublishPermission(permission)) {
            if (SessionAuthorizationType.READ.equals(authType)) {
                throw new FacebookException(
                        String.format(
                                "Cannot pass a publish or manage permission (%s) to a request for read authorization",
                                permission));
            }
        } else {
            if (SessionAuthorizationType.PUBLISH.equals(authType)) {
                Log.w(TAG,
                        String.format(
                                "Should not pass a read permission (%s) to a request for publish or manage authorization",
                                permission));
            }
        }
    }
}
 
Example #17
Source File: FacebookDialog.java    From barterli_android with Apache License 2.0 6 votes vote down vote up
/**
 * Constructor.
 * @param activity the Activity which is presenting the native Open Graph action publish dialog;
 *                 must not be null
 * @param action the Open Graph action to be published, which must contain a reference to at least one
 *               Open Graph object with the property name specified by setPreviewPropertyName; the action
 *               must have had its type specified via the {@link OpenGraphAction#setType(String)} method
 * @param actionType the type of the Open Graph action to be published, which should be the namespace-qualified
 *                   name of the action type (e.g., "myappnamespace:myactiontype"); this will override the type
 *                   of the action passed in.
 * @param previewPropertyName the name of a property on the Open Graph action that contains the
 *                            Open Graph object which will be displayed as a preview to the user
 */
@Deprecated
public OpenGraphActionDialogBuilder(Activity activity, OpenGraphAction action, String actionType,
        String previewPropertyName) {
    super(activity);

    Validate.notNull(action, "action");
    Validate.notNullOrEmpty(actionType, "actionType");
    Validate.notNullOrEmpty(previewPropertyName, "previewPropertyName");
    if (action.getProperty(previewPropertyName) == null) {
        throw new IllegalArgumentException(
                "A property named \"" + previewPropertyName + "\" was not found on the action.  The name of " +
                        "the preview property must match the name of an action property.");
    }
    String typeOnAction = action.getType();
    if (!Utility.isNullOrEmpty(typeOnAction) && !typeOnAction.equals(actionType)) {
        throw new IllegalArgumentException("'actionType' must match the type of 'action' if it is specified. " +
                "Consider using OpenGraphActionDialogBuilder(Activity activity, OpenGraphAction action, " +
                "String previewPropertyName) instead.");
    }
    this.action = action;
    this.actionType = actionType;
    this.previewPropertyName = previewPropertyName;
}
 
Example #18
Source File: ShareApi.java    From kognitivo with Apache License 2.0 6 votes vote down vote up
private void shareLinkContent(final ShareLinkContent linkContent,
                              final FacebookCallback<Sharer.Result> callback) {
    final GraphRequest.Callback requestCallback = new GraphRequest.Callback() {
        @Override
        public void onCompleted(GraphResponse response) {
            final JSONObject data = response.getJSONObject();
            final String postId = (data == null ? null : data.optString("id"));
            ShareInternalUtility.invokeCallbackWithResults(callback, postId, response);
        }
    };
    final Bundle parameters = new Bundle();
    this.addCommonParameters(parameters, linkContent);
    parameters.putString("message", this.getMessage());
    parameters.putString("link", Utility.getUriString(linkContent.getContentUrl()));
    parameters.putString("picture", Utility.getUriString(linkContent.getImageUrl()));
    parameters.putString("name", linkContent.getContentTitle());
    parameters.putString("description", linkContent.getContentDescription());
    parameters.putString("ref", linkContent.getRef());
    new GraphRequest(
            AccessToken.getCurrentAccessToken(),
            getGraphPath("feed"),
            parameters,
            HttpMethod.POST,
            requestCallback).executeAsync();
}
 
Example #19
Source File: FacebookDialog.java    From Abelana-Android with Apache License 2.0 6 votes vote down vote up
@Override
protected Bundle getMethodArguments() {
    Bundle methodArguments = new Bundle();

    putExtra(methodArguments, NativeProtocol.METHOD_ARGS_TITLE, name);
    putExtra(methodArguments, NativeProtocol.METHOD_ARGS_SUBTITLE, caption);
    putExtra(methodArguments, NativeProtocol.METHOD_ARGS_DESCRIPTION, description);
    putExtra(methodArguments, NativeProtocol.METHOD_ARGS_LINK, link);
    putExtra(methodArguments, NativeProtocol.METHOD_ARGS_IMAGE, picture);
    putExtra(methodArguments, NativeProtocol.METHOD_ARGS_PLACE_TAG, place);
    putExtra(methodArguments, NativeProtocol.METHOD_ARGS_TITLE, name);
    putExtra(methodArguments, NativeProtocol.METHOD_ARGS_REF, ref);

    methodArguments.putBoolean(NativeProtocol.METHOD_ARGS_DATA_FAILURES_FATAL, dataErrorsFatal);
    if (!Utility.isNullOrEmpty(friends)) {
        methodArguments.putStringArrayList(NativeProtocol.METHOD_ARGS_FRIEND_TAGS, friends);
    }

    return methodArguments;
}
 
Example #20
Source File: NativeAppCallAttachmentStore.java    From Klyph with MIT License 6 votes vote down vote up
/**
 * Adds a number of bitmap attachments associated with a native app call. The attachments will be
 * served via {@link NativeAppCallContentProvider#openFile(android.net.Uri, String) openFile}.
 *
 * @param context the Context the call is being made from
 * @param callId the unique ID of the call
 * @param imageAttachments a Map of attachment names to Bitmaps; the attachment names will be part of
 *                         the URI processed by openFile
 * @throws java.io.IOException
 */
public void addAttachmentsForCall(Context context, UUID callId, Map<String, Bitmap> imageAttachments) {
    Validate.notNull(context, "context");
    Validate.notNull(callId, "callId");
    Validate.containsNoNulls(imageAttachments.values(), "imageAttachments");
    Validate.containsNoNullOrEmpty(imageAttachments.keySet(), "imageAttachments");

    addAttachments(context, callId, imageAttachments, new ProcessAttachment<Bitmap>() {
        @Override
        public void processAttachment(Bitmap attachment, File outputFile) throws IOException {
            FileOutputStream outputStream = new FileOutputStream(outputFile);
            try {
                attachment.compress(Bitmap.CompressFormat.JPEG, 100, outputStream);
            } finally {
                Utility.closeQuietly(outputStream);
            }
        }
    });
}
 
Example #21
Source File: Profile.java    From kognitivo with Apache License 2.0 5 votes vote down vote up
/**
 * Fetches and sets the current profile from the current access token.
 * <p/>
 * This should only be called from the UI thread.
 */
public static void fetchProfileForCurrentAccessToken() {
    AccessToken accessToken = AccessToken.getCurrentAccessToken();
    if (accessToken == null) {
        Profile.setCurrentProfile(null);
        return;
    }

    Utility.getGraphMeRequestWithCacheAsync(accessToken.getToken(),
            new Utility.GraphMeRequestWithCacheCallback() {
                @Override
                public void onSuccess(JSONObject userInfo) {
                    String id = userInfo.optString("id");
                    if (id == null) {
                        return;
                    }
                    String link = userInfo.optString("link");
                    Profile profile = new Profile(
                            id,
                            userInfo.optString("first_name"),
                            userInfo.optString("middle_name"),
                            userInfo.optString("last_name"),
                            userInfo.optString("name"),
                            link != null ? Uri.parse(link) : null
                    );
                    Profile.setCurrentProfile(profile);
                }

                @Override
                public void onFailure(FacebookException error) {
                    return;
                }
            });
}
 
Example #22
Source File: Response.java    From Abelana-Android with Apache License 2.0 5 votes vote down vote up
static List<Response> createResponsesFromStream(InputStream stream, HttpURLConnection connection,
        RequestBatch requests, boolean isFromCache) throws FacebookException, JSONException, IOException {

    String responseString = Utility.readStreamToString(stream);
    Logger.log(LoggingBehavior.INCLUDE_RAW_RESPONSES, RESPONSE_LOG_TAG,
            "Response (raw)\n  Size: %d\n  Response:\n%s\n", responseString.length(),
            responseString);

    return createResponsesFromString(responseString, connection, requests, isFromCache);
}
 
Example #23
Source File: AuthorizationClient.java    From FacebookNewsfeedSample-Android with Apache License 2.0 5 votes vote down vote up
@Override
boolean tryAuthorize(final AuthorizationRequest request) {
    String applicationId = request.getApplicationId();
    Bundle parameters = new Bundle();
    if (!Utility.isNullOrEmpty(request.getPermissions())) {
        parameters.putString(ServerProtocol.DIALOG_PARAM_SCOPE, TextUtils.join(",", request.getPermissions()));
    }

    String previousToken = request.getPreviousAccessToken();
    if (!Utility.isNullOrEmpty(previousToken) && (previousToken.equals(loadCookieToken()))) {
        parameters.putString(ServerProtocol.DIALOG_PARAM_ACCESS_TOKEN, previousToken);
    } else {
        // The call to clear cookies will create the first instance of CookieSyncManager if necessary
        Utility.clearFacebookCookies(context);
    }

    WebDialog.OnCompleteListener listener = new WebDialog.OnCompleteListener() {
        @Override
        public void onComplete(Bundle values, FacebookException error) {
            onWebDialogComplete(request, values, error);
        }
    };

    WebDialog.Builder builder =
            new AuthDialogBuilder(getStartActivityDelegate().getActivityContext(), applicationId, parameters)
                    .setOnCompleteListener(listener);
    loginDialog = builder.build();
    loginDialog.show();

    return true;
}
 
Example #24
Source File: AppEventsLogger.java    From facebook-api-android-maven with Apache License 2.0 5 votes vote down vote up
/**
 * Constructor is private, newLogger() methods should be used to build an instance.
 */
private AppEventsLogger(Context context, String applicationId, Session session) {

    Validate.notNull(context, "context");
    this.context = context;

    if (session == null) {
        session = Session.getActiveSession();
    }

    // If we have a session and the appId passed is null or matches the session's app ID:
    if (session != null &&
            (applicationId == null || applicationId.equals(session.getApplicationId()))
            ) {
        accessTokenAppId = new AccessTokenAppIdPair(session);
    } else {
        // If no app ID passed, get it from the manifest:
        if (applicationId == null) {
            applicationId = Utility.getMetadataApplicationId(context);
        }
        accessTokenAppId = new AccessTokenAppIdPair(null, applicationId);
    }

    synchronized (staticLock) {

        if (hashedDeviceAndAppId == null) {
            hashedDeviceAndAppId = Utility.getHashedDeviceAndAppID(context, applicationId);
        }

        if (applicationContext == null) {
            applicationContext = context.getApplicationContext();
        }
    }

    initializeTimersIfNeeded();
}
 
Example #25
Source File: FacebookDialog.java    From android-skeleton-project with MIT License 5 votes vote down vote up
@Override
Bundle setBundleExtras(Bundle extras) {
    putExtra(extras, NativeProtocol.EXTRA_APPLICATION_ID, applicationId);
    putExtra(extras, NativeProtocol.EXTRA_APPLICATION_NAME, applicationName);
    putExtra(extras, NativeProtocol.EXTRA_PLACE_TAG, place);
    extras.putStringArrayList(NativeProtocol.EXTRA_PHOTOS, imageAttachmentUrls);

    if (!Utility.isNullOrEmpty(friends)) {
        extras.putStringArrayList(NativeProtocol.EXTRA_FRIEND_TAGS, friends);
    }
    return extras;
}
 
Example #26
Source File: TestSession.java    From facebook-api-android-maven with Apache License 2.0 5 votes vote down vote up
private static synchronized TestSession createTestSession(Activity activity, List<String> permissions, Mode mode,
        String sessionUniqueUserTag) {
    if (Utility.isNullOrEmpty(testApplicationId) || Utility.isNullOrEmpty(testApplicationSecret)) {
        throw new FacebookException("Must provide app ID and secret");
    }

    if (Utility.isNullOrEmpty(permissions)) {
        permissions = Arrays.asList("email", "publish_actions");
    }

    return new TestSession(activity, permissions, new TestTokenCachingStrategy(), sessionUniqueUserTag,
            mode);
}
 
Example #27
Source File: VideoUploader.java    From kognitivo with Apache License 2.0 5 votes vote down vote up
@Override
public Bundle getParameters() {
    Bundle parameters = new Bundle();
    if (uploadContext.params != null) {
        parameters.putAll(uploadContext.params);
    }
    parameters.putString(PARAM_UPLOAD_PHASE, PARAM_VALUE_UPLOAD_FINISH_PHASE);
    parameters.putString(PARAM_SESSION_ID, uploadContext.sessionId);
    Utility.putNonEmptyString(parameters, PARAM_TITLE, uploadContext.title);
    Utility.putNonEmptyString(parameters, PARAM_DESCRIPTION, uploadContext.description);
    Utility.putNonEmptyString(parameters, PARAM_REF, uploadContext.ref);

    return parameters;
}
 
Example #28
Source File: WebDialog.java    From FacebookImageShareIntent with MIT License 5 votes vote down vote up
@Override
public void onPageStarted(WebView view, String url, Bitmap favicon) {
    Utility.logd(LOG_TAG, "Webview loading URL: " + url);
    super.onPageStarted(view, url, favicon);
    if (!isDetached) {
        spinner.show();
    }
}
 
Example #29
Source File: ShareInternalUtility.java    From kognitivo with Apache License 2.0 5 votes vote down vote up
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);
    }
}
 
Example #30
Source File: Session.java    From Klyph with MIT License 5 votes vote down vote up
/**
 * Closes the local in-memory Session object and clears any persisted token
 * cache related to the Session.
 */
public final void closeAndClearTokenInformation() {
    if (this.tokenCachingStrategy != null) {
        this.tokenCachingStrategy.clear();
    }
    Utility.clearFacebookCookies(staticContext);
    Utility.clearCaches(staticContext);
    close();
}