Example usage for org.json JSONObject getString

List of usage examples for org.json JSONObject getString

Introduction

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

Prototype

public String getString(String key) throws JSONException 

Source Link

Document

Get the string associated with a key.

Usage

From source file:org.liberty.android.fantastischmemo.downloader.FEDirectory.java

private List<DownloadItem> retrieveList() throws Exception {
    List<DownloadItem> diList = new ArrayList<DownloadItem>();
    String url = FE_API_DIRECTORY;
    String jsonString = downloaderUtils.downloadJSONString(url);
    JSONObject jsonObject = new JSONObject(jsonString);
    String status = jsonObject.getString("response_type");
    Log.v(TAG, "JSON String: " + jsonString);
    if (!status.equals("ok")) {
        Log.v(TAG, "JSON String: " + jsonString);
        throw new IOException("Status is not OK. Status: " + status);
    }/*from w  ww .j av  a 2 s  .  c  o  m*/
    JSONArray directoryArray = jsonObject.getJSONArray("results");
    /*
     * Each result has tags which is an array containing
     * tags and a string of tag group title
     */
    for (int i = 0; i < directoryArray.length(); i++) {
        JSONArray tagsArray = directoryArray.getJSONObject(i).getJSONArray("tags");
        for (int j = 0; j < tagsArray.length(); j++) {
            JSONObject jsonItem = tagsArray.getJSONObject(j);
            String s = jsonItem.getString("tag");
            DownloadItem di = new DownloadItem(DownloadItem.ItemType.Database, s, "", "");
            di.setType(DownloadItem.ItemType.Category);
            diList.add(di);
        }
    }
    return diList;
}

From source file:com.example.android.samplesync.client.RawContact.java

/**
 * Creates and returns an instance of the RawContact from the provided JSON data.
 *
 * @param user The JSONObject containing user data
 * @return user The new instance of Sample RawContact created from the JSON data.
 *///from www .  j  a v a 2s . c o  m
public static RawContact valueOf(JSONObject contact) {

    try {
        final String userName = !contact.isNull("u") ? contact.getString("u") : null;
        final int serverContactId = !contact.isNull("i") ? contact.getInt("i") : -1;
        // If we didn't get either a username or serverId for the contact, then
        // we can't do anything with it locally...
        if ((userName == null) && (serverContactId <= 0)) {
            throw new JSONException("JSON contact missing required 'u' or 'i' fields");
        }

        final int rawContactId = !contact.isNull("c") ? contact.getInt("c") : -1;
        final String firstName = !contact.isNull("f") ? contact.getString("f") : null;
        final String lastName = !contact.isNull("l") ? contact.getString("l") : null;
        final String cellPhone = !contact.isNull("m") ? contact.getString("m") : null;
        final String officePhone = !contact.isNull("o") ? contact.getString("o") : null;
        final String homePhone = !contact.isNull("h") ? contact.getString("h") : null;
        final String email = !contact.isNull("e") ? contact.getString("e") : null;
        final String status = !contact.isNull("s") ? contact.getString("s") : null;
        final String avatarUrl = !contact.isNull("a") ? contact.getString("a") : null;
        final boolean deleted = !contact.isNull("d") ? contact.getBoolean("d") : false;
        final long syncState = !contact.isNull("x") ? contact.getLong("x") : 0;
        return new RawContact(userName, null, firstName, lastName, cellPhone, officePhone, homePhone, email,
                status, avatarUrl, deleted, serverContactId, rawContactId, syncState, false);
    } catch (final Exception ex) {
        Log.i(TAG, "Error parsing JSON contact object" + ex.toString());
    }
    return null;
}

From source file:org.brickred.socialauth.provider.HotmailImpl.java

