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:ai.susi.mind.SusiThought.java

/**
 * Merging of data is required during an mind-meld.
 * To meld two thoughts, we combine their data arrays into one.
 * The resulting table has at maximum the length of both source tables combined.
 * @param table the information to be melted into our existing table.
 * @return the thought//from w  ww  . j a  v a 2s.  c o  m
 */
public SusiThought mergeData(JSONArray table1) {
    JSONArray table0 = this.getData();
    int t0c = 0;
    for (int i = 0; i < table1.length(); i++) {
        JSONObject j1i = table1.getJSONObject(i);
        while (t0c < table0.length() && anyObjectKeySame(j1i, table0.getJSONObject(t0c))) {
            t0c++;
        }
        if (t0c >= table0.length())
            table0.put(new JSONObject(true));
        table0.getJSONObject(t0c).putAll(table1.getJSONObject(i));
    }
    setData(table0);
    return this;
}

From source file:ai.susi.mind.SusiThought.java

/**
 * If during thinking we observe something that we want to memorize, we can memorize this here.
 * We insert the new data always in front of existing same data to make it visible as primary
 * backtracking option. This means that new observations are always more important than old
 * observations but do not overwrite them; they can be used again in case that the new observation
 * is not valid during inference computation.
 * @param featureName the object key// w  ww . j  ava2s. c  om
 * @param observation the object value
 * @return the thought
 */
public SusiThought addObservation(String featureName, String observation) {
    JSONArray data = getData();

    // find first occurrence of key in rows
    int rowc = 0;
    boolean found = false;
    while (rowc < data.length()) {
        JSONObject row = data.getJSONObject(rowc);
        if (row.has(featureName))
            found = true;
        if (found)
            break;
        rowc++;
    }
    if (found) {
        // insert feature in front of row
        if (rowc == 0) {
            // insert a row and shift everything up
            JSONArray newData = new JSONArray();
            JSONObject row = new JSONObject();
            row.put(featureName, observation);
            newData.put(row);
            for (Object o : data)
                newData.put(o);
            this.setData(newData);
        } else {
            JSONObject row = data.getJSONObject(rowc - 1);
            row.put(featureName, observation);
        }
    } else {
        // insert into first line
        if (data.length() == 0) {
            JSONObject row = new JSONObject();
            row.put(featureName, observation);
            data.put(row);
        } else {
            JSONObject row = data.getJSONObject(0);
            row.put(featureName, observation);
        }
    }
    return this;
}

From source file:ai.susi.mind.SusiThought.java

/**
 * Every information may have a set of (re-)actions assigned.
 * Those (re-)actions are methods to do something with the thought.
 * @param actions (re-)actions on this thought
 * @return the thought//w  w  w. j a  v  a2s  .c  om
 */
public SusiThought addActions(List<SusiAction> actions) {
    JSONArray a = getActionsJSON();
    actions.forEach(action -> a.put(action.toJSONClone()));
    return this;
}

From source file:ai.susi.mind.SusiThought.java

public SusiThought addAction(SusiAction action) {
    JSONArray a = getActionsJSON();
    a.put(action.toJSONClone());
    return this;
}

From source file:vOS.controller.socket.IOConnection.java

/**
 * Creates a new {@link IOAcknowledge} instance which sends its arguments
 * back to the server.//from   www .  j a  v a2s.co m
 * 
 * @param message
 *            the message
 * @return an {@link IOAcknowledge} instance, may be <code>null</code> if
 *         server doesn't request one.
 */
private IOAcknowledge remoteAcknowledge(IOMessage message) {
    String _id = message.getId();
    if (_id.equals(""))
        return null;
    else if (_id.endsWith("+") == false)
        _id = _id + "+";
    final String id = _id;
    final String endPoint = message.getEndpoint();
    return new IOAcknowledge() {
        @Override
        public void ack(Object... args) {
            JSONArray array = new JSONArray();
            for (Object o : args) {
                try {
                    array.put(o == null ? JSONObject.NULL : o);
                } catch (Exception e) {
                    error(new SocketIOException(
                            "You can only put values in IOAcknowledge.ack() which can be handled by JSONArray.put()",
                            e));
                }
            }
            IOMessage ackMsg = new IOMessage(IOMessage.TYPE_ACK, endPoint, id + array.toString());
            sendPlain(ackMsg.toString());
        }
    };
}

