Example usage for org.json JSONObject optString

List of usage examples for org.json JSONObject optString

Introduction

In this page you can find the example usage for org.json JSONObject optString.

Prototype

public String optString(String key) 

Source Link

Document

Get an optional string associated with a key.

Usage

From source file:com.facebook.share.internal.ShareInternalUtility.java

public static JSONObject toJSONObjectForCall(final UUID callId, final ShareOpenGraphContent content)
        throws JSONException {
    final ShareOpenGraphAction action = content.getAction();
    final ArrayList<NativeAppCallAttachmentStore.Attachment> attachments = new ArrayList<>();
    JSONObject actionJSON = OpenGraphJSONUtility.toJSONObject(action,
            new OpenGraphJSONUtility.PhotoJSONProcessor() {
                @Override/*ww w.j ava2s .  co m*/
                public JSONObject toJSONObject(SharePhoto photo) {
                    NativeAppCallAttachmentStore.Attachment attachment = getAttachment(callId, photo);

                    if (attachment == null) {
                        return null;
                    }

                    attachments.add(attachment);

                    JSONObject photoJSONObject = new JSONObject();
                    try {
                        photoJSONObject.put(NativeProtocol.IMAGE_URL_KEY, attachment.getAttachmentUrl());
                        if (photo.getUserGenerated()) {
                            photoJSONObject.put(NativeProtocol.IMAGE_USER_GENERATED_KEY, true);
                        }
                    } catch (JSONException e) {
                        throw new FacebookException("Unable to attach images", e);
                    }
                    return photoJSONObject;
                }
            });

    NativeAppCallAttachmentStore.addAttachments(attachments);
    // People and place tags must be moved from the share content to the open graph action
    if (content.getPlaceId() != null) {
        String placeTag = actionJSON.optString("place");

        // Only if the place tag is already empty or null replace with the id from the
        // share content
        if (Utility.isNullOrEmpty(placeTag)) {
            actionJSON.put("place", content.getPlaceId());
        }
    }

    if (content.getPeopleIds() != null) {
        JSONArray peopleTags = actionJSON.optJSONArray("tags");
        Set<String> peopleIdSet = peopleTags == null ? new HashSet<String>()
                : Utility.jsonArrayToSet(peopleTags);

        for (String peopleId : content.getPeopleIds()) {
            peopleIdSet.add(peopleId);
        }
        actionJSON.put("tags", new ArrayList<>(peopleIdSet));
    }

    return actionJSON;
}

From source file:com.facebook.share.internal.ShareInternalUtility.java

/**
 * Creates a new Request configured to create a user owned Open Graph object.
 *
 * @param accessToken     the accessToken to use, or null
 * @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
 */// w  w w  . j  a v  a 2  s . com
public static GraphRequest newPostOpenGraphObjectRequest(AccessToken accessToken, JSONObject openGraphObject,
        Callback callback) {
    if (openGraphObject == null) {
        throw new FacebookException("openGraphObject cannot be null");
    }
    if (Utility.isNullOrEmpty(openGraphObject.optString("type"))) {
        throw new FacebookException("openGraphObject must have non-null 'type' property");
    }
    if (Utility.isNullOrEmpty(openGraphObject.optString("title"))) {
        throw new FacebookException("openGraphObject must have non-null 'title' property");
    }

    String path = String.format(MY_OBJECTS_FORMAT, openGraphObject.optString("type"));
    Bundle bundle = new Bundle();
    bundle.putString(OBJECT_PARAM, openGraphObject.toString());
    return new GraphRequest(accessToken, path, bundle, HttpMethod.POST, callback);
}

From source file:com.facebook.share.internal.ShareInternalUtility.java

/**
 * Creates a new Request configured to publish an Open Graph action.
 *
 * @param accessToken     the access token to use, or null
 * @param openGraphAction the Open Graph action to create; must not be null, and must have a
 *                        non-empty 'type'
 * @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
 *///  w ww. j a  v  a2 s. co m
public static GraphRequest newPostOpenGraphActionRequest(AccessToken accessToken, JSONObject openGraphAction,
        Callback callback) {
    if (openGraphAction == null) {
        throw new FacebookException("openGraphAction cannot be null");
    }
    String type = openGraphAction.optString("type");
    if (Utility.isNullOrEmpty(type)) {
        throw new FacebookException("openGraphAction must have non-null 'type' property");
    }

    String path = String.format(MY_ACTION_FORMAT, type);
    return GraphRequest.newPostRequest(accessToken, path, openGraphAction, callback);
}

