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.google.appengine.tools.mapreduce.impl.MapperStateEntity.java

/**
 * Create json object from this one. If detailed is true creates an object
 * with all the information needed for the job detail status view. Otherwise,
 * only includes the overview information.
 *///from  ww w .  ja  va 2 s . com
public JSONObject toJson(boolean detailed) {
    JSONObject jobObject = new JSONObject();
    try {
        jobObject.put("name", getName());
        jobObject.put("mapreduce_id", getJobID());
        jobObject.put("active", getStatus() == Status.ACTIVE);
        jobObject.put("updated_timestamp_ms", getLastPollTime());
        jobObject.put("start_timestamp_ms", getStartTime());
        jobObject.put("result_status", String.valueOf(getStatus()));

        if (detailed) {
            jobObject.put("counters", toJson(getCounters()));
            jobObject.put("chart_url", getChartUrl());

            // TODO(user): Fill this from the Configuration
            JSONObject mapperSpec = new JSONObject();
            mapperSpec.put("mapper_params", new JSONObject());
            jobObject.put("mapper_spec", mapperSpec);

            List<ShardStateEntity<K, V, OK, OV>> shardStates = ShardStateEntity.getShardStates(this);

            JSONArray shardArray = new JSONArray();
            for (ShardStateEntity<K, V, OK, OV> shardState : shardStates) {
                shardArray.put(shardState.toJson());
            }
            jobObject.put("shards", shardArray);
        } else {
            jobObject.put("shards", getShardCount());
            jobObject.put("active_shards", getActiveShardCount());
        }
    } catch (JSONException e) {
        throw new RuntimeException("Hard coded string is null", e);
    }

    return jobObject;
}

From source file:org.protorabbit.json.DefaultSerializer.java

public Object serialize(Object o) {

    // null is null
    if (o == null) {
        return JSONObject.NULL;
    }/*from  ww  w.  j  a  v  a 2 s.  co  m*/

    // collections
    if (Collection.class.isAssignableFrom(o.getClass())) {
        Iterator<?> it = ((Collection<?>) o).iterator();

        JSONArray ja = new JSONArray();
        while (it.hasNext()) {

            Object i = serialize(it.next());
            ja.put(i);
        }
        return ja;
    }

    // maps
    if (Map.class.isAssignableFrom(o.getClass())) {
        JSONObject jo = new JSONObject();
        Map<?, ?> m = ((Map<?, ?>) o);
        Iterator<?> ki = m.keySet().iterator();
        while (ki.hasNext()) {
            Object key = ki.next();
            Object value = serialize(m.get(key));
            try {
                jo.put(key.toString(), value);
            } catch (JSONException e) {
                e.printStackTrace();
            }
        }
        return jo;
    }

    // primitives
    if (o instanceof Double || o instanceof Number || o instanceof Integer || o instanceof String
            || o instanceof Enum<?> || o instanceof Boolean) {
        return o;
    }

    if (o instanceof Date) {
        return ((Date) o).getTime();
    }

    // convert arrays to collections
    boolean b = o.getClass().isArray();

    if (b) {
        try {
            Object[] objs = (Object[]) o;
            List<Object> l = Arrays.asList(objs);
            return serialize(l);
        } catch (ClassCastException e) {
            return JSONObject.NULL;
        }
    }
    // serialize using bean like methods
    return serializePOJO(o, true);

}

From source file:com.whizzosoftware.hobson.scheduler.ical.ICalTaskProviderTest.java