From source file:org.dspace.globus.Globus.java

public static String getAllMetadata(Context context, Item item, Collection collection) {
    try {//from  w  ww  . ja  va 2  s  .co m
        JSONObject dataset = new JSONObject();
        if (collection == null) {
            collection = item.getOwningCollection();
        }
        Community community = collection.getCommunities()[0];
        EPerson person = item.getSubmitter();

        dataset.put("_comment", "This file was auto-generated by Globus");
        dataset.put(Globus.makeJSONLDKey("globus", "publication", "submitter"), person.getGlobusUserName());
        dataset.put(Globus.makeJSONLDKey("globus", "publication", "collection"), collection.getName());
        dataset.put(Globus.makeJSONLDKey("globus", "publication", "collection_id"), collection.getID());
        dataset.put(Globus.makeJSONLDKey("globus", "publication", "community"), community.getName());
        dataset.put(Globus.makeJSONLDKey("globus", "publication", "community_id"), community.getID());
        dataset.put(Globus.makeJSONLDKey("globus", "publication", "item_id"), item.getID());

        Set<String> schemas = new HashSet<String>();
        schemas.add("globus");
        String key;
        DCValue[] dcv = item.getMetadata(Item.ANY, Item.ANY, Item.ANY, Item.ANY);
        for (DCValue dcval : dcv) {
            // Make a unique key for this piece of metadata
            // if its a DC term we map to datacite
            if (dublinCoreDataciteMap.containsKey(dcval.getField())) {
                key = dublinCoreDataciteMap.getProperty(dcval.getField());
                schemas.add("datacite");
            } else {
                key = Globus.makeJSONLDKey(dcval);
                schemas.add(dcval.schema);
            }
            // We assume all metadata values could be multivalued
            // There is no way to tell so we encode all in an array
            JSONArray valueArray = null;
            if (!dataset.has(key)) {
                valueArray = new JSONArray();
            } else {
                valueArray = dataset.getJSONArray(key);
            }
            valueArray.put(dcval.value);
            dataset.put(key, valueArray);
        }
        // create JSON-LD context heading
        JSONObject jsonLDContext = new JSONObject();
        MetadataSchema metadataSchema;
        for (String s : schemas) {
            metadataSchema = MetadataSchema.find(context, s);
            jsonLDContext.put(s, metadataSchema.getNamespace());
        }
        dataset.put("@context", jsonLDContext);
        return dataset.toString();
    } catch (Exception e) {
        logger.error("Error getting item metadata " + e);
    }
    return "";
}

From source file:com.richtodd.android.quiltdesign.block.Quilt.java

JSONObject createJSONObject() throws JSONException {

    JSONArray jsonQuiltBlocks = new JSONArray();
    for (int row = 0; row < m_rowCount; ++row) {
        for (int column = 0; column < m_columnCount; ++column) {
            QuiltBlock quiltBlock = getQuiltBlock(row, column);
            if (quiltBlock != null) {
                jsonQuiltBlocks.put(quiltBlock.createJSONObject());
            } else {
                jsonQuiltBlocks.put(JSONObject.NULL);
            }/*w ww  . ja  v  a  2s. co  m*/
        }
    }

    JSONObject jsonQuilt = new JSONObject();
    jsonQuilt.put("objectType", "quilt");
    jsonQuilt.put("rowCount", m_rowCount);
    jsonQuilt.put("columnCount", m_columnCount);
    jsonQuilt.put("width", m_width);
    jsonQuilt.put("height", m_height);
    jsonQuilt.put("quiltBlocks", jsonQuiltBlocks);

    return jsonQuilt;
}

From source file:sh.calaba.driver.server.DriverRegistrationHandler.java

