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:org.csp.everyaware.internet.StoreAndForwardService.java

public void postTags()
        throws IllegalArgumentException, ClientProtocolException, HttpHostConnectException, IOException {
    Log.d("StoreAndForwardService", "postTags()");

    int sepIndex = 1; //default is '.' separator (see Constants.separators array)
    if ((Utils.report_country != null) && (Utils.report_country.equals("IT")))
        sepIndex = 0; //0 is for '-' separator (for italian CSP server)

    List<String> sids = mDbManager.getSidsOfRecordsWithTags();

    if ((sids != null) && (sids.size() > 0)) {
        for (int i = 0; i < sids.size(); i++) {
            String sessionId = (String) sids.get(i);

            //load records containing user tags with actual session id
            List<Record> recordsWithTags = mDbManager.loadRecordsWithTagBySessionId(sessionId);

            if ((recordsWithTags != null) && (recordsWithTags.size() > 0)) {
                //get size of array of records containing tags and reference to the last record
                int size = recordsWithTags.size();

                //obtain reference to the last record of serie
                Record lastToSendRecord = recordsWithTags.get(size - 1);
                Log.d("StoreAndForwardService", "postTags()--> # of records containing tags: " + size);

                //save timestamp of last record containing tags
                long lastTimestamp = 0;
                if (lastToSendRecord.mSysTimestamp > 0)
                    lastTimestamp = lastToSendRecord.mSysTimestamp;
                else
                    lastTimestamp = lastToSendRecord.mBoxTimestamp;

                String lastTsFormatted = new SimpleDateFormat("yyyy-MM-dd_HH:mm:ss.SSSz", Locale.US)
                        .format(new Date(lastTimestamp));

                //********* MAKING OF HTTP HEADER **************

                DefaultHttpClient httpClient = new DefaultHttpClient();
                HttpPost httpPost = new HttpPost(Utils.report_url);

                httpPost.setHeader("Content-Encoding", "gzip");
                httpPost.setHeader("Content-Type", "application/json");
                httpPost.setHeader("Accept", "application/json");
                httpPost.setHeader("User-Agent", "AirProbe" + Utils.appVer);

                // ******* authorization bearer header ********

                httpPost.setHeader("Authorization", "Bearer " + Utils.getAccessToken(getApplicationContext()));

                //******** meta header (for new version API V1)

                httpPost.setHeader("meta" + Constants.separators[sepIndex] + "timestampRecorded",
                        lastTsFormatted);
                httpPost.setHeader("meta" + Constants.separators[sepIndex] + "deviceId", Utils.deviceID);
                httpPost.setHeader("meta" + Constants.separators[sepIndex] + "installId", Utils.installID);

                //******** data header (for new version API V1)

                //httpPost.setHeader("data"+Constants.separators[sepIndex]+"extendedPacketId", "");
                //httpPost.setHeader("data"+Constants.separators[sepIndex]+"extendedPacketPointId", "");
                //httpPost.setHeader("data"+Constants.separators[sepIndex]+"extendedSessionId", ""); //deprecated from AP 1.4

                httpPost.setHeader("data" + Constants.separators[sepIndex] + "contentDetails"
                        + Constants.separators[sepIndex] + "type", "airprobe_tags");
                httpPost.setHeader("data" + Constants.separators[sepIndex] + "contentDetails"
                        + Constants.separators[sepIndex] + "format", "json");
                //httpPost.setHeader("data"+Constants.separators[sepIndex]+"contentDetails"+Constants.separators[sepIndex]+"specification", "at-3");   //deprecated from AP 1.4
                if (size > 1)
                    httpPost.setHeader("data" + Constants.separators[sepIndex] + "contentDetails"
                            + Constants.separators[sepIndex] + "list", "true");
                else
                    httpPost.setHeader("data" + Constants.separators[sepIndex] + "contentDetails"
                            + Constants.separators[sepIndex] + "list", "false");
                httpPost.setHeader("data" + Constants.separators[sepIndex] + "contentDetails"
                        + Constants.separators[sepIndex] + "listSize", String.valueOf(size));

                /* from AP 1.4 */
                if ((lastToSendRecord.mBoxMac != null) && (!lastToSendRecord.mBoxMac.equals("")))
                    httpPost.setHeader("meta" + Constants.separators[sepIndex] + "sourceId",
                            lastToSendRecord.mBoxMac);

                httpPost.setHeader("data" + Constants.separators[sepIndex] + "extendedSourceSessionId"
                        + Constants.separators[sepIndex] + "seed", lastToSendRecord.mSourceSessionSeed);
                httpPost.setHeader(//from w w  w  .j  av  a2  s  .  co  m
                        "data" + Constants.separators[sepIndex] + "extendedSourceSessionId"
                                + Constants.separators[sepIndex] + "number",
                        String.valueOf(lastToSendRecord.mSourceSessionNumber));
                if ((lastToSendRecord.mSemanticSessionSeed != null)
                        && (!lastToSendRecord.mSemanticSessionSeed.equals(""))) {
                    httpPost.setHeader(
                            "data" + Constants.separators[sepIndex] + "extendedSemanticSessionId"
                                    + Constants.separators[sepIndex] + "seed",
                            lastToSendRecord.mSemanticSessionSeed);
                    httpPost.setHeader(
                            "data" + Constants.separators[sepIndex] + "extendedSemanticSessionId"
                                    + Constants.separators[sepIndex] + "number",
                            String.valueOf(lastToSendRecord.mSemanticSessionNumber));
                }

                httpPost.setHeader("data" + Constants.separators[sepIndex] + "contentDetails"
                        + Constants.separators[sepIndex] + "typeVersion", "30"); //update by increment this field on header changes                
                /* end of from AP 1.4 */

                //******** geo header (for new version API V1)

                //add the right provider to header
                if (lastToSendRecord.mGpsProvider.equals(Constants.GPS_PROVIDERS[0])) //sensor box
                {
                    httpPost.setHeader("geo" + Constants.separators[sepIndex] + "longitude",
                            String.valueOf(lastToSendRecord.mBoxLon));
                    httpPost.setHeader("geo" + Constants.separators[sepIndex] + "latitude",
                            String.valueOf(lastToSendRecord.mBoxLat));
                    if (lastToSendRecord.mBoxAcc != 0)
                        httpPost.setHeader("geo" + Constants.separators[sepIndex] + "hdop",
                                String.valueOf(lastToSendRecord.mBoxAcc)); //from AP 1.4
                    if (lastToSendRecord.mBoxAltitude != 0)
                        httpPost.setHeader("geo" + Constants.separators[sepIndex] + "altitude",
                                String.valueOf(lastToSendRecord.mBoxAltitude)); //from AP 1.4
                    if (lastToSendRecord.mBoxSpeed != 0)
                        httpPost.setHeader("geo" + Constants.separators[sepIndex] + "speed",
                                String.valueOf(lastToSendRecord.mBoxSpeed)); //from AP 1.4
                    if (lastToSendRecord.mBoxBear != 0)
                        httpPost.setHeader("geo" + Constants.separators[sepIndex] + "bearing",
                                String.valueOf(lastToSendRecord.mBoxBear)); //from AP 1.4           
                    httpPost.setHeader("geo" + Constants.separators[sepIndex] + "provider",
                            lastToSendRecord.mGpsProvider);
                    httpPost.setHeader("geo" + Constants.separators[sepIndex] + "timestamp", lastTsFormatted);
                } else if (lastToSendRecord.mGpsProvider.equals(Constants.GPS_PROVIDERS[1])) //phone
                {
                    httpPost.setHeader("geo" + Constants.separators[sepIndex] + "longitude",
                            String.valueOf(lastToSendRecord.mPhoneLon));
                    httpPost.setHeader("geo" + Constants.separators[sepIndex] + "latitude",
                            String.valueOf(lastToSendRecord.mPhoneLat));
                    if (lastToSendRecord.mPhoneAcc != 0)
                        httpPost.setHeader("geo" + Constants.separators[sepIndex] + "accuracy",
                                String.valueOf(lastToSendRecord.mPhoneAcc));
                    if (lastToSendRecord.mPhoneAltitude != 0)
                        httpPost.setHeader("geo" + Constants.separators[sepIndex] + "altitude",
                                String.valueOf(lastToSendRecord.mPhoneAltitude)); //from AP 1.4
                    if (lastToSendRecord.mPhoneSpeed != 0)
                        httpPost.setHeader("geo" + Constants.separators[sepIndex] + "speed",
                                String.valueOf(lastToSendRecord.mPhoneSpeed)); //from AP 1.4
                    if (lastToSendRecord.mPhoneBear != 0)
                        httpPost.setHeader("geo" + Constants.separators[sepIndex] + "bearing",
                                String.valueOf(lastToSendRecord.mPhoneBear)); //from AP 1.4
                    httpPost.setHeader("geo" + Constants.separators[sepIndex] + "provider",
                            lastToSendRecord.mGpsProvider);
                    httpPost.setHeader("geo" + Constants.separators[sepIndex] + "timestamp", lastTsFormatted);
                } else if (lastToSendRecord.mGpsProvider.equals(Constants.GPS_PROVIDERS[2])) //network
                {
                    httpPost.setHeader("geo" + Constants.separators[sepIndex] + "longitude",
                            String.valueOf(lastToSendRecord.mNetworkLon));
                    httpPost.setHeader("geo" + Constants.separators[sepIndex] + "latitude",
                            String.valueOf(lastToSendRecord.mNetworkLat));
                    if (lastToSendRecord.mNetworkAcc != 0)
                        httpPost.setHeader("geo" + Constants.separators[sepIndex] + "accuracy",
                                String.valueOf(lastToSendRecord.mNetworkAcc));
                    if (lastToSendRecord.mNetworkAltitude != 0)
                        httpPost.setHeader("geo" + Constants.separators[sepIndex] + "altitude",
                                String.valueOf(lastToSendRecord.mNetworkAltitude)); //from AP 1.4
                    if (lastToSendRecord.mNetworkSpeed != 0)
                        httpPost.setHeader("geo" + Constants.separators[sepIndex] + "speed",
                                String.valueOf(lastToSendRecord.mNetworkSpeed)); //from AP 1.4
                    if (lastToSendRecord.mNetworkBear != 0)
                        httpPost.setHeader("geo" + Constants.separators[sepIndex] + "bearing",
                                String.valueOf(lastToSendRecord.mNetworkBear)); //from AP 1.4            
                    httpPost.setHeader("geo" + Constants.separators[sepIndex] + "provider",
                            lastToSendRecord.mGpsProvider);
                    httpPost.setHeader("geo" + Constants.separators[sepIndex] + "timestamp", lastTsFormatted);
                }

                //******** MAKING OF HTTP CONTENT (JSON) *************

                //writing string content as an array of json object
                StringBuilder sb = new StringBuilder();
                sb.append("[");

                JSONObject object = new JSONObject();

                try {
                    object.put("timestamp", lastTimestamp);

                    JSONArray locations = new JSONArray();

                    //sensor box gps data
                    if (lastToSendRecord.mBoxLat != 0) {
                        JSONObject boxLocation = new JSONObject();
                        boxLocation.put("latitude", lastToSendRecord.mBoxLat);
                        boxLocation.put("longitude", lastToSendRecord.mBoxLon);
                        if (lastToSendRecord.mBoxAcc != 0)
                            boxLocation.put("hdpop", lastToSendRecord.mBoxAcc);
                        if (lastToSendRecord.mBoxAltitude != 0)
                            boxLocation.put("altitude", lastToSendRecord.mBoxAltitude);
                        if (lastToSendRecord.mBoxSpeed != 0)
                            boxLocation.put("speed", lastToSendRecord.mBoxSpeed);
                        if (lastToSendRecord.mBoxBear != 0)
                            boxLocation.put("bearing", lastToSendRecord.mBoxBear);
                        boxLocation.put("provider", Constants.GPS_PROVIDERS[0]);
                        boxLocation.put("timestamp", lastToSendRecord.mBoxTimestamp);

                        locations.put(0, boxLocation);
                    }

                    //phone gps data
                    if (lastToSendRecord.mPhoneLat != 0) {
                        JSONObject phoneLocation = new JSONObject();
                        phoneLocation.put("latitude", lastToSendRecord.mPhoneLat);
                        phoneLocation.put("longitude", lastToSendRecord.mPhoneLon);
                        if (lastToSendRecord.mPhoneAcc != 0)
                            phoneLocation.put("accuracy", lastToSendRecord.mPhoneAcc);
                        if (lastToSendRecord.mPhoneAltitude != 0)
                            phoneLocation.put("altitude", lastToSendRecord.mPhoneAltitude);
                        if (lastToSendRecord.mPhoneSpeed != 0)
                            phoneLocation.put("speed", lastToSendRecord.mPhoneSpeed);
                        if (lastToSendRecord.mPhoneBear != 0)
                            phoneLocation.put("bearing", lastToSendRecord.mPhoneBear);
                        phoneLocation.put("provider", Constants.GPS_PROVIDERS[1]);
                        phoneLocation.put("timestamp", lastToSendRecord.mPhoneTimestamp);

                        locations.put(1, phoneLocation);
                    }

                    //network gps data
                    if (lastToSendRecord.mNetworkLat != 0) {
                        JSONObject netLocation = new JSONObject();
                        netLocation.put("latitude", lastToSendRecord.mNetworkLat);
                        netLocation.put("longitude", lastToSendRecord.mNetworkLon);
                        if (lastToSendRecord.mNetworkAcc != 0)
                            netLocation.put("accuracy", lastToSendRecord.mNetworkAcc);
                        if (lastToSendRecord.mNetworkAltitude != 0)
                            netLocation.put("altitude", lastToSendRecord.mNetworkAltitude);
                        if (lastToSendRecord.mNetworkSpeed != 0)
                            netLocation.put("speed", lastToSendRecord.mNetworkSpeed);
                        if (lastToSendRecord.mNetworkBear != 0)
                            netLocation.put("bearing", lastToSendRecord.mNetworkBear);
                        netLocation.put("provider", Constants.GPS_PROVIDERS[2]);
                        netLocation.put("timestamp", lastToSendRecord.mNetworkTimestamp);

                        locations.put(2, netLocation);
                    }

                    object.put("locations", locations);
                } catch (JSONException e) {
                    e.printStackTrace();
                }

                String concatOfTags = "";

                //put the tags of all records in concatOfTags string
                for (int j = 0; j < recordsWithTags.size(); j++) {
                    if ((recordsWithTags.get(j).mUserData1 != null)
                            && (!recordsWithTags.get(j).mUserData1.equals("")))
                        concatOfTags += recordsWithTags.get(j).mUserData1 + " ";
                }
                Log.d("StoreAndForwardService", "postTags()--> concat of tags: " + concatOfTags);

                try {
                    String[] tags = concatOfTags.split(" ");
                    JSONArray tagsArray = new JSONArray();
                    if ((tags != null) && (tags.length > 0)) {
                        for (int k = 0; k < tags.length; k++) {
                            if (!tags[k].equals(""))
                                tagsArray.put(k, tags[k]);
                        }
                    }
                    object.put("tags", tagsArray);
                    //object.put("tags_cause", null);
                    //object.put("tags_location", null);
                    //object.put("tags_perception", null);
                } catch (JSONException e) {
                    e.printStackTrace();
                }
                sb.append(object.toString());
                sb.append("]");

                //Log.d("StoreAndForwardService", "]");   
                Log.d("StoreAndForwardService", "postTags()--> json to string: " + sb.toString());

                byte[] contentGzippedBytes = zipStringToBytes(sb.toString());
                ByteArrayEntity byteArrayEntity = new ByteArrayEntity(contentGzippedBytes);

                byteArrayEntity.setChunked(false); //IMPORTANT: must put false for smartcity.csp.it server

                //IMPORTANT: do not set the content-Length, because is embedded in Entity
                //httpPost.setHeader("Content-Length", byteArrayEntity.getContentLength()+"");

                httpPost.setEntity(byteArrayEntity);

                Log.d("StoreAndForwardService",
                        "postTags()--> Content length: " + httpPost.getEntity().getContentLength());
                Log.d("StoreAndForwardService", "postTags()--> Method: " + httpPost.getMethod());

                //do http post (it performs asynchronously)
                HttpResponse response = httpClient.execute(httpPost);

                sb = null;

                //server response
                //String responseBody = EntityUtils.toString(response.getEntity());
                //Log.d("StoreAndForwardService", "postTags()--> response: " +responseBody);
                Log.d("StoreAndForwardService", "postTags()--> status line: " + response.getStatusLine());

                httpClient.getConnectionManager().shutdown();

                //server response, status line
                StatusLine statusLine = response.getStatusLine();
                int statusCode = statusLine.getStatusCode();

                if (statusCode == Constants.STATUS_OK) {
                    Log.d("StoreAndForwardService", "postTags()--> STATUS OK");
                    mDbManager.deleteRecordsWithTagsBySessionId(sessionId);
                } else
                    Log.d("StoreAndForwardService", "postTags()--> status error code: " + statusCode);
            } else
                Log.d("StoreAndForwardService", "postTags()--> no tags to send");
        }
    }
}

