Example usage for org.json JSONObject get

List of usage examples for org.json JSONObject get

Introduction

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

Prototype

public Object get(String key) throws JSONException 

Source Link

Document

Get the value object associated with a key.

Usage

From source file:com.hp.mqm.atrf.octane.services.OctaneEntityService.java

private OctaneEntity parseEntity(JSONObject entObj) {

    String type = entObj.getString("type");

    OctaneEntity entity = createEntity(type);
    for (String key : entObj.keySet()) {
        Object value = entObj.get(key);
        if (value instanceof JSONObject) {
            JSONObject jObj = (JSONObject) value;
            if (jObj.has("type")) {
                OctaneEntity valueEntity = parseEntity(jObj);
                value = valueEntity;/*w w  w .j  a  va2s.  c o  m*/
            } else if (jObj.has("total_count")) {
                OctaneEntityCollection coll = parseCollection(jObj);
                value = coll;
            } else {
                value = jObj.toString();
            }
        } else if (JSONObject.NULL.equals(value)) {
            value = null;
        }
        entity.put(key, value);
    }
    return entity;
}

From source file:de.elepferd.web.pushnotifier.server.PushNotifierServlet.java

@JsonRpcMethod(method = PushNotifierProtocol.NotesSync.METHOD, requires_login = true)
public JSONObject notesSync(final CallContext context) throws JSONException, JsonRpcException {
    // This method should return a list of updated notes since a current
    // date, optionally reconciling/merging a set of a local notes.
    String clientDeviceId = null;
    UserInfo userInfo = getCurrentUserInfo(context);
    Date sinceDate;/* w w w  .  j a v a2s. c  o  m*/

    try {
        clientDeviceId = context.getParams().optString(PushNotifierProtocol.ARG_CLIENT_DEVICE_ID);
        sinceDate = Util
                .parseDateISO8601(context.getParams().getString(PushNotifierProtocol.NotesSync.ARG_SINCE_DATE));
    } catch (ParseException e) {
        throw new JsonRpcException(400, "Invalid since_date.", e);
    } catch (JSONException e) {
        throw new JsonRpcException(400, "Invalid since_date.", e);
    }

    JSONObject responseJson = new JSONObject();
    JSONArray notesJson = new JSONArray();
    Transaction tx = context.getPersistenceManager().currentTransaction();
    Date newSinceDate = new Date();
    try {
        tx.begin();
        List<Note> localNotes = new ArrayList<Note>();
        if (context.getParams().has(PushNotifierProtocol.NotesSync.ARG_LOCAL_NOTES)) {
            JSONArray localChangesJson = context.getParams()
                    .getJSONArray(PushNotifierProtocol.NotesSync.ARG_LOCAL_NOTES);
            for (int i = 0; i < localChangesJson.length(); i++) {
                try {
                    JSONObject noteJson = localChangesJson.getJSONObject(i);

                    if (noteJson.has("id")) {
                        Key existingNoteKey = Note.makeKey(userInfo.getId(), noteJson.get("id").toString());
                        try {
                            Note existingNote = (Note) context.getPersistenceManager().getObjectById(Note.class,
                                    existingNoteKey);
                            if (!existingNote.getOwnerId().equals(userInfo.getId())) {
                                // User doesn't have permission to edit this note. Instead of
                                // throwing an error, just re-create it on the server side.
                                //throw new JsonRpcException(403,
                                //        "You do not have permission to modify this note.");
                                noteJson.remove("id");
                            }
                        } catch (JDOObjectNotFoundException e) {
                            // Note doesn't exist, instead of throwing an error,
                            // just re-create the note on the server side (unassign its ID).
                            //throw new JsonRpcException(404, "Note with ID "
                            //        + noteJson.get("id").toString() + " does not exist.");
                            noteJson.remove("id");
                        }
                    }

                    noteJson.put("owner_id", userInfo.getId());
                    Note localNote = new Note(noteJson);
                    localNotes.add(localNote);
                } catch (JSONException e) {
                    throw new JsonRpcException(400, "Invalid local note content.", e);
                }
            }
        }

        // Query server-side note changes.
        Query query = context.getPersistenceManager().newQuery(Note.class);
        query.setFilter("ownerKey == ownerKeyParam && modifiedDate > sinceDate");
        query.setOrdering("modifiedDate desc");
        query.declareParameters(Key.class.getName() + " ownerKeyParam, java.util.Date sinceDate");
        @SuppressWarnings("unchecked")
        List<Note> notes = (List<Note>) query.execute(userInfo.getKey(), sinceDate);

        // Now merge the lists and conflicting objects.
        /*Reconciler<Note> reconciler = new Reconciler<Note>() {
        @Override
        public Note reconcile(Note o1, Note o2) {
            boolean pick1 = o1.getModifiedDate().after(o2.getModifiedDate());
                
            // Make sure only the chosen version of the note is persisted
            context.getPersistenceManager().makeTransient(pick1 ? o2 : o1);
                
            return pick1 ? o1 : o2;
        }
        };
                
        Collection<Note> reconciledNotes = reconciler.reconcileLists(notes, localNotes);
                
        for (Note note : reconciledNotes) {
        // Save the note.
        context.getPersistenceManager().makePersistent(note);
                
        // Put it in the response output.
        notesJson.put(note.toJSON());
        }
        tx.commit();*/
    } finally {
        if (tx.isActive()) {
            tx.rollback();
        }
    }

    enqueueDeviceMessage(context.getPersistenceManager(), userInfo, clientDeviceId);

    responseJson.put(PushNotifierProtocol.NotesSync.RET_NOTES, notesJson);
    responseJson.put(PushNotifierProtocol.NotesSync.RET_NEW_SINCE_DATE, Util.formatDateISO8601(newSinceDate));
    return responseJson;
}