private JSONObject getNodeConfig() {
    JSONObject res = new JSONObject();
    try {/*from www  . j  a  v a2  s  . c  om*/
        res.put("class", "org.openqa.grid.common.RegistrationRequest");
        res.put("configuration", getConfiguration());
        JSONArray caps = new JSONArray();
        for (CalabashCapabilities c : config.getCapabilities()) {
            caps.put(c.getRawCapabilities());
        }
        res.put("capabilities", caps);
    } catch (JSONException e) {
        throw new CalabashException("Error encoding to JSON " + e.getMessage(), e);
    }

    return res;
}

From source file:com.phonegap.ContactAccessorSdk3_4.java

@Override
/** /*from w  ww. j a va  2  s  . co m*/
 * 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 
 */
public JSONArray search(JSONArray fields, JSONObject 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 = "%";
    }

    ContentResolver cr = mApp.getContentResolver();

    Set<String> contactIds = buildSetOfContactIds(fields, searchTerm);
    HashMap<String, Boolean> populate = buildPopulationSet(fields);

    Iterator<String> it = contactIds.iterator();

    JSONArray contacts = new JSONArray();
    JSONObject contact;
    String contactId;
    int pos = 0;
    while (it.hasNext() && (pos < limit)) {
        contact = new JSONObject();
        try {
            contactId = it.next();
            contact.put("id", contactId);

            // Do query for name and note
            Cursor cur = cr.query(People.CONTENT_URI, new String[] { People.DISPLAY_NAME, People.NOTES },
                    PEOPLE_ID_EQUALS, new String[] { contactId }, null);
            cur.moveToFirst();

            if (isRequired("displayName", populate)) {
                contact.put("displayName", cur.getString(cur.getColumnIndex(People.DISPLAY_NAME)));
            }
            if (isRequired("phoneNumbers", populate)) {
                contact.put("phoneNumbers", phoneQuery(cr, contactId));
            }
            if (isRequired("emails", populate)) {
                contact.put("emails", emailQuery(cr, contactId));
            }
            if (isRequired("addresses", populate)) {
                contact.put("addresses", addressQuery(cr, contactId));
            }
            if (isRequired("organizations", populate)) {
                contact.put("organizations", organizationQuery(cr, contactId));
            }
            if (isRequired("ims", populate)) {
                contact.put("ims", imQuery(cr, contactId));
            }
            if (isRequired("note", populate)) {
                contact.put("note", cur.getString(cur.getColumnIndex(People.NOTES)));
            }
            // nickname
            // urls
            // relationship
            // birthdays
            // anniversary

            pos++;
            cur.close();
        } catch (JSONException e) {
            Log.e(LOG_TAG, e.getMessage(), e);
        }
        contacts.put(contact);
    }
    return contacts;
}

From source file:com.phonegap.ContactAccessorSdk3_4.java

/**
 * Create a ContactField JSONArray/*from www.  ja v a 2s  .c om*/
 * @param cr database access object
 * @param contactId the ID to search the database for
 * @return a JSONArray representing a set of ContactFields
 */
private JSONArray imQuery(ContentResolver cr, String contactId) {
    String imWhere = ContactMethods.PERSON_ID + " = ? AND " + ContactMethods.KIND + " = ?";
    String[] imWhereParams = new String[] { contactId, ContactMethods.CONTENT_IM_ITEM_TYPE };
    Cursor cursor = cr.query(ContactMethods.CONTENT_URI, null, imWhere, imWhereParams, null);
    JSONArray ims = new JSONArray();
    JSONObject im;
    while (cursor.moveToNext()) {
        im = new JSONObject();
        try {
            im.put("id", cursor.getString(cursor.getColumnIndex(ContactMethods._ID)));
            im.put("perf", false);
            im.put("value", cursor.getString(cursor.getColumnIndex(ContactMethodsColumns.DATA)));
            im.put("type", getContactType(cursor.getInt(cursor.getColumnIndex(ContactMethodsColumns.TYPE))));
            ims.put(im);
        } catch (JSONException e) {
            Log.e(LOG_TAG, e.getMessage(), e);
        }
    }
    cursor.close();
    return null;
}