Example usage for org.json JSONArray put

List of usage examples for org.json JSONArray put

Introduction

In this page you can find the example usage for org.json JSONArray put.

Prototype

public JSONArray put(int index, Object value) throws JSONException 

Source Link

Document

Put or replace an object value in the JSONArray.

Usage

From source file:com.cssweb.android.view.KlineView.java

private void makeTmpData() throws JSONException {
    JSONObject tempvalue = quoteData.getJSONObject("joTMP");
    int l = quoteData.getJSONArray("K").length();
    double zrsp = quoteData.getDouble("zrsp");
    //      quoteData.getJSONArray("K").getJSONArray(l-1).put(1, tempvalue.getJSONObject(period).getDouble("open")) ;
    //      quoteData.getJSONArray("K").getJSONArray(l-1).put(2, tempvalue.getJSONObject(period).getDouble("high")) ;
    //      quoteData.getJSONArray("K").getJSONArray(l-1).put(3, tempvalue.getJSONObject(period).getDouble("low")) ;
    //      quoteData.getJSONArray("K").getJSONArray(l-1).put(5, tempvalue.getJSONObject(period).getDouble("cjsl")) ;
    //      quoteData.getJSONArray("K").getJSONArray(l-1).put(6, tempvalue.getJSONObject(period).getDouble("cjje")) ;

    Log.i("#####111####", quoteData + ">>>>>>>>>>");
    int tp = quoteData.getInt("tp");
    if (tp == 1) {
        String date = tempvalue.getJSONObject(period).getString("date");
        //Log.i("#####date####", date+">>>>>>>>" + DateTool.isSameWeekMonthYear(date, period));
        if (DateTool.isSameWeekMonthYear(date, period)) {
            quoteData.getJSONArray("K").getJSONArray(l - 1).put(1,
                    tempvalue.getJSONObject(period).getDouble("open"));
            quoteData.getJSONArray("K").getJSONArray(l - 1).put(2,
                    tempvalue.getJSONObject(period).getDouble("high"));
            quoteData.getJSONArray("K").getJSONArray(l - 1).put(3,
                    tempvalue.getJSONObject(period).getDouble("low"));
            quoteData.getJSONArray("K").getJSONArray(l - 1).put(4, zrsp);
            quoteData.getJSONArray("K").getJSONArray(l - 1).put(5,
                    tempvalue.getJSONObject(period).getDouble("cjsl"));
            quoteData.getJSONArray("K").getJSONArray(l - 1).put(6,
                    tempvalue.getJSONObject(period).getDouble("cjje"));
            //quoteData.getJSONArray("K").getJSONArray(l-1).put(0, ) ;
            zrsp = quoteData.getJSONArray("K").getJSONArray(l - 1).getDouble(0);
        }/*from   w  w w.  j  av a  2 s.  co  m*/
    } else {
        int spayday = quoteData.getInt("spday");
        double cjsl = quoteData.getJSONArray("K").getJSONArray(l - 1).getDouble(5);
        double cjje = quoteData.getJSONArray("K").getJSONArray(l - 1).getDouble(6);
        if (spayday == 0) {//0??temp?????
            quoteData.getJSONArray("K").getJSONArray(l - 1).put(2,
                    Math.max(quoteData.getJSONArray("K").getJSONArray(l - 1).getDouble(2),
                            tempvalue.getJSONObject(period).getDouble("high")));
            quoteData.getJSONArray("K").getJSONArray(l - 1).put(3,
                    Math.min(quoteData.getJSONArray("K").getJSONArray(l - 1).getDouble(3),
                            tempvalue.getJSONObject(period).getDouble("low")));
            quoteData.getJSONArray("K").getJSONArray(l - 1).put(5,
                    cjsl + tempvalue.getJSONObject(period).getDouble("cjsl"));
            quoteData.getJSONArray("K").getJSONArray(l - 1).put(6,
                    cjje + tempvalue.getJSONObject(period).getDouble("cjje"));
        } else {
            quoteData.getJSONArray("K").getJSONArray(l - 1).put(2,
                    Math.max(quoteData.getJSONArray("K").getJSONArray(l - 1).getDouble(2),
                            tempvalue.getJSONObject(period).getDouble("high")));
            quoteData.getJSONArray("K").getJSONArray(l - 1).put(3,
                    Math.min(quoteData.getJSONArray("K").getJSONArray(l - 1).getDouble(3),
                            tempvalue.getJSONObject(period).getDouble("low")));
            quoteData.getJSONArray("K").getJSONArray(l - 1).put(5,
                    tempvalue.getJSONObject(period).getDouble("cjsl"));
            quoteData.getJSONArray("K").getJSONArray(l - 1).put(6,
                    tempvalue.getJSONObject(period).getDouble("cjje"));
        }
        double jrkp = tempvalue.getJSONObject(period).getDouble("open");
        if (jrkp != 0) {
            quoteData.getJSONArray("K").getJSONArray(l - 1).put(1, jrkp);
        }
        zrsp = tempvalue.getJSONObject(period).getDouble("close");
        Log.i("#####222####", quoteData + ">>>>>>>>>>");
    }

    if (mainIndicatorType.toUpperCase().equals("BOLL")) {
        JSONArray jMA = new JSONArray();
        jMA.put(0, 0);
        jMA.put(1, 0);
        jMA.put(2, 0);
        jMA.put(3, 0);
        jMA.put(4, 0);
        jMA.put(5, 0);
        jMA.put(6, 0);
        quoteData.put("BOLL", new JSONArray().put(jMA));
    }

    //Log.i("#######MA#########", quoteData.isNull("MA")+">>>>>>>>>>>" + quoteData);
    if (quoteData.isNull("MA")) {
        JSONArray jMA = new JSONArray();
        jMA.put(0, 0);
        jMA.put(1, 0);
        jMA.put(2, 0);
        jMA.put(3, 0);
        jMA.put(4, 0);
        jMA.put(5, 0);
        jMA.put(6, 0);
        quoteData.put("MA", new JSONArray().put(jMA));
    } else {
        if (quoteData.getJSONArray("MA").length() == 0) {
            JSONArray jMA = new JSONArray();
            jMA.put(0, 0);
            jMA.put(1, 0);
            jMA.put(2, 0);
            jMA.put(3, 0);
            jMA.put(4, 0);
            jMA.put(5, 0);
            jMA.put(6, 0);
            quoteData.put("MA", new JSONArray().put(jMA));
        }
    }
    //Log.i("#######MA#########" + indicatorType.toUpperCase(), quoteData.isNull(indicatorType.toUpperCase())+">>>>>>>>>>>");
    if (quoteData.isNull(indicatorType.toUpperCase())) {
        JSONArray jIn = new JSONArray();
        jIn.put(0, 0);
        jIn.put(1, 0);
        jIn.put(2, 0);
        jIn.put(3, 0);
        quoteData.put(indicatorType.toUpperCase(), new JSONArray().put(jIn));
    }
    if (tempvalue.isNull("ma") && quoteData.getJSONArray("K").length() > 1) //??
        actualDataLen = quoteData.getJSONArray("K").length() - 1;
    else
        actualDataLen = quoteData.getJSONArray("K").length();
    if (actualDataLen < visualKLineCount) {
        count = actualDataLen;
    } else {
        count = visualKLineCount;
    }
    if (this.actualDataLen - this.actualPos - 1 <= this.visualKLineCount) {
        actualPos = actualDataLen - count;
    }
    //      Log.i("#######makeTmpData########" + actualPos, actualDataLen+">>>>>>>>" + count);
}