From source file:org.collectionspace.chain.csp.webui.record.RecordSearchList.java

public JSONObject getJSON(Storage storage, JSONObject restriction, String key, String mybase)
        throws JSONException, UIException, ExistException, UnimplementedException, UnderlyingStorageException {
    JSONObject out = new JSONObject();

    JSONObject data = storage.getPathsJSON(mybase, restriction);
    String[] paths = (String[]) data.get("listItems");
    JSONObject pagination = new JSONObject();
    if (data.has("pagination")) {
        pagination = data.getJSONObject("pagination");
    }/*from w  w  w .j a  v a  2 s . c  o  m*/

    for (int i = 0; i < paths.length; i++) {
        if (paths[i].startsWith(mybase + "/")) {
            paths[i] = paths[i].substring((mybase + "/").length());
        }
    }
    out = pathsToJSON(storage, mybase, paths, key, pagination);
    return out;
}

From source file:com.microsoft.office365.snippetapp.helpers.APIErrorMessageHelper.java

public static String getErrorMessage(String result) {
    String errorMessage;/*from   w w  w . j a va  2s. c o  m*/
    try {

        // Gets the JSON object out of the result string.
        String responseJSON = result.substring(result.indexOf("{"), result.length());

        JSONObject jObject = new JSONObject(responseJSON);
        JSONObject error = (JSONObject) jObject.get("error");
        errorMessage = error.getString("message");

    } catch (JSONException e) {
        e.printStackTrace();
        errorMessage = result;
    } catch (Exception ex) {
        ex.printStackTrace();
        errorMessage = result;
    }
    return errorMessage;
}

From source file:org.seadpdt.impl.RepoServicesImpl.java

@POST
@Path("/")
@Consumes(MediaType.APPLICATION_JSON)/*from  w w  w  .j av  a  2 s. com*/
@Produces(MediaType.APPLICATION_JSON)
public Response registerRepository(String profileString) {
    JSONObject profile = new JSONObject(profileString);

    if (!profile.has("orgidentifier")) {
        return Response.status(Status.BAD_REQUEST)
                .entity(new BasicDBObject("Failure",
                        "Invalid request format: " + "Request must contain the field \"orgidentifier\""))
                .build();
    }

    String newID = (String) profile.get("orgidentifier");
    FindIterable<Document> iter = repositoriesCollection.find(new Document("orgidentifier", newID));
    if (iter.iterator().hasNext()) {
        return Response.status(Status.CONFLICT)
                .entity(new BasicDBObject("Failure", "Repository with Identifier " + newID + " already exists"))
                .build();
    } else {
        repositoriesCollection.insertOne(Document.parse(profile.toString()));
        URI resource = null;
        try {
            resource = new URI("./" + newID);
        } catch (URISyntaxException e) {
            // Should not happen given simple ids
            e.printStackTrace();
        }
        return Response.created(resource).entity(new Document("orgidentifier", newID)).build();
    }
}

From source file:com.cmackay.plugins.googleanalytics.GoogleAnalyticsPlugin.java

private static Map<String, String> objectToMap(JSONObject o) throws JSONException {
    if (o.length() == 0) {
        return Collections.<String, String>emptyMap();
    }// w  w w  .j  av  a  2s . co  m
    Map<String, String> map = new HashMap<String, String>(o.length());
    Iterator it = o.keys();
    String key, value;
    while (it.hasNext()) {
        key = it.next().toString();
        value = o.has(key) ? o.get(key).toString() : null;
        map.put(key, value);
    }
    return map;
}