From source file:org.csp.everyaware.internet.StoreAndForwardService.java

public void postSecureTags()
        throws IllegalArgumentException, ClientProtocolException, HttpHostConnectException, IOException {
    Log.d("StoreAndForwardService", "postSecureTags()");

    int sepIndex = 1; //default is '.' separator (see Constants.separators array)
    if ((Utils.report_country != null) && (Utils.report_country.equals("IT")))
        sepIndex = 0; //0 is for '-' separator (for italian CSP server)

    List<String> sids = mDbManager.getSidsOfRecordsWithTags();

    if ((sids != null) && (sids.size() > 0)) {
        for (int i = 0; i < sids.size(); i++) {
            String sessionId = (String) sids.get(i);

            //load records containing user tags with actual session id
            List<Record> recordsWithTags = mDbManager.loadRecordsWithTagBySessionId(sessionId);

            if ((recordsWithTags != null) && (recordsWithTags.size() > 0)) {
                //get size of array of records containing tags and reference to the last record
                int size = recordsWithTags.size();

                //obtain reference to the last record of serie
                Record lastToSendRecord = recordsWithTags.get(size - 1);
                Log.d("StoreAndForwardService", "postSecureTags()--> # of records containing tags: " + size);

                //save timestamp of last record containing tags
                long lastTimestamp = 0;
                if (lastToSendRecord.mSysTimestamp > 0)
                    lastTimestamp = lastToSendRecord.mSysTimestamp;
                else
                    lastTimestamp = lastToSendRecord.mBoxTimestamp;

                String lastTsFormatted = new SimpleDateFormat("yyyy-MM-dd_HH:mm:ss.SSSz", Locale.US)
                        .format(new Date(lastTimestamp));

                //********* MAKING OF HTTP HEADER **************

                URL url = new URL(Utils.report_url);
                HttpsURLConnection con = (HttpsURLConnection) url.openConnection();

                con.setRequestMethod("POST");
                con.setUseCaches(false);
                con.setDoInput(true);/* w w  w.  j  ava  2  s .  c o  m*/
                con.setDoOutput(true);

                con.setRequestProperty("Content-Encoding", "gzip");
                con.setRequestProperty("Content-Type", "application/json");
                con.setRequestProperty("Accept", "application/json");
                con.setRequestProperty("User-Agent", "AirProbe" + Utils.appVer);

                //******** authorization bearer header ********

                if (Utils.getAccountActivationState(getApplicationContext()))
                    con.setRequestProperty("Authorization",
                            "Bearer " + Utils.getAccessToken(getApplicationContext()));
                else if (Utils.getAccountActivationStateForClient(getApplicationContext()))
                    con.setRequestProperty("Authorization",
                            "Bearer " + Utils.getAccessTokenForClient(getApplicationContext()));

                //******** meta header (for new version API V1)

                con.setRequestProperty("meta" + Constants.separators[sepIndex] + "timestampRecorded",
                        lastTsFormatted);
                con.setRequestProperty("meta" + Constants.separators[sepIndex] + "deviceId", Utils.deviceID);
                con.setRequestProperty("meta" + Constants.separators[sepIndex] + "installId", Utils.installID);

                //******** data header (for new version API V1)

                //con.setRequestProperty("data"+Constants.separators[sepIndex]+"extendedPacketId", "");
                //con.setRequestProperty("data"+Constants.separators[sepIndex]+"extendedPacketPointId", "");
                //con.setRequestProperty("data"+Constants.separators[sepIndex]+"extendedSessionId", ""); //deprecated from AP 1.4

                con.setRequestProperty("data" + Constants.separators[sepIndex] + "contentDetails"
                        + Constants.separators[sepIndex] + "type", "airprobe_tags");
                con.setRequestProperty("data" + Constants.separators[sepIndex] + "contentDetails"
                        + Constants.separators[sepIndex] + "format", "json");
                //con.setRequestProperty("data"+Constants.separators[sepIndex]+"contentDetails"+Constants.separators[sepIndex]+"specification", "at-3");   //update by increment this field on header changes    
                if (size > 1)
                    con.setRequestProperty("data" + Constants.separators[sepIndex] + "contentDetails"
                            + Constants.separators[sepIndex] + "list", "true");
                else
                    con.setRequestProperty("data" + Constants.separators[sepIndex] + "contentDetails"
                            + Constants.separators[sepIndex] + "list", "false");
                con.setRequestProperty("data" + Constants.separators[sepIndex] + "contentDetails"
                        + Constants.separators[sepIndex] + "listSize", String.valueOf(size));

                /* from AP 1.4 */
                if ((lastToSendRecord.mBoxMac != null) && (!lastToSendRecord.mBoxMac.equals(""))) {
                    Log.d("StoreAndForwardService",
                            "postSecureData()--> box mac address: " + lastToSendRecord.mBoxMac);
                    con.setRequestProperty("meta" + Constants.separators[sepIndex] + "sourceId",
                            lastToSendRecord.mBoxMac);
                } else
                    con.setRequestProperty("meta" + Constants.separators[sepIndex] + "sourceId",
                            Utils.getDeviceAddress(getApplicationContext()));

                con.setRequestProperty("data" + Constants.separators[sepIndex] + "extendedSourceSessionId"
                        + Constants.separators[sepIndex] + "seed", lastToSendRecord.mSourceSessionSeed);
                con.setRequestProperty(
                        "data" + Constants.separators[sepIndex] + "extendedSourceSessionId"
                                + Constants.separators[sepIndex] + "number",
                        String.valueOf(lastToSendRecord.mSourceSessionNumber));
                if ((lastToSendRecord.mSemanticSessionSeed != null)
                        && (!lastToSendRecord.mSemanticSessionSeed.equals(""))) {
                    con.setRequestProperty(
                            "data" + Constants.separators[sepIndex] + "extendedSemanticSessionId"
                                    + Constants.separators[sepIndex] + "seed",
                            lastToSendRecord.mSemanticSessionSeed);
                    con.setRequestProperty(
                            "data" + Constants.separators[sepIndex] + "extendedSemanticSessionId"
                                    + Constants.separators[sepIndex] + "number",
                            String.valueOf(lastToSendRecord.mSemanticSessionNumber));
                }

                con.setRequestProperty("data" + Constants.separators[sepIndex] + "contentDetails"
                        + Constants.separators[sepIndex] + "typeVersion", "30"); //update by increment this field on header changes                
                /* end of from AP 1.4 */

                //******** geo header (for new version API V1)

                //add the right provider to header
                if (lastToSendRecord.mGpsProvider.equals(Constants.GPS_PROVIDERS[0])) //sensor box
                {
                    con.setRequestProperty("geo" + Constants.separators[sepIndex] + "longitude",
                            String.valueOf(lastToSendRecord.mBoxLon));
                    con.setRequestProperty("geo" + Constants.separators[sepIndex] + "latitude",
                            String.valueOf(lastToSendRecord.mBoxLat));
                    con.setRequestProperty("geo" + Constants.separators[sepIndex] + "provider",
                            lastToSendRecord.mGpsProvider);
                    con.setRequestProperty("geo" + Constants.separators[sepIndex] + "timestamp",
                            lastTsFormatted);
                } else if (lastToSendRecord.mGpsProvider.equals(Constants.GPS_PROVIDERS[1])) //phone
                {
                    con.setRequestProperty("geo" + Constants.separators[sepIndex] + "longitude",
                            String.valueOf(lastToSendRecord.mPhoneLon));
                    con.setRequestProperty("geo" + Constants.separators[sepIndex] + "latitude",
                            String.valueOf(lastToSendRecord.mPhoneLat));
                    con.setRequestProperty("geo" + Constants.separators[sepIndex] + "accuracy",
                            String.valueOf(lastToSendRecord.mPhoneAcc));
                    con.setRequestProperty("geo" + Constants.separators[sepIndex] + "altitude",
                            String.valueOf(lastToSendRecord.mPhoneAltitude)); //from AP 1.4
                    con.setRequestProperty("geo" + Constants.separators[sepIndex] + "speed",
                            String.valueOf(lastToSendRecord.mPhoneSpeed)); //from AP 1.4
                    con.setRequestProperty("geo" + Constants.separators[sepIndex] + "bearing",
                            String.valueOf(lastToSendRecord.mPhoneBear)); //from AP 1.4
                    con.setRequestProperty("geo" + Constants.separators[sepIndex] + "provider",
                            lastToSendRecord.mGpsProvider);
                    con.setRequestProperty("geo" + Constants.separators[sepIndex] + "timestamp",
                            lastTsFormatted);
                } else if (lastToSendRecord.mGpsProvider.equals(Constants.GPS_PROVIDERS[2])) //network
                {
                    con.setRequestProperty("geo" + Constants.separators[sepIndex] + "longitude",
                            String.valueOf(lastToSendRecord.mNetworkLon));
                    con.setRequestProperty("geo" + Constants.separators[sepIndex] + "latitude",
                            String.valueOf(lastToSendRecord.mNetworkLat));
                    con.setRequestProperty("geo" + Constants.separators[sepIndex] + "accuracy",
                            String.valueOf(lastToSendRecord.mNetworkAcc));
                    con.setRequestProperty("geo" + Constants.separators[sepIndex] + "altitude",
                            String.valueOf(lastToSendRecord.mNetworkAltitude)); //from AP 1.4
                    con.setRequestProperty("geo" + Constants.separators[sepIndex] + "speed",
                            String.valueOf(lastToSendRecord.mNetworkSpeed)); //from AP 1.4
                    con.setRequestProperty("geo" + Constants.separators[sepIndex] + "bearing",
                            String.valueOf(lastToSendRecord.mNetworkBear)); //from AP 1.4            
                    con.setRequestProperty("geo" + Constants.separators[sepIndex] + "provider",
                            lastToSendRecord.mGpsProvider);
                    con.setRequestProperty("geo" + Constants.separators[sepIndex] + "timestamp",
                            lastTsFormatted);
                }

                //******** MAKING OF HTTP CONTENT (JSON) *************

                //writing string content as an array of json object
                StringBuilder sb = new StringBuilder();
                sb.append("[");

                JSONObject object = new JSONObject();

                try {
                    object.put("timestamp", lastTimestamp);

                    JSONArray locations = new JSONArray();

                    //sensor box gps data
                    if (lastToSendRecord.mBoxLat != 0) {
                        JSONObject boxLocation = new JSONObject();
                        boxLocation.put("latitude", lastToSendRecord.mBoxLat);
                        boxLocation.put("longitude", lastToSendRecord.mBoxLon);
                        //boxLocation.put("accuracy", "null");
                        //boxLocation.put("altitude", "null");
                        //boxLocation.put("speed", "null");
                        //boxLocation.put("bearing", "null");
                        boxLocation.put("provider", Constants.GPS_PROVIDERS[0]);
                        boxLocation.put("timestamp", lastToSendRecord.mBoxTimestamp);

                        locations.put(0, boxLocation);
                    }

                    //phone gps data
                    if (lastToSendRecord.mPhoneLat != 0) {
                        JSONObject phoneLocation = new JSONObject();
                        phoneLocation.put("latitude", lastToSendRecord.mPhoneLat);
                        phoneLocation.put("longitude", lastToSendRecord.mPhoneLon);
                        phoneLocation.put("accuracy", lastToSendRecord.mAccuracy);
                        phoneLocation.put("altitude", lastToSendRecord.mPhoneAltitude);
                        phoneLocation.put("speed", lastToSendRecord.mPhoneSpeed);
                        phoneLocation.put("bearing", lastToSendRecord.mPhoneBear);
                        phoneLocation.put("provider", Constants.GPS_PROVIDERS[1]);
                        phoneLocation.put("timestamp", lastToSendRecord.mPhoneTimestamp);

                        locations.put(1, phoneLocation);
                    }

                    //network gps data
                    if (lastToSendRecord.mNetworkLat != 0) {
                        JSONObject netLocation = new JSONObject();
                        netLocation.put("latitude", lastToSendRecord.mNetworkLat);
                        netLocation.put("longitude", lastToSendRecord.mNetworkLon);
                        netLocation.put("accuracy", lastToSendRecord.mNetworkAcc);
                        netLocation.put("altitude", lastToSendRecord.mNetworkAltitude);
                        netLocation.put("speed", lastToSendRecord.mNetworkSpeed);
                        netLocation.put("bearing", lastToSendRecord.mNetworkBear);
                        netLocation.put("provider", Constants.GPS_PROVIDERS[2]);
                        netLocation.put("timestamp", lastToSendRecord.mNetworkTimestamp);

                        locations.put(2, netLocation);
                    }

                    object.put("locations", locations);
                } catch (JSONException e) {
                    e.printStackTrace();
                }

                String concatOfTags = "";

                //put the tags of all records in concatOfTags string
                for (int j = 0; j < recordsWithTags.size(); j++) {
                    if ((recordsWithTags.get(j).mUserData1 != null)
                            && (!recordsWithTags.get(j).mUserData1.equals("")))
                        concatOfTags += recordsWithTags.get(j).mUserData1 + " ";
                }
                Log.d("StoreAndForwardService", "postSecureTags()--> concat of tags: " + concatOfTags);

                try {
                    String[] tags = concatOfTags.split(" ");
                    JSONArray tagsArray = new JSONArray();
                    if ((tags != null) && (tags.length > 0)) {
                        for (int k = 0; k < tags.length; k++) {
                            if (!tags[k].equals(""))
                                tagsArray.put(k, tags[k]);
                        }
                    }
                    object.put("tags", tagsArray);
                    //object.put("tags_cause", null);
                    //object.put("tags_location", null);
                    //object.put("tags_perception", null);
                } catch (JSONException e) {
                    e.printStackTrace();
                }
                sb.append(object.toString());
                sb.append("]");

                Log.d("StoreAndForwardService", "postSecureTags()--> json to string: " + sb.toString());

                //compress json content into byte array entity
                byte[] contentGzippedBytes = zipStringToBytes(sb.toString());

                //write json compressed content into output stream
                OutputStream outputStream = con.getOutputStream();
                outputStream.write(contentGzippedBytes);
                outputStream.flush();
                outputStream.close();

                int responseCode = con.getResponseCode();

                Log.d("StoreAndForwardService", "postSecureTags()--> response code: " + responseCode);

                sb = null;

                if (responseCode == Constants.STATUS_OK) {
                    Log.d("StoreAndForwardService", "postSecureTags()--> STATUS OK");
                    mDbManager.deleteRecordsWithTagsBySessionId(sessionId);
                } else
                    Log.d("StoreAndForwardService", "postSecureTags()--> status error code: " + responseCode);
            } else
                Log.d("StoreAndForwardService", "postTags()--> no tags to send");
        }
    }
}

