Search in sources :

Example 16 with GraphObject

use of com.facebook.model.GraphObject in project facebook-api-android-maven by avianey.

the class GraphObjectAdapter method getPictureUriOfGraphObject.

protected URI getPictureUriOfGraphObject(T graphObject) {
    String uri = null;
    Object o = graphObject.getProperty(PICTURE);
    if (o instanceof String) {
        uri = (String) o;
    } else if (o instanceof JSONObject) {
        ItemPicture itemPicture = GraphObject.Factory.create((JSONObject) o).cast(ItemPicture.class);
        ItemPictureData data = itemPicture.getData();
        if (data != null) {
            uri = data.getUrl();
        }
    }
    if (uri != null) {
        try {
            return new URI(uri);
        } catch (URISyntaxException e) {
        }
    }
    return null;
}
Also used : JSONObject(org.json.JSONObject) GraphObject(com.facebook.model.GraphObject) JSONObject(org.json.JSONObject) URISyntaxException(java.net.URISyntaxException) URI(java.net.URI)

Example 17 with GraphObject

use of com.facebook.model.GraphObject in project facebook-api-android-maven by avianey.

the class FacebookAppLinkResolver method getAppLinkFromUrlsInBackground.

/**
     * Asynchronously resolves App Link data for multiple Urls
     *
     * @param uris A list of Uri objects to resolve into App Links
     * @return A Task that, when successful, will return a Map of Uri->AppLink for each Uri that was successfully
     * resolved into an App Link. Uris that could not be resolved into App Links will not be present in the Map.
     * In the case of general server errors, the task will be completed with the corresponding error.
     */
public Task<Map<Uri, AppLink>> getAppLinkFromUrlsInBackground(List<Uri> uris) {
    final Map<Uri, AppLink> appLinkResults = new HashMap<Uri, AppLink>();
    final HashSet<Uri> urisToRequest = new HashSet<Uri>();
    StringBuilder graphRequestFields = new StringBuilder();
    for (Uri uri : uris) {
        AppLink appLink = null;
        synchronized (cachedAppLinks) {
            appLink = cachedAppLinks.get(uri);
        }
        if (appLink != null) {
            appLinkResults.put(uri, appLink);
        } else {
            if (!urisToRequest.isEmpty()) {
                graphRequestFields.append(',');
            }
            graphRequestFields.append(uri.toString());
            urisToRequest.add(uri);
        }
    }
    if (urisToRequest.isEmpty()) {
        return Task.forResult(appLinkResults);
    }
    final Task<Map<Uri, AppLink>>.TaskCompletionSource<Map<Uri, AppLink>> taskCompletionSource = Task.create();
    Bundle appLinkRequestParameters = new Bundle();
    appLinkRequestParameters.putString("ids", graphRequestFields.toString());
    appLinkRequestParameters.putString("fields", String.format("%s.fields(%s,%s)", APP_LINK_KEY, APP_LINK_ANDROID_TARGET_KEY, APP_LINK_WEB_TARGET_KEY));
    Request appLinkRequest = new Request(null, /* Session */
    "", /* Graph path */
    appLinkRequestParameters, /* Query parameters */
    null, /* HttpMethod */
    new Request.Callback() {

        /* Callback */
        @Override
        public void onCompleted(Response response) {
            FacebookRequestError error = response.getError();
            if (error != null) {
                taskCompletionSource.setError(error.getException());
                return;
            }
            GraphObject responseObject = response.getGraphObject();
            JSONObject responseJson = responseObject != null ? responseObject.getInnerJSONObject() : null;
            if (responseJson == null) {
                taskCompletionSource.setResult(appLinkResults);
                return;
            }
            for (Uri uri : urisToRequest) {
                String uriString = uri.toString();
                if (!responseJson.has(uriString)) {
                    continue;
                }
                JSONObject urlData = null;
                try {
                    urlData = responseJson.getJSONObject(uri.toString());
                    JSONObject appLinkData = urlData.getJSONObject(APP_LINK_KEY);
                    JSONArray rawTargets = appLinkData.getJSONArray(APP_LINK_ANDROID_TARGET_KEY);
                    int targetsCount = rawTargets.length();
                    List<AppLink.Target> targets = new ArrayList<AppLink.Target>(targetsCount);
                    for (int i = 0; i < targetsCount; i++) {
                        AppLink.Target target = getAndroidTargetFromJson(rawTargets.getJSONObject(i));
                        if (target != null) {
                            targets.add(target);
                        }
                    }
                    Uri webFallbackUrl = getWebFallbackUriFromJson(uri, appLinkData);
                    AppLink appLink = new AppLink(uri, targets, webFallbackUrl);
                    appLinkResults.put(uri, appLink);
                    synchronized (cachedAppLinks) {
                        cachedAppLinks.put(uri, appLink);
                    }
                } catch (JSONException e) {
                    // The data for this uri was missing or badly formed.
                    continue;
                }
            }
            taskCompletionSource.setResult(appLinkResults);
        }
    });
    appLinkRequest.executeAsync();
    return taskCompletionSource.getTask();
}
Also used : Task(bolts.Task) Bundle(android.os.Bundle) JSONArray(org.json.JSONArray) JSONException(org.json.JSONException) GraphObject(com.facebook.model.GraphObject) Uri(android.net.Uri) JSONObject(org.json.JSONObject) AppLink(bolts.AppLink)

Example 18 with GraphObject

use of com.facebook.model.GraphObject in project facebook-api-android-maven by avianey.

the class TestSession method deleteTestAccount.