@Test
public void testEditEvent() throws Exception {
    File file = File.createTempFile("hob", ".ics");
    try {// w  ww  .  ja  v  a  2  s .  c om
        String ical = "BEGIN:VCALENDAR\n" + "PRODID:-//Whizzo Software//Hobson 1.0//EN\n" + "VERSION:2.0\n"
                + "BEGIN:VEVENT\n" + "UID:15dee4fe-a841-4cf6-8d7f-76c3ad5492b1\n" + "DTSTART:20130714T170000Z\n"
                + "DTEND:20130714T170000Z\n" + "SUMMARY:My Task\n"
                + "COMMENT:[{'pluginId':'com.whizzosoftware.hobson.server-api','actionId':'log','name':'My Action','properties':{'message':'foo'}}]\n"
                + "END:VEVENT\n" + "END:VCALENDAR";

        String ical2 = "BEGIN:VCALENDAR\n" + "PRODID:-//Whizzo Software//Hobson 1.0//EN\n" + "VERSION:2.0\n"
                + "BEGIN:VEVENT\n" + "UID:15dee4fe-a841-4cf6-8d7f-76c3ad5492b1\n" + "DTSTART:20130714T170000Z\n"
                + "DTEND:20130714T170000Z\n" + "SUMMARY:My Edited Task\n"
                + "COMMENT:[{'pluginId':'com.whizzosoftware.hobson.server-api','actionId':'log','name':'My Edited Action','properties':{'message':'foobar'}}]\n"
                + "END:VEVENT\n" + "END:VCALENDAR";

        // write out ICS to temp file
        FileWriter fw = new FileWriter(file);
        fw.append(ical);
        fw.close();

        ICalTaskProvider p = new ICalTaskProvider("pluginId", null, null,
                TimeZone.getTimeZone("America/Denver"));
        p.setScheduleExecutor(new MockScheduledTaskExecutor());
        p.setScheduleFile(file);
        p.start();

        // make sure the task was created
        assertEquals(1, p.getTasks().size());

        // create task JSON
        JSONObject json = new JSONObject();
        json.put("name", "My Edited Task");
        JSONArray conds = new JSONArray();
        json.put("conditions", conds);
        JSONObject cond = new JSONObject();
        conds.put(cond);
        cond.put("start", "20130714T170000Z");
        JSONArray actions = new JSONArray();
        json.put("actions", actions);
        JSONObject action = new JSONObject();
        actions.put(action);
        action.put("pluginId", "com.whizzosoftware.hobson.server-api");
        action.put("actionId", "log");
        action.put("name", "My Edited Action");
        JSONObject props = new JSONObject();
        action.put("properties", props);
        props.put("message", "foobar");

        // update the task
        p.updateTask("15dee4fe-a841-4cf6-8d7f-76c3ad5492b1", json);

        assertTrue(file.exists());

        // read back file
        Calendar cal = new CalendarBuilder().build(new FileInputStream(file));
        assertEquals(1, cal.getComponents().size());
        VEvent c = (VEvent) cal.getComponents().get(0);
        assertEquals("My Edited Task", c.getProperty("SUMMARY").getValue());
        assertEquals("15dee4fe-a841-4cf6-8d7f-76c3ad5492b1", c.getProperty("UID").getValue());
        assertEquals("20130714T170000Z", c.getProperty("DTSTART").getValue());
        JSONArray aj = new JSONArray(new JSONTokener(c.getProperty("COMMENT").getValue()));
        assertEquals(1, aj.length());
        JSONObject cj = aj.getJSONObject(0);
        assertEquals("com.whizzosoftware.hobson.server-api", cj.getString("pluginId"));
        assertEquals("My Edited Action", cj.getString("name"));
        assertEquals("log", cj.getString("actionId"));
        assertTrue(cj.has("properties"));
        JSONObject pj = cj.getJSONObject("properties");
        assertEquals("foobar", pj.getString("message"));
    } finally {
        file.delete();
    }
}

From source file:com.google.android.gms.location.sample.geofencing.MainActivity.java

private void storeInDb(LatLng latLng) {
    String towerIds = Constants.NOT_AVAILABLE;
    if (mNetworkDetailModelList != null && !mNetworkDetailModelList.isEmpty()) {
        JSONArray array = new JSONArray();
        int size = mNetworkDetailModelList.size();
        for (int i = 0; i < size; i++) {
            JSONObject object = new JSONObject();
            NetworkDetailModel model = mNetworkDetailModelList.get(i);

            try {
                object.put(DatabaseHelper.IUserGeoFenceDetails.Columns.LAC, model.getLac());
                object.put(DatabaseHelper.IUserGeoFenceDetails.Columns.TOWER_IDS, model.getCellID());
                object.put(DatabaseHelper.IUserGeoFenceDetails.Columns.MNC, model.getMnc());
                object.put(DatabaseHelper.IUserGeoFenceDetails.Columns.MCC, model.getMcc());
                object.put(DatabaseHelper.IUserGeoFenceDetails.Columns.LAT, latLng.latitude);
                object.put(DatabaseHelper.IUserGeoFenceDetails.Columns.LNG, latLng.longitude);
                object.put(DatabaseHelper.IUserGeoFenceDetails.Columns.OPERATOR_NAME, model.getOperatorName());
                object.put(DatabaseHelper.IUserGeoFenceDetails.Columns.RSSI, model.getRssid());
                array.put(object);
            } catch (JSONException ex) {
                Log.i("Exception", "exception" + ex);
            }//from   w w  w . ja  v a 2 s .c  o  m
            towerIds = array.toString();
        }

        long i = dataSource.insertGeofenceDetails(place, Double.toString(latLng.latitude),
                Double.toString(latLng.longitude), towerIds,
                GeoFenceApp.getLocationUtilityInstance().getLocation());
        Log.i("tag", "i:" + i);
    }

}

From source file:de.kasoki.jfeedly.JFeedly.java

/**
 * Subscribe to a feed//from ww w. j a  va 2s . c  om
 * @param feedUrl The URL of the feed
 * @param title The title of this feed
 * @param categories A list of categories, if this is empty the feed will be in the "Uncategorized" category.
 */