From source file:org.wso2.app.catalog.services.DynamicClientManager.java

/**
 * This method is used to send requests to backend.
 * The reason to use this method because the function which is already
 * available for sending requests is secured with token. Therefor this can be used
 * to send requests without tokens.//from w  w  w.j  a v a2  s.c  o  m
 */
private void sendRequest(final EndPointInfo endPointInfo, final APIResultCallBack apiResultCallback,
        final int requestCode) {
    RequestQueue queue = null;
    int requestMethod = 0;
    org.wso2.emm.agent.proxy.utils.Constants.HTTP_METHODS httpMethod = endPointInfo.getHttpMethod();
    switch (httpMethod) {
    case POST:
        requestMethod = Request.Method.POST;
        break;
    case DELETE:
        requestMethod = Request.Method.DELETE;
        break;
    }

    try {
        queue = ServerUtilities.getCertifiedHttpClient();
    } catch (IDPTokenManagerException e) {
        Log.e(TAG, "Failed to retrieve HTTP client", e);
    }

    JsonObjectRequest request = null;
    try {
        request = new JsonObjectRequest(requestMethod, endPointInfo.getEndPoint(),
                (endPointInfo.getRequestParams() != null) ? new JSONObject(endPointInfo.getRequestParams())
                        : null,
                new Response.Listener<JSONObject>() {
                    @Override
                    public void onResponse(JSONObject response) {
                        Log.d(TAG, response.toString());
                    }
                }, new Response.ErrorListener() {
                    @Override
                    public void onErrorResponse(VolleyError error) {
                        Log.d(TAG, error.toString());
                    }
                })

        {
            @Override
            protected Response<JSONObject> parseNetworkResponse(NetworkResponse response) {
                String result = new String(response.data);
                if (org.wso2.emm.agent.proxy.utils.Constants.DEBUG_ENABLED) {
                    if (result != null && !result.isEmpty()) {
                        Log.d(TAG, "Result :" + result);
                    }
                }
                Map<String, String> responseParams = new HashMap<>();
                responseParams.put(org.wso2.emm.agent.proxy.utils.Constants.SERVER_RESPONSE_BODY, result);
                responseParams.put(org.wso2.emm.agent.proxy.utils.Constants.SERVER_RESPONSE_STATUS,
                        String.valueOf(response.statusCode));
                if (apiResultCallback != null) {
                    apiResultCallback.onReceiveAPIResult(responseParams, requestCode);
                }
                return super.parseNetworkResponse(response);
            }

            @Override
            public Map<String, String> getHeaders() throws AuthFailureError {
                Map<String, String> headers = new HashMap<>();
                headers.put("Content-Type", "application/json");
                headers.put("Accept", "application/json");
                headers.put("User-Agent", Constants.USER_AGENT);
                if (endPointInfo.getHeader() != null && !endPointInfo.getHeader().trim().isEmpty()) {
                    headers.put("Authorization", endPointInfo.getHeader().trim());
                }
                return headers;
            }
        };
    } catch (JSONException e) {
        Log.e(TAG, "Failed to parse request JSON", e);
    }

    queue.add(request);
}

