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:eu.smartfp7.linkeddatamanager.interfaces.StructuredSearch.java

/**
 * Finding activities within a geo-spatial rectangle identified by the exact geographical coordinates of its lower-left corner and its upper-right corner
 * @param lat1: Between 0 and 90 degrees. Positive (North) o negative (South)
 * @param long1: Between 0 and 180 degrees. Positive (East) o negative (West)
 * @param lat2: Between 0 and 90 degrees. Positive (North) o negative (South)
 * @param long2: Between 0 and 180 degrees. Positive (East) o negative (West)
 * @param since: To delimit the date (an optional requirement)
 * @param until: To delimit the date (an optional requirement)
 * @param dataset. The dataset in which perform the search. By default Factforge
 * @return A JSON file format with the found activities
 * @throws IOException// w  w  w . j av  a2  s .  co m
 */
@GET
@Path("actRec")
@Produces({ MediaType.APPLICATION_JSON })
public Response sActRec(@QueryParam("lat1") float lat1, @QueryParam("long1") float long1,
        @QueryParam("lat2") float lat2, @QueryParam("long2") float long2,
        @QueryParam("since") @DefaultValue("") String since,
        @QueryParam("until") @DefaultValue("") String until,
        @QueryParam("dataset") @DefaultValue("factforge") String dataset) throws IOException {
    logger.info("Invoking search activities by coordinates, rectangule");
    logger.info("Dataset: " + dataset);
    logger.info("Lat1: " + lat1);
    logger.info("Long1: " + long1);
    logger.info("Lat2: " + lat2);
    logger.info("Long2: " + long2);
    logger.info("Since: " + since);
    logger.info("Until: " + until);

    InputStream in = null;
    Mapping m = new MappingManager().getMapping(dataset);

    SimpleQueryBuilder builder = new SimpleQueryBuilder(m);
    builder.setCriteria("activity", since, until, lat1, long1, lat2, long2, -1);
    String query = builder.printQuery();

    SPARQLtoJSON queryer = new SPARQLtoJSON(m.getEndpoint(), m);
    try {
        JSONObject res = queryer.executeSPARQL(query);
        in = new ByteArrayInputStream(res.toString().getBytes());
    } catch (Exception e) {
        e.printStackTrace();
        return Response.serverError().build();
    }
    logger.info("Invoked search activities by coordinates, rectangule");
    return Response.ok(in).build();

}

From source file:eu.smartfp7.linkeddatamanager.interfaces.StructuredSearch.java

/**
 * Finding locations located within a geo-spatial circle identified by the geo-graphical coordinates (a pair of latitude and longitude) of its centre and its radius
 * @param lat1: The latitude coordinate indicating the centre. Between 0 and 90 degrees. Positive (North) o negative (South)
 * @param long1: The longitude coordinate indicating the centre. Between 0 and 180 degrees. Positive (East) o negative (West)
 * @param radius: The radio from the centre
 * @param since: To delimit the date (an optional requirement)
 * @param until: To delimit the date (an optional requirement)
 * @param dataset: The dataset in which perform the search. By default Factforge
 * @return A JSON file format with the found activities
 * @throws IOException /*  ww w . j  a v a2 s.c  om*/
 */
@GET
@Path("actCirc")
@Produces({ MediaType.APPLICATION_JSON })
public Response sActCirc(@QueryParam("lat1") float lat1, @QueryParam("long1") float long1,
        @QueryParam("radius") float radius, @QueryParam("since") @DefaultValue("") String since,
        @QueryParam("until") @DefaultValue("") String until,
        @QueryParam("dataset") @DefaultValue("factforge") String dataset) throws IOException {
    logger.info("Invoking search activities by coordinates, circule");
    logger.info("Dataset: " + dataset);
    logger.info("Lat1: " + lat1);
    logger.info("Long1: " + long1);
    logger.info("Radius: " + radius);
    logger.info("Since: " + since);
    logger.info("Until: " + until);

    InputStream in = null;
    Mapping m = new MappingManager().getMapping(dataset);

    SimpleQueryBuilder builder = new SimpleQueryBuilder(m);
    builder.setCriteria("activity", since, until, lat1, long1, -91, -81, radius);
    String query = builder.printQuery();

    SPARQLtoJSON queryer = new SPARQLtoJSON(m.getEndpoint(), m);
    try {
        JSONObject res = queryer.executeSPARQL(query);
        in = new ByteArrayInputStream(res.toString().getBytes());
    } catch (Exception e) {
        e.printStackTrace();
        return Response.serverError().build();
    }
    logger.info("Invoked search activities by coordinates, circule");
    return Response.ok(in).build();
}