From source file:com.facebook.share.internal.ShareInternalUtility.java

/**
 * Creates a new Request configured to update a user owned Open Graph object.
 *
 * @param accessToken     the access token to use, or null
 * @param openGraphObject the Open Graph object to update, which must have a valid 'id'
 *                        property/* ww w  .jav a 2  s  .com*/
 * @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 GraphRequest newUpdateOpenGraphObjectRequest(AccessToken accessToken, JSONObject openGraphObject,
        Callback callback) {
    if (openGraphObject == null) {
        throw new FacebookException("openGraphObject cannot be null");
    }

    String path = openGraphObject.optString("id");
    if (path == null) {
        throw new FacebookException("openGraphObject must have an id");
    }

    Bundle bundle = new Bundle();
    bundle.putString(OBJECT_PARAM, openGraphObject.toString());
    return new GraphRequest(accessToken, path, bundle, HttpMethod.POST, callback);
}

From source file:com.facebook.share.internal.ShareInternalUtility.java

/**
 * Creates a new Request configured to post a status update to a user's feed.
 *
 * @param accessToken the access token to use, or null
 * @param message     the text of the status update
 * @param place       an optional place to associate with the post
 * @param tags        an optional list of users to tag in the post
 * @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
 *//*from  w  w  w  .  j av  a 2  s  . c  o  m*/
public static GraphRequest newStatusUpdateRequest(AccessToken accessToken, String message, JSONObject place,
        List<JSONObject> tags, Callback callback) {

    List<String> tagIds = null;
    if (tags != null) {
        tagIds = new ArrayList<String>(tags.size());
        for (JSONObject tag : tags) {
            tagIds.add(tag.optString("id"));
        }
    }
    String placeId = place == null ? null : place.optString("id");
    return newStatusUpdateRequest(accessToken, message, placeId, tagIds, callback);
}

From source file:com.google.blockly.model.FieldImage.java

public static FieldImage fromJson(JSONObject json) {
    return new FieldImage(json.optString("name"),
            json.optString("src", "https://www.gstatic.com/codesite/ph/images/star_on.gif"),
            json.optInt("width", 15), json.optInt("height", 15), json.optString("alt", "*"));
}

From source file:com.phonegap.ContactAccessorSdk5.java

/** 
 * This method takes the fields required and search options in order to produce an 
 * array of contacts that matches the criteria provided.
 * @param fields an array of items to be used as search criteria
 * @param options that can be applied to contact searching
 * @return an array of contacts /*from ww w  . j av  a  2  s .  c  o m*/
 */