private List<Contact> getContacts(final String url) throws Exception {
    Response serviceResponse;//from   w  w w.ja  v a  2 s .c o  m
    try {
        serviceResponse = authenticationStrategy.executeFeed(url);
    } catch (Exception e) {
        throw new SocialAuthException("Error while getting contacts from " + url, e);
    }
    if (serviceResponse.getStatus() != 200) {
        throw new SocialAuthException(
                "Error while getting contacts from " + url + "Status : " + serviceResponse.getStatus());
    }
    String result;
    try {
        result = serviceResponse.getResponseBodyAsString(Constants.ENCODING);
    } catch (Exception e) {
        throw new ServerDataException("Failed to get response from " + url, e);
    }
    LOG.debug("User Contacts list in JSON " + result);
    JSONObject resp = new JSONObject(result);
    List<Contact> plist = new ArrayList<Contact>();
    if (resp.has("data")) {
        JSONArray addArr = resp.getJSONArray("data");
        LOG.debug("Contacts Found : " + addArr.length());
        for (int i = 0; i < addArr.length(); i++) {
            JSONObject obj = addArr.getJSONObject(i);
            Contact p = new Contact();
            if (obj.has("email_hashes")) {
                JSONArray emailArr = obj.getJSONArray("email_hashes");
                if (emailArr.length() > 0) {
                    p.setEmailHash(emailArr.getString(0));
                }
            }
            if (obj.has("name")) {
                p.setDisplayName(obj.getString("name"));
            }
            if (obj.has("first_name")) {
                p.setFirstName(obj.getString("first_name"));
            }
            if (obj.has("last_name")) {
                p.setLastName(obj.getString("last_name"));
            }
            if (obj.has("id")) {
                p.setId(obj.getString("id"));
            }
            plist.add(p);
        }
    }
    serviceResponse.close();
    return plist;
}

From source file:org.brickred.socialauth.provider.HotmailImpl.java

private Profile getProfile() throws Exception {
    Profile p = new Profile();
    Response serviceResponse;/*from  ww  w  .ja va 2  s .  co m*/
    try {
        serviceResponse = authenticationStrategy.executeFeed(PROFILE_URL);
    } catch (Exception e) {
        throw new SocialAuthException("Failed to retrieve the user profile from  " + PROFILE_URL, e);
    }

    String result;
    try {
        result = serviceResponse.getResponseBodyAsString(Constants.ENCODING);
        LOG.debug("User Profile :" + result);
    } catch (Exception e) {
        throw new SocialAuthException("Failed to read response from  " + PROFILE_URL, e);
    }
    try {
        JSONObject resp = new JSONObject(result);
        if (resp.has("id")) {
            p.setValidatedId(resp.getString("id"));
        }
        if (resp.has("name")) {
            p.setFullName(resp.getString("name"));
        }
        if (resp.has("first_name")) {
            p.setFirstName(resp.getString("first_name"));
        }
        if (resp.has("last_name")) {
            p.setLastName(resp.getString("last_name"));
        }
        if (resp.has("Location")) {
            p.setLocation(resp.getString("Location"));
        }
        if (resp.has("gender")) {
            p.setGender(resp.getString("gender"));
        }
        if (resp.has("ThumbnailImageLink")) {
            p.setProfileImageURL(resp.getString("ThumbnailImageLink"));
        }

        if (resp.has("birth_day") && !resp.isNull("birth_day")) {
            BirthDate bd = new BirthDate();
            bd.setDay(resp.getInt("birth_day"));
            if (resp.has("birth_month") && !resp.isNull("birth_month")) {
                bd.setMonth(resp.getInt("birth_month"));
            }
            if (resp.has("birth_year") && !resp.isNull("birth_year")) {
                bd.setYear(resp.getInt("birth_year"));
            }
            p.setDob(bd);
        }

        if (resp.has("emails")) {
            JSONObject eobj = resp.getJSONObject("emails");
            String email = null;
            if (eobj.has("preferred")) {
                email = eobj.getString("preferred");
            }
            if ((email == null || email.isEmpty()) && eobj.has("account")) {
                email = eobj.getString("account");
            }
            if ((email == null || email.isEmpty()) && eobj.has("personal")) {
                email = eobj.getString("personal");
            }
            p.setEmail(email);

        }
        if (resp.has("locale")) {
            p.setLanguage(resp.getString("locale"));
        }
        serviceResponse.close();
        p.setProviderId(getProviderId());
        String picUrl = String.format(PROFILE_PICTURE_URL, accessGrant.getKey());
        p.setProfileImageURL(picUrl);
        userProfile = p;
        return p;
    } catch (Exception e) {
        throw new SocialAuthException("Failed to parse the user profile json : " + result, e);
    }
}

