Example usage for org.json JSONArray put

List of usage examples for org.json JSONArray put

Introduction

In this page you can find the example usage for org.json JSONArray put.

Prototype

public JSONArray put(Object value) 

Source Link

Document

Append an object value.

Usage

From source file:com.phonegap.ContactAccessorSdk3_4.java

/**
 * Create a ContactOrganization JSONArray
 * @param cr database access object//from w w  w .ja va  2 s.c o  m
 * @param contactId the ID to search the database for
 * @return a JSONArray representing a set of ContactOrganization
 */
private JSONArray organizationQuery(ContentResolver cr, String contactId) {
    String orgWhere = ContactMethods.PERSON_ID + " = ?";
    String[] orgWhereParams = new String[] { contactId };
    Cursor cursor = cr.query(Organizations.CONTENT_URI, null, orgWhere, orgWhereParams, null);
    JSONArray organizations = new JSONArray();
    JSONObject organization;
    while (cursor.moveToNext()) {
        organization = new JSONObject();
        try {
            organization.put("id", cursor.getString(cursor.getColumnIndex(Organizations._ID)));
            organization.put("name", cursor.getString(cursor.getColumnIndex(Organizations.COMPANY)));
            organization.put("title", cursor.getString(cursor.getColumnIndex(Organizations.TITLE)));
            // organization.put("department", cursor.getString(cursor.getColumnIndex(Organizations)));
            organizations.put(organization);
        } catch (JSONException e) {
            Log.e(LOG_TAG, e.getMessage(), e);
        }
    }
    return organizations;
}

From source file:com.phonegap.ContactAccessorSdk3_4.java

/**
 * Create a ContactAddress JSONArray//from w  ww  .j a  v a 2 s  . com
 * @param cr database access object
 * @param contactId the ID to search the database for
 * @return a JSONArray representing a set of ContactAddress
 */
private JSONArray addressQuery(ContentResolver cr, String contactId) {
    String addrWhere = ContactMethods.PERSON_ID + " = ? AND " + ContactMethods.KIND + " = ?";
    String[] addrWhereParams = new String[] { contactId, ContactMethods.CONTENT_POSTAL_ITEM_TYPE };
    Cursor cursor = cr.query(ContactMethods.CONTENT_URI, null, addrWhere, addrWhereParams, null);
    JSONArray addresses = new JSONArray();
    JSONObject address;
    while (cursor.moveToNext()) {
        address = new JSONObject();
        try {
            address.put("id", cursor.getString(cursor.getColumnIndex(ContactMethods._ID)));
            address.put("formatted", cursor.getString(cursor.getColumnIndex(ContactMethodsColumns.DATA)));
            addresses.put(address);
        } catch (JSONException e) {
            Log.e(LOG_TAG, e.getMessage(), e);
        }
    }
    return addresses;
}

From source file:com.phonegap.ContactAccessorSdk3_4.java

/**
 * Create a ContactField JSONArray/*w  ww  .  j  a  v  a2s . com*/
 * @param cr database access object
 * @param contactId the ID to search the database for
 * @return a JSONArray representing a set of ContactFields
 */
private JSONArray phoneQuery(ContentResolver cr, String contactId) {
    Cursor cursor = cr.query(Phones.CONTENT_URI, null, Phones.PERSON_ID + " = ?", new String[] { contactId },
            null);
    JSONArray phones = new JSONArray();
    JSONObject phone;
    while (cursor.moveToNext()) {
        phone = new JSONObject();
        try {
            phone.put("id", cursor.getString(cursor.getColumnIndex(Phones._ID)));
            phone.put("perf", false);
            phone.put("value", cursor.getString(cursor.getColumnIndex(Phones.NUMBER)));
            phone.put("type", getPhoneType(cursor.getInt(cursor.getColumnIndex(Phones.TYPE))));
            phones.put(phone);
        } catch (JSONException e) {
            Log.e(LOG_TAG, e.getMessage(), e);
        }
    }
    return phones;
}

From source file:com.phonegap.ContactAccessorSdk3_4.java

/**
 * Create a ContactField JSONArray//  w  w  w  .  j a va 2  s.co  m
 * @param cr database access object
 * @param contactId the ID to search the database for
 * @return a JSONArray representing a set of ContactFields
 */
