Example usage for org.json JSONObject put

List of usage examples for org.json JSONObject put

Introduction

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

Prototype

public JSONObject put(String key, Object value) throws JSONException 

Source Link

Document

Put a key/value pair in the JSONObject.

Usage

From source file:com.ibm.mobilefirst.mobileedge.abstractmodel.MagnetometerData.java

@Override
public JSONObject asJSON() {
    JSONObject json = super.asJSON();

    try {//ww  w .j ava  2s. c om
        JSONObject data = new JSONObject();
        data.put("x", x);
        data.put("y", y);
        data.put("z", z);
        json.put("magnometer", data);
    } catch (JSONException e) {
        e.printStackTrace();
    }

    return json;
}

From source file:com.github.cambierr.lorawanpacket.semtech.Rxpk.java

public JSONObject toJson() throws MalformedPacketException {
    JSONObject output = new JSONObject();

    output.put("time", time);
    output.put("tmst", tmst);
    output.put("freq", freq);
    output.put("chan", chan);
    output.put("rfch", rfch);
    output.put("stat", stat);
    output.put("modu", modu.name());

    if (modu.equals(Modulation.LORA)) {
        output.put("codr", codr);
        output.put("lsnr", lsnr);
    }//from ww w.jav a  2 s  . c  o  m

    output.put("datr", datr);
    output.put("rssi", rssi);
    output.put("size", size);

    ByteBuffer bb = ByteBuffer.allocate(384);
    data.toRaw(bb);
    output.put("data", Base64.getEncoder()
            .encodeToString(Arrays.copyOfRange(bb.array(), 0, bb.capacity() - bb.remaining())));

    return output;
}

From source file:org.pixmob.droidlink.sync.SyncAdapter.java