@Override
public JSONArray search(JSONArray fields, JSONObject options) {
    long totalEnd;
    long totalStart = System.currentTimeMillis();

    // Get the find options
    String searchTerm = "";
    int limit = Integer.MAX_VALUE;
    boolean multiple = true;

    if (options != null) {
        searchTerm = options.optString("filter");
        if (searchTerm.length() == 0) {
            searchTerm = "%";
        } else {
            searchTerm = "%" + searchTerm + "%";
        }
        try {
            multiple = options.getBoolean("multiple");
            if (!multiple) {
                limit = 1;
            }
        } catch (JSONException e) {
            // Multiple was not specified so we assume the default is true.
        }
    } else {
        searchTerm = "%";
    }

    //Log.d(LOG_TAG, "Search Term = " + searchTerm);
    //Log.d(LOG_TAG, "Field Length = " + fields.length());
    //Log.d(LOG_TAG, "Fields = " + fields.toString());

    // Loop through the fields the user provided to see what data should be returned.
    HashMap<String, Boolean> populate = buildPopulationSet(fields);

    // Build the ugly where clause and where arguments for one big query.
    WhereOptions whereOptions = buildWhereClause(fields, searchTerm);

    // Get all the id's where the search term matches the fields passed in.
    Cursor idCursor = mApp.getContentResolver().query(ContactsContract.Data.CONTENT_URI,
            new String[] { ContactsContract.Data.CONTACT_ID }, whereOptions.getWhere(),
            whereOptions.getWhereArgs(), ContactsContract.Data.CONTACT_ID + " ASC");

    // Create a set of unique ids
    //Log.d(LOG_TAG, "ID cursor query returns = " + idCursor.getCount());
    Set<String> contactIds = new HashSet<String>();
    while (idCursor.moveToNext()) {
        contactIds.add(idCursor.getString(idCursor.getColumnIndex(ContactsContract.Data.CONTACT_ID)));
    }
    idCursor.close();

    // Build a query that only looks at ids
    WhereOptions idOptions = buildIdClause(contactIds, searchTerm);

    // Do the id query
    Cursor c = mApp.getContentResolver().query(ContactsContract.Data.CONTENT_URI, null, idOptions.getWhere(),
            idOptions.getWhereArgs(), ContactsContract.Data.CONTACT_ID + " ASC");

    //Log.d(LOG_TAG, "Cursor length = " + c.getCount());

    String contactId = "";
    String rawId = "";
    String oldContactId = "";
    boolean newContact = true;
    String mimetype = "";

    JSONArray contacts = new JSONArray();
    JSONObject contact = new JSONObject();
    JSONArray organizations = new JSONArray();
    JSONArray addresses = new JSONArray();
    JSONArray phones = new JSONArray();
    JSONArray emails = new JSONArray();
    JSONArray ims = new JSONArray();
    JSONArray websites = new JSONArray();
    JSONArray photos = new JSONArray();

    if (c.getCount() > 0) {
        while (c.moveToNext() && (contacts.length() <= (limit - 1))) {
            try {
                contactId = c.getString(c.getColumnIndex(ContactsContract.Data.CONTACT_ID));
                rawId = c.getString(c.getColumnIndex(ContactsContract.Data.RAW_CONTACT_ID));

                // If we are in the first row set the oldContactId
                if (c.getPosition() == 0) {
                    oldContactId = contactId;
                }

                // When the contact ID changes we need to push the Contact object 
                // to the array of contacts and create new objects.
                if (!oldContactId.equals(contactId)) {
                    // Populate the Contact object with it's arrays
                    // and push the contact into the contacts array
                    contacts.put(populateContact(contact, organizations, addresses, phones, emails, ims,
                            websites, photos));

                    // Clean up the objects
                    contact = new JSONObject();
                    organizations = new JSONArray();
                    addresses = new JSONArray();
                    phones = new JSONArray();
                    emails = new JSONArray();
                    ims = new JSONArray();
                    websites = new JSONArray();
                    photos = new JSONArray();

                    // Set newContact to true as we are starting to populate a new contact
                    newContact = true;
                }

                // When we detect a new contact set the ID and display name.
                // These fields are available in every row in the result set returned.
                if (newContact) {
                    newContact = false;
                    contact.put("id", contactId);
                    contact.put("rawId", rawId);
                    contact.put("displayName", c.getString(
                            c.getColumnIndex(ContactsContract.CommonDataKinds.StructuredName.DISPLAY_NAME)));
                }

                // Grab the mimetype of the current row as it will be used in a lot of comparisons
                mimetype = c.getString(c.getColumnIndex(ContactsContract.Data.MIMETYPE));

                if (mimetype.equals(ContactsContract.CommonDataKinds.StructuredName.CONTENT_ITEM_TYPE)
                        && isRequired("name", populate)) {
                    contact.put("name", nameQuery(c));
                } else if (mimetype.equals(ContactsContract.CommonDataKinds.Phone.CONTENT_ITEM_TYPE)
                        && isRequired("phoneNumbers", populate)) {
                    phones.put(phoneQuery(c));
                } else if (mimetype.equals(ContactsContract.CommonDataKinds.Email.CONTENT_ITEM_TYPE)
                        && isRequired("emails", populate)) {
                    emails.put(emailQuery(c));
                } else if (mimetype.equals(ContactsContract.CommonDataKinds.StructuredPostal.CONTENT_ITEM_TYPE)
                        && isRequired("addresses", populate)) {
                    addresses.put(addressQuery(c));
                } else if (mimetype.equals(ContactsContract.CommonDataKinds.Organization.CONTENT_ITEM_TYPE)
                        && isRequired("organizations", populate)) {
                    organizations.put(organizationQuery(c));
                } else if (mimetype.equals(ContactsContract.CommonDataKinds.Im.CONTENT_ITEM_TYPE)
                        && isRequired("ims", populate)) {
                    ims.put(imQuery(c));
                } else if (mimetype.equals(ContactsContract.CommonDataKinds.Note.CONTENT_ITEM_TYPE)
                        && isRequired("note", populate)) {
                    contact.put("note",
                            c.getString(c.getColumnIndex(ContactsContract.CommonDataKinds.Note.NOTE)));
                } else if (mimetype.equals(ContactsContract.CommonDataKinds.Nickname.CONTENT_ITEM_TYPE)
                        && isRequired("nickname", populate)) {
                    contact.put("nickname",
                            c.getString(c.getColumnIndex(ContactsContract.CommonDataKinds.Nickname.NAME)));
                } else if (mimetype.equals(ContactsContract.CommonDataKinds.Website.CONTENT_ITEM_TYPE)
                        && isRequired("urls", populate)) {
                    websites.put(websiteQuery(c));
                } else if (mimetype.equals(ContactsContract.CommonDataKinds.Event.CONTENT_ITEM_TYPE)) {
                    if (ContactsContract.CommonDataKinds.Event.TYPE_BIRTHDAY == c
                            .getInt(c.getColumnIndex(ContactsContract.CommonDataKinds.Event.TYPE))
                            && isRequired("birthday", populate)) {
                        contact.put("birthday", c.getString(
                                c.getColumnIndex(ContactsContract.CommonDataKinds.Event.START_DATE)));
                    }
                } else if (mimetype.equals(ContactsContract.CommonDataKinds.Photo.CONTENT_ITEM_TYPE)
                        && isRequired("photos", populate)) {
                    photos.put(photoQuery(c, contactId));
                }
            } catch (JSONException e) {
                Log.e(LOG_TAG, e.getMessage(), e);
            }

            // Set the old contact ID 
            oldContactId = contactId;
        }

        // Push the last contact into the contacts array
        if (contacts.length() < limit) {
            contacts.put(
                    populateContact(contact, organizations, addresses, phones, emails, ims, websites, photos));
        }
    }
    c.close();

    totalEnd = System.currentTimeMillis();
    Log.d(LOG_TAG, "Total time = " + (totalEnd - totalStart));
    return contacts;
}

