예제 #1
0
  /**
   * Subscribe - Private Interface
   *
   * <p>Patch provided by petereddy on GitHub
   *
   * @param String channel name.
   * @param Callback function callback.
   * @param String timetoken.
   */
  private void _subscribe(String channel, Callback callback, String timetoken) {
    while (true) {
      try {
        // Build URL
        List<String> url =
            java.util.Arrays.asList("subscribe", this.SUBSCRIBE_KEY, channel, "0", timetoken);

        // Wait for Message
        JSONArray response = _request(url);
        JSONArray messages = response.optJSONArray(0);

        // Update TimeToken
        if (response.optString(1).length() > 0) timetoken = response.optString(1);

        // Run user Callback and Reconnect if user permits. If
        // there's a timeout then messages.length() == 0.
        for (int i = 0; messages.length() > i; i++) {
          JSONObject message = messages.optJSONObject(i);
          if (!callback.execute(message) || cancel) return;
        }
      } catch (Exception e) {
        try {
          Thread.sleep(1000);
        } catch (InterruptedException ie) {
          return;
        }
      }
    }
  }
 /**
  * Helper method that returns whether the specified soup name exists in the master soup.
  *
  * @param soupName Soup name.
  * @return True - if it exists, False - otherwise.
  */
 private boolean doesMasterSoupContainSoup(String soupName) {
   final JSONArray soupNames = getAllSoupNames();
   for (int i = 0; i < soupNames.length(); i++) {
     final JSONArray names = soupNames.optJSONArray(i);
     if (names != null && names.length() > 0) {
       final String name = names.optString(0);
       if (soupName.equals(name)) {
         return true;
       }
     }
   }
   return false;
 }
 /** Clears all soups used by this class and the master soup. */
 private void clearAllSoups() {
   final JSONArray soupNames = getAllSoupNames();
   for (int i = 0; i < soupNames.length(); i++) {
     final JSONArray names = soupNames.optJSONArray(i);
     if (names != null && names.length() > 0) {
       final String name = names.optString(0);
       if (name != null) {
         smartStore.dropSoup(name);
       }
     }
   }
   clearMasterSoup();
 }
예제 #4
0
 private Map<Integer, List<JSONArray>> buildErrorMap(JSONArray errors) {
   Map<Integer, List<JSONArray>> result = new HashMap<Integer, List<JSONArray>>();
   if (errors != null) {
     for (int i = 0; i < errors.length(); i++) {
       JSONArray error = errors.optJSONArray(i);
       if (error != null && error.length() > 0) {
         int index = error.optInt(0);
         List<JSONArray> errorList = result.get(index);
         if (errorList == null) {
           errorList = new LinkedList<JSONArray>();
           result.put(index, errorList);
         }
         errorList.add(error);
       }
     }
   }
   return result;
 }
예제 #5
0
  private static void recursivelyBuildChildren(
      Node node, JSONArray children, JSONTreeModelBuilder callback) throws JSONException {
    for (int i = 1; i < children.length(); i++) {
      JSONArray subarray = children.optJSONArray(i);
      String uuid;
      if (subarray == null) {
        uuid = children.getString(i);
      } else {
        uuid = subarray.getString(0);
      }

      Node child = new Node(uuid, node, node.indent + 1);
      if (subarray != null) {
        recursivelyBuildChildren(child, subarray, callback);
      }
      node.children.add(child);
      if (callback != null) {
        callback.afterAddNode(child);
      }
    }
  }
 /**
  * Returns the last time the cache was refreshed.
  *
  * @param cacheType Cache type.
  * @param cacheKey Cache key.
  * @return Last update time of the cache.
  */
 public long getLastCacheUpdateTime(String cacheType, String cacheKey) {
   try {
     if (cacheType == null
         || cacheKey == null
         || Constants.EMPTY_STRING.equals(cacheType)
         || Constants.EMPTY_STRING.equals(cacheKey)) {
       return 0;
     }
     final String soupName = cacheType + cacheKey;
     if (!doesCacheExist(soupName)) {
       return 0;
     }
     final String smartSql =
         "SELECT {"
             + soupName
             + ":"
             + String.format(CACHE_TIME_KEY, cacheKey)
             + "} FROM {"
             + soupName
             + "}";
     final QuerySpec querySpec = QuerySpec.buildSmartQuerySpec(smartSql, 1);
     final JSONArray results = smartStore.query(querySpec, 0);
     if (results != null && results.length() > 0) {
       final JSONArray array = results.optJSONArray(0);
       if (array != null && array.length() > 0) {
         return array.optLong(0);
       }
     }
   } catch (IllegalStateException e) {
     Log.e(TAG, "IllegalStateException occurred while attempting to read last cached time", e);
   } catch (JSONException e) {
     Log.e(TAG, "JSONException occurred while attempting to read last cached time", e);
   } catch (SmartStoreException e) {
     Log.e(TAG, "SmartStoreException occurred while attempting to read last cached time", e);
   }
   return 0;
 }
