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.commontime.plugin.LocationManager.java

private void createManagerCallbacks(final CallbackContext callbackContext) {
    beaconServiceNotifier = new IBeaconServiceNotifier() {

        @Override//from ww  w.  j  a va 2 s .co m
        public void rangingBeaconsDidFailForRegion(final Region region, final Exception exception) {
            threadPoolExecutor.execute(new Runnable() {
                public void run() {

                    sendFailEvent("rangingBeaconsDidFailForRegion", region, exception, callbackContext);
                }
            });
        }

        @Override
        public void monitoringDidFailForRegion(final Region region, final Exception exception) {
            threadPoolExecutor.execute(new Runnable() {
                public void run() {

                    sendFailEvent("monitoringDidFailForRegionWithError", region, exception, callbackContext);
                }
            });
        }

        @Override
        public void didStartMonitoringForRegion(final Region region) {
            threadPoolExecutor.execute(new Runnable() {
                public void run() {

                    try {
                        JSONObject data = new JSONObject();
                        data.put("eventType", "didStartMonitoringForRegion");
                        data.put("region", mapOfRegion(region));

                        debugLog("didStartMonitoringForRegion: " + data.toString());

                        //send and keep reference to callback 
                        PluginResult result = new PluginResult(PluginResult.Status.OK, data);
                        result.setKeepCallback(true);
                        callbackContext.sendPluginResult(result);

                    } catch (Exception e) {
                        Log.e(TAG, "'startMonitoringForRegion' exception " + e.getCause());
                        monitoringDidFailForRegion(region, e);
                    }
                }
            });
        }

        @Override
        public void didChangeAuthorizationStatus(final String status) {
            threadPoolExecutor.execute(new Runnable() {
                public void run() {

                    try {
                        JSONObject data = new JSONObject();
                        data.put("eventType", "didChangeAuthorizationStatus");
                        data.put("authorizationStatus", status);
                        debugLog("didChangeAuthorizationStatus: " + data.toString());

                        //send and keep reference to callback 
                        PluginResult result = new PluginResult(PluginResult.Status.OK, data);
                        result.setKeepCallback(true);
                        callbackContext.sendPluginResult(result);

                    } catch (Exception e) {
                        callbackContext.error("didChangeAuthorizationStatus error: " + e.getMessage());
                    }
                }
            });
        }

        private void sendFailEvent(String eventType, Region region, Exception exception,
                final CallbackContext callbackContext) {
            try {
                JSONObject data = new JSONObject();
                data.put("eventType", eventType);//not perfect mapping, but it's very unlikely to happen here
                data.put("region", mapOfRegion(region));
                data.put("error", exception.getMessage());

                PluginResult result = new PluginResult(PluginResult.Status.OK, data);
                result.setKeepCallback(true);
                callbackContext.sendPluginResult(result);
            } catch (Exception e) {
                //still failing, so kill all further event dispatch
                Log.e(TAG, eventType + " error " + e.getMessage());
                callbackContext.error(eventType + " error " + e.getMessage());
            }
        }
    };
}

From source file:com.commontime.plugin.LocationManager.java

private void getAuthorizationStatus(CallbackContext callbackContext) {
    _handleCallSafely(callbackContext, new ILocationManagerCommand() {

        @Override// ww w  . j av a  2 s  .  c o  m
        public PluginResult run() {

            try {

                //Check app has the necessary permissions
                if (!hasBlueToothPermission()) {
                    return new PluginResult(PluginResult.Status.ERROR,
                            "Application does not BLUETOOTH or BLUETOOTH_ADMIN permissions");
                }

                //Check the Bluetooth service is running
                String authStatus = iBeaconManager.checkAvailability() ? "AuthorizationStatusAuthorized"
                        : "AuthorizationStatusDenied";
                JSONObject result = new JSONObject();
                result.put("authorizationStatus", authStatus);
                return new PluginResult(PluginResult.Status.OK, result);

            } catch (BleNotAvailableException e) {
                //if device does not support iBeacons and error is thrown
                debugLog("'getAuthorizationStatus' Device not supported: " + e.getMessage());
                return new PluginResult(PluginResult.Status.ERROR, e.getMessage());
            } catch (Exception e) {
                debugWarn("'getAuthorizationStatus' exception " + e.getMessage());
                return new PluginResult(PluginResult.Status.ERROR, e.getMessage());
            }

        }
    });
}

From source file:com.commontime.plugin.LocationManager.java