From source file:fr.cph.stock.android.activity.OverallActivity.java

@Override
public void displayError(JSONObject json) {
    Log.i(TAG, json.toString());//  w ww. j ava 2  s  .c o m
    boolean sessionError = ((StockTrackerApp) getApplication()).isSessionError(json);
    if (sessionError) {
        ((StockTrackerApp) getApplication()).loadErrorActivity(this, json);
    } else {
        errorView.setText(json.optString("error"));
        RelativeLayout.LayoutParams params = new RelativeLayout.LayoutParams((int) LayoutParams.MATCH_PARENT,
                (int) LayoutParams.MATCH_PARENT);
        params.addRule(RelativeLayout.BELOW, errorView.getId());
        ListView listView = (ListView) findViewById(android.R.id.list);
        listView.setLayoutParams(params);
        refreshItem.collapseActionView();
        refreshItem.setActionView(null);
    }
}

From source file:org.uiautomation.ios.server.command.web.LongTapHandler.java

public LongTapHandler(IOSServerManager driver, WebDriverLikeRequest request) throws Exception {
    super(driver, request);

    JSONObject payload = request.getPayload();
    String elementId = payload.optString("element");

    Dimension screenSize = driver.getSession(request.getSession()).getNativeDriver().getScreenSize();
    RemoteWebNativeBackedElement element = (RemoteWebNativeBackedElement) getSession().getRemoteWebDriver()
            .createElement(elementId);//  w  w  w  . j  av a 2s  .  co  m
    Point tapPoint = element.getLocation();
    tapPoint = CoordinateUtils.forcePointOnScreen(tapPoint, screenSize);

    String js = longTapTemplate.replace(":sessionId", request.getSession())
            .replace("tapX", Integer.toString(tapPoint.getX()))
            .replace("tapY", Integer.toString(tapPoint.getY()));

    setJS(js);
}

From source file:com.alchemiasoft.common.model.Book.java

public static Book oneFrom(@NonNull JSONObject json) {
    final Book book = new Book();
    book.mServerId = json.optString("serverId");
    book.mTitle = json.optString("title");
    book.mAuthor = json.optString("author");
    book.mSource = json.optString("source");
    book.mDescription = json.optString("description");
    book.mPages = json.optInt("pages");
    return book;/*from  ww  w  .j a v a 2  s . c o  m*/
}