예제 #7
0
 public JSONArray optJSONArray(int index) {
   return baseArgs.optJSONArray(index);
 }
예제 #8
0
  /**
   * Parses the supplied JSON string and returns a list of comments.
   *
   * @param json
   * @return
   * @throws JSONException
   */
  static List<Comment> parseComments(String json) throws JSONException {
    List<Comment> comments = new ArrayList<Comment>();
    /*
     * null
     * Array containing arrays of comments
     * numberOfComments
     */
    JSONArray jsonComments = new JSONObject(json).getJSONArray("result").getJSONArray(1);
    int count = jsonComments.length();
    for (int i = 0; i < count; i++) {
      Comment comment = new Comment();
      JSONArray jsonComment = jsonComments.getJSONArray(i);
      /*
       * null
       * "gaia:17919762185957048423:1:vm:11887109942373535891", -- ID?
       * "REVIEWERS_NAME",
       * "1343652956570", -- DATE?
       * RATING,
       * null
       * "COMMENT",
       * null,
       * "VERSION_NAME",
       * [ null,
       * "DEVICE_CODE_NAME",
       * "DEVICE_MANFACTURER",
       * "DEVICE_MODEL"
       * ],
       * "LOCALE",
       * null,
       * 0
       */
      // Example with developer reply
      /*
       * [
       * null,
       * "gaia:12824185113034449316:1:vm:18363775304595766012",
       * "Micka�l",
       * "1350333837326",
       * 1,
       * "",
       * "Nul\tNul!! N'arrive pas a scanner le moindre code barre!",
       * 73,
       * "3.2.5",
       * [
       * null,
       * "X10i",
       * "SEMC",
       * "Xperia X10"
       * ],
       * "fr_FR",
       * [
       * null,
       * "Prixing fonctionne pourtant bien sur Xperia X10. Essayez de prendre un minimum de recul, au moins 20 � 30cm, �vitez les ombres et les reflets. N'h�sitez pas � nous �crire sur [email protected] pour une assistance personnalis�e."
       * ,
       * null,
       * "1350393460968"
       * ],
       * 1
       * ]
       */
      String user = jsonComment.getString(2);
      if (user != null && !"null".equals(user)) {
        comment.setUser(user);
      }
      comment.setDate(parseDate(jsonComment.getLong(3)));
      comment.setRating(jsonComment.getInt(4));
      String version = jsonComment.getString(8);
      if (version != null && !version.equals("null")) {
        comment.setAppVersion(version);
      }
      comment.setText(jsonComment.getString(6));
      JSONArray jsonDevice = jsonComment.optJSONArray(9);
      if (jsonDevice != null) {
        String device = jsonDevice.optString(3);
        JSONArray extraInfo = jsonDevice.optJSONArray(2);
        if (extraInfo != null) {
          device += " " + extraInfo.optString(0);
        }
        comment.setDevice(device.trim());
      }

      JSONArray jsonReply = jsonComment.optJSONArray(11);
      if (jsonReply != null) {
        Comment reply = new Comment(true);
        reply.setText(jsonReply.getString(1));
        reply.setReplyDate(parseDate(jsonReply.getLong(3)));
        reply.setDate(comment.getDate());
        comment.setReply(reply);
      }

      comments.add(comment);
    }

    return comments;
  }