From source file:com.marpies.ane.facebook.accountkit.functions.LoadPreferenceFunction.java

@Override
public FREObject call(FREContext context, FREObject[] args) {
    super.call(context, args);

    AIR.log("AccountKit::loadPreference");
    final int callbackId = FREObjectUtils.getInt(args[1]);

    /* User is not logged in, cannot load preference */
    if (AccountKit.getCurrentAccessToken() == null) {
        dispatchError(callbackId, "User is not logged in, cannot load preference.");
        return null;
    }/* w  ww .j av  a2 s. c o m*/

    String prefKey = FREObjectUtils.getString(args[0]);
    AccountKit.getAccountPreferences().loadPreference(prefKey,
            new AccountPreferences.OnLoadPreferenceListener() {
                @Override
                public void onLoadPreference(String key, @Nullable String value,
                        @Nullable AccountKitError accountKitError) {
                    if (accountKitError != null) {
                        dispatchError(callbackId, accountKitError.getErrorType().getMessage());
                    } else {
                        if (value == null) {
                            dispatchError(callbackId, "Value for key '" + key + "' not found.");
                            return;
                        }
                        AIR.log("AccountKit | successfully loaded preference");
                        JSONObject response = new JSONObject();
                        JSONUtils.addToJSON(response, "callbackId", callbackId);
                        JSONUtils.addToJSON(response, "key", key);
                        JSONUtils.addToJSON(response, "value", value);
                        AIR.dispatchEvent(AccountKitEvent.LOAD_PREFERENCE, response.toString());
                    }
                }
            });

    return null;
}