From source file:com.cssweb.android.view.KlineView.java

private void newStockhandler() throws JSONException {
    //      if(!quoteData.getBoolean("tradeFlag")){
    //         return;
    //      }//from w  w w  .j  a  v a 2 s  .  c o m
    //      Log.i("#######quoteData########", quoteData.isNull("MA") + ">>>>>>>>>>>>>>>>>" + quoteData);
    if (mainIndicatorType.toUpperCase().equals("BOLL")) {
        if (quoteData.isNull(mainIndicatorType.toUpperCase())) {
            JSONArray jMA = new JSONArray();
            jMA.put(0, 0);
            jMA.put(1, 0);
            jMA.put(2, 0);
            jMA.put(3, 0);
            jMA.put(4, 0);
            jMA.put(5, 0);
            jMA.put(6, 0);
            quoteData.put(mainIndicatorType.toUpperCase(), new JSONArray().put(jMA));
        }
    }

    if (quoteData.isNull(mainIndicatorType.toUpperCase())) {
        JSONArray jMA = new JSONArray();
        jMA.put(0, 0);
        jMA.put(1, 0);
        jMA.put(2, 0);
        jMA.put(3, 0);
        jMA.put(4, 0);
        jMA.put(5, 0);
        jMA.put(6, 0);
        quoteData.put(mainIndicatorType.toUpperCase(), new JSONArray().put(jMA));
    }

    if (quoteData.isNull(indicatorType.toUpperCase())) {
        JSONArray jIn = new JSONArray();
        jIn.put(0, 0);
        jIn.put(1, 0);
        jIn.put(2, 0);
        jIn.put(3, 0);
        quoteData.put(indicatorType.toUpperCase(), new JSONArray().put(jIn));
    }

    actualDataLen = quoteData.getJSONArray("K").length();
    if (actualDataLen < visualKLineCount) {
        count = actualDataLen;
    } else {
        count = visualKLineCount;
    }
    if (this.actualDataLen - this.actualPos - 1 <= this.visualKLineCount) {
        actualPos = actualDataLen - count;
    }
    //      Log.i("#######quoteData########" + actualPos, actualDataLen+">>>>>>>>" + count);
}