private void doPerformSync(NetworkClient client, SharedPreferences prefs, ContentProviderClient provider,
        SyncResult syncResult, boolean fullSync) {
    // Prepare the query.
    final String selection = DEVICE_ID + "=? AND " + STATE + "=? OR " + STATE + "=?";
    final String[] selectionArgs = { client.getDeviceId(), String.valueOf(EventsContract.PENDING_UPLOAD_STATE),
            String.valueOf(EventsContract.PENDING_DELETE_STATE) };

    // Get local data to sync.
    final Map<String, JSONObject> eventsToUpload = new HashMap<String, JSONObject>(8);
    final Set<String> eventsToDelete = new HashSet<String>(4);
    Cursor c = null;/*w  w  w .  j a  v a2 s  .  c o  m*/
    try {
        c = provider.query(EventsContract.CONTENT_URI, PROJECTION, selection, selectionArgs, null);

        final int idIdx = c.getColumnIndexOrThrow(_ID);
        final int typeIdx = c.getColumnIndexOrThrow(TYPE);
        final int createdIdx = c.getColumnIndexOrThrow(CREATED);
        final int numberIdx = c.getColumnIndexOrThrow(NUMBER);
        final int nameIdx = c.getColumnIndexOrThrow(NAME);
        final int messageIdx = c.getColumnIndexOrThrow(MESSAGE);
        final int stateIdx = c.getColumnIndexOrThrow(STATE);

        while (c.moveToNext()) {
            final String eventId = c.getString(idIdx);
            final int eventState = c.getInt(stateIdx);

            if (EventsContract.PENDING_UPLOAD_STATE == eventState) {
                // This is a newly created event.
                final JSONObject event = new JSONObject();
                try {
                    event.put("deviceId", client.getDeviceId());
                    event.put("created", c.getLong(createdIdx));
                    event.put("type", c.getInt(typeIdx));
                    event.put("number", c.getString(numberIdx));
                    event.put("name", c.getString(nameIdx));
                    event.put("message", c.getString(messageIdx));
                } catch (JSONException e) {
                    Log.w(TAG, "Invalid event " + eventId + ": cannot sync", e);
                    syncResult.stats.numSkippedEntries++;
                    continue;
                }
                eventsToUpload.put(eventId, event);
            } else if (EventsContract.PENDING_DELETE_STATE == eventState) {
                // The user wants this event to be deleted.
                eventsToDelete.add(eventId);
            }
        }
    } catch (RemoteException e) {
        Log.e(TAG, "Failed to get events: cannot sync", e);
        syncResult.stats.numIoExceptions++;
    } finally {
        if (c != null) {
            c.close();
            c = null;
        }
    }

    final ArrayList<ContentProviderOperation> batch = new ArrayList<ContentProviderOperation>(32);
    final ContentValues values = new ContentValues(8);

    if (eventsToDelete.isEmpty()) {
        Log.i(TAG, "No events to delete");
    } else {
        Log.i(TAG, "Found " + eventsToDelete.size() + " event(s) to delete");
    }

    // Delete events on the remote server.
    for (final String eventId : eventsToDelete) {
        if (DEVELOPER_MODE) {
            Log.d(TAG, "Deleting event: " + eventId);
        }

        try {
            client.delete("/events/" + eventId);

            if (DEVELOPER_MODE) {
                Log.d(TAG, "Deleting event in local database: " + eventId);
            }
            batch.add(ContentProviderOperation
                    .newDelete(Uri.withAppendedPath(EventsContract.CONTENT_URI, eventId)).build());
            syncResult.stats.numDeletes++;
        } catch (IOException e) {
            Log.e(TAG, "Event deletion error: cannot sync", e);
            syncResult.stats.numIoExceptions++;
            return;
        } catch (AppEngineAuthenticationException e) {
            Log.e(TAG, "Authentication error: cannot sync", e);
            syncResult.stats.numAuthExceptions++;
            return;
        }
    }

    try {
        provider.applyBatch(batch);
    } catch (Exception e) {
        Log.w(TAG, "Database error: cannot sync", e);
        syncResult.stats.numIoExceptions++;
        return;
    }
    batch.clear();

    if (fullSync) {
        // Get all events from the remote server.
        final JSONArray events;
        if (DEVELOPER_MODE) {
            Log.d(TAG, "Fetching events from the remote server");
        }
        try {
            events = client.getAsArray("/events");
        } catch (IOException e) {
            Log.e(TAG, "Event listing error: cannot sync", e);
            syncResult.stats.numIoExceptions++;
            return;
        } catch (AppEngineAuthenticationException e) {
            Log.e(TAG, "Authentication error: cannot sync", e);
            syncResult.stats.numAuthExceptions++;
            return;
        }

        final int eventsLen = events != null ? events.length() : 0;
        if (eventsLen == 0) {
            Log.i(TAG, "No events from the remote server");
        } else {
            Log.i(TAG, "Found " + eventsLen + " event(s) from the remote server");
        }

        // Build a collection with local event identifiers.
        // This collection will be used to identify which events have
        // been deleted on the remote server.
        final Set<String> localEventIds;
        try {
            c = provider.query(EventsContract.CONTENT_URI, PROJECTION_ID, STATE + "=?",
                    new String[] { String.valueOf(EventsContract.UPLOADED_STATE) }, null);
            localEventIds = new HashSet<String>(c.getCount());

            final int idIdx = c.getColumnIndexOrThrow(_ID);
            while (c.moveToNext()) {
                final String eventId = c.getString(idIdx);
                localEventIds.add(eventId);
            }
        } catch (RemoteException e) {
            Log.e(TAG, "Failed to get events from local database", e);
            syncResult.stats.numIoExceptions++;
            return;
        } finally {
            if (c != null) {
                c.close();
                c = null;
            }
        }

        String newEventId = null;
        int newEventCount = 0;

        // Reconcile remote events with local events.
        for (int i = 0; i < eventsLen; ++i) {
            String eventId = null;
            try {
                final JSONObject event = events.getJSONObject(i);
                eventId = event.getString("id");

                // Check if this event exists in the local database.
                if (localEventIds.contains(eventId)) {
                    // Found the event: update it.
                    values.clear();
                    values.put(NUMBER, trimToNull(event.getString("number")));
                    values.put(NAME, trimToNull(event.getString("name")));
                    values.put(MESSAGE, trimToNull(event.getString("message")));

                    if (DEVELOPER_MODE) {
                        Log.d(TAG, "Updating event in local database: " + eventId);
                    }
                    batch.add(ContentProviderOperation
                            .newUpdate(Uri.withAppendedPath(EventsContract.CONTENT_URI, eventId))
                            .withExpectedCount(1).withValues(values).build());
                    syncResult.stats.numUpdates++;
                } else {
                    // The event was not found: insert it.
                    values.clear();
                    values.put(_ID, eventId);
                    values.put(DEVICE_ID, event.getString("deviceId"));
                    values.put(CREATED, event.getLong("created"));
                    values.put(TYPE, event.getInt("type"));
                    values.put(NUMBER, trimToNull(event.getString("number")));
                    values.put(NAME, trimToNull(event.getString("name")));
                    values.put(MESSAGE, trimToNull(event.getString("message")));
                    values.put(STATE, EventsContract.UPLOADED_STATE);

                    if (DEVELOPER_MODE) {
                        Log.d(TAG, "Adding event to local database: " + eventId);
                    }
                    batch.add(ContentProviderOperation
                            .newInsert(Uri.withAppendedPath(EventsContract.CONTENT_URI, eventId))
                            .withValues(values).build());
                    syncResult.stats.numInserts++;

                    ++newEventCount;
                    if (newEventId == null) {
                        newEventId = eventId;
                    }
                }

                // This event now exists in the local database:
                // remove its identifier from this collection as we
                // don't want to delete it.
                localEventIds.remove(eventId);
            } catch (JSONException e) {
                Log.w(TAG, "Invalid event at index " + i + ": cannot sync", e);
                syncResult.stats.numSkippedEntries++;
                continue;
            }
        }

        // The remaining event identifiers was removed on the remote
        // server: there are still present in the local database. These
        // events are now being deleted.
        for (final String eventId : localEventIds) {
            if (DEVELOPER_MODE) {
                Log.d(TAG, "Deleting event in local database: " + eventId);
            }
            batch.add(ContentProviderOperation
                    .newDelete(Uri.withAppendedPath(EventsContract.CONTENT_URI, eventId)).build());
            syncResult.stats.numDeletes++;
        }

        try {
            provider.applyBatch(batch);
        } catch (Exception e) {
            Log.e(TAG, "Database error: cannot sync", e);
            syncResult.stats.numIoExceptions++;
            return;
        }
        batch.clear();

        if (newEventCount > 1) {
            newEventId = null;
        }
        if (newEventCount != 0) {
            startSyncNotificationService(newEventCount, newEventId);
        }
    }

    final int numEventsToUpload = eventsToUpload.size();
    if (numEventsToUpload == 0) {
        Log.i(TAG, "No events to upload");
    } else {
        Log.i(TAG, "Found " + numEventsToUpload + " event(s) to upload");
    }

    // Send local events to the remote server.
    for (final Map.Entry<String, JSONObject> entry : eventsToUpload.entrySet()) {
        final String eventId = entry.getKey();

        if (DEVELOPER_MODE) {
            Log.d(TAG, "Uploading event: " + eventId);
        }

        final JSONObject event = entry.getValue();
        try {
            client.put("/events/" + eventId, event);

            if (DEVELOPER_MODE) {
                Log.d(TAG, "Updating event state to UPLOADED: " + eventId);
            }
            values.clear();
            values.put(STATE, EventsContract.UPLOADED_STATE);
            batch.add(ContentProviderOperation
                    .newUpdate(Uri.withAppendedPath(EventsContract.CONTENT_URI, eventId)).withValues(values)
                    .withExpectedCount(1).build());
            syncResult.stats.numUpdates++;

            Log.i(TAG, "Event upload successful: " + eventId);
        } catch (NetworkClientException e) {
            if (e.getStatusCode() == 404) {
                Log.e(TAG, "Device not found: cannot sync", e);
                registerDevice();
            } else {
                Log.e(TAG, "Network error: cannot sync", e);
            }
            syncResult.stats.numIoExceptions++;
            return;
        } catch (IOException e) {
            Log.e(TAG, "Event upload error: cannot sync", e);
            syncResult.stats.numIoExceptions++;
            return;
        } catch (AppEngineAuthenticationException e) {
            Log.e(TAG, "Authentication error: cannot sync", e);
            syncResult.stats.numAuthExceptions++;
            return;
        }
    }

    try {
        provider.applyBatch(batch);
    } catch (Exception e) {
        Log.w(TAG, "Database error: cannot sync", e);
        syncResult.stats.numIoExceptions++;
        return;
    }
    batch.clear();

    final SharedPreferences.Editor prefsEditor = prefs.edit();
    final boolean syncRequired = !eventsToDelete.isEmpty() || !eventsToUpload.isEmpty();
    if (syncRequired) {
        // Generate an unique sync token: the server will send this token to
        // every devices. If this token is received on this device, the sync
        // will not start.
        final String syncToken = UUID.randomUUID().toString();
        prefsEditor.putString(SP_KEY_SYNC_TOKEN, syncToken);
        Features.getFeature(SharedPreferencesSaverFeature.class).save(prefsEditor);

        // Sync user devices.
        try {
            final JSONObject data = new JSONObject();
            data.put("token", syncToken);
            client.post("/devices/" + client.getDeviceId() + "/sync", data);
        } catch (NetworkClientException e) {
            if (e.getStatusCode() == 404) {
                registerDevice();
            }
        } catch (IOException e) {
            Log.e(TAG, "Device sync error: cannot sync", e);
            syncResult.stats.numIoExceptions++;
            return;
        } catch (AppEngineAuthenticationException e) {
            Log.e(TAG, "Authentication error: cannot sync", e);
            syncResult.stats.numAuthExceptions++;
            return;
        } catch (JSONException e) {
            Log.w(TAG, "Invalid sync token " + syncToken + ": cannot sync", e);
            syncResult.stats.numIoExceptions++;
            return;
        }
    }

    // Store sync time.
    prefsEditor.putLong(SP_KEY_LAST_SYNC, System.currentTimeMillis());
    Features.getFeature(SharedPreferencesSaverFeature.class).save(prefsEditor);
}