From source file:de.decoit.visa.http.ajax.handlers.IOToolDisconnectHandler.java

@Override
public void handle(HttpExchange he) throws IOException {
    log.info(he.getRequestURI().toString());

    // Create String for the response
    String response = null;/*from   ww w  . ja va 2  s  .  c  o  m*/

    // Any exception thrown during object creation will
    // cause failure of the AJAX request
    try {
        TEBackend.closeIOConnector(false);

        JSONObject rv = new JSONObject();
        rv.put("status", AJAXServer.AJAX_SUCCESS);
        response = rv.toString();
    } catch (IOToolException iote) {
        JSONObject rv = new JSONObject();
        try {
            rv.put("status", AJAXServer.AJAX_ERROR_IOTOOL_BUSY);
            response = rv.toString();
        } catch (JSONException exc) {
            /* Ignore */
        }
    } catch (Throwable ex) {
        TEBackend.logException(ex, log);

        JSONObject rv = new JSONObject();
        try {
            rv.put("status", AJAXServer.AJAX_ERROR_EXCEPTION);
            rv.put("type", ex.getClass().getSimpleName());
            rv.put("message", ex.getMessage());
        } catch (JSONException exc) {
            /* Ignore */
        }

        response = rv.toString();
    }

    // Send the response
    sendResponse(he, response);
}