From source file:it.unicaradio.android.tasks.DownloadCaptchaAsyncTask.java

/**
 * {@inheritDoc}//from  w w  w .  ja  v a  2  s  . c  om
 */
@Override
protected Response<String> doInBackground(Void... params) {
    try {
        JSONObject request = new JSONObject();
        request.put("method", "getCaptcha");
        byte[] postData = request.toString().getBytes();

        Response<String> response = new Response<String>();
        byte[] resultBytes = NetworkUtils.httpPost(WEB_SERVICE, postData, "application/json");

        String resultString = new String(resultBytes);
        Log.d(TAG, "Got CAPTCHA answer: " + resultString);
        JSONObject resultJSON = new JSONObject(resultString);
        response.setResult(resultJSON.getString("result"));

        return response;
    } catch (ClientProtocolException e) {
        Log.e(TAG, e.getMessage(), e);
        return new Response<String>(Error.INTERNAL_GENERIC_ERROR);
    } catch (IOException e) {
        Log.e(TAG, e.getMessage(), e);
        return new Response<String>(Error.INTERNAL_DOWNLOAD_ERROR);
    } catch (HttpException e) {
        Log.e(TAG, e.getMessage(), e);
        return new Response<String>(Error.INTERNAL_GENERIC_ERROR);
    } catch (JSONException e) {
        Log.e(TAG, e.getMessage(), e);
        return new Response<String>(Error.INTERNAL_GENERIC_ERROR);
    }
}

From source file:com.github.akinaru.bleanalyzer.bluetooth.connection.BluetoothDeviceConn.java

/**
 * Build Bluetooth device connection/*from  w  w w . j av a  2s.  c o  m*/
 *
 * @param address
 */
