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:reseau.jeu.serveur.Protocole.java

public static String construireMsgJoueursEtat(ArrayList<Joueur> joueurs) {
    JSONObject msg = new JSONObject();
    JSONArray JSONjoueurs = new JSONArray();

    try {/*  w ww .  j av  a2 s .c  om*/
        msg.put("TYPE", JOUEURS_ETAT);

        Joueur joueur;
        JSONObject JSONjoueur;

        for (int j = 0; j < joueurs.size(); j++) {
            // recuperation du joueur
            joueur = joueurs.get(j);

            // construction du joueur
            JSONjoueur = new JSONObject();
            JSONjoueur.put("ID_JOUEUR", joueur.getId());
            JSONjoueur.put("NOM_JOUEUR", joueur.getPseudo());
            JSONjoueur.put("ID_EMPLACEMENT", joueur.getEmplacement().getId());
            JSONjoueur.put("ID_EQUIPE", joueur.getEquipe().getId());

            // ajout  la liste des joueurs
            JSONjoueurs.put(JSONjoueur);
        }

        msg.put("JOUEURS", JSONjoueurs);
    } catch (JSONException e) {
        e.printStackTrace();
    }

    return msg.toString();
}

From source file:reseau.jeu.serveur.Protocole.java

public static String construireMsgPartieTerminee(Jeu jeu) {
    JSONObject msg = new JSONObject();

    try {//from   w w w.  jav a2 s .  c o  m
        msg.put("TYPE", PARTIE_ETAT);
        msg.put("ETAT", PARTIE_TERMINEE);

        // construction des tats des quipes
        JSONArray JSONequipes = new JSONArray();
        for (Equipe e : jeu.getEquipes()) {
            JSONObject JSONequipe = new JSONObject();

            JSONequipe.put("ID_EQUIPE", e.getId());

            if (e.estHorsJeu())
                JSONequipe.put("NB_VIES_RESTANTES", 0);
            else
                JSONequipe.put("NB_VIES_RESTANTES", e.getNbViesRestantes());

            JSONequipes.put(JSONequipe);
        }
        msg.put("EQUIPES", JSONequipes);

        // TODO construction des tats des joueurs
        // ...
    } catch (JSONException e) {
        e.printStackTrace();
    }

    return msg.toString();
}

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

public JSONArray getAllSessionDetails() {
    JSONArray sessions = new JSONArray();
    if (!sessionConnectors.isEmpty()) {
        for (Map.Entry<String, CalabashAndroidConnector> entry : sessionConnectors.entrySet()) {
            JSONObject jsonEntry = new JSONObject();
            try {
                jsonEntry.put("id", entry.getKey());
                jsonEntry.put("capabilities",
                        new JSONObject(entry.getValue().getSessionCapabilities().getRawCapabilities()));
                sessions.put(jsonEntry);
            } catch (JSONException e) {
                throw new CalabashException("Error occured while JSON handling: ", e);
            }/*from   w w  w .  ja v a  2  s . co  m*/
        }
    }

    return sessions;
}

From source file:com.jennifer.ui.chart.grid.DateGrid.java

private void initDomain() {

    if (has("target") && !has("domain")) {

        if (options.get("target") instanceof String) {
            JSONArray list = new JSONArray();
            list.put(options.getString("target"));
            options.put("target", list);
        }/*from   w w w  .  ja v  a  2 s. c o  m*/

        JSONArray target = (JSONArray) options.getJSONArray("target");
        JSONArray domain = new JSONArray();
        JSONArray data = chart.data();

        long min = 0;
        long max = 0;

        boolean hasMin = options.has("min");
        boolean hasMax = options.has("max");

        for (int i = 0, len = target.length(); i < len; i++) {
            String key = target.getString(i);

            for (int index = 0, dataLength = data.length(); index < dataLength; index++) {
                JSONObject row = data.getJSONObject(index);

                long value = 0;

                if (row.get(key) instanceof Date) {
                    value = ((Date) row.get(key)).getTime();
                } else {
                    value = row.getLong(key);
                }

                if (!hasMin) {
                    min = value;
                    hasMin = true;
                } else if (min > value)
                    min = value;

                if (!hasMax) {
                    max = value;
                    hasMax = true;
                } else if (max < value)
                    max = value;
            }

        }

        options.put("max", max);
        options.put("min", min);

        domain.put(min).put(max);

        if (options.optBoolean("reverse", false)) {
            JSONUtil.reverse(domain);
        }

        options.put("domain", domain);

    }

}