From source file:com.soomla.store.domain.VirtualCategory.java

/** Constructor
 *
 * Generates an instance of {@link VirtualCategory} from a JSONObject.
 * @param jsonObject is a JSONObject representation of the wanted {@link VirtualCategory}.
 * @throws JSONException// w w w.j  a va  2 s  .c o  m
 */
public VirtualCategory(JSONObject jsonObject) throws JSONException {
    mName = jsonObject.getString(JSONConsts.CATEGORY_NAME);

    JSONArray goodsArr = jsonObject.getJSONArray(JSONConsts.CATEGORY_GOODSITEMIDS);
    for (int i = 0; i < goodsArr.length(); i++) {
        String goodItemId = goodsArr.getString(i);
        mGoodsItemIds.add(goodItemId);
    }
}

From source file:com.google.testing.web.screenshotter.Screenshot.java

Screenshot(JSONObject response) throws JSONException {
    this.base64 = response.getString("value");
}

From source file:org.dasein.cloud.benchmark.Suite.java

static public void main(String... args) throws Exception {
    ArrayList<Map<String, Object>> suites = new ArrayList<Map<String, Object>>();
    ArrayList<Map<String, Object>> tests = new ArrayList<Map<String, Object>>();

    for (String suiteFile : args) {
        HashMap<String, Object> suite = new HashMap<String, Object>();

        ArrayList<Benchmark> benchmarks = new ArrayList<Benchmark>();

        BufferedReader reader = new BufferedReader(new InputStreamReader(new FileInputStream(suiteFile)));
        StringBuilder json = new StringBuilder();
        String line;/* www  . java  2 s  .c o m*/

        while ((line = reader.readLine()) != null) {
            json.append(line);
            json.append("\n");
        }
        JSONObject ob = new JSONObject(json.toString());

        suite.put("name", ob.getString("name"));
        suite.put("description", ob.getString("description"));

        JSONArray benchmarkClasses = ob.getJSONArray("benchmarks");

        for (int i = 0; i < benchmarkClasses.length(); i++) {
            String cname = benchmarkClasses.getString(i);

            benchmarks.add((Benchmark) Class.forName(cname).newInstance());
        }

        JSONArray clouds = ob.getJSONArray("clouds");

        for (int i = 0; i < clouds.length(); i++) {
            JSONObject cloud = clouds.getJSONObject(i);

            if (cloud.has("regions")) {
                JSONObject regions = cloud.getJSONObject("regions");
                String[] regionIds = JSONObject.getNames(regions);

                if (regionIds != null) {
                    for (String regionId : regionIds) {
                        final JSONObject regionCfg = regions.getJSONObject(regionId);
                        String cname = cloud.getString("providerClass");
                        CloudProvider provider = (CloudProvider) Class.forName(cname).newInstance();
                        JSONObject ctxCfg = cloud.getJSONObject("context");
                        ProviderContext ctx = new ProviderContext();

                        ctx.setEndpoint(regionCfg.getString("endpoint"));
                        ctx.setAccountNumber(ctxCfg.getString("accountNumber"));
                        ctx.setRegionId(regionId);
                        if (ctxCfg.has("accessPublic")) {
                            ctx.setAccessPublic(ctxCfg.getString("accessPublic").getBytes("utf-8"));
                        }
                        if (ctxCfg.has("accessPrivate")) {
                            ctx.setAccessPrivate(ctxCfg.getString("accessPrivate").getBytes("utf-8"));
                        }
                        ctx.setCloudName(ctxCfg.getString("cloudName"));
                        ctx.setProviderName(ctxCfg.getString("providerName"));
                        if (ctxCfg.has("x509Cert")) {
                            ctx.setX509Cert(ctxCfg.getString("x509Cert").getBytes("utf-8"));
                        }
                        if (ctxCfg.has("x509Key")) {
                            ctx.setX509Key(ctxCfg.getString("x509Key").getBytes("utf-8"));
                        }
                        if (ctxCfg.has("customProperties")) {
                            JSONObject p = ctxCfg.getJSONObject("customProperties");
                            String[] names = JSONObject.getNames(p);

                            if (names != null) {
                                Properties props = new Properties();

                                for (String name : names) {
                                    String value = p.getString(name);

                                    if (value != null) {
                                        props.put(name, value);
                                    }
                                }
                                ctx.setCustomProperties(props);
                            }
                        }
                        provider.connect(ctx);

                        Suite s = new Suite(benchmarks, provider);

                        tests.add(s.runBenchmarks(regionCfg));
                    }
                }
            }
        }
        suite.put("benchmarks", tests);
        suites.add(suite);
    }
    System.out.println((new JSONArray(suites)).toString());
}