@SuppressLint("NewApi")
public BluetoothDeviceConn(String address, String deviceName, final IBluetoothCustomManager manager) {
    this.deviceAddr = address;
    this.deviceName = deviceName;
    this.manager = manager;

    gattCallback = new BluetoothGattCallback() {
        @Override
        public void onConnectionStateChange(BluetoothGatt gatt, int status, int newState) {

            if (newState == BluetoothProfile.STATE_CONNECTED) {

                Log.i(TAG, "Connected to GATT server.");
                Log.i(TAG, "Attempting to start service discovery:" + gatt.discoverServices());

            } else if (newState == BluetoothProfile.STATE_DISCONNECTED) {

                connected = false;
                Log.i(TAG, "Disconnected from GATT server.");

                try {
                    JSONObject object = new JSONObject();
                    object.put(JsonConstants.BT_ADDRESS, getAddress());
                    object.put(JsonConstants.BT_DEVICE_NAME, getDeviceName());

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

                    //when device is fully intitialized broadcast service discovery
                    manager.broadcastUpdateStringList(BluetoothEvents.BT_EVENT_DEVICE_DISCONNECTED, values);
                } catch (JSONException e) {
                    e.printStackTrace();
                }

                if (manager.getWaitingMap().containsKey(deviceAddr)) {
                    manager.getWaitingMap().get(deviceAddr).cancel(true);
                    manager.getWaitingMap().remove(deviceAddr);
                }

                if (BluetoothDeviceConn.this.gatt != null) {
                    Log.i(TAG, "connection close clean");
                    BluetoothDeviceConn.this.gatt.close();
                }
            }
        }

        @Override
        // New services discovered
        public void onServicesDiscovered(BluetoothGatt gatt, int status) {

            if (status == BluetoothGatt.GATT_SUCCESS) {

                Runnable test = new Runnable() {
                    @Override
                    public void run() {

                        //you can improve this by using reflection
                        device = new RfduinoDevice(BluetoothDeviceConn.this);

                        device.addInitListener(new IDeviceInitListener() {
                            @Override
                            public void onInit() {
                                try {
                                    JSONObject object = new JSONObject();
                                    object.put(JsonConstants.BT_ADDRESS, getAddress());
                                    object.put(JsonConstants.BT_DEVICE_NAME, getDeviceName());

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

                                    connected = true;
                                    //when device is fully intitialized broadcast service discovery
                                    manager.broadcastUpdateStringList(BluetoothEvents.BT_EVENT_DEVICE_CONNECTED,
                                            values);
                                } catch (JSONException e) {
                                    e.printStackTrace();
                                }
                            }
                        });
                        device.init();
                    }
                };
                Thread testThread = new Thread(test);
                testThread.start();

            } else {
                Log.w(TAG, "onServicesDiscovered received: " + status);
            }
        }

        @Override
        public void onCharacteristicWrite(BluetoothGatt gatt, BluetoothGattCharacteristic characteristic,
                int status) {
            //manager.getEventManager().set();
            if (device != null) {
                device.notifyCharacteristicWriteReceived(characteristic);
            }
        }

        @Override
        // Result of a characteristic read operation
        public void onCharacteristicRead(BluetoothGatt gatt, BluetoothGattCharacteristic characteristic,
                int status) {
            manager.getEventManager().set();
            if (device != null) {
                Log.i(TAG, "onCharacteristicRead");
                device.notifyCharacteristicReadReceived(characteristic);
            }
        }

        @Override
        public void onDescriptorWrite(BluetoothGatt gatt, BluetoothGattDescriptor descriptor, int status) {
            manager.getEventManager().set();
        }

        @Override
        // Characteristic notification
        public void onCharacteristicChanged(BluetoothGatt gatt, BluetoothGattCharacteristic characteristic) {
            manager.getEventManager().set();
            if (device != null) {
                Log.i(TAG, "onCharacteristicChanged");
                device.notifyCharacteristicChangeReceived(characteristic);
            }
        }
    };
}

From source file:com.aniruddhc.acemusic.player.GMusicHelpers.GMusicClientCalls.java

/****************************************************************************
 * Creates a new, user generated playlist. This method only creates the 
 * playlist; it does not add songs to the playlist.
 * //from w w w  .j  av  a 2s .c  o m
 * @param context The context to use while creating the new playlist.
 * @param playlistName The name of the new playlist.
 * @return Returns the playlistId of the newly created playlist.
 * @throws JSONException
 * @throws IllegalArgumentException
 ****************************************************************************/
public final static String createPlaylist(Context context, String playlistName)
        throws JSONException, IllegalArgumentException {

    JSONObject jsonParam = new JSONObject();
    JSONArray mutationsArray = new JSONArray();
    JSONObject createObject = new JSONObject();

    createObject.put("lastModifiedTimestamp", "0");
    createObject.put("name", playlistName);
    createObject.put("creationTimestamp", "-1");
    createObject.put("type", "USER_GENERATED");
    createObject.put("deleted", false);

    mutationsArray.put(new JSONObject().put("create", createObject));
    jsonParam.put("mutations", mutationsArray);

    mHttpClient.setUserAgent(mMobileClientUserAgent);
    String result = mHttpClient.post(context,
            "https://www.googleapis.com/sj/v1.1/playlistbatch?alt=json&hl=en_US",
            new ByteArrayEntity(jsonParam.toString().getBytes()), "application/json");

    mHttpClient.setUserAgent(mWebClientUserAgent);
    return new JSONObject(result).optJSONArray("mutate_response").getJSONObject(0).optString("id");
}