From source file:org.loklak.api.iot.ImportProfileServlet.java

private void doSearch(Query post, HttpServletResponse response) throws IOException {
    String callback = post.get("callback", "");
    boolean minified = post.get("minified", false);
    boolean jsonp = callback != null && callback.length() > 0;
    String source_type = post.get("source_type", "");
    String screen_name = post.get("screen_name", "");
    String msg_id = post.get("msg_id", "");
    String detailed = post.get("detailed", "");
    // source_type either has to be null a a valid SourceType value
    if (!"".equals(source_type) && !SourceType.isValid(source_type)) {
        response.sendError(400, "your request must contain a valid source_type parameter.");
        return;/*  ww  w .  ja v a 2  s  .  co  m*/
    }
    Map<String, String> searchConstraints = new HashMap<>();
    if (!"".equals(source_type)) {
        searchConstraints.put("source_type", source_type);
    }
    if (!"".equals(screen_name)) {
        searchConstraints.put("sharers", screen_name);
    }
    if (!"".equals(msg_id)) {
        searchConstraints.put("imported", msg_id);
    }
    Collection<ImportProfileEntry> entries = DAO.SearchLocalImportProfilesWithConstraints(searchConstraints,
            true);
    JSONArray entries_to_map = new JSONArray();
    for (ImportProfileEntry entry : entries) {
        JSONObject entry_to_map = entry.toJSON();
        if ("true".equals(detailed)) {
            String query = "";
            for (String msgId : entry.getImported()) {
                query += "id:" + msgId + " ";
            }
            DAO.SearchLocalMessages search = new DAO.SearchLocalMessages(query, Timeline.Order.CREATED_AT, 0,
                    1000, 0);
            entry_to_map.put("imported",
                    search.timeline.toJSON(false, "search_metadata", "statuses").get("statuses"));
        }
        entries_to_map.put(entry_to_map);
    }
    post.setResponse(response, "application/javascript");

    JSONObject m = new JSONObject(true);
    JSONObject metadata = new JSONObject();
    metadata.put("count", entries.size());
    metadata.put("client", post.getClientHost());
    m.put("search_metadata", metadata);
    m.put("profiles", entries_to_map);

    // write json
    response.setCharacterEncoding("UTF-8");
    PrintWriter sos = response.getWriter();
    if (jsonp)
        sos.print(callback + "(");
    sos.print(minified ? m.toString() : m.toString(2));
    if (jsonp)
        sos.println(");");
    sos.println();
}

From source file:net.iubris.ipc_d3.cap.CamelizeSomeFieldsAndExtractInformazioniStoricheDates.java

private JSONArray adjustTimeAndTipiSpecifici(String dataAsCSV) throws ParseException {
    JSONArray jsonArray = CDL.toJSONArray(dataAsCSV);
    int length = jsonArray.length();
    JSONArray jsonArrayNew = new JSONArray();
    for (int i = 0; i < length; i++) {
        JSONObject jsonObject = jsonArray.getJSONObject(i);

        JSONObject jsonObjectNew = new JSONObject();

        jsonObjectNew.put("nome", jsonObject.getString("nome"));
        jsonObjectNew.put("indirizzo", jsonObject.getString("indirizzo"));
        jsonObjectNew.put("numeroCivico", jsonObject.getString("numero-civico"));
        jsonObjectNew.put("cap", jsonObject.getString("cap"));
        jsonObjectNew.put("quartiere", jsonObject.getString("quartiere"));
        jsonObjectNew.put("citta", jsonObject.getString("citta"));
        jsonObjectNew.put("geolocazione", jsonObject.getString("geolocazione"));
        jsonObjectNew.put("telefono", jsonObject.getString("telefono"));
        jsonObjectNew.put("mobile", jsonObject.getString("mobile"));
        jsonObjectNew.put("email", jsonObject.getString("email"));
        jsonObjectNew.put("web", jsonObject.getString("web"));
        jsonObjectNew.put("tipi", jsonObject.getString("tipi"));
        jsonObjectNew.put("tipiSpecifici", jsonObject.getString("tipi-specifici"));

        //         jsonObjectNew.put("tipiSpecificiReduced", getTipiReduced(jsonObject));
        //         jsonObjectNew.put("times", getTimes(jsonObject));

        LinkedList<String> date = findNumbers(jsonObject.getString("luogo-da-visitare.informazioni_storiche"));
        String dateString = date.toString().replace("[", "").replace("]", "");
        jsonObjectNew.put("luoghiDaVisitare.informazioniStoriche.date", dateString);

        jsonArrayNew.put(jsonObjectNew);
    }//from  ww w  . j a  v a  2s  .com
    return jsonArrayNew;
}