private JSONArray emailQuery(ContentResolver cr, String contactId) {
    Cursor cursor = cr.query(ContactMethods.CONTENT_EMAIL_URI, null, ContactMethods.PERSON_ID + " = ?",
            new String[] { contactId }, null);
    JSONArray emails = new JSONArray();
    JSONObject email;
    while (cursor.moveToNext()) {
        email = new JSONObject();
        try {
            email.put("id", cursor.getString(cursor.getColumnIndex(ContactMethods._ID)));
            email.put("perf", false);
            email.put("value", cursor.getString(cursor.getColumnIndex(ContactMethods.DATA)));
            // TODO Find out why adding an email type throws and exception
            //email.put("type", cursor.getString(cursor.getColumnIndex(ContactMethods.TYPE)));
            emails.put(email);
        } catch (JSONException e) {
            Log.e(LOG_TAG, e.getMessage(), e);
        }
    }
    return emails;
}

From source file:at.alladin.rmbt.android.util.InformationCollector.java

public JSONObject getResultValues(long startTimestampNs) throws JSONException {

    final JSONObject result = new JSONObject();

    final Enumeration<?> pList = fullInfo.propertyNames();

    final int network = getNetwork();
    while (pList.hasMoreElements()) {
        final String key = (String) pList.nextElement();
        boolean add = true;
        if (network == NETWORK_WIFI) {
            if (key.startsWith("TELEPHONY_")) // no mobile data if wifi
                add = false;/*  w  ww .j  a v  a 2 s .  com*/
        } else if (key.startsWith("WIFI_")) // no wifi data if mobile
            add = false;
        if ((network == NETWORK_ETHERNET || network == NETWORK_BLUETOOTH)
                && (key.startsWith("TELEPHONY_") || key.startsWith("WIFI_"))) // add neither mobile nor wifi data 
            add = false;
        if (add)
            result.put(key.toLowerCase(Locale.US), fullInfo.getProperty(key));
    }

    if (geoLocations.size() > 0) {

        final JSONArray itemList = new JSONArray();

        for (int i = 0; i < geoLocations.size(); i++) {

            final GeoLocationItem tmpItem = geoLocations.get(i);

            final JSONObject jsonItem = new JSONObject();

            jsonItem.put("tstamp", tmpItem.tstamp);
            jsonItem.put("time_ns", tmpItem.tstampNano - startTimestampNs);
            jsonItem.put("geo_lat", tmpItem.geo_lat);
            jsonItem.put("geo_long", tmpItem.geo_long);
            jsonItem.put("accuracy", tmpItem.accuracy);
            jsonItem.put("altitude", tmpItem.altitude);
            jsonItem.put("bearing", tmpItem.bearing);
            jsonItem.put("speed", tmpItem.speed);
            jsonItem.put("provider", tmpItem.provider);

            itemList.put(jsonItem);
        }

        result.put("geoLocations", itemList);

    }

    if (cellLocations.size() > 0 && isMobileNetwork(network)) {

        final JSONArray itemList = new JSONArray();

        for (int i = 0; i < cellLocations.size(); i++) {

            final CellLocationItem tmpItem = cellLocations.get(i);

            final JSONObject jsonItem = new JSONObject();

            jsonItem.put("time", tmpItem.tstamp); //add for backward compatibility
            jsonItem.put("time_ns", tmpItem.tstampNano - startTimestampNs);
            jsonItem.put("location_id", tmpItem.locationId);
            Log.i(DEBUG_TAG, "Cell ID:" + tmpItem.locationId);
            jsonItem.put("area_code", tmpItem.areaCode);
            jsonItem.put("primary_scrambling_code", tmpItem.scramblingCode);
            Log.i(DEBUG_TAG, "Scrambling Code:" + tmpItem.scramblingCode);
            itemList.put(jsonItem);
        }

        result.put("cellLocations", itemList);
    }

    //Log.i(DEBUG_TAG, "Signals: " + signals.toString());

    if (signals.size() > 0) {

        final JSONArray itemList = new JSONArray();

        for (int i = 0; i < signals.size(); i++) {
            final SignalItem tmpItem = signals.get(i);

            final JSONObject jsonItem = tmpItem.toJson();
            jsonItem.put("time_ns", tmpItem.tstampNano - startTimestampNs);
            itemList.put(jsonItem);
        }

        result.put("signals", itemList);
    }

    final String tag = ConfigHelper.getTag(context);
    if (tag != null && !tag.isEmpty())
        result.put("tag", tag);

    return result;
}