private void deleteTestAccount(String testAccountId, String appAccessToken) {
    Bundle parameters = new Bundle();
    parameters.putString("access_token", appAccessToken);
    Request request = new Request(null, testAccountId, parameters, HttpMethod.DELETE);
    Response response = request.executeAndWait();
    FacebookRequestError error = response.getError();
    GraphObject graphObject = response.getGraphObject();
    if (error != null) {
        Log.w(LOG_TAG, String.format("Could not delete test account %s: %s", testAccountId, error.getException().toString()));
    } else if (graphObject.getProperty(Response.NON_JSON_RESPONSE_PROPERTY) == (Boolean) false || graphObject.getProperty(Response.SUCCESS_KEY) == (Boolean) false) {
        Log.w(LOG_TAG, String.format("Could not delete test account %s: unknown reason", testAccountId));
    }
}
Also used : Bundle(android.os.Bundle) GraphObject(com.facebook.model.GraphObject)

Example 19 with GraphObject

use of com.facebook.model.GraphObject in project facebook-api-android-maven by avianey.

the class TestSession method retrieveTestAccountsForAppIfNeeded.

private static synchronized void retrieveTestAccountsForAppIfNeeded() {
    if (appTestAccounts != null) {
        return;
    }
    appTestAccounts = new HashMap<String, TestAccount>();
    // The data we need is split across two different graph API queries. We construct two queries, submit them
    // together (the second one refers to the first one), then cross-reference the results.
    Request.setDefaultBatchApplicationId(testApplicationId);
    Bundle parameters = new Bundle();
    parameters.putString("access_token", getAppAccessToken());
    Request requestTestUsers = new Request(null, "app/accounts/test-users", parameters, null);
    requestTestUsers.setBatchEntryName("testUsers");
    requestTestUsers.setBatchEntryOmitResultOnSuccess(false);
    Bundle testUserNamesParam = new Bundle();
    testUserNamesParam.putString("access_token", getAppAccessToken());
    testUserNamesParam.putString("ids", "{result=testUsers:$.data.*.id}");
    testUserNamesParam.putString("fields", "name");
    Request requestTestUserNames = new Request(null, "", testUserNamesParam, null);
    requestTestUserNames.setBatchEntryDependsOn("testUsers");
    List<Response> responses = Request.executeBatchAndWait(requestTestUsers, requestTestUserNames);
    if (responses == null || responses.size() != 2) {
        throw new FacebookException("Unexpected number of results from TestUsers batch query");
    }
    TestAccountsResponse testAccountsResponse = responses.get(0).getGraphObjectAs(TestAccountsResponse.class);
    GraphObjectList<TestAccount> testAccounts = testAccountsResponse.getData();
    // Response should contain a map of test accounts: { id's => { GraphUser } }
    GraphObject userAccountsMap = responses.get(1).getGraphObject();
    populateTestAccounts(testAccounts, userAccountsMap);
    return;
}
Also used : Bundle(android.os.Bundle) GraphObject(com.facebook.model.GraphObject)

Example 20 with GraphObject

use of com.facebook.model.GraphObject in project facebook-api-android-maven by avianey.

the class Response method createResponseFromObject.

private static Response createResponseFromObject(Request request, HttpURLConnection connection, Object object, boolean isFromCache, Object originalResult) throws JSONException {
    if (object instanceof JSONObject) {
        JSONObject jsonObject = (JSONObject) object;
        FacebookRequestError error = FacebookRequestError.checkResponseAndCreateError(jsonObject, originalResult, connection);
        if (error != null) {
            if (error.getErrorCode() == INVALID_SESSION_FACEBOOK_ERROR_CODE) {
                Session session = request.getSession();
                if (session != null) {
                    session.closeAndClearTokenInformation();
                }
            }
            return new Response(request, connection, error);
        }
        Object body = Utility.getStringPropertyAsJSON(jsonObject, BODY_KEY, NON_JSON_RESPONSE_PROPERTY);
        if (body instanceof JSONObject) {
            GraphObject graphObject = GraphObject.Factory.create((JSONObject) body);
            return new Response(request, connection, body.toString(), graphObject, isFromCache);
        } else if (body instanceof JSONArray) {
            GraphObjectList<GraphObject> graphObjectList = GraphObject.Factory.createList((JSONArray) body, GraphObject.class);
            return new Response(request, connection, body.toString(), graphObjectList, isFromCache);
        }
        // We didn't get a body we understand how to handle, so pretend we got nothing.
        object = JSONObject.NULL;
    }
    if (object == JSONObject.NULL) {
        return new Response(request, connection, object.toString(), (GraphObject) null, isFromCache);
    } else {
        throw new FacebookException("Got unexpected object type in response, class: " + object.getClass().getSimpleName());
    }
}
Also used : GraphObjectList(com.facebook.model.GraphObjectList) JSONObject(org.json.JSONObject) JSONArray(org.json.JSONArray) GraphObject(com.facebook.model.GraphObject) JSONObject(org.json.JSONObject) GraphObject(com.facebook.model.GraphObject)

Aggregations

GraphObject (com.facebook.model.GraphObject)42 JSONObject (org.json.JSONObject)23 Bundle (android.os.Bundle)13 JSONException (org.json.JSONException)11 JSONArray (org.json.JSONArray)10 GraphObjectList (com.facebook.model.GraphObjectList)6 SharedPreferences (android.content.SharedPreferences)5 Request (com.facebook.Request)4 GraphMultiResult (com.facebook.model.GraphMultiResult)4 URI (java.net.URI)4 URISyntaxException (java.net.URISyntaxException)4 Collator (java.text.Collator)4 JSONTokener (org.json.JSONTokener)4 GraphUser (com.facebook.model.GraphUser)3 ActivityNotFoundException (android.content.ActivityNotFoundException)2 Uri (android.net.Uri)2 AppLink (bolts.AppLink)2 Task (bolts.Task)2 FacebookException (com.facebook.FacebookException)2 GraphUserCallback (com.facebook.Request.GraphUserCallback)2