From source file:net.iubris.ipc_d3.cap.CamelizeSomeFieldsAndExtractInformazioniStoricheDates.java

private JSONArray getTimes(JSONObject jsonObject) throws ParseException {
    DateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm");
    String date = "1970-01-01";
    JSONArray times = new JSONArray();
    String apertura = jsonObject.getString("apertura");
    long startingTimeEpoch = 0;
    if (apertura.isEmpty())
        apertura = "19.00"; // default
    startingTimeEpoch = sdf.parse(date + " " + apertura.replace(".", ":")).getTime();

    String chiusura = jsonObject.getString("chiusura");
    long endingTimeEpoch = 0;
    if (chiusura.isEmpty())
        chiusura = "1.00"; // default
    double parsedEndingTime = Double.parseDouble(chiusura);
    if (parsedEndingTime >= 0f && parsedEndingTime < 6f) // we are in next day
        date = "1970-01-02";
    endingTimeEpoch = sdf.parse(date + " " + chiusura.replace(".", ":")).getTime();

    String startingTimeEpoched = "" + startingTimeEpoch;
    String endingTimeEpoched = "" + endingTimeEpoch;
    JSONObject et = new JSONObject();
    et.put("starting_time", startingTimeEpoched);
    et.put("ending_time", endingTimeEpoched);
    times.put(et);

    return times;
}

From source file:com.handshake.notifications.MyGcmListenerService.java

/**
 * Called when message is received./*from  w w  w  .  j av a  2 s.c  o m*/
 *
 * @param from SenderID of the sender.
 * @param data Data bundle containing message data as key/value pairs.
 *             For Set of keys use data.keySet().
 */
// [START receive_message]
@Override
public void onMessageReceived(String from, final Bundle data) {
    SessionManager session = new SessionManager(this);
    if (!session.isLoggedIn())
        return;

    /**
     * Production applications would usually process the message here.
     * Eg: - Syncing with server.
     *     - Store message in local database.
     *     - Update UI.
     */

    /**
     * In some cases it may be useful to show a notification indicating to the user
     * that a message was received.
     */

    try {
        final JSONArray users = new JSONArray();
        if (!data.containsKey("user"))
            return;
        final JSONObject user = new JSONObject(data.getString("user"));
        users.put(user);
        UserServerSync.cacheUser(getApplicationContext(), users, new UserArraySyncCompleted() {
            @Override
            public void syncCompletedListener(final ArrayList<User> users) {
                if (users.size() == 0) {
                    sendNotification(data, 0, false);
                    return;
                }

                final long userId = users.get(0).getUserId();
                final boolean isContact = users.get(0).isContact();

                FeedItemServerSync.performSync(getApplicationContext(), new SyncCompleted() {
                    @Override
                    public void syncCompletedListener() {
                        ContactSync.performSync(getApplicationContext(), new SyncCompleted() {
                            @Override
                            public void syncCompletedListener() {
                                if (data.containsKey("group_id")) {
                                    Realm realm = Realm.getInstance(getApplicationContext());
                                    Group group = realm.where(Group.class)
                                            .equalTo("groupId", Long.parseLong(data.getString("group_id")))
                                            .findFirst();
                                    GroupServerSync.loadGroupMembers(group);
                                    realm.close();
                                }

                                sendNotification(data, userId, isContact);
                            }
                        });
                    }
                });
            }
        });
    } catch (JSONException e) {
        e.printStackTrace();
    }
}

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

/**
 * Converts the current {@link VirtualCategory} to a JSONObject.
 * @return a JSONObject representation of the current {@link VirtualCategory}.
 *///  w  w w.  j  av  a  2 s .co m
public JSONObject toJSONObject() {
    JSONObject jsonObject = new JSONObject();
    try {
        jsonObject.put(JSONConsts.CATEGORY_NAME, mName);

        JSONArray goodsArr = new JSONArray();
        for (String goodItemId : mGoodsItemIds) {
            goodsArr.put(goodItemId);
        }

        jsonObject.put(JSONConsts.CATEGORY_GOODSITEMIDS, goodsArr);
    } catch (JSONException e) {
        StoreUtils.LogError(TAG, "An error occurred while generating JSON object.");
    }

    return jsonObject;
}