From source file:com.mobeelizer.mobile.android.types.FileFieldTypeHelper.java

@Override
public void setValueFromDatabaseToMap(final Cursor cursor, final Map<String, String> values,
        final MobeelizerFieldAccessor field, final Map<String, String> options) {
    int columnIndex = cursor.getColumnIndex(field.getName() + _GUID);

    if (cursor.isNull(columnIndex)) {
        values.put(field.getName(), null);
    } else {/*from  w w w  . j a v  a2s .c  o  m*/
        try {
            JSONObject json = new JSONObject();
            json.put(JSON_GUID, cursor.getString(columnIndex));
            json.put(JSON_NAME, cursor.getString(cursor.getColumnIndex(field.getName() + _NAME)));

            values.put(field.getName(), json.toString());
        } catch (JSONException e) {
            throw new IllegalStateException(e.getMessage(), e);
        }
    }
}

From source file:com.ibm.hellotodoadvanced.MainActivity.java

/**
 * Initializes the main list view and sets long click listener for delete.
 * Note: the Node delete endpoint is protected by Mobile Client Access and can only be accessed with an authorization header from the Bluemix Mobile Services Client SDK.
 *///  w  w w  .  j  ava  2s .co m
private void initListView() {
    // Get MainActivity's ListView
    mListView = (ListView) findViewById(R.id.listView);

    // Init array to hold TodoItems
    mTodoItemList = new ArrayList<>();

    // Create and set ListView adapter for displaying TodoItems
    mTodoItemAdapter = new TodoItemAdapter(getBaseContext(), mTodoItemList);
    mListView.setAdapter(mTodoItemAdapter);

    // Set long click listener for deleting TodoItems
    mListView.setOnItemLongClickListener(new AdapterView.OnItemLongClickListener() {
        @Override
        public boolean onItemLongClick(android.widget.AdapterView<?> parent, View view, int position, long id) {

            // Grab TodoItem to delete from current showing list
            TodoItem todoItem = mTodoItemList.get(position);

            // Grab TodoItem id number and append to the DELETE REST request using the Bluemix Mobile Services Client SDK
            String todoId = Integer.toString(todoItem.idNumber);
            Request request = new Request(bmsClient.getBluemixAppRoute() + "/api/Items/" + todoId,
                    Request.DELETE);

            // Send the request and use the response listener to react
            request.send(getApplicationContext(), new ResponseListener() {
                // Update the list if successful
                @Override
                public void onSuccess(Response response) {
                    Log.i(TAG, "Item  deleted successfully");

                    loadList();
                }

                // If the request fails, log errors
                @Override
                public void onFailure(Response response, Throwable throwable, JSONObject extendedInfo) {

                    String errorMessage = "";

                    // different responses can cause different parameters to be null, be sure to check for those cases
                    if (response != null) {
                        errorMessage += response.toString() + "\n";
                    }

                    if (throwable != null) {
                        StringWriter sw = new StringWriter();
                        PrintWriter pw = new PrintWriter(sw);
                        throwable.printStackTrace(pw);
                        errorMessage += "THROWN" + sw.toString() + "\n";
                    }

                    if (extendedInfo != null) {
                        errorMessage += "EXTENDED_INFO" + extendedInfo.toString() + "\n";
                    }

                    if (errorMessage.isEmpty())
                        errorMessage = "Request Failed With Unknown Error.";

                    Log.e(TAG, "deleteItem failed with error: " + errorMessage);

                }
            });

            return true;
        }
    });
}