From source file:com.pimp.companionforband.utils.jsontocsv.parser.JsonFlattener.java

private void flatten(JSONObject obj, Map<String, String> flatJson, String prefix) {
    Iterator iterator = obj.keys();
    while (iterator.hasNext()) {
        String key = iterator.next().toString();
        try {/*from   w  w  w.jav  a  2s .  c  o m*/
            if (obj.get(key).getClass() == JSONObject.class) {
                JSONObject jsonObject = (JSONObject) obj.get(key);
                flatten(jsonObject, flatJson, prefix);
            } else if (obj.get(key).getClass() == JSONArray.class) {
                JSONArray jsonArray = (JSONArray) obj.get(key);
                if (jsonArray.length() < 1)
                    continue;
                flatten(jsonArray, flatJson, key);
            } else {
                String value = obj.getString(key);
                if (value != null && !value.equals("null"))
                    flatJson.put(prefix + key, value);
            }
        } catch (Exception e) {
            Log.e("flattenJson", e.toString());
        }
    }
}

From source file:org.chromium.ChromeStorage.java

private JSONObject getStoredValuesForKeys(CordovaArgs args, boolean useDefaultValues) {
    JSONObject ret = new JSONObject();
    try {// www. j  ava2  s.  c o m
        String namespace = args.getString(0);
        JSONObject jsonObject = (JSONObject) args.optJSONObject(1);
        JSONArray jsonArray = args.optJSONArray(1);
        boolean isNull = args.isNull(1);
        List<String> keys = new ArrayList<String>();

        if (jsonObject != null) {
            keys = toStringList(jsonObject.names());
            // Ensure default values of keys are maintained
            if (useDefaultValues) {
                ret = jsonObject;
            }
        } else if (jsonArray != null) {
            keys = toStringList(jsonArray);
        } else if (isNull) {
            keys = null;
        }

        if (keys != null && keys.isEmpty()) {
            ret = new JSONObject();
        } else {
            JSONObject storage = getStorage(namespace);

            if (keys == null) {
                // return the whole storage if the key given is null
                ret = storage;
            } else {
                // return the storage for the keys specified
                for (String key : keys) {
                    if (storage.has(key)) {
                        Object value = storage.get(key);
                        ret.put(key, value);
                    }
                }
            }
        }
    } catch (JSONException e) {
        Log.e(LOG_TAG, "Storage is corrupted!", e);
        ret = null;
    } catch (IOException e) {
        Log.e(LOG_TAG, "Could not retrieve storage", e);
        ret = null;
    }

    return ret;
}

From source file:org.chromium.ChromeStorage.java

private void set(final CordovaArgs args, final CallbackContext callbackContext) {
    cordova.getThreadPool().execute(new Runnable() {
        @Override//from  w w w .j  a  v  a  2  s  .  c om
        public void run() {
            try {
                String namespace = args.getString(0);
                JSONObject jsonObject = (JSONObject) args.getJSONObject(1);
                JSONArray keyArray = jsonObject.names();
                JSONObject oldValues = new JSONObject();

                if (keyArray != null) {
                    List<String> keys = toStringList(keyArray);
                    JSONObject storage = getStorage(namespace);
                    for (String key : keys) {
                        Object oldValue = storage.opt(key);
                        if (oldValue != null) {
                            oldValues.put(key, oldValue);
                        }
                        storage.put(key, jsonObject.get(key));
                    }
                    setStorage(namespace, storage);
                }
                callbackContext.success(oldValues);
            } catch (Exception e) {
                Log.e(LOG_TAG, "Could not update storage", e);
                callbackContext.error("Could not update storage");
            }
        }
    });
}

From source file:ui.panel.UIBucketSelect.java

private void getBucketData() {

    JSONArray bucketList = new APIProcess().bucketList(Data.targetURL, Data.sessionKey);
    try {/*w ww.  jav  a  2 s . c  o  m*/
        Object columnName[] = new Object[] { "Bucket ID", "Bucket Name" };
        Object[][] rowData = new Object[bucketList.length()][columnName.length];
        for (int i = 0; i < bucketList.length(); i++) {
            JSONObject bucket = bucketList.getJSONObject(i);
            rowData[i][0] = bucket.get("bucketID");
            rowData[i][1] = bucket.get("bucketName");
        }
        listBucket.setModel(new UneditableModel(rowData, columnName));
    } catch (JSONException e1) {
        e1.printStackTrace();
    }
}