private JSONObject mapOfBeaconRegion(Region region) throws JSONException {
    JSONObject dict = new JSONObject();

    // identifier
    if (region.getUniqueId() != null) {
        dict.put("identifier", region.getUniqueId());
    }/*from w w w.  ja  v  a 2  s.c o m*/

    dict.put("uuid", region.getId1());

    if (region.getId2() != null) {
        dict.put("major", region.getId2());
    }

    if (region.getId3() != null) {
        dict.put("minor", region.getId3());
    }

    dict.put("typeName", "BeaconRegion");

    return dict;

}

From source file:com.commontime.plugin.LocationManager.java

private JSONObject mapOfBeacon(Beacon region) throws JSONException {
    JSONObject dict = new JSONObject();

    //beacon id//from  w  w w .  j  a  v a  2 s .c o  m
    dict.put("uuid", region.getId1());
    dict.put("major", region.getId2());
    dict.put("minor", region.getId3());

    // proximity
    dict.put("proximity", nameOfProximity(region.getDistance()));

    // signal strength and transmission power
    dict.put("rssi", region.getRssi());
    dict.put("tx", region.getTxPower());

    // accuracy = rough distance estimate limited to two decimal places (in metres)
    // NO NOT ASSUME THIS IS ACCURATE - it is effected by radio interference and obstacles
    dict.put("accuracy", Math.round(region.getDistance() * 100.0) / 100.0);

    return dict;
}

From source file:com.nextgis.maplib.display.SimpleLineStyle.java

@Override
public JSONObject toJSON() throws JSONException {
    JSONObject rootConfig = super.toJSON();
    rootConfig.put(JSON_WIDTH_KEY, mWidth);
    rootConfig.put(JSON_NAME_KEY, "SimpleLineStyle");
    return rootConfig;
}

From source file:edu.stanford.mobisocial.dungbeetle.feed.objects.StatusObj.java

public static JSONObject json(String status) {
    JSONObject obj = new JSONObject();
    try {/*from w  ww.  ja  v  a 2  s . c  o m*/
        obj.put(TEXT, status);
    } catch (JSONException e) {
    }
    return obj;
}

From source file:net.cellcloud.talk.HttpDialogueHandler.java

@Override
protected void doPost(HttpRequest request, HttpResponse response) throws IOException {
    HttpSession session = request.getSession();
    if (null != session) {
        try {/*from   w  ww.  j ava2 s  .  c o  m*/
            // ??
            JSONObject json = new JSONObject(new String(request.readRequestData(), Charset.forName("UTF-8")));
            // ? JSON ?
            String speakerTag = json.getString(Tag);
            String celletIdentifier = json.getString(Identifier);
            JSONObject primitiveJSON = json.getJSONObject(Primitive);
            // ?
            Primitive primitive = new Primitive(speakerTag);
            PrimitiveSerializer.read(primitive, primitiveJSON);
            // ?
            this.talkService.processDialogue(session, speakerTag, celletIdentifier, primitive);

            // ?
            // FIXME 2014/10/03 ??
            JSONObject responseData = new JSONObject();

            // ??
            Queue<Message> queue = session.getQueue();
            if (!queue.isEmpty()) {
                ArrayList<String> identifiers = new ArrayList<String>(queue.size());
                ArrayList<Primitive> primitives = new ArrayList<Primitive>(queue.size());
                for (int i = 0, size = queue.size(); i < size; ++i) {
                    // ?
                    Message message = queue.poll();
                    // 
                    Packet packet = Packet.unpack(message.get());
                    if (null != packet) {
                        // ? cellet identifier
                        byte[] identifier = packet.getSubsegment(1);

                        // ?????
                        byte[] primData = packet.getSubsegment(0);
                        ByteArrayInputStream stream = new ByteArrayInputStream(primData);

                        // ???
                        Primitive prim = new Primitive(Nucleus.getInstance().getTagAsString());
                        prim.read(stream);

                        // 
                        identifiers.add(Utils.bytes2String(identifier));
                        primitives.add(prim);
                    }
                }

                // ?
                JSONArray jsonPrimitives = this.convert(identifiers, primitives);
                responseData.put(Primitives, jsonPrimitives);
            }

            // ?
            responseData.put(Queue, queue.size());

            // ?
            this.respondWithOk(response, responseData);
        } catch (JSONException e) {
            Logger.log(HttpDialogueHandler.class, e, LogLevel.ERROR);
            this.respond(response, HttpResponse.SC_BAD_REQUEST);
        }
    } else {
        this.respond(response, HttpResponse.SC_UNAUTHORIZED);
    }
}

From source file:net.cellcloud.talk.HttpDialogueHandler.java

/**
 *  JSON //w w w. j a v  a2s .  c o m
 * @param queue
 * @return
 */