From source file:com.aniruddhc.acemusic.player.GMusicHelpers.GMusicClientCalls.java

/*****************************************************************************
 * Creates a JSONObject object that contains the delete command for the 
 * specified playlist and adds it to the JSONArray that will pass the the 
 * command on to Google's servers. //from   www  . j  a  v  a2  s  .co m
 * 
 * @param context The context to use while deleting the playlist.
 * @param playlistId The playlistId of the playlist to delete.
 * @throws JSONException
 * @throws IllegalArgumentException
 *****************************************************************************/
public static final String deletePlaylist(Context context, String playlistId)
        throws JSONException, IllegalArgumentException {

    JSONObject jsonParam = new JSONObject();
    JSONArray mutationsArray = new JSONArray();

    mutationsArray.put(new JSONObject().put("delete", playlistId));
    jsonParam.put("mutations", mutationsArray);

    mHttpClient.setUserAgent(mMobileClientUserAgent);
    String result = mHttpClient.post(context,
            "https://www.googleapis.com/sj/v1.1/playlistbatch?alt=json&hl=en_US",
            new ByteArrayEntity(jsonParam.toString().getBytes()), "application/json");

    mHttpClient.setUserAgent(mWebClientUserAgent);
    return result;
}

From source file:com.aniruddhc.acemusic.player.GMusicHelpers.GMusicClientCalls.java

/******************************************************************************************
 * Executes a single/batch modification operation on a playlist's entry(ies). This method 
 * is a general purpose method that simply hits the MobileClient endpoints using
 * mPlaylistEntriesMutationsArray. Supported mutation operations include "create", 
 * "delete", and "update". /*www  . j  a v a 2  s . c o m*/
 * 
 * @param context The context to use while carrying out the modification operation.
 * @param mutationsArray The JSONArray that contains the mutations command to be 
 * carried out.
 * @return The JSON response as a String.
 * @throws JSONException
 * @throws IllegalArgumentException
 ******************************************************************************************/
public static final String modifyPlaylist(Context context) throws JSONException, IllegalArgumentException {

    JSONObject jsonParam = new JSONObject();
    jsonParam.put("mutations", mPlaylistEntriesMutationsArray);

    mHttpClient.setUserAgent(mMobileClientUserAgent);
    String result = mHttpClient.post(context,
            "https://www.googleapis.com/sj/v1.1/plentriesbatch?alt=json&hl=en_US",
            new ByteArrayEntity(jsonParam.toString().getBytes()), "application/json");

    mHttpClient.setUserAgent(mWebClientUserAgent);

    //Clear out and reset the mutationsArray now that we're done using it.
    mPlaylistEntriesMutationsArray = null;
    mPlaylistEntriesMutationsArray = new JSONArray();

    return result;
}

From source file:com.aniruddhc.acemusic.player.GMusicHelpers.GMusicClientCalls.java

/*******************************************************************************************
 * Sends a POST request to Google's servers and retrieves a JSONArray with all user 
 * playlists. The JSONArray contains the fields of the playlist such as "id", "name", 
 * "type", etc. (for a list of all response fields, see MobileClientPlaylistsSchema.java).
 * // w  ww.  ja v  a2  s.c  o m
 * @return A JSONArray object that contains all user playlists and their fields.
 * @param context The context to use while retrieving user playlists.
 *******************************************************************************************/
public static final JSONArray getUserPlaylistsMobileClient(Context context)
        throws JSONException, IllegalArgumentException {

    JSONObject jsonRequestParams = new JSONObject();
    JSONArray playlistsJSONArray = new JSONArray();

    jsonRequestParams.put("max-results", 250);
    jsonRequestParams.put("start-token", "0");

    mHttpClient.setUserAgent(mMobileClientUserAgent);
    String result = mHttpClient.post(context,
            "https://www.googleapis.com/sj/v1.1/playlistfeed?alt=json&hl=en_US&tier=basic",
            new ByteArrayEntity(jsonRequestParams.toString().getBytes()), "application/json");

    JSONObject resultJSONObject = new JSONObject(result);
    JSONObject dataJSONObject = new JSONObject();

    if (resultJSONObject != null) {
        dataJSONObject = resultJSONObject.optJSONObject("data");
    }

    if (dataJSONObject != null) {
        playlistsJSONArray = dataJSONObject.getJSONArray("items");
    }

    return playlistsJSONArray;
}