From source file:com.ca.mas.cordova.storage.MASStoragePlugin.java

private JSONObject getResultJson(Object result) throws Exception {
    JSONObject response = new JSONObject();
    if (result == null) {
        response.put("mime", "text/plain");
        response.put("value", "");
        return response;
    }//from  w  w  w  .ja  v  a  2 s .  com
    DataMarshaller marshaller = StorageDataMarshaller.findMarshaller(result);
    String mime = marshaller.getTypeAsString();

    byte[] bytes = null;
    try {
        response.put("mime", mime);
        bytes = marshaller.marshall(result);
        String b64 = new String(Base64.encode(bytes, 0), "UTF-8");
        StringBuilder base64String = new StringBuilder();
        base64String.append(b64);
        if (base64String.lastIndexOf(System.getProperty("line.separator")) != -1) {
            base64String.deleteCharAt(base64String.lastIndexOf(System.getProperty("line.separator")));
        }
        if (base64String.lastIndexOf("\r") != -1) {
            base64String.deleteCharAt(base64String.lastIndexOf("\r"));
        }
        response.put("value", base64String.toString());
        return response;
    } catch (Exception ex) {
        throw ex;
    }
}

From source file:com.asd.littleprincesbeauty.data.SqlNote.java

public JSONObject getContent() {
    try {//  ww w.ja v a  2  s.  co  m
        JSONObject js = new JSONObject();

        if (mIsCreate) {
            Log.e(TAG, "it seems that we haven't created this in database yet");
            return null;
        }

        JSONObject note = new JSONObject();
        if (mType == Notes.TYPE_NOTE) {
            note.put(NoteColumns.ID, mId);
            note.put(NoteColumns.ALERTED_DATE, mAlertDate);
            note.put(NoteColumns.BG_COLOR_ID, mBgColorId);
            note.put(NoteColumns.CREATED_DATE, mCreatedDate);
            note.put(NoteColumns.HAS_ATTACHMENT, mHasAttachment);
            note.put(NoteColumns.MODIFIED_DATE, mModifiedDate);
            note.put(NoteColumns.PARENT_ID, mParentId);
            note.put(NoteColumns.SNIPPET, mSnippet);
            note.put(NoteColumns.TYPE, mType);
            note.put(NoteColumns.WIDGET_ID, mWidgetId);
            note.put(NoteColumns.WIDGET_TYPE, mWidgetType);
            note.put(NoteColumns.ORIGIN_PARENT_ID, mOriginParent);
            js.put(GTaskStringUtils.META_HEAD_NOTE, note);

            JSONArray dataArray = new JSONArray();
            for (SqlData sqlData : mDataList) {
                JSONObject data = sqlData.getContent();
                if (data != null) {
                    dataArray.put(data);
                }
            }
            js.put(GTaskStringUtils.META_HEAD_DATA, dataArray);
        } else if (mType == Notes.TYPE_FOLDER || mType == Notes.TYPE_SYSTEM) {
            note.put(NoteColumns.ID, mId);
            note.put(NoteColumns.TYPE, mType);
            note.put(NoteColumns.SNIPPET, mSnippet);
            js.put(GTaskStringUtils.META_HEAD_NOTE, note);
        }

        return js;
    } catch (JSONException e) {
        Log.e(TAG, e.toString());
        e.printStackTrace();
    }
    return null;
}