From source file:com.cssweb.android.view.KlineViewSingle.java

private void makeTmpData() throws JSONException {
    JSONObject tempvalue = quoteData.getJSONObject("joTMP");
    int l = quoteData.getJSONArray("K").length();
    double zrsp = quoteData.getDouble("zrsp");
    //      quoteData.getJSONArray("K").getJSONArray(l-1).put(1, tempvalue.getJSONObject(period).getDouble("open")) ;
    //      quoteData.getJSONArray("K").getJSONArray(l-1).put(2, tempvalue.getJSONObject(period).getDouble("high")) ;
    //      quoteData.getJSONArray("K").getJSONArray(l-1).put(3, tempvalue.getJSONObject(period).getDouble("low")) ;
    //      //quoteData.getJSONArray("K").getJSONArray(l-1).put(4, zrsp) ;
    //      quoteData.getJSONArray("K").getJSONArray(l-1).put(5, tempvalue.getJSONObject(period).getDouble("cjsl")) ;
    //      quoteData.getJSONArray("K").getJSONArray(l-1).put(6, tempvalue.getJSONObject(period).getDouble("cjje")) ;

    int tp = quoteData.getInt("tp");
    if (tp == 1) {
        String date = tempvalue.getJSONObject(period).getString("date");
        Log.i("#####date####", date + ">>>>>>>>" + DateTool.isSameWeekMonthYear(date, period));
        if (DateTool.isSameWeekMonthYear(date, period)) {
            quoteData.getJSONArray("K").getJSONArray(l - 1).put(1,
                    tempvalue.getJSONObject(period).getDouble("open"));
            quoteData.getJSONArray("K").getJSONArray(l - 1).put(2,
                    tempvalue.getJSONObject(period).getDouble("high"));
            quoteData.getJSONArray("K").getJSONArray(l - 1).put(3,
                    tempvalue.getJSONObject(period).getDouble("low"));
            quoteData.getJSONArray("K").getJSONArray(l - 1).put(4, zrsp);
            quoteData.getJSONArray("K").getJSONArray(l - 1).put(5,
                    tempvalue.getJSONObject(period).getDouble("cjsl"));
            quoteData.getJSONArray("K").getJSONArray(l - 1).put(6,
                    tempvalue.getJSONObject(period).getDouble("cjje"));
            //quoteData.getJSONArray("K").getJSONArray(l-1).put(0, ) ;
            zrsp = quoteData.getJSONArray("K").getJSONArray(l - 1).getDouble(0);
        }/*from   ww w.j a  v  a 2  s  .  c  o m*/
    } else {
        int spayday = quoteData.getInt("spday");
        double cjsl = quoteData.getJSONArray("K").getJSONArray(l - 1).getDouble(5);
        double cjje = quoteData.getJSONArray("K").getJSONArray(l - 1).getDouble(6);
        if (spayday == 0) {//0??temp?????
            quoteData.getJSONArray("K").getJSONArray(l - 1).put(2,
                    Math.max(quoteData.getJSONArray("K").getJSONArray(l - 1).getDouble(2),
                            tempvalue.getJSONObject(period).getDouble("high")));
            quoteData.getJSONArray("K").getJSONArray(l - 1).put(3,
                    Math.min(quoteData.getJSONArray("K").getJSONArray(l - 1).getDouble(3),
                            tempvalue.getJSONObject(period).getDouble("low")));
            quoteData.getJSONArray("K").getJSONArray(l - 1).put(5,
                    cjsl + tempvalue.getJSONObject(period).getDouble("cjsl"));
            quoteData.getJSONArray("K").getJSONArray(l - 1).put(6,
                    cjje + tempvalue.getJSONObject(period).getDouble("cjje"));
        } else {
            quoteData.getJSONArray("K").getJSONArray(l - 1).put(2,
                    Math.max(quoteData.getJSONArray("K").getJSONArray(l - 1).getDouble(2),
                            tempvalue.getJSONObject(period).getDouble("high")));
            quoteData.getJSONArray("K").getJSONArray(l - 1).put(3,
                    Math.min(quoteData.getJSONArray("K").getJSONArray(l - 1).getDouble(3),
                            tempvalue.getJSONObject(period).getDouble("low")));
            quoteData.getJSONArray("K").getJSONArray(l - 1).put(5,
                    tempvalue.getJSONObject(period).getDouble("cjsl"));
            quoteData.getJSONArray("K").getJSONArray(l - 1).put(6,
                    tempvalue.getJSONObject(period).getDouble("cjje"));
        }
        double jrkp = tempvalue.getJSONObject(period).getDouble("open");
        if (jrkp != 0) {
            quoteData.getJSONArray("K").getJSONArray(l - 1).put(1, jrkp);
        }
        zrsp = tempvalue.getJSONObject(period).getDouble("close");
    }

    if (quoteData.isNull("MA") && mainIndicatorType.toUpperCase().equals("BOLL")) {
        JSONArray jMA = new JSONArray();
        jMA.put(0, 0);
        jMA.put(1, 0);
        jMA.put(2, 0);
        jMA.put(3, 0);
        jMA.put(4, 0);
        jMA.put(5, 0);
        jMA.put(6, 0);
        quoteData.put("MA", new JSONArray().put(jMA));
    }

    Log.i("#######MA#########", quoteData.isNull("MA") + ">>>>>>>>>>>");
    if (quoteData.isNull("MA")) {
        JSONArray jMA = new JSONArray();
        jMA.put(0, 0);
        jMA.put(1, 0);
        jMA.put(2, 0);
        jMA.put(3, 0);
        jMA.put(4, 0);
        jMA.put(5, 0);
        jMA.put(6, 0);
        quoteData.put(mainIndicatorType.toUpperCase(), new JSONArray().put(jMA));
    } else {
        if (quoteData.getJSONArray("MA").length() == 0) {
            JSONArray jMA = new JSONArray();
            jMA.put(0, 0);
            jMA.put(1, 0);
            jMA.put(2, 0);
            jMA.put(3, 0);
            jMA.put(4, 0);
            jMA.put(5, 0);
            jMA.put(6, 0);
            quoteData.put("MA", new JSONArray().put(jMA));
        }
    }
    Log.i("#######MA#########" + indicatorType.toUpperCase(),
            quoteData.isNull(indicatorType.toUpperCase()) + ">>>>>>>>>>>");
    if (quoteData.isNull(indicatorType.toUpperCase())) {
        JSONArray jIn = new JSONArray();
        jIn.put(0, 0);
        jIn.put(1, 0);
        jIn.put(2, 0);
        jIn.put(3, 0);
        quoteData.put(indicatorType.toUpperCase(), new JSONArray().put(jIn));
    }
    if (tempvalue.isNull("ma") && quoteData.getJSONArray("K").length() > 1) //??
        actualDataLen = quoteData.getJSONArray("K").length() - 1;
    else
        actualDataLen = quoteData.getJSONArray("K").length();
    if (actualDataLen < visualKLineCount) {
        count = actualDataLen;
    } else {
        count = visualKLineCount;
    }
    if (this.actualDataLen - this.actualPos - 1 <= this.visualKLineCount) {
        actualPos = actualDataLen - count;
    }
    Log.i("#######makeTmpData########" + actualPos, actualDataLen + ">>>>>>>>" + count);
}