From source file:ru.otdelit.astrid.opencrx.sync.OpencrxSyncProvider.java

protected void performSync() {

    labelMap = new HashMap<String, String>();
    lastSync = new Time();

    preferences.recordSyncStart();/*  w  ww.  java2  s .c  o m*/

    Log.i(OpencrxUtils.TAG, "Starting sync!");

    try {
        // load user information
        JSONObject user = invoker.userUpdateOpencrx();
        saveUserData(user);
        String userCrxId = user.getString("crxid_user");

        Time cur = new Time();

        String lastServerSync = Preferences.getStringValue(OpencrxUtilities.PREF_SERVER_LAST_SYNC);

        try {
            if (lastServerSync != null) {
                lastSync.parse(lastServerSync);
            } else {
                // very long time ago
                lastSync.set(1, 1, 1980);
            }
        } catch (TimeFormatException ex) {
            lastSync.set(1, 1, 1980);
        }

        String lastNotificationId = Preferences.getStringValue(OpencrxUtilities.PREF_SERVER_LAST_NOTIFICATION);
        String lastActivityId = Preferences.getStringValue(OpencrxUtilities.PREF_SERVER_LAST_ACTIVITY);

        // read dashboards
        updateCreators();

        // read contacts
        updateContacts();

        // read labels
        updateResources(userCrxId);

        // read activity process graph
        graph = invoker.getActivityProcessGraph();

        ArrayList<OpencrxTaskContainer> remoteTasks = new ArrayList<OpencrxTaskContainer>();
        JSONArray tasks = invoker.tasksShowListOpencrx(graph);

        for (int i = 0; i < tasks.length(); i++) {

            JSONObject task = tasks.getJSONObject(i);
            OpencrxTaskContainer remote = parseRemoteTask(task);

            // update reminder flags for incoming remote tasks to prevent annoying
            if (remote.task.hasDueDate() && remote.task.getValue(Task.DUE_DATE) < DateUtilities.now())
                remote.task.setFlag(Task.REMINDER_FLAGS, Task.NOTIFY_AFTER_DEADLINE, false);

            dataService.findLocalMatch(remote);

            remoteTasks.add(remote);

        }

        // TODO: delete
        Log.i(OpencrxUtils.TAG, "Matching local to remote...");

        matchLocalTasksToRemote(remoteTasks);

        // TODO: delete
        Log.i(OpencrxUtils.TAG, "Matching local to remote finished");

        // TODO: delete
        Log.i(OpencrxUtils.TAG, "Synchronizing tasks...");

        SyncData<OpencrxTaskContainer> syncData = populateSyncData(remoteTasks);
        try {
            synchronizeTasks(syncData);
        } finally {
            syncData.localCreated.close();
            syncData.localUpdated.close();
        }

        // TODO: delete
        Log.i(OpencrxUtils.TAG, "Synchronizing tasks finished");

        cur.setToNow();
        Preferences.setString(OpencrxUtilities.PREF_SERVER_LAST_SYNC, cur.format2445());

        preferences.recordSuccessfulSync();

        Intent broadcastIntent = new Intent(AstridApiConstants.BROADCAST_EVENT_REFRESH);
        ContextManager.getContext().sendBroadcast(broadcastIntent, AstridApiConstants.PERMISSION_READ);

        // store lastIds in Preferences
        Preferences.setString(OpencrxUtilities.PREF_SERVER_LAST_NOTIFICATION, lastNotificationId);
        Preferences.setString(OpencrxUtilities.PREF_SERVER_LAST_ACTIVITY, lastActivityId);

        labelMap = null;
        lastSync = null;

        // TODO: delete
        Log.i(OpencrxUtils.TAG, "Sync successfull");

    } catch (IllegalStateException e) {
        // occurs when application was closed
    } catch (Exception e) {
        handleException("opencrx-sync", e, true); //$NON-NLS-1$
    }
}