private JSONArray convert(ArrayList<String> identifiers, ArrayList<Primitive> list) {
    JSONArray ret = new JSONArray();

    try {
        for (int i = 0, size = identifiers.size(); i < size; ++i) {
            String identifier = identifiers.get(i);
            Primitive prim = list.get(i);

            JSONObject primJson = new JSONObject();
            PrimitiveSerializer.write(primJson, prim);

            JSONObject json = new JSONObject();
            json.put(Identifier, identifier);
            json.put(Primitive, primJson);

            // 
            ret.put(json);
        }
    } catch (JSONException e) {
        // Nothing
    }

    return ret;
}

From source file:org.jahia.modules.modulemanager.flow.DuplicateModuleAction.java

@Override
public ActionResult doExecute(HttpServletRequest req, RenderContext renderContext, Resource resource,
        JCRSessionWrapper session, Map<String, List<String>> parameters, URLResolver urlResolver)
        throws Exception {

    String newModuleName = getParameter(parameters, "newModuleName");
    String newModuleId = getParameter(parameters, "newModuleId");
    String newGroupId = getParameter(parameters, "newGroupId");
    String newDstPath = getParameter(parameters, "newDstPath");

    String srcPath = getParameter(parameters, "srcPath");
    String newScmUri = getParameter(parameters, "newScmUri");
    String branchOrTag = getParameter(parameters, "branchOrTag");
    String moduleId = getParameter(parameters, "moduleId");
    String version = getParameter(parameters, "version");
    boolean containsTypeDefinitions = Boolean
            .valueOf(getParameter(parameters, "containsTypeDefinitions", "false"));
    boolean areSourcesTemporary = Boolean.valueOf(getParameter(parameters, "areSourcesTemporary", "false"));

    try {//from  w  ww  .  j  av a  2 s .  co  m
        JahiaTemplatesPackage newModule = jahiaTemplateManagerService.duplicateModule(newModuleName,
                newModuleId, newGroupId, srcPath, newScmUri, branchOrTag, moduleId, version,
                containsTypeDefinitions, newDstPath, areSourcesTemporary, session);
        String contextPath = renderContext.getRequest().getContextPath();
        String newModuleStudioUrl = (StringUtils.equals(contextPath, "/") ? "" : contextPath)
                + "/cms/studio/default/" + resource.getLocale() + "/modules/" + newModule.getId() + ".html";
        JSONObject json = new JSONObject();
        json.put("newModuleStudioUrl", newModuleStudioUrl);
        return new ActionResult(HttpServletResponse.SC_OK, null, json);
    } catch (ScmUnavailableModuleIdException e) {
        String message = Messages.getWithArgs("resources.ModuleManager",
                "serverSettings.manageModules.duplicateModuleError.moduleExists", resource.getLocale(),
                newModuleName);
        JSONObject json = new JSONObject();
        json.put("error", message);
        return new ActionResult(HttpServletResponse.SC_OK, null, json);
    } catch (ScmWrongVersionException e) {
        String message = Messages.get("resources.ModuleManager",
                "serverSettings.manageModules.downloadSourcesError.wrongVersion", resource.getLocale());
        JSONObject json = new JSONObject();
        json.put("error", message);
        return new ActionResult(HttpServletResponse.SC_OK, null, json);
    } catch (SourceControlException e) {
        String message = Messages.getWithArgs("resources.ModuleManager",
                "serverSettings.manageModules.downloadSourcesError", resource.getLocale(), version);
        JSONObject json = new JSONObject();
        json.put("error", message);
        return new ActionResult(HttpServletResponse.SC_OK, null, json);
    } catch (Exception e) {
        String message = e.getLocalizedMessage();
        if (StringUtils.isBlank(message)) {
            message = e.toString();
        }
        JSONObject json = new JSONObject();
        json.put(e instanceof BundleException ? "bundleError" : "error", message);
        return new ActionResult(HttpServletResponse.SC_OK, null, json);
    }
}

From source file:nl.spellenclubeindhoven.dominionshuffle.Application.java

public void saveResult() {
    if (result == null)
        return;//from   ww w.j  a  v a2 s  . c  om

    JSONObject jsonResult = new JSONObject();

    JSONArray jsonCards = new JSONArray();
    for (Card card : result.getCards()) {
        jsonCards.put(card.getName());
    }

    try {
        jsonResult.put("cards", jsonCards);
        if (result.getBaneCard() != null) {
            jsonResult.put("baneCard", result.getBaneCard().getName());
        }
        if (result.getObeliskCard() != null) {
            jsonResult.put("obeliskCard", result.getObeliskCard().getName());
        }
        DataReader.writeStringToFile(this, "result.json", jsonResult.toString());
    } catch (JSONException ignore) {
        ignore.printStackTrace();
    }
}