public void subscribe(String feedUrl, String title, List<Category> categories) {
    if (this.connection != null) {
        JSONObject object = new JSONObject();

        object.put("id", "feed/" + feedUrl);
        object.put("title", title);

        JSONArray categoriesArray = new JSONArray();

        for (Category c : categories) {
            HashMap<String, String> category = new HashMap<String, String>();

            category.put("id", c.getCategoryId());
            category.put("label", c.getLabel());

            categoriesArray.put(category);
        }

        object.put("categories", categoriesArray);

        String input = object.toString();

        httpHelper.sendPostRequestToFeedly("/v3/subscriptions/", input, true);
    } else {
        System.err
                .println("JFeedly: Connection required to do this...\n\nCall jfeedlyInstance.authenticate();");
    }
}

From source file:de.kasoki.jfeedly.JFeedly.java

/** Save changes on a subscription to the feedly server */
public void updateSubscription(Subscription subscription, ArrayList<Category> categories) {
    if (this.connection != null) {
        JSONObject object = new JSONObject();

        object.put("id", subscription.getId());
        object.put("title", subscription.getTitle());

        JSONArray categoriesArray = new JSONArray();

        for (Category c : categories) {
            HashMap<String, String> category = new HashMap<String, String>();

            category.put("id", c.getCategoryId());
            category.put("label", c.getLabel());

            categoriesArray.put(category);
        }/*from w w w  . j  a v  a2 s .  c o  m*/

        object.put("categories", categoriesArray);

        String input = object.toString();

        httpHelper.sendPostRequestToFeedly("/v3/subscriptions/", input, true);
    } else {
        System.err
                .println("JFeedly: Connection required to do this...\n\nCall jfeedlyInstance.authenticate();");
    }
}

From source file:de.kasoki.jfeedly.JFeedly.java

private void markAsRead(String id, String type, Entry newestEntry) {
    JSONObject object = new JSONObject();

    object.put("action", "markAsRead");

    object.put("type", type);

    JSONArray ids = new JSONArray();
    ids.put(id);

    String typeIdIdentificator = null;

    if (type.equals("entries")) {
        typeIdIdentificator = "entryIds";
    } else if (type.equals("feeds")) {
        typeIdIdentificator = "feedIds";
    } else if (type.equals("categories")) {
        typeIdIdentificator = "categoryIds";
    } else {//from w w w .  j a va  2  s.  c om
        System.err.println("jfeedly: Unknown type: " + type + " don't know what to do with this.");
    }

    object.put(typeIdIdentificator, ids);

    if (!type.equals("entries") && newestEntry != null) {
        object.put("lastReadEntryId", newestEntry.getId());
    }

    httpHelper.sendPostRequestToFeedly("/v3/markers", object.toString(), true);
}

From source file:org.loklak.harvester.JsonFieldConverter.java

public JSONArray convert(JSONArray initialJson) throws IOException {
    JSONArray result = new JSONArray();
    for (Object o : initialJson) {
        result.put(this.convert((JSONObject) o));
    }//from ww w .j  av  a2s  .com
    return result;
}

From source file:de.kp.ames.web.core.search.SearcherImpl.java

/**
 * This helper method supports the term suggest 
 * mechanism of the AMES search functionality
 * //from   w  w w.  j ava2s. c  o m
 * @param field
 * @param terms
 * @return
 * @throws Exception
 */
@SuppressWarnings("unchecked")
protected JSONArray getTermValues(String field, NamedList<Object> terms) throws Exception {

    JSONArray jTerms = new JSONArray();

    NamedList<Object> items = null;
    int i = 0;

    for (i = 0; i < terms.size(); i++) {
        String fieldName = terms.getName(i);
        if (fieldName.equals(field))
            items = (NamedList<Object>) terms.getVal(i);
    }

    if (items == null)
        return jTerms;

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

        String name = items.getName(i);
        Integer card = (Integer) items.getVal(i);

        JSONObject jTerm = new JSONObject();

        jTerm.put(JsonConstants.J_NAME, name + "(" + card + ")");
        jTerm.put(JsonConstants.J_TERM, name);

        jTerms.put(jTerm);

    }

    return jTerms;
}

From source file:org.official.json.CDL.java

/**
 * Produce a JSONArray of strings from a row of comma delimited values.
 * @param x A JSONTokener of the source text.
 * @return A JSONArray of strings./*from w w  w  .  j  a  va2 s  . co m*/
 * @throws JSONException
 */
public static JSONArray rowToJSONArray(JSONTokener x) throws JSONException {
    JSONArray ja = new JSONArray();
    for (;;) {
        String value = getValue(x);
        char c = x.next();
        if (value == null || (ja.length() == 0 && value.length() == 0 && c != ',')) {
            return null;
        }
        ja.put(value);
        for (;;) {
            if (c == ',') {
                break;
            }
            if (c != ' ') {
                if (c == '\n' || c == '\r' || c == 0) {
                    return ja;
                }
                throw x.syntaxError("Bad character '" + c + "' (" + (int) c + ").");
            }
            c = x.next();
        }
    }
}