예제 #9
0
  /**
   * Parses the supplied JSON string and builds a list of apps from it
   *
   * @param json
   * @param accountName
   * @return List of apps
   * @throws JSONException
   */
  static List<AppInfo> parseAppInfos(String json, String accountName) throws JSONException {

    Date now = new Date();
    List<AppInfo> apps = new ArrayList<AppInfo>();
    // Extract the base array containing apps
    JSONArray jsonApps = new JSONObject(json).getJSONArray("result").getJSONArray(1);
    if (DEBUG) {
      pp("jsonApps", jsonApps);
    }

    int numberOfApps = jsonApps.length();
    for (int i = 0; i < numberOfApps; i++) {
      AppInfo app = new AppInfo();
      app.setAccount(accountName);
      app.setLastUpdate(now);
      /*
       * Per app:
       * null
       * [ APP_INFO_ARRAY
       * * null
       * * packageName
       * * Nested array with details
       * * null
       * * Nested array with version details
       * * Nested array with price details
       * * Last update Date
       * * Number [1=published, 5 = draft?]
       * ]
       * null
       * [ APP_STATS_ARRAY
       * * null,
       * * Active installs
       * * Total ratings
       * * Average rating
       * * Errors
       * * Total installs
       * ]
       */
      JSONArray jsonApp = jsonApps.getJSONArray(i);
      JSONArray jsonAppInfo = jsonApp.getJSONArray(1);
      if (DEBUG) {
        pp("jsonAppInfo", jsonAppInfo);
      }
      String packageName = jsonAppInfo.getString(1);
      // Look for "tmp.7238057230750432756094760456.235728507238057230542"
      if (packageName == null
          || (packageName.startsWith("tmp.") && Character.isDigit(packageName.charAt(4)))) {
        continue;
        // Draft app
      }
      // Check number code and last updated date
      // Published: 1
      // Unpublished: 2
      // Draft: 5
      // Draft w/ in-app items?: 6
      // TODO figure out the rest and add don't just skip, filter, etc. Cf. #223
      int publishState = jsonAppInfo.getInt(7);
      Log.d(TAG, String.format("%s: publishState=%d", packageName, publishState));
      if (publishState != 1) {
        // Not a published app, skipping
        continue;
      }
      app.setPublishState(publishState);
      app.setPackageName(packageName);

      /*
       * Per app details:
       * null
       * Country code
       * App Name
       * Description
       * Unknown
       * Last what's new
       */
      if (jsonAppInfo.length() < 5) {
        // skip if we can't get all the data
        continue;
      }
      JSONArray appDetails = jsonAppInfo.getJSONArray(2).getJSONArray(1).getJSONArray(0);
      if (DEBUG) {
        pp("appDetails", appDetails);
      }
      app.setName(appDetails.getString(2));

      /*
       * Per app version details:
       * null
       * null
       * packageName
       * versionNumber
       * versionName
       * null
       * Array with app icon [null,null,null,icon]
       */
      JSONArray appVersions = jsonAppInfo.optJSONArray(4);
      if (DEBUG) {
        pp("appVersions", appVersions);
      }
      if (appVersions == null) {
        continue;
      }
      JSONArray lastAppVersionDetails =
          appVersions.getJSONArray(appVersions.length() - 1).getJSONArray(2);
      if (DEBUG) {
        pp("lastAppVersionDetails", lastAppVersionDetails);
      }
      app.setVersionName(lastAppVersionDetails.getString(4));
      app.setIconUrl(lastAppVersionDetails.getJSONArray(6).getString(3));

      // App stats
      /*
       * null,
       * Active installs
       * Total ratings
       * Average rating
       * Errors
       * Total installs
       */
      // XXX this index might not be correct for all apps?
      JSONArray jsonAppStats = jsonApp.optJSONArray(3);
      if (DEBUG) {
        pp("jsonAppStats", jsonAppStats);
      }
      if (jsonAppStats == null) {
        continue;
      }
      AppStats stats = new AppStats();
      stats.setRequestDate(now);
      if (jsonAppStats.length() < 6) {
        // no statistics (yet?) or weird format
        // TODO do we need differentiate?
        stats.setActiveInstalls(0);
        stats.setTotalDownloads(0);
        stats.setNumberOfErrors(0);
      } else {
        stats.setActiveInstalls(jsonAppStats.getInt(1));
        stats.setTotalDownloads(jsonAppStats.getInt(5));
        stats.setNumberOfErrors(jsonAppStats.optInt(4));
      }
      app.setLatestStats(stats);

      apps.add(app);
    }

    return apps;
  }
  /**
   * Reads a list of Salesforce object layouts from the cache.
   *
   * @param cacheType Cache type.
   * @param cacheKey Cache key.
   * @return List of Salesforce object layouts.
   */
  public List<SalesforceObjectTypeLayout> readObjectLayouts(String cacheType, String cacheKey) {
    if (cacheType == null
        || cacheKey == null
        || Constants.EMPTY_STRING.equals(cacheType)
        || Constants.EMPTY_STRING.equals(cacheKey)) {
      return null;
    }
    final String soupName = cacheType + cacheKey;
    if (!doesCacheExist(soupName)) {
      return null;
    }

    // Checks in memory cache first.
    if (objectTypeLayoutCacheMap != null) {
      final List<SalesforceObjectTypeLayout> cachedObjs = objectTypeLayoutCacheMap.get(cacheKey);
      if (cachedObjs != null && cachedObjs.size() > 0) {
        return cachedObjs;
      }
    }

    // Falls back on smart store cache if in memory cache is empty.
    final String smartSql =
        "SELECT {"
            + soupName
            + ":"
            + String.format(CACHE_DATA_KEY, cacheKey)
            + "} FROM {"
            + soupName
            + "}";
    try {
      final QuerySpec querySpec = QuerySpec.buildSmartQuerySpec(smartSql, 1);
      final JSONArray results = smartStore.query(querySpec, 0);
      if (results != null && results.length() > 0) {
        final JSONArray array = results.optJSONArray(0);
        if (array != null && array.length() > 0) {
          final String res = array.optString(0);
          if (res != null && res.length() > 0) {
            final JSONArray cachedResults = new JSONArray(res);
            if (cachedResults.length() > 0) {
              final List<SalesforceObjectTypeLayout> cachedList =
                  new ArrayList<SalesforceObjectTypeLayout>();
              for (int j = 0; j < cachedResults.length(); j++) {
                final JSONObject sfObj = cachedResults.optJSONObject(j);
                if (sfObj != null) {
                  final JSONObject rawData = sfObj.optJSONObject("rawData");
                  final String type = sfObj.optString("type");
                  if (rawData != null && type != null && !Constants.EMPTY_STRING.equals(type)) {
                    cachedList.add(new SalesforceObjectTypeLayout(type, rawData));
                  }
                }
              }
              if (cachedList.size() > 0) {

                // Inserts or updates data in memory cache.
                if (objectTypeLayoutCacheMap != null) {
                  if (objectTypeLayoutCacheMap.get(cacheKey) != null) {
                    objectTypeLayoutCacheMap.remove(cacheKey);
                  }
                  objectTypeLayoutCacheMap.put(cacheKey, cachedList);
                }
                return cachedList;
              }
            }
          }
        }
      }
    } catch (JSONException e) {
      Log.e(TAG, "JSONException occurred while attempting to read cached data", e);
    } catch (SmartStoreException e) {
      Log.e(TAG, "SmartStoreException occurred while attempting to read cached data", e);
    }
    return null;
  }