From source file:com.ibm.hellotodoadvanced.MainActivity.java

/**
 * Uses Bluemix Mobile Services SDK to GET the TodoItems from Bluemix and updates the local list.
 *//*from w w  w  .  j a  va  2 s. com*/
private void loadList() {

    // Send GET Request to Bluemix backend to retreive item list with response listener
    Request request = new Request(bmsClient.getBluemixAppRoute() + "/api/Items", Request.GET);
    request.send(getApplicationContext(), new ResponseListener() {
        // Loop through JSON response and create local TodoItems if successful
        @Override
        public void onSuccess(Response response) {
            if (response.getStatus() != 200) {
                Log.e(TAG, "Error pulling items from Bluemix: " + response.toString());
            } else {

                try {

                    mTodoItemList.clear();

                    JSONArray jsonArray = new JSONArray(response.getResponseText());

                    for (int i = 0; i < jsonArray.length(); i++) {
                        JSONObject tempTodoJSON = jsonArray.getJSONObject(i);
                        TodoItem tempTodo = new TodoItem();

                        tempTodo.idNumber = tempTodoJSON.getInt("id");
                        tempTodo.text = tempTodoJSON.getString("text");
                        tempTodo.isDone = tempTodoJSON.getBoolean("isDone");

                        mTodoItemList.add(tempTodo);
                    }

                    // Need to notify adapter on main thread in order for list changes to update visually
                    runOnUiThread(new Runnable() {
                        @Override
                        public void run() {
                            mTodoItemAdapter.notifyDataSetChanged();

                            Log.i(TAG, "List updated successfully");

                            if (mSwipeLayout.isRefreshing()) {
                                mSwipeLayout.setRefreshing(false);
                            }
                        }
                    });

                } catch (Exception exception) {
                    Log.e(TAG, "Error reading response JSON: " + exception.getLocalizedMessage());
                }
            }
        }

        // Log Errors on failure
        @Override
        public void onFailure(Response response, Throwable throwable, JSONObject extendedInfo) {
            String errorMessage = "";

            if (response != null) {
                errorMessage += response.toString() + "\n";
            }

            if (throwable != null) {
                StringWriter sw = new StringWriter();
                PrintWriter pw = new PrintWriter(sw);
                throwable.printStackTrace(pw);
                errorMessage += "THROWN" + sw.toString() + "\n";
            }

            if (extendedInfo != null) {
                errorMessage += "EXTENDED_INFO" + extendedInfo.toString() + "\n";
            }

            if (errorMessage.isEmpty())
                errorMessage = "Request Failed With Unknown Error.";

            Log.e(TAG, "loadList failed with error: " + errorMessage);
        }
    });

}