From source file:com.cssweb.android.view.KlineViewSingle.java

private void newStockhandler() throws JSONException {
    //      if(!quoteData.getBoolean("tradeFlag")){
    //         return;
    //      }//from ww  w .  jav  a  2  s  .c om
    Log.i("#######quoteData########", quoteData.isNull("MA") + ">>>>>>>>>>>>>>>>>" + quoteData);
    if (mainIndicatorType.toUpperCase().equals("BOLL")) {
        if (quoteData.isNull(mainIndicatorType.toUpperCase())) {
            JSONArray jMA = new JSONArray();
            jMA.put(0, 0);
            jMA.put(1, 0);
            jMA.put(2, 0);
            jMA.put(3, 0);
            jMA.put(4, 0);
            jMA.put(5, 0);
            jMA.put(6, 0);
            quoteData.put(mainIndicatorType.toUpperCase(), new JSONArray().put(jMA));
        }
    }

    if (quoteData.isNull(mainIndicatorType.toUpperCase())) {
        JSONArray jMA = new JSONArray();
        jMA.put(0, 0);
        jMA.put(1, 0);
        jMA.put(2, 0);
        jMA.put(3, 0);
        jMA.put(4, 0);
        jMA.put(5, 0);
        jMA.put(6, 0);
        quoteData.put(mainIndicatorType.toUpperCase(), new JSONArray().put(jMA));
    }

    if (quoteData.isNull(indicatorType.toUpperCase())) {
        JSONArray jIn = new JSONArray();
        jIn.put(0, 0);
        jIn.put(1, 0);
        jIn.put(2, 0);
        jIn.put(3, 0);
        quoteData.put(indicatorType.toUpperCase(), new JSONArray().put(jIn));
    }

    actualDataLen = quoteData.getJSONArray("K").length();
    if (actualDataLen < visualKLineCount) {
        count = actualDataLen;
    } else {
        count = visualKLineCount;
    }
    if (this.actualDataLen - this.actualPos - 1 <= this.visualKLineCount) {
        actualPos = actualDataLen - count;
    }
    Log.i("#######quoteData########" + actualPos, actualDataLen + ">>>>>>>>" + count);
}

