Example usage for org.json JSONObject toString

List of usage examples for org.json JSONObject toString

Introduction

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

Prototype

public String toString() 

Source Link

Document

Make a JSON text of this JSONObject.

Usage

From source file:com.github.akinaru.rfdroid.bluetooth.BluetoothCustomManager.java

private void dispatchRFdroid(BluetoothDevice device, int rssi, final byte[] scanRecord) {

    if (scanningList.containsKey(device.getAddress())) {

        if (adListener != null && measurement.getBtDevice() != null
                && measurement.getBtDevice().getDeviceAddress().equals(device.getAddress())) {

            long ts = new Date().getTime();
            measurement.getHistoryList().add(ts);
            adListener.onADframeReceived(ts, measurement.getHistoryList());
        }/*from  w w w. ja  v  a2s  . c o  m*/
    } else {
        Log.i(TAG, "found a RFdroid");

        List<ADStructure> structures = ADPayloadParser.getInstance().parse(scanRecord);

        int advInterval = -1;

        for (ADStructure structure : structures) {

            if (structure instanceof ADManufacturerSpecific) {

                ADManufacturerSpecific data = (ADManufacturerSpecific) structure;

                if (data.getData().length == 9) {

                    byte[] name = new byte[7];
                    System.arraycopy(data.getData(), 0, name, 0, 7);

                    String nameStr = new String(name);
                    if (nameStr.equals("RFdroid")) {
                        advInterval = (data.getData()[7] << 8) + (data.getData()[8] & 0xFF);
                        Log.i(TAG, "current scan interval : " + advInterval);
                    }
                }
            }
        }

        if (advInterval != -1) {

            scanningList.put(device.getAddress(), device);

            if (!measurement.isSelectionningDevice())
                measurement.setBtDevice(new BluetoothObject(device.getAddress(), device.getName(),
                        (int) (advInterval * 0.625)));

            try {
                JSONObject object = new JSONObject();
                object.put(JsonConstants.BT_ADDRESS, device.getAddress());
                object.put(JsonConstants.BT_DEVICE_NAME, device.getName());
                object.put(JsonConstants.BT_ADVERTISING_INTERVAL, (int) (advInterval * 0.625));

                ArrayList<String> deviceInfo = new ArrayList<>();
                deviceInfo.add(object.toString());

                broadcastUpdateStringList(BluetoothEvents.BT_EVENT_DEVICE_DISCOVERED, deviceInfo);

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

}

From source file:com.github.akinaru.rfdroid.bluetooth.BluetoothCustomManager.java

private void dispatchBtDevices(BluetoothDevice device, int rssi, final byte[] scanRecord) {

    if (scanningList.containsKey(device.getAddress())) {

        if (adListener != null && measurement.getBtDevice() != null
                && measurement.getBtDevice().getDeviceAddress().equals(device.getAddress())) {

            long ts = new Date().getTime();
            measurement.getHistoryList().add(ts);
            adListener.onADframeReceived(ts, measurement.getHistoryList());
        }//from   w ww  .  ja  v  a  2 s .com
    } else {

        Log.i(TAG, "found a new Bluetooth device : " + device.getName() + " : " + device.getAddress());

        scanningList.put(device.getAddress(), device);

        try {
            JSONObject object = new JSONObject();
            object.put(JsonConstants.BT_ADDRESS, device.getAddress());
            object.put(JsonConstants.BT_DEVICE_NAME, device.getName());
            object.put(JsonConstants.BT_ADVERTISING_INTERVAL, -1);

            ArrayList<String> deviceInfo = new ArrayList<>();
            deviceInfo.add(object.toString());

            broadcastUpdateStringList(BluetoothEvents.BT_EVENT_DEVICE_DISCOVERED, deviceInfo);

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

From source file:com.ibm.mobilefirstplatform.clientsdk.android.push.api.MFPPush.java

/**
 * Subscribes to the given tag//  w  ww.jav  a  2  s .  c o m
 *
 * @param tagName  name of the tag
 * @param listener Mandatory listener class. When the subscription is created
 *                 successfully the {@link MFPPushResponseListener}.onSuccess
 *                 method is called with the tagName for which subscription is
 *                 created. {@link MFPPushResponseListener}.onFailure method is
 *                 called otherwise
 */
public void subscribe(final String tagName, final MFPPushResponseListener<String> listener) {
    if (isAbleToSubscribe()) {
        MFPPushUrlBuilder builder = new MFPPushUrlBuilder(applicationId);
        String path = builder.getSubscriptionsUrl();
        logger.debug("MFPPush:subscribe() - The tag subscription path is: " + path);
        MFPPushInvoker invoker = MFPPushInvoker.newInstance(appContext, path, Request.POST, clientSecret);
        invoker.setJSONRequestBody(buildSubscription(tagName));
        invoker.setResponseListener(new ResponseListener() {
            @Override
            public void onSuccess(Response response) {
                //Subscription successfully created.
                logger.info("MFPPush:subscribe() - Tag subscription successfully created.  The response is: "
                        + response.toString());
                listener.onSuccess(tagName);
            }

            @Override
            public void onFailure(Response response, Throwable throwable, JSONObject jsonObject) {
                //Error while subscribing to tags.
                errorString = null;
                statusCode = 0;
                if (response != null) {
                    errorString = response.getResponseText();
                    statusCode = response.getStatus();
                } else if (errorString == null && throwable != null) {
                    errorString = throwable.toString();
                } else if (errorString == null && jsonObject != null) {
                    errorString = jsonObject.toString();
                }
                listener.onFailure(new MFPPushException(errorString, statusCode));
            }

        });
        invoker.execute();
    }
}

From source file:com.ibm.mobilefirstplatform.clientsdk.android.push.api.MFPPush.java

/**
 * Unsubscribes to the given tag/*from  ww  w .ja va2  s  . c  o m*/
 *
 * @param tagName  name of the tag
 * @param listener Mandatory listener class. When the subscription is deleted
 *                 successfully the {@link MFPPushResponseListener}.onSuccess
 *                 method is called with the tagName for which subscription is
 *                 deleted. {@link MFPPushResponseListener}.onFailure method is
 *                 called otherwise
 */
public void unsubscribe(final String tagName, final MFPPushResponseListener<String> listener) {
    if (isAbleToSubscribe()) {
        MFPPushUrlBuilder builder = new MFPPushUrlBuilder(applicationId);
        String path = builder.getSubscriptionsUrl(deviceId, tagName);
        logger.debug("MFPPush:unsubscribe() - The tag unsubscription path is: " + path);
        MFPPushInvoker invoker = MFPPushInvoker.newInstance(appContext, path, Request.DELETE, clientSecret);

        invoker.setResponseListener(new ResponseListener() {
            @Override
            public void onSuccess(Response response) {
                logger.info("MFPPush:unsubscribe() - Tag unsubscription successful.  The response is: "
                        + response.toString());
                listener.onSuccess(tagName);
            }

            @Override
            public void onFailure(Response response, Throwable throwable, JSONObject jsonObject) {
                //Error while subscribing to tags.
                errorString = null;
                statusCode = 0;
                if (response != null) {
                    errorString = response.getResponseText();
                    statusCode = response.getStatus();
                } else if (errorString == null && throwable != null) {
                    errorString = throwable.toString();
                } else if (errorString == null && jsonObject != null) {
                    errorString = jsonObject.toString();
                }
                listener.onFailure(new MFPPushException(errorString, statusCode));
            }
        });
        invoker.execute();
    }
}

From source file:com.ibm.mobilefirstplatform.clientsdk.android.push.api.MFPPush.java

/**
 * Unregister the device from Push Server
 *
 * @param listener Mandatory listener class. When the subscription is deleted
 *                 successfully the {@link MFPPushResponseListener}.onSuccess
 *                 method is called with the tagName for which subscription is
 *                 deleted. {@link MFPPushResponseListener}.onFailure method is
 *                 called otherwise/*w w  w  .  j  av a  2  s .co m*/
 */
public void unregister(final MFPPushResponseListener<String> listener) {
    MFPPushUrlBuilder builder = new MFPPushUrlBuilder(applicationId);
    String path = builder.getUnregisterUrl(deviceId);
    logger.debug("MFPPush:unregister() - The device unregister url is: " + path);
    MFPPushInvoker invoker = MFPPushInvoker.newInstance(appContext, path, Request.DELETE, clientSecret);

    invoker.setResponseListener(new ResponseListener() {
        @Override
        public void onSuccess(Response response) {
            logger.info("MFPPush:unregister() - Successfully unregistered device. Response is: "
                    + response.toString());
            isTokenUpdatedOnServer = false;
            isRegisteredForPush = false;
            listener.onSuccess("Device Successfully unregistered from receiving push notifications.");
        }

        @Override
        public void onFailure(Response response, Throwable throwable, JSONObject jsonObject) {
            errorString = null;
            statusCode = 0;
            if (response != null) {
                errorString = response.getResponseText();
                statusCode = response.getStatus();
            } else if (errorString == null && throwable != null) {
                errorString = throwable.toString();
            } else if (errorString == null && jsonObject != null) {
                errorString = jsonObject.toString();
            }
            listener.onFailure(new MFPPushException(errorString, statusCode));
        }
    });
    invoker.execute();
}

From source file:com.ibm.mobilefirstplatform.clientsdk.android.push.api.MFPPush.java

/**
 * Get the list of tags/*  w w  w.j a  va 2s .c o  m*/
 *
 * @param listener Mandatory listener class. When the list of tags are
 *                 successfully retrieved the {@link MFPPushResponseListener}
 *                 .onSuccess method is called with the list of tagNames
 *                 {@link MFPPushResponseListener}.onFailure method is called
 *                 otherwise
 */
public void getTags(final MFPPushResponseListener<List<String>> listener) {
    MFPPushUrlBuilder builder = new MFPPushUrlBuilder(applicationId);
    String path = builder.getTagsUrl();
    MFPPushInvoker invoker = MFPPushInvoker.newInstance(appContext, path, Request.GET, clientSecret);

    invoker.setResponseListener(new ResponseListener() {

        @Override
        public void onSuccess(Response response) {
            logger.info("MFPPush:getTags() - Successfully retreived tags.  The response is: "
                    + response.toString());
            List<String> tagNames = new ArrayList<String>();
            try {
                String responseText = response.getResponseText();
                JSONArray tags = (JSONArray) (new JSONObject(responseText)).get(TAGS);
                Log.d("JSONArray of tags is: ", tags.toString());
                int tagsCnt = tags.length();
                for (int tagsIdx = 0; tagsIdx < tagsCnt; tagsIdx++) {
                    Log.d("Adding tag: ", tags.getJSONObject(tagsIdx).toString());
                    tagNames.add(tags.getJSONObject(tagsIdx).getString(NAME));
                }
                listener.onSuccess(tagNames);
            } catch (JSONException e) {
                logger.error("MFPPush: getTags() - Error while retrieving tags.  Error is: " + e.getMessage());
                listener.onFailure(new MFPPushException(e));
            }
        }

        @Override
        public void onFailure(Response response, Throwable throwable, JSONObject jsonObject) {
            //Error while subscribing to tags.
            errorString = null;
            statusCode = 0;
            if (response != null) {
                errorString = response.getResponseText();
                statusCode = response.getStatus();
            } else if (errorString == null && throwable != null) {
                errorString = throwable.toString();
            } else if (errorString == null && jsonObject != null) {
                errorString = jsonObject.toString();
            }
            listener.onFailure(new MFPPushException(errorString, statusCode));
        }
    });
    invoker.execute();
}

From source file:com.ibm.mobilefirstplatform.clientsdk.android.push.api.MFPPush.java

/**
 * Get the list of tags subscribed to/*from  www . ja  v  a 2  s.  c  o m*/
 *
 * @param listener Mandatory listener class. When the list of tags subscribed to
 *                 are successfully retrieved the {@link MFPPushResponseListener}
 *                 .onSuccess method is called with the list of tagNames
 *                 {@link MFPPushResponseListener}.onFailure method is called
 *                 otherwise
 */
public void getSubscriptions(final MFPPushResponseListener<List<String>> listener) {

    MFPPushUrlBuilder builder = new MFPPushUrlBuilder(applicationId);
    String path = builder.getSubscriptionsUrl(deviceId, null);
    MFPPushInvoker invoker = MFPPushInvoker.newInstance(appContext, path, Request.GET, clientSecret);

    invoker.setResponseListener(new ResponseListener() {
        @Override
        public void onSuccess(Response response) {
            List<String> tagNames = new ArrayList<String>();
            try {
                JSONArray tags = (JSONArray) (new JSONObject(response.getResponseText())).get(SUBSCRIPTIONS);
                int tagsCnt = tags.length();
                for (int tagsIdx = 0; tagsIdx < tagsCnt; tagsIdx++) {
                    tagNames.add(tags.getJSONObject(tagsIdx).getString(TAG_NAME));
                }
                listener.onSuccess(tagNames);

            } catch (JSONException e) {
                logger.error(
                        "MFPPush: getSubscriptions() - Failure while getting subscriptions.  Failure response is: "
                                + e.getMessage());
                listener.onFailure(new MFPPushException(e));
            }
        }

        @Override
        public void onFailure(Response response, Throwable throwable, JSONObject jsonObject) {
            //Error while subscribing to tags.
            errorString = null;
            statusCode = 0;
            if (response != null) {
                errorString = response.getResponseText();
                statusCode = response.getStatus();
            } else if (errorString == null && throwable != null) {
                errorString = throwable.toString();
            } else if (errorString == null && jsonObject != null) {
                errorString = jsonObject.toString();
            }
            listener.onFailure(new MFPPushException(errorString, statusCode));
        }
    });
    invoker.execute();
}

From source file:com.ibm.mobilefirstplatform.clientsdk.android.push.api.MFPPush.java

private void updateTokenCallback(String deviceToken, String userId) {
    if (isNewRegistration) {
        logger.debug(/*from   w w  w.ja  v a 2  s .co  m*/
                "MFPPush:updateTokenCallback() - Device is registering with push server for the first time.");
        MFPPushUrlBuilder builder = new MFPPushUrlBuilder(applicationId);
        String path = builder.getDevicesUrl();
        MFPPushInvoker invoker = MFPPushInvoker.newInstance(appContext, path, Request.POST, clientSecret);

        //Add header for xtify deviceId for migration
        final SharedPreferences sharedPreferences = appContext
                .getSharedPreferences("com.ibm.mobile.services.push", 0);
        if (MFPPushUtils.validateString(userId)) {
            invoker.setJSONRequestBody(buildDevice(userId));
        } else {
            invoker.setJSONRequestBody(buildDevice(""));
        }
        invoker.setResponseListener(new ResponseListener() {

            @Override
            public void onSuccess(Response response) {
                isNewRegistration = false;
                isTokenUpdatedOnServer = true;
                isRegisteredForPush = true;
                logger.info("MFPPush:updateTokenCallback() - Successfully registered device.");
                registerResponseListener.onSuccess(response.toString());
            }

            @Override
            public void onFailure(Response response, Throwable throwable, JSONObject jsonObject) {
                logger.error("MFPPush:updateTokenCallback() - Failure during device registration.");
                errorString = null;
                statusCode = 0;
                if (response != null) {
                    errorString = response.getResponseText();
                    statusCode = response.getStatus();
                } else if (errorString == null && throwable != null) {
                    errorString = throwable.toString();
                } else if (errorString == null && jsonObject != null) {
                    errorString = jsonObject.toString();
                }
                registerResponseListener.onFailure(new MFPPushException(errorString, statusCode));
            }
        });
        invoker.execute();
    } else if (hasRegisterParametersChanged) {
        logger.debug(
                "MFPPush:updateTokenCallback() - Device is already registered. Registration parameters have changed.");
        MFPPushUrlBuilder builder = new MFPPushUrlBuilder(applicationId);
        String path = builder.getDeviceIdUrl(deviceId);
        MFPPushInvoker invoker = MFPPushInvoker.newInstance(appContext, path, Request.PUT, clientSecret);

        if (MFPPushUtils.validateString(userId)) {
            invoker.setJSONRequestBody(buildDevice(userId));
        } else {
            invoker.setJSONRequestBody(buildDevice(""));
        }
        invoker.setResponseListener(new ResponseListener() {

            @Override
            public void onSuccess(Response response) {
                logger.debug("MFPPush:updateTokenCallback() - Device registration successfully updated.");
                isTokenUpdatedOnServer = true;
                isNewRegistration = false;
                isRegisteredForPush = true;
                registerResponseListener.onSuccess(response.toString());
            }

            @Override
            public void onFailure(Response response, Throwable throwable, JSONObject jsonObject) {
                logger.debug(
                        "MFPPush:updateTokenCallback() - Failure while updating device registration details.");
                errorString = null;
                statusCode = 0;
                if (response != null) {
                    errorString = response.getResponseText();
                    statusCode = response.getStatus();
                } else if (errorString == null && throwable != null) {
                    errorString = throwable.toString();
                } else if (errorString == null && jsonObject != null) {
                    errorString = jsonObject.toString();
                }
                registerResponseListener.onFailure(new MFPPushException(errorString, statusCode));
            }
        });
        invoker.execute();

        hasRegisterParametersChanged = false;
    } else {
        isTokenUpdatedOnServer = true;
        registerResponseListener.onSuccess(deviceId);
    }
}

From source file:com.ibm.mobilefirstplatform.clientsdk.android.push.api.MFPPush.java

private void getSenderIdFromServerAndRegisterInBackground(final String userId) {
    MFPPushUrlBuilder builder = new MFPPushUrlBuilder(applicationId);
    String path = builder.getSettingsUrl();
    MFPPushInvoker invoker = MFPPushInvoker.newInstance(appContext, path, Request.GET, clientSecret);
    logger.debug(/*from w  ww.j  a  va  2 s  . c o m*/
            "MFPPush: getSenderIdFromServerAndRegisterInBackground() - The url for getting gcm configuration is: "
                    + path);
    invoker.setJSONRequestBody(null);

    invoker.setResponseListener(new ResponseListener() {

        @Override
        public void onSuccess(Response response) {
            logger.debug(
                    "MFPPush: getSenderIdFromServerAndRegisterInBackground() - success retrieving senderId from server");
            String senderId = null;
            try {
                senderId = (String) (new JSONObject(response.getResponseText())).get(SENDER_ID);
            } catch (JSONException e) {
                logger.error(
                        "MFPPush: getSenderIdFromServerAndRegisterInBackground() - Failure while parsing JSON object for "
                                + "retrieving senderId");
                e.printStackTrace();
            }

            if (senderId == null) {
                errorString = "MFPPush: getSenderIdFromServerAndRegisterInBackgound() - SenderId is not configured in the backend application.";
                registerResponseListener.onFailure(new MFPPushException(errorString));
            } else {
                gcmSenderId = senderId;
                MFPPushUtils.storeContentInSharedPreferences(appContext, applicationId, SENDER_ID, gcmSenderId);
                registerInBackground(userId);
            }
        }

        @Override
        public void onFailure(Response response, Throwable throwable, JSONObject object) {
            logger.error(
                    "MFPPush: getSenderIdFromServerAndRegisterInBackground() - Error while getting senderId from push server.");
            errorString = null;
            statusCode = 0;
            if (response != null) {
                errorString = response.getResponseText();
                statusCode = response.getStatus();
            } else if (errorString == null && throwable != null) {
                errorString = throwable.toString();
            } else if (errorString == null && object != null) {
                errorString = object.toString();
            }
            registerResponseListener.onFailure(new MFPPushException(errorString, statusCode));
        }
    });

    invoker.execute();
}

From source file:com.riotgames.mondev.JMXDiscovery.java

protected String discoverMBeans(String key) throws Exception {
    try {/*from  ww w .j  a v a 2s. com*/
        HashMap<String, String[]> env = null;
        if (null != username && null != password) {
            env = new HashMap<String, String[]>();
            env.put(JMXConnector.CREDENTIALS, new String[] { username, password });
        }

        jmxc = JMXConnectorFactory.connect(jmxServerUrl, env);
        mbsc = jmxc.getMBeanServerConnection();

        ObjectName filter = new ObjectName(key);
        JSONArray beanList = new JSONArray();
        JSONObject mapping = new JSONObject();

        Set beans = mbsc.queryMBeans(filter, null);
        for (Object obj : beans) {
            JSONObject bean = new JSONObject();
            ObjectName beanName;

            // Return the ObjectName instance correctly for both Objects and Instances
            if (obj instanceof ObjectName)
                beanName = (ObjectName) obj;
            else if (obj instanceof ObjectInstance)
                beanName = ((ObjectInstance) obj).getObjectName();
            else
                throw new RuntimeException("Unexpected object type: " + obj);

            // Build the standing info, description and object path
            MBeanInfo mbi = mbsc.getMBeanInfo(beanName);
            bean.put("{#JMXDESC}", mbi.getDescription());
            bean.put("{#JMXOBJ}", beanName.getCanonicalName());

            // Build a list of all the MBean properties as {#PROP<NAME>}
            Hashtable<String, String> pt = beanName.getKeyPropertyList();
            for (Map.Entry<String, String> prop : pt.entrySet())
                bean.put(String.format("{#PROP%s}", prop.getKey().toUpperCase()), prop.getValue());

            beanList.put(bean);
        }

        mapping.put("data", beanList);
        return mapping.toString();
    } catch (Exception e) {
        JSONArray data = new JSONArray();
        JSONObject out = new JSONObject();
        out.put("data", data);

        return out.toString();
    } finally {
        try {
            if (null != jmxc)
                jmxc.close();
        } catch (java.io.IOException exception) {
        }

        jmxc = null;
        mbsc = null;
    }
}