From source file:org.chronotext.cinder.CinderBridge.java

public synchronized String getMemoryInfo() {
    MemoryInfo memoryInfo = new MemoryInfo();
    ((ActivityManager) activity.getSystemService(Context.ACTIVITY_SERVICE)).getMemoryInfo(memoryInfo);

    JSONObject json = new JSONObject();

    try {//from w  w  w  .  j  av a  2 s . c o m
        json.put("availMem", memoryInfo.availMem);
        json.put("threshold", memoryInfo.threshold);
        json.put("lowMemory", memoryInfo.lowMemory);
    } catch (JSONException e) {
    }

    return json.toString();
}

From source file:org.uiautomation.ios.server.command.web.ClickHandler.java

@Override
public JSONObject configurationDescription() throws JSONException {
    JSONObject desc = new JSONObject();
    desc.put("nativeEvents", "{boolean}, default to " + nativeEvents
            + ".true = UIAutomation native events will be used to enter the URL (slow) , Web =  WebKit remote debugging will be used.Faster.");
    return desc;//from  w  w w  .  j  av a2  s  . c o m
}

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

public static String construireMsgJoueurInitialisation(Joueur joueur, Terrain terrain) {
    JSONObject msg = new JSONObject();

    try {//from w  w w .j a v  a 2s.c  om
        msg.put("TYPE", JOUEUR_INITIALISATION);
        msg.put("STATUS", OK);
        msg.put("ID_JOUEUR", joueur.getId());
        msg.put("ID_EMPLACEMENT", joueur.getEmplacement().getId());
        msg.put("ID_EQUIPE", joueur.getEquipe().getId());
        msg.put("NOM_FICHIER_TERRAIN", terrain.getNomFichier());
    } catch (JSONException e) {
        e.printStackTrace();
    }

    return msg.toString();
}

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

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

    try {//from   w  w  w.  ja va 2  s.c o  m
        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 construireMsgJoueurInitialisation(int etat) {
    JSONObject msg = new JSONObject();

    try {/*from w  w  w.j  a va  2  s  .  c  o m*/
        msg.put("TYPE", JOUEUR_INITIALISATION);
        msg.put("STATUS", etat);
    } catch (JSONException jsone) {
        jsone.printStackTrace();
    }

    return msg.toString();
}