From source file:com.browseengine.bobo.server.protocol.BrowseJSONSerializer.java

public static String serialize(BrowseResult result) throws JSONException {
    JSONObject obj = new JSONObject();
    if (result != null) {
        obj.put("time", ((double) result.getTime()) / 1000.0);
        obj.put("hitCount", result.getNumHits());
        obj.put("totalDocs", result.getTotalDocs());

        // serialize choices
        JSONObject choices = new JSONObject();
        Set<Entry<String, FacetAccessible>> facetAccessors = result.getFacetMap().entrySet();
        for (Entry<String, FacetAccessible> entry : facetAccessors) {
            JSONObject choiceObject = new JSONObject();
            JSONArray choiceValArray = new JSONArray();

            choiceObject.put("choicelist", choiceValArray);
            int k = 0;

            String name = entry.getKey();
            FacetAccessible facets = entry.getValue();

            List<BrowseFacet> facetList = facets.getFacets();
            for (BrowseFacet facet : facetList) {
                JSONObject choice = new JSONObject();
                choice.put("val", facet.getValue());
                choice.put("hits", facet.getHitCount());
                choiceValArray.put(k++, choice);
            }/*from w  w w.j ava  2 s . co  m*/
            choices.put(name, choiceObject);
        }
        obj.put("choices", choices);

        JSONArray hitsArray = new JSONArray();
        BrowseHit[] hits = result.getHits();
        if (hits != null && hits.length > 0) {
            for (int i = 0; i < hits.length; ++i) {
                hitsArray.put(i, serializeHits(hits[i]));
            }
        }
        obj.put("hits", hitsArray);
        // serialize documents
    }
    return obj.toString();
}