From source file:org.helios.jzab.agent.commands.impl.jmx.JMXPassiveDiscoveryCommandProcessor.java

/**
 * Var parameters:<ol>/* www.  j a v  a 2 s. c o m*/
 *  <li><b>JMX Object Name</b>: The ObjectName pattern query.</li>
 *  <li><b>Domain</b>: (Optional) Defines the MBeanServer domain in which the target MBeans are registered. Can also be interpreted as a {@link JMXServiceURL} in which case a remote connection will be used to retrieve the attribute values.</li>
 * </ol>
 * {@inheritDoc}
 * @see org.helios.jzab.agent.commands.impl.jmx.JMXDiscoveryCommandProcessor#doExecute(java.lang.String, java.lang.String[])
 */
@Override
protected Object doExecute(String commandName, String... args) throws Exception {
    if (commandName == null || commandName.trim().isEmpty())
        throw new IllegalArgumentException("Null or empty command name", new Throwable());
    if (args == null || args.length < 1)
        throw new IllegalArgumentException("Invalid argument count for command [" + commandName
                + "] with args [" + (args == null ? 0 : args.length) + "]", new Throwable());
    commandName = commandName.trim();
    JSONObject[] parentResults = (JSONObject[]) super.doExecute(commandName, args);
    JSONObject result = new JSONObject();
    JSONArray array = new JSONArray();

    for (JSONObject jo : parentResults) {
        try {
            array.put(jo);
        } catch (Exception e) {
            log.debug("Failed to add parent result [{}]", jo, e);
        }
    }
    try {
        result.put("data", array);
    } catch (Exception e) {
        log.warn("Error adding final [{}]", array, e);
    }
    log.debug("Returning Discovery Result:\n[{}]", result);
    return result;
}

From source file:es.stork.ws.StorkSamlEngineWS.java

/**
 * Validates and translates SAML Tokens// w w  w  . j a va 2 s .c  om
 * @response SAML Token
 * @userIP citizen's IP
 * @return attribute list in JSON format
 */
public String validateSTORKAuthnResponse(@WebParam(name = "response") byte[] response,
        @WebParam(name = "userIP") String userIP) {

    //Validate response
    STORKAuthnResponse tokenSaml = null;

    try {
        tokenSaml = engine.validateSTORKAuthnResponse(response, userIP);
        LOG.info("Validated STORKAuthnResponse(id: {})", tokenSaml.getSamlId());
    } catch (STORKSAMLEngineException e) {
        LOG.error("Validating STORKAuthnResponse: " + e.getMessage());
        e.printStackTrace();
        throw new STORKSAMLEngineWSException(e.getMessage());
    }

    PersonalAttributeList pAttList = (PersonalAttributeList) tokenSaml.getPersonalAttributeList();
    JSONObject json = new JSONObject();

    if (pAttList != null) {

        Iterator<?> itr = pAttList.iterator();

        while (itr.hasNext()) {
            PersonalAttribute att = (PersonalAttribute) itr.next();
            String attName = att.getName();
            if (pAttList.get(attName).getValue().size() > 1) {
                JSONArray jarray = new JSONArray();
                Iterator<?> iter = pAttList.get(attName).getValue().iterator();
                while (iter.hasNext()) {
                    jarray.put(iter.next());
                }
                json.put(attName, jarray);
            } else if (pAttList.get(attName).getValue().size() == 1) {
                json.put(attName, pAttList.get(attName).getValue().get(0));
            } else {
                json.put(attName, "");
            }
        }
        return json.toString();
    } else {
        return null;
    }
}

From source file:com.openerp.addons.note.AddFollowerFragment.java