From source file:ru.otdelit.astrid.opencrx.sync.OpencrxSyncProvider.java

/** Create a task container for the given RtmTaskSeries
 * @throws JSONException/*from w ww .  j av  a 2 s.com*/
 * @throws IOException
 * @throws ApiServiceException */
private OpencrxTaskContainer parseRemoteTask(JSONObject remoteTask)
        throws JSONException, ApiServiceException, IOException {

    String resourceId = Preferences.getStringValue(OpencrxUtilities.PREF_RESOURCE_ID);

    String crxId = remoteTask.getString("repeating_value");

    JSONArray labels = invoker.resourcesShowForTask(crxId);

    int secondsSpentOnTask = invoker.getSecondsSpentOnTask(crxId, resourceId);

    Task task = new Task();
    ArrayList<Metadata> metadata = new ArrayList<Metadata>();

    if (remoteTask.has("task"))
        remoteTask = remoteTask.getJSONObject("task");

    task.setValue(Task.TITLE, ApiUtilities.decode(remoteTask.getString("title")));
    task.setValue(Task.NOTES, remoteTask.getString("detailedDescription"));
    task.setValue(Task.CREATION_DATE,
            ApiUtilities.producteevToUnixTime(remoteTask.getString("time_created"), 0));
    task.setValue(Task.COMPLETION_DATE, remoteTask.getInt("status") == 1 ? DateUtilities.now() : 0);
    task.setValue(Task.DELETION_DATE, remoteTask.getInt("deleted") == 1 ? DateUtilities.now() : 0);
    task.setValue(Task.ELAPSED_SECONDS, secondsSpentOnTask);
    task.setValue(Task.MODIFICATION_DATE, remoteTask.getLong("modifiedAt"));

    long dueDate = ApiUtilities.producteevToUnixTime(remoteTask.getString("deadline"), 0);
    if (remoteTask.optInt("all_day", 0) == 1)
        task.setValue(Task.DUE_DATE, Task.createDueDate(Task.URGENCY_SPECIFIC_DAY, dueDate));
    else
        task.setValue(Task.DUE_DATE, Task.createDueDate(Task.URGENCY_SPECIFIC_DAY_TIME, dueDate));
    task.setValue(Task.IMPORTANCE, 5 - remoteTask.getInt("star"));

    for (int i = 0; i < labels.length(); i++) {
        JSONObject label = labels.getJSONObject(i);

        Metadata tagData = new Metadata();
        tagData.setValue(Metadata.KEY, OpencrxDataService.TAG_KEY);
        tagData.setValue(OpencrxDataService.TAG, label.getString("name"));
        metadata.add(tagData);
    }

    OpencrxTaskContainer container = new OpencrxTaskContainer(task, metadata, remoteTask);

    return container;
}

From source file:ru.otdelit.astrid.opencrx.sync.OpencrxSyncProvider.java

/**
 * Read labels into label map//  ww w .  j  a  v  a  2s  .  com
 * @param userCrxId
 * @param dashboardId
 * @throws JSONException
 * @throws ApiServiceException
 * @throws IOException
 */
private void readLabels(JSONArray labels, String userCrxId)
        throws JSONException, ApiServiceException, IOException {
    for (int i = 0; i < labels.length(); i++) {
        JSONObject label = labels.getJSONObject(i);
        putLabelIntoCache(label);

        String contactId = label.optString("contact_id");
        if (userCrxId.equals(contactId)) {
            Preferences.setString(OpencrxUtilities.PREF_RESOURCE_ID, label.getString("id"));
        }
    }
}