From source file:IoTatWork.AuCapTreeResource.java

/**
 * /*w w w .  ja v  a  2 s . c  o  m*/
 * @param auCapRid
 * @param depth 
 * @param jsonNodeTree 
 * @return
 */
private void getJsonNodeTree(Vertex auCapNode, JSONObject jsonNodeTree, int depth, boolean toRevoke,
        Object revokedSince) {

    //graph.getRawGraph();
    try {

        OGraphDatabase rawGraph = graph.getRawGraph();
        ODocument doc = rawGraph.load((ORID) auCapNode.getId());
        //System.out.println(doc.getClassName());
        if (doc.getClassName().equals(DataMapper.AUCAP_VERTEX)) {
            getJsonAuCapVertexData(auCapNode, jsonNodeTree);
            JSONObject jsonData = (JSONObject) jsonNodeTree.get("data");
            if (!toRevoke) {
                //controllo se lui o i figli sono sa revocare
                String status = (String) auCapNode.getProperty(DataMapper.STATUS);
                if (status.equals(Status.REVOKED)) {
                    String revocationScope = (String) auCapNode.getProperty(DataMapper.REVOCATION_SCOPE);
                    if (revocationScope.equals(RevocationScope.ALL)) {
                        jsonData.put(DataMapper.STATUS, Status.REVOKED);
                        jsonData.put(DataMapper.REVOKED_SINCE, auCapNode.getProperty(DataMapper.REVOKED_SINCE));
                        toRevoke = true;
                        revokedSince = auCapNode.getProperty(DataMapper.DESCENDANT_REVOKED_SINCE);
                    } else if (revocationScope.equals(RevocationScope.THIS)) {
                        jsonData.put(DataMapper.STATUS, Status.REVOKED);
                        jsonData.put(DataMapper.REVOKED_SINCE, auCapNode.getProperty(DataMapper.REVOKED_SINCE));
                    } else if (revocationScope.equals(RevocationScope.DESCENDANT)) {
                        jsonData.put(DataMapper.STATUS, Status.VALID);
                        toRevoke = true;
                        revokedSince = auCapNode.getProperty(DataMapper.DESCENDANT_REVOKED_SINCE);
                    }

                }

            } else {
                //metto lo status a Revoked e metto il campo revokedSince
                jsonData.put(DataMapper.REVOKED_SINCE, revokedSince);
                jsonData.put(DataMapper.STATUS, Status.REVOKED);
            }

            Iterable<Edge> dependentEdges = auCapNode.getEdges(Direction.OUT,
                    DataMapper.DEPENDENT_CAPABILIES_LABEL);
            JSONArray jsonArrayDependant = new JSONArray();
            depth++;
            for (Edge depend : dependentEdges) {

                if (depth <= this.depth) {
                    JSONObject jsonDependantNode = new JSONObject();
                    jsonArrayDependant.put(jsonDependantNode);
                    Vertex dependantVertex = depend.getVertex(Direction.IN);
                    getJsonNodeTree(dependantVertex, jsonDependantNode, depth, toRevoke, revokedSince);
                }

            }

            jsonNodeTree.put("children", jsonArrayDependant);

        } else {
            jsonNodeTree.put("id", auCapNode.getId().toString().substring(1));
            jsonNodeTree.put("name", auCapNode.getProperty("name").toString());

            Iterable<Edge> dependentEdges = auCapNode.getEdges(Direction.OUT);

            JSONObject jsonData = new JSONObject();
            String edgeLabel = dependentEdges.iterator().next().getLabel();
            jsonData.put("edgeLabel", edgeLabel);
            jsonNodeTree.put("data", jsonData);

            JSONArray jsonArrayDependant = new JSONArray();
            depth++;
            for (Edge depend : dependentEdges) {

                if (depth <= this.depth) {
                    JSONObject jsonDependantNode = new JSONObject();
                    jsonArrayDependant.put(jsonDependantNode);
                    Vertex dependantVertex = depend.getVertex(Direction.IN);
                    getJsonNodeTree(dependantVertex, jsonDependantNode, depth, false, null);
                }
            }

            jsonNodeTree.put("children", jsonArrayDependant);
        }

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

}