From source file:com.ibm.hellotodoadvanced.MainActivity.java

/**
 * Clears list data when authentication against MCA fails and logs errors/response.
 * @param response HTTP response object from MCA
 *///w  w  w.  ja v a  2  s  . co m
@Override
public void onFailure(Response response, Throwable throwable, JSONObject extendedInfo) {

    if (!mTodoItemAdapter.isEmpty()) {
        Log.i(TAG, "clearing list data since authentication failed");
        mTodoItemList.clear();
        mTodoItemAdapter.notifyDataSetChanged();
    }

    String errorMessage = "";

    // Check for 404s and unknown host exception since this is the first request made by the app
    if (response != null) {
        if (response.getStatus() == 404) {
            errorMessage += "Application Route not found at:\n" + BMSClient.getInstance().getBluemixAppRoute()
                    + "\nPlease verify your Application Route and rebuild the app.";
        } else {
            errorMessage += response.toString() + "\n";
        }
    }

    // Be sure to check for null pointers, any of the above parameters may be null depending on the failure.
    if (throwable != null) {
        if (throwable.getClass().equals(UnknownHostException.class)) {
            errorMessage = "Unable to access Bluemix host!\nPlease verify internet connectivity and try again.";
        } else {
            StringWriter sw = new StringWriter();
            PrintWriter pw = new PrintWriter(sw);
            throwable.printStackTrace(pw);
            errorMessage += "THROWN" + sw.toString() + "\n";
        }
    }

    if (extendedInfo != null) {
        errorMessage += "EXTENDED_INFO" + extendedInfo.toString() + "\n";
    }

    if (errorMessage.isEmpty())
        errorMessage = "Request Failed With Unknown Error.";

    Log.e(TAG, "Failed to authenticate against MCA: " + errorMessage);

}

From source file:com.ibm.hellotodoadvanced.MainActivity.java

/**
 * Launches a dialog for adding a new TodoItem. Called when plus button is tapped.
 *
 * @param view The plus button that is tapped.
 *//*from  w  w  w .  j a  v a  2 s .  c  o m*/
public void addTodo(View view) {

    final Dialog addDialog = new Dialog(this);

    // UI settings for dialog pop-up
    addDialog.setContentView(R.layout.add_edit_dialog);
    addDialog.setTitle("Add Todo");
    TextView textView = (TextView) addDialog.findViewById(android.R.id.title);
    if (textView != null) {
        textView.setGravity(Gravity.CENTER);
    }
    addDialog.setCancelable(true);
    Button add = (Button) addDialog.findViewById(R.id.Add);
    addDialog.show();

    // When done is pressed, send POST request to create TodoItem on Bluemix
    add.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View view) {
            EditText itemToAdd = (EditText) addDialog.findViewById(R.id.todo);
            final String name = itemToAdd.getText().toString();
            // If text was added, continue with normal operations
            if (!name.isEmpty()) {

                // Create JSON for new TodoItem, id should be 0 for new items
                String json = "{\"text\":\"" + name + "\",\"isDone\":false,\"id\":0}";

                // Create POST request with the Bluemix Mobile Services SDK and set HTTP headers so Bluemix knows what to expect in the request
                Request request = new Request(bmsClient.getBluemixAppRoute() + "/api/Items", Request.POST);

                HashMap headers = new HashMap();
                List<String> contentType = new ArrayList<>();
                contentType.add("application/json");
                List<String> accept = new ArrayList<>();
                accept.add("Application/json");

                headers.put("Content-Type", contentType);
                headers.put("Accept", accept);

                request.setHeaders(headers);

                request.send(getApplicationContext(), json, new ResponseListener() {
                    // On success, update local list with new TodoItem
                    @Override
                    public void onSuccess(Response response) {
                        Log.i(TAG, "Item " + name + " created successfully");

                        loadList();
                    }

                    // On failure, log errors
                    @Override
                    public void onFailure(Response response, Throwable throwable, JSONObject extendedInfo) {
                        String errorMessage = "";

                        if (response != null) {
                            errorMessage += response.toString() + "\n";
                        }

                        if (throwable != null) {
                            StringWriter sw = new StringWriter();
                            PrintWriter pw = new PrintWriter(sw);
                            throwable.printStackTrace(pw);
                            errorMessage += "THROWN" + sw.toString() + "\n";
                        }

                        if (extendedInfo != null) {
                            errorMessage += "EXTENDED_INFO" + extendedInfo.toString() + "\n";
                        }

                        if (errorMessage.isEmpty())
                            errorMessage = "Request Failed With Unknown Error.";

                        Log.e(TAG, "addTodo failed with error: " + errorMessage);
                    }
                });
            }

            // Close dialog when finished, or if no text was added
            addDialog.dismiss();
        }
    });
}