From source file:de.kp.ames.web.function.transform.cache.XslCacheManager.java

/**
 * This method retrieves the actually uploaded transformators 
 * that are currently not registered in the OASIS ebXML RegRep
 * /* w ww  . j  ava 2 s. c o  m*/
 * @return
 * @throws Exception
 */
public JSONArray getJEntries() throws Exception {

    JSONArray jEntries = new JSONArray();

    List<CacheEntry> transformators = cache.getAll();
    for (int ix = 0; ix < transformators.size(); ix++) {

        XslTransformator transformator = (XslTransformator) transformators.get(ix);
        String key = transformator.getKey();

        JSONObject jTransformator = new JSONObject();

        jTransformator.put(JsonConstants.J_KEY, key);
        jTransformator.put(JsonConstants.J_NAME, transformator.getName());

        jTransformator.put(JsonConstants.J_DESC, "No description available.");
        jTransformator.put(JsonConstants.J_MIME, transformator.getMimetype());

        jEntries.put(jEntries.length(), jTransformator);

    }

    return jEntries;

}

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 a  v a2 s.  c  o 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);// www.  ja  va  2 s  .  c om
                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:com.hichinaschool.flashcards.anki.StudyOptionsFragment.java

private void onPrepareDialog(int id, StyledDialog styledDialog) {
    Resources res = getResources();
    switch (id) {
    case DIALOG_CUSTOM_STUDY_DETAILS:
        styledDialog.setTitle(res.getStringArray(R.array.custom_study_options_labels)[mCustomDialogChoice]);
        switch (mCustomDialogChoice + 1) {
        case CUSTOM_STUDY_NEW:
            if (AnkiDroidApp.colIsOpen()) {
                Collection col = AnkiDroidApp.getCol();
                mCustomStudyTextView1.setText(res.getString(R.string.custom_study_new_total_new,
                        col.getSched().totalNewForCurrentDeck()));
            }//from  ww  w. j a  v  a  2s  .co m
            mCustomStudyTextView2.setText(res.getString(R.string.custom_study_new_extend));
            mCustomStudyEditText.setText(
                    Integer.toString(AnkiDroidApp.getSharedPrefs(getActivity()).getInt("extendNew", 10)));
            styledDialog.setButtonOnClickListener(Dialog.BUTTON_POSITIVE,
                    new DialogInterface.OnClickListener() {
                        @Override
                        public void onClick(DialogInterface dialog, int which) {
                            if (AnkiDroidApp.colIsOpen()) {
                                try {
                                    int n = Integer.parseInt(mCustomStudyEditText.getText().toString());
                                    AnkiDroidApp.getSharedPrefs(getActivity()).edit().putInt("extendNew", n)
                                            .commit();
                                    Collection col = AnkiDroidApp.getCol();
                                    JSONObject deck = col.getDecks().current();
                                    deck.put("extendNew", n);
                                    col.getDecks().save(deck);
                                    col.getSched().extendLimits(n, 0);
                                    resetAndUpdateValuesFromDeck();
                                    finishCongrats();
                                } catch (NumberFormatException e) {
                                    // ignore non numerical values
                                    Themes.showThemedToast(getActivity().getBaseContext(),
                                            getResources().getString(R.string.custom_study_invalid_number),
                                            false);
                                } catch (JSONException e) {
                                    throw new RuntimeException(e);
                                }
                            }
                        }
                    });
            break;

        case CUSTOM_STUDY_REV:
            if (AnkiDroidApp.colIsOpen()) {
                Collection col = AnkiDroidApp.getCol();
                mCustomStudyTextView1.setText(res.getString(R.string.custom_study_rev_total_rev,
                        col.getSched().totalRevForCurrentDeck()));
            }
            mCustomStudyTextView2.setText(res.getString(R.string.custom_study_rev_extend));
            mCustomStudyEditText.setText(
                    Integer.toString(AnkiDroidApp.getSharedPrefs(getActivity()).getInt("extendRev", 10)));
            styledDialog.setButtonOnClickListener(Dialog.BUTTON_POSITIVE,
                    new DialogInterface.OnClickListener() {
                        @Override
                        public void onClick(DialogInterface dialog, int which) {
                            if (AnkiDroidApp.colIsOpen()) {
                                try {
                                    int n = Integer.parseInt(mCustomStudyEditText.getText().toString());
                                    AnkiDroidApp.getSharedPrefs(getActivity()).edit().putInt("extendRev", n)
                                            .commit();
                                    Collection col = AnkiDroidApp.getCol();
                                    JSONObject deck = col.getDecks().current();
                                    deck.put("extendRev", n);
                                    col.getDecks().save(deck);
                                    col.getSched().extendLimits(0, n);
                                    resetAndUpdateValuesFromDeck();
                                    finishCongrats();
                                } catch (NumberFormatException e) {
                                    // ignore non numerical values
                                    Themes.showThemedToast(getActivity().getBaseContext(),
                                            getResources().getString(R.string.custom_study_invalid_number),
                                            false);
                                } catch (JSONException e) {
                                    throw new RuntimeException(e);
                                }
                            }
                        }
                    });
            break;

        case CUSTOM_STUDY_FORGOT:
            mCustomStudyTextView1.setText("");
            mCustomStudyTextView2.setText(res.getString(R.string.custom_study_forgotten));
            mCustomStudyEditText.setText(
                    Integer.toString(AnkiDroidApp.getSharedPrefs(getActivity()).getInt("forgottenDays", 2)));
            styledDialog.setButtonOnClickListener(Dialog.BUTTON_POSITIVE,
                    new DialogInterface.OnClickListener() {
                        @Override
                        public void onClick(DialogInterface dialog, int which) {
                            JSONArray ar = new JSONArray();
                            try {
                                int forgottenDays = Integer
                                        .parseInt(((EditText) mCustomStudyEditText).getText().toString());
                                ar.put(0, 1);
                                createFilteredDeck(ar,
                                        new Object[] { String.format(Locale.US, "rated:%d:1", forgottenDays),
                                                9999, Sched.DYN_RANDOM },
                                        false);
                            } catch (NumberFormatException e) {
                                // ignore non numerical values
                                Themes.showThemedToast(getActivity().getBaseContext(),
                                        getResources().getString(R.string.custom_study_invalid_number), false);
                            } catch (JSONException e) {
                                throw new RuntimeException(e);
                            }
                        }
                    });
            break;

        case CUSTOM_STUDY_AHEAD:
            mCustomStudyTextView1.setText("");
            mCustomStudyTextView2.setText(res.getString(R.string.custom_study_ahead));
            mCustomStudyEditText.setText(
                    Integer.toString(AnkiDroidApp.getSharedPrefs(getActivity()).getInt("aheadDays", 1)));
            styledDialog.setButtonOnClickListener(Dialog.BUTTON_POSITIVE,
                    new DialogInterface.OnClickListener() {
                        @Override
                        public void onClick(DialogInterface dialog, int which) {
                            try {
                                int days = Integer
                                        .parseInt(((EditText) mCustomStudyEditText).getText().toString());
                                createFilteredDeck(new JSONArray(), new Object[] {
                                        String.format(Locale.US, "prop:due<=%d", days), 9999, Sched.DYN_DUE },
                                        true);
                            } catch (NumberFormatException e) {
                                // ignore non numerical values
                                Themes.showThemedToast(getActivity().getBaseContext(),
                                        getResources().getString(R.string.custom_study_invalid_number), false);
                            }
                        }
                    });
            break;

        case CUSTOM_STUDY_RANDOM:
            mCustomStudyTextView1.setText("");
            mCustomStudyTextView2.setText(res.getString(R.string.custom_study_random));
            mCustomStudyEditText.setText(
                    Integer.toString(AnkiDroidApp.getSharedPrefs(getActivity()).getInt("randomCards", 100)));
            styledDialog.setButtonOnClickListener(Dialog.BUTTON_POSITIVE,
                    new DialogInterface.OnClickListener() {
                        @Override
                        public void onClick(DialogInterface dialog, int which) {
                            try {
                                int randomCards = Integer
                                        .parseInt(((EditText) mCustomStudyEditText).getText().toString());
                                createFilteredDeck(new JSONArray(),
                                        new Object[] { "", randomCards, Sched.DYN_RANDOM }, true);
                            } catch (NumberFormatException e) {
                                // ignore non numerical values
                                Themes.showThemedToast(getActivity().getBaseContext(),
                                        getResources().getString(R.string.custom_study_invalid_number), false);
                            }
                        }
                    });
            break;

        case CUSTOM_STUDY_PREVIEW:
            mCustomStudyTextView1.setText("");
            mCustomStudyTextView2.setText(res.getString(R.string.custom_study_preview));
            mCustomStudyEditText.setText(
                    Integer.toString(AnkiDroidApp.getSharedPrefs(getActivity()).getInt("previewDays", 1)));
            styledDialog.setButtonOnClickListener(Dialog.BUTTON_POSITIVE,
                    new DialogInterface.OnClickListener() {
                        @Override
                        public void onClick(DialogInterface dialog, int which) {
                            String previewDays = ((EditText) mCustomStudyEditText).getText().toString();
                            createFilteredDeck(new JSONArray(),
                                    new Object[] { "is:new added:" + previewDays, 9999, Sched.DYN_OLDEST },
                                    false);
                        }
                    });
            break;

        case CUSTOM_STUDY_TAGS:
            mCustomStudyTextView1.setText("");
            mCustomStudyTextView2.setText(res.getString(R.string.custom_study_tags));
            mCustomStudyEditText
                    .setText(AnkiDroidApp.getSharedPrefs(getActivity()).getString("customTags", ""));
            styledDialog.setButtonOnClickListener(Dialog.BUTTON_POSITIVE,
                    new DialogInterface.OnClickListener() {
                        @Override
                        public void onClick(DialogInterface dialog, int which) {
                            String tags = ((EditText) mCustomStudyEditText).getText().toString();
                            createFilteredDeck(new JSONArray(),
                                    new Object[] { "(is:new or is:due) " + tags, 9999, Sched.DYN_RANDOM },
                                    true);
                        }
                    });
            break;
        }
    }
}

From source file:com.maxleapmobile.gitmaster.ui.fragment.RecommendFragment.java

private void getGenes() {
    MLQueryManager.findAllInBackground(query, new FindCallback<MLObject>() {
        @Override/*w  ww  .j  a  v  a2s .  co m*/
        public void done(List<MLObject> list, MLException e) {
            if (e == null) {
                Logger.d("get genes success");
                for (MLObject o : list) {
                    genes.add(Gene.from(o));
                }
                JSONArray jsonArray = new JSONArray();
                for (int i = 0; i < genes.size(); i++) {
                    JSONObject jsonObject = new JSONObject();
                    try {
                        jsonObject.put("language", genes.get(i).getLanguage());
                        jsonObject.put("skill", genes.get(i).getSkill());
                        jsonArray.put(i, jsonObject);
                    } catch (Exception jsonException) {

                    }
                }
                mParmasMap.put("genes", jsonArray);
                fetchTrendingGeneDate();
            } else {
                Logger.d("get genes failed");
                if (e.getCode() == MLException.OBJECT_NOT_FOUND) {
                    fetchSearchGeneDate();
                } else {
                    Logger.toast(mContext, R.string.toast_get_recommend_failed);
                }
            }
        }
    });
}