public void addFollowers(int partnerId) {

    res_partners = new Res_PartnerDBHelper(scope.context());
    oe = res_partners.getOEInstance();//from   w w  w  .j  av  a  2  s . c om
    try {
        JSONObject args = new JSONObject();
        args.put("res_model", "note.note");
        args.put("res_id", record_id);
        args.put("message", message);
        JSONArray partner_ids = new JSONArray();
        partner_ids.put(6);
        partner_ids.put(false);
        JSONArray c_ids = new JSONArray();
        c_ids.put(partnerId);
        partner_ids.put(c_ids);
        args.put("partner_ids", new JSONArray("[" + partner_ids.toString() + "]"));
        JSONObject result = oe.createNew("mail.wizard.invite", args);
        int id = result.getInt("result");

        // calling mail.wizard.invite method
        JSONArray arguments = new JSONArray();
        JSONArray result_id = new JSONArray();
        result_id.put(id);
        arguments.put(result_id);

        JSONObject newValues = new JSONObject();
        newValues.put("default_res_model", "note.note");
        newValues.put("default_res_id", args.getInt("res_id"));
        JSONObject newContext = oe.updateContext(newValues);
        arguments.put(newContext);
        oe.call_kw("mail.wizard.invite", "add_followers", arguments);

    } catch (Exception e) {
        e.printStackTrace();
    }
}

From source file:com.miz.apis.trakt.Trakt.java

public static boolean markMovieAsWatched(List<Movie> movies, Context c) {
    SharedPreferences settings = PreferenceManager.getDefaultSharedPreferences(c);
    String username = settings.getString(TRAKT_USERNAME, "").trim();
    String password = settings.getString(TRAKT_PASSWORD, "");

    if (TextUtils.isEmpty(username) || TextUtils.isEmpty(password) || movies.size() == 0)
        return false;

    try {/*from ww  w.j  a  va 2s . com*/
        JSONObject holder = new JSONObject();
        holder.put("username", username);
        holder.put("password", password);

        JSONArray array = new JSONArray();
        int count = movies.size();
        for (int i = 0; i < count; i++) {
            JSONObject jsonMovie = new JSONObject();
            jsonMovie.put("imdb_id", movies.get(i).getImdbId());
            jsonMovie.put("tmdb_id", movies.get(i).getTmdbId());
            jsonMovie.put("year", movies.get(i).getReleaseYear());
            jsonMovie.put("title", movies.get(i).getTitle());
            array.put(jsonMovie);
        }
        holder.put("movies", array);

        Request request = MizLib
                .getJsonPostRequest((movies.get(0).hasWatched() ? "http://api.trakt.tv/movie/seen/"
                        : "http://api.trakt.tv/movie/unseen/") + getApiKey(c), holder);
        Response response = MizuuApplication.getOkHttpClient().newCall(request).execute();
        return response.isSuccessful();
    } catch (Exception e) {
        return false;
    }
}

From source file:com.miz.apis.trakt.Trakt.java

public static boolean markMoviesAsWatched(List<MediumMovie> movies, Context c) {
    SharedPreferences settings = PreferenceManager.getDefaultSharedPreferences(c);
    String username = settings.getString(TRAKT_USERNAME, "").trim();
    String password = settings.getString(TRAKT_PASSWORD, "");

    if (TextUtils.isEmpty(username) || TextUtils.isEmpty(password) || movies.size() == 0)
        return false;

    try {//  www .  j  a  v a2 s.  com
        JSONObject holder = new JSONObject();
        holder.put("username", username);
        holder.put("password", password);

        JSONArray array = new JSONArray();
        int count = movies.size();
        for (int i = 0; i < count; i++) {
            JSONObject jsonMovie = new JSONObject();
            jsonMovie.put("tmdb_id", movies.get(i).getTmdbId());
            jsonMovie.put("year", movies.get(i).getReleaseYear());
            jsonMovie.put("title", movies.get(i).getTitle());
            array.put(jsonMovie);
        }
        holder.put("movies", array);

        Request request = MizLib
                .getJsonPostRequest((movies.get(0).hasWatched() ? "http://api.trakt.tv/movie/seen/"
                        : "http://api.trakt.tv/movie/unseen/") + getApiKey(c), holder);
        Response response = MizuuApplication.getOkHttpClient().newCall(request).execute();
        return response.isSuccessful();
    } catch (Exception e) {
        return false;
    }
}