From source file:com.aniruddhc.acemusic.player.GMusicHelpers.GMusicClientCalls.java

/******************************************************************************************
 * Retrieves a JSONAray with all songs in <i><b>every</b></i> playlist. The JSONArray 
 * contains the fields of the songs such as "id", "clientId", "trackId", etc. (for a list 
 * of all fields, see MobileClientPlaylistEntriesSchema.java). 
 * /*from   ww w .  ja  v  a 2s  . c  o  m*/
 * @deprecated This method is fully functional. However, there are issues with retrieving 
 * the correct playlist entryIds. Specifically, the entryIds do not seem to work with 
 * reordering playlists via the MobileClient mutations protocol. 
 * 
 * @return A JSONArray object that contains all songs and their fields within every playlist. 
 * @param context The context to use while retrieving songs from the playlist.
 ******************************************************************************************/
public static final JSONArray getPlaylistEntriesMobileClient(Context context)
        throws JSONException, IllegalArgumentException {

    JSONArray playlistEntriesJSONArray = new JSONArray();
    JSONObject jsonRequestParams = new JSONObject();

    jsonRequestParams.put("max-results", 10000);
    jsonRequestParams.put("start-token", "0");

    mHttpClient.setUserAgent(mMobileClientUserAgent);
    String result = mHttpClient.post(context,
            "https://www.googleapis.com/sj/v1.1/plentryfeed?alt=json&hl=en_US&tier=basic",
            new ByteArrayEntity(jsonRequestParams.toString().getBytes()), "application/json");

    JSONObject resultJSONObject = new JSONObject(result);
    JSONObject dataJSONObject = new JSONObject();

    if (resultJSONObject != null) {
        dataJSONObject = resultJSONObject.optJSONObject("data");
    }

    if (dataJSONObject != null) {
        playlistEntriesJSONArray = dataJSONObject.getJSONArray("items");
    }

    return playlistEntriesJSONArray;
}

From source file:com.aniruddhc.acemusic.player.GMusicHelpers.GMusicClientCalls.java

/**************************************************************************************************
 * Retrieves a JSONAray with all songs within the <b><i>specified</b></i> playlist. The JSONArray 
 * contains the fields of the songs such as "id", "clientId", "trackId", etc. (for a list 
 * of all fields, see WebClientSongsSchema.java). Uses the WebClient endpoint.
 * /*from w  ww .  j  av  a2s. c  o m*/
 * @return A JSONArray object that contains the songs and their fields within the specified playlist.
 * @param context The context to use while retrieving songs from the playlist.
 * @param playlistId The id of the playlist we need to fetch the songs from.
 **************************************************************************************************/
public static final JSONArray getPlaylistEntriesWebClient(Context context, String playlistId)
        throws JSONException, IllegalArgumentException {

    JSONObject jsonParam = new JSONObject();
    jsonParam.putOpt("id", playlistId);

    JSONForm form = new JSONForm();
    form.addField("json", jsonParam.toString());
    form.close();

    mHttpClient.setUserAgent(mMobileClientUserAgent);
    String result = mHttpClient.post(context,
            "https://play.google.com/music/services/loadplaylist?u=0&xt=" + getXtCookieValue(),
            new ByteArrayEntity(form.toString().getBytes()), form.getContentType());

    JSONArray jsonArray = new JSONArray();
    JSONObject jsonObject = new JSONObject(result);

    if (jsonObject != null) {
        jsonArray = jsonObject.getJSONArray("playlist");
    }

    return jsonArray;
}