예제 #11
0
  private void loadRoutes() throws Exception {
    String routeDetails = "";

    int a = 0;

    setContentView(R.layout.main);
    mAdapter = new MergeAdapter();

    try {
      // JSONObject dataObject = jObject.getJSONObject("data");
      JSONArray dataArray = jObject.getJSONArray("data");

      //	JSONArray fieldArray = dataArray.getJSONArray

      String routeName;
      int size = dataArray.length();
      myListView = new ListView[size];

      for (a = 0; a < size; a++) {
        routeName = "";
        routeDetails = "";

        routeName = dataArray.optJSONObject(a).getString("route_short_name").toString();
        routeDetails = routeDetails + "routeName: " + routeName;
        mAdapter.addView(buildLabel(routeName));
        JSONArray hsArray = dataArray.getJSONObject(a).getJSONArray("headsigns");

        int resID = R.layout.routes_row;
        myListView[a] = (ListView) findViewById(android.R.id.list);

        schedItems = new ArrayList<transItem>();
        transAdapter aa = new transAdapter(this, resID, schedItems);
        myListView[a].setAdapter(aa);

        for (int i = 0; i < 2; i++) {
          String headsign = "";
          String remTrips = "";
          String type = "";

          if (hsArray.optJSONArray(i) != null) {

            headsign = hsArray.getJSONArray(i).optString(0);
            remTrips = hsArray.getJSONArray(i).optString(1) + " trips remaining today";
            if (hsArray.getJSONArray(i).optString(2) != "") {
              // type = "y" + transType;
              // above is a future feature to provide indication that info is real time by showing a
              // colored icon
              type = transType;
            } else {
              // type = "bus";
              type = transType;
            }

            transItem tObject = new transItem(routeName, headsign, remTrips, type);
            fullList.add(tObject);
            aa.add(tObject);
            aa.notifyDataSetChanged();
          }
        }

        mAdapter.addAdapter(aa);
      }
      setListAdapter(mAdapter);
    } catch (JSONException je) {
      Log.e("JSONException", "Error::" + je.toString() + "a=" + Integer.toString(a));
    }
  }