public void parseDiscoverList(String discovered, String url) {

    JSONObject page = new JSONObject(discovered);
    totalPages = page.optInt("total_pages");
    totalResults = page.optInt("total_results");

    resultsLeft = totalResults;

    System.out.println("DISC: " + discovered);
    JSONArray list = page.optJSONArray("results");
    System.out.println("LIST: " + list);

    parseDiscoverPage(list);

    if (totalPages > 40) {
      for (int i = 2; i <= 40; i++) {
        page = nextPage(url, i);
        if (page != null) {
          list = page.optJSONArray("results");
          parseDiscoverPage(list);
        }
      }
    } else {
      for (int i = 2; i <= totalPages; i++) {
        page = nextPage(url, i);
        if (page != null) {
          list = page.optJSONArray("results");
          parseDiscoverPage(list);
        }
      }
    }
  }
Example #2
0
 private UserData processLookup(JSONObject json) {
   final UserData data = new UserData();
   try {
     final JSONArray local = json.optJSONArray("local");
     if (local == null) {
       SuperBans.log("Unable to properly communicate with MCBans. Check your API Key");
       return data;
     }
     for (int i = 0; i < local.length(); i++) {
       final String[] ban = processBanLookup(local.getString(i));
       data.getBanList()
           .addBanData(new MCBansBanData(ban[1], MCBansBanData.BanType.LOCAL, ban[0]));
     }
     final JSONArray global = json.optJSONArray("global");
     for (int i = 0; i < global.length(); i++) {
       final String[] ban = processBanLookup(global.getString(i));
       data.getBanList()
           .addBanData(new MCBansBanData(ban[1], MCBansBanData.BanType.GLOBAL, ban[0]));
     }
   } catch (final JSONException e) {
     e.printStackTrace();
   }
   data.setExtra("mcbans_rep", String.valueOf(json.optDouble("reputation", 10.0)));
   return data;
 }
Example #3
0
  public static void completeTest(NeoTwDatabase neoTwDatabase) throws Exception {
    // https://api.twitter.com/1.1/search/tweets.json?q=562b47a2e2704e07768b464c

    System.out.println("Parsing...");

    JSONObject completeJsonObject =
        new JSONObject(
            new String(Files.readAllBytes(Paths.get(SAMPLE_TWITTER_DIR + "complete.json"))));

    System.out.println("Inserting...");

    try (Transaction tx = neoTwDatabase.beginTx()) {
      JSONArray statusesJsonArray = completeJsonObject.optJSONArray("statuses");
      for (int i = 0; i < statusesJsonArray.length(); ++i) {
        JSONObject jsonObject = statusesJsonArray.getJSONObject(i);
        TwStatus twStatus = new TwStatus(jsonObject);
        Node node = neoTwDatabase.getOrCreateTwStatusNode(twStatus);
      }
      tx.success();
    }

    System.out.println("Checking...");

    try (Transaction tx = neoTwDatabase.beginTx()) {
      JSONArray statusesJsonArray = completeJsonObject.optJSONArray("statuses");
      for (int i = 0; i < statusesJsonArray.length(); ++i) {
        JSONObject jsonObject = statusesJsonArray.getJSONObject(i);
        TwStatus twStatus = new TwStatus(jsonObject);
        Node node = neoTwDatabase.getTwStatusNodeById(twStatus.getId());
        System.out.println(node.getProperty("jsonObject"));
      }
    }
  }
Example #4
0
 @Override
 public void parseJson(String jsonStr) {
   JSONObject jsonObject = getJsonObject(jsonStr);
   if (jsonObject.optJSONArray("list").length() > 0) {
     super.parseJson(
         jsonObject.optJSONObject("pages"), jsonObject.optJSONArray("list"), GainGiftRecord.class);
   }
 }
Example #5
0
  public void createNewGui() {
    try {
      clearCache();
      String gui = Json.getJSON(Api.getUrl() + "/gui");
      Log.response("GUI", gui);
      if (Json.isJson(gui)) {
        JSONObject json = new JSONObject(gui);
        JSONArray itemArray = json.optJSONArray("result");
        JSONArray categoryArray = json.optJSONArray("categories");
        int max = itemArray.length();
        for (int i = 0; i < categoryArray.length(); i++) {
          if (i == 0) {

            // Creating categories hub
            guiHub = createInventory("Categories", getInventorySize(categoryArray.length()));
            for (int cate = 0; cate < categoryArray.length(); cate++) {
              String name = getJsonString(categoryArray, cate, "name");
              String icon = "130";
              try {
                icon = getJsonString(categoryArray, cate, "iconid");
              } catch (Exception e) {
                icon = "130";
              }
              if (icon.equalsIgnoreCase("null") || icon.equals("")) {
                icon = "130";
              }
              guiHub.setItem(cate, Createcategory(name, icon));
            }
          }

          // Creating single category packages
          int id = getJsonInt(categoryArray, i, "id");
          String name = "Category: " + getJsonString(categoryArray, i, "name");
          int InvSize = itemCount(id, itemArray);
          Inventory inv = createInventory(name, getInventorySize(InvSize + 1));

          // Adding packages to caregory
          int placement = 0;
          for (int t = 0; t < max; t++) {
            int iid = getJsonInt(itemArray, t, "categoryid");
            if (iid == id) {
              inv.setItem(placement, createItem(t, itemArray));
              placement++;
            }
          }
          inv.setItem(inv.getSize() - 1, createCategoryPage());

          // Setting up new category
          ShopCategory category = new ShopCategory(name, id, i, inv);
          // Create || adding to GUI
          category.create();
        }
      }
    } catch (Exception e) {
      Log.log(e);
    }
  }
Example #6
0
  public void fillInEchoNestInfo() throws IOException, EchoNestException {
    if (artist == null || title == null) {
      JSONObject songProfile = null;
      try {
        songProfile =
            EchoNestQuery.get("song", "profile", "id=" + EchoNestId + "&bucket=audio_summary");
      } catch (EchoNestException e) {
      }

      JSONObject song = songProfile.optJSONArray("songs").optJSONObject(0);

      artist = new Artist(song.optString("artist_name"), song.optString("artist_id"));
      title = song.optString("title");
      duration = song.optJSONObject("audio_summary").optInt("duration");
    } else if (EchoNestId == null) {
      String artistName = URLEncoder.encode(artist.getName(), "UTF-8");
      String title = URLEncoder.encode(this.title, "UTF-8");

      JSONObject songSearch = null;
      try {
        songSearch =
            EchoNestQuery.get(
                "song",
                "search",
                "artist="
                    + artistName
                    + "&title="
                    + title
                    + "&results=1"
                    + "&bucket=audio_summary");
      } catch (EchoNestException e) {
      }

      JSONArray songs = songSearch.optJSONArray("songs");
      if (songs.length() == 0) throw new EchoNestException(6, "No items found.");

      JSONObject song = songs.optJSONObject(0);

      artist = new Artist(song.optString("artist_name"), song.optString("artist_id"));
      EchoNestId = song.optString("id");
      duration = song.optJSONObject("audio_summary").optInt("duration");
    } else if (duration == -1) {
      JSONObject songProfile = null;
      try {
        songProfile =
            EchoNestQuery.get("song", "profile", "id=" + EchoNestId + "&bucket=audio_summary");
      } catch (EchoNestException e) {
      }

      duration =
          songProfile
              .optJSONArray("songs")
              .optJSONObject(0)
              .optJSONObject("audio_summary")
              .optInt("duration");
    }
  }
  @Override
  void retrieveSupplementalInfo() throws IOException {

    CharSequence contents =
        HttpHelper.downloadViaHttp(
            "https://www.googleapis.com/books/v1/volumes?q=isbn:" + isbn,
            HttpHelper.ContentType.JSON);

    if (contents.length() == 0) {
      return;
    }

    String title;
    String pages;
    Collection<String> authors = null;

    try {

      JSONObject topLevel = (JSONObject) new JSONTokener(contents.toString()).nextValue();
      JSONArray items = topLevel.optJSONArray("items");
      if (items == null || items.isNull(0)) {
        return;
      }

      JSONObject volumeInfo = ((JSONObject) items.get(0)).getJSONObject("volumeInfo");
      if (volumeInfo == null) {
        return;
      }

      title = volumeInfo.optString("title");
      pages = volumeInfo.optString("pageCount");

      JSONArray authorsArray = volumeInfo.optJSONArray("authors");
      if (authorsArray != null && !authorsArray.isNull(0)) {
        authors = new ArrayList<String>(authorsArray.length());
        for (int i = 0; i < authorsArray.length(); i++) {
          authors.add(authorsArray.getString(i));
        }
      }

    } catch (JSONException e) {
      throw new IOException(e.toString());
    }

    Collection<String> newTexts = new ArrayList<String>();
    maybeAddText(title, newTexts);
    maybeAddTextSeries(authors, newTexts);
    maybeAddText(pages == null || pages.length() == 0 ? null : pages + "pp.", newTexts);

    String baseBookUri =
        "http://www.google."
            + LocaleManager.getBookSearchCountryTLD(context)
            + "/search?tbm=bks&source=zxing&q=";

    append(isbn, source, newTexts.toArray(new String[newTexts.size()]), baseBookUri + isbn);
  }
  private void JsonResondResult(String con) {
    // TODO Auto-generated method stub
    try {
      resonpList = new ArrayList<Map<String, String>>();

      JSONObject all = new JSONObject(con);
      Log.d(TAG + "JsonResult", con);
      Boolean result = all.optBoolean("result");
      String resultMSG = all.optString("resultMSG");
      if (mToastLoding != null && mToastLoding.isShowing()) {
        mToastLoding.cancel();
      }
      if (result) {
        JSONObject data = all.optJSONObject("data");
        if (null != data) {
          JSONArray acceptPhoneNums = data.optJSONArray("acceptPhoneNums");
          if (null != acceptPhoneNums) {
            for (int i = 0; i < acceptPhoneNums.length(); i++) {
              Map<String, String> map = new HashMap<String, String>();
              map.put("accept", acceptPhoneNums.getString(i));
              map.put("type", "1");
              resonpList.add(map);
            }
          }
          JSONArray refusePhoneNums = data.optJSONArray("refusePhoneNums");
          if (null != refusePhoneNums) {
            for (int i = 0; i < refusePhoneNums.length(); i++) {
              Map<String, String> map1 = new HashMap<String, String>();
              map1.put("refuse", refusePhoneNums.getString(i));
              map1.put("type", "2");
              resonpList.add(map1);
            }
          }
          JSONArray notRespondPhoneNums = data.optJSONArray("notRespondPhoneNums");
          if (null != notRespondPhoneNums) {
            for (int i = 0; i < notRespondPhoneNums.length(); i++) {
              Map<String, String> map2 = new HashMap<String, String>();
              map2.put("notRespond", notRespondPhoneNums.getString(i));
              map2.put("type", "3");
              resonpList.add(map2);
            }
          }
        }
        RespondPopupWindow mRespondPopupWindow = new RespondPopupWindow(this);
        mRespondPopupWindow.initmPopupWindowView(
            (LinearLayout) findViewById(R.id.MySendMemoActivityID), resonpList);
      } else {
        new DialogUtil(this, resultMSG).show();
      }
      all = null;

    } catch (JSONException e) {
      // TODO Auto-generated catch block
      e.printStackTrace();
    }
  }
Example #9
0
  public void paser(JSONObject json) throws Exception {
    //	HupuLog.e("--------json----------", "---"+json.toString());

    if (json.optJSONArray("reddot") != null) {

      reddotList = new ArrayList<String>();
      for (int i = 0; i < json.optJSONArray("reddot").length(); i++) {
        reddotList.add(json.optJSONArray("reddot").optString(i));
      }
    }
  }
Example #10
0
 /**
  * 设定字段的值
  *
  * @param obj 待赋值字段的对象
  * @param field 字段
  * @param jo json实例
  */
 @SuppressWarnings("unused")
 private static void setField(Object obj, Field field, JSONObject jo) {
   String name = field.getName();
   Class<?> clazz = field.getType();
   try {
     if (isArray(clazz)) { // 数组
       Class<?> c = clazz.getComponentType();
       JSONArray ja = jo.optJSONArray(name);
       if (!isNull(ja)) {
         Object array = parseArray(ja, c);
         field.set(obj, array);
       }
     } else if (isCollection(clazz)) { // 泛型集合
       // 获取定义的泛型类型
       Class<?> c = null;
       Type gType = field.getGenericType();
       if (gType instanceof ParameterizedType) {
         ParameterizedType ptype = (ParameterizedType) gType;
         Type[] targs = ptype.getActualTypeArguments();
         if (targs != null && targs.length > 0) {
           Type t = targs[0];
           c = (Class<?>) t;
         }
       }
       JSONArray ja = jo.optJSONArray(name);
       if (!isNull(ja)) {
         Object o = parseCollection(ja, clazz, c);
         field.set(obj, o);
       }
     } else if (isSingle(clazz)) { // 值类型
       Object o = jo.opt(name);
       if (o != null) {
         field.set(obj, o);
       }
     } else if (isObject(clazz)) { // 对象
       JSONObject j = jo.optJSONObject(name);
       if (!isNull(j)) {
         Object o = parseObject(j, clazz);
         field.set(obj, o);
       }
     } else if (isList(clazz)) { // 列表
       JSONObject j = jo.optJSONObject(name);
       if (!isNull(j)) {
         Object o = parseObject(j, clazz);
         field.set(obj, o);
       }
     } else {
       throw new Exception("unknow type!");
     }
   } catch (Exception e) {
     e.printStackTrace();
   }
 }
Example #11
0
 private IGPSObject parsePOLL(final JSONObject json) throws ParseException {
   IGPSObject gps;
   // for gpsd version > 3.5
   final PollObject poll = new PollObject();
   poll.setTimestamp(this.parseTimestamp(json, "time"));
   poll.setActive(json.optInt("active", 0));
   poll.setFixes(this.parseObjectArray(json.optJSONArray("tpv"), TPVObject.class));
   poll.setSkyviews(this.parseObjectArray(json.optJSONArray("sky"), SKYObject.class));
   poll.setGst(this.parseObjectArray(json.optJSONArray("gst"), GSTObject.class));
   gps = poll;
   return gps;
 }
  private BrowseResult getResultForUrl(URL url) {
    String content;
    try {
      content = contentFromURL(url);
    } catch (IOException e) {
      Log.e(TAG, "Error grabbing json", e);
      return null;
    }

    DIDLContent didl;
    int totalMatches = -1;
    int size = 0;
    try {
      didl = new DIDLContent();
      JSONObject obj = new JSONObject(content);
      JSONArray nodes = obj.optJSONArray("nodes");
      if (nodes != null) {
        size = nodes.length();
        addDidlNodes(didl, nodes);
      }

      nodes = obj.optJSONArray("tracks");
      if (nodes != null) {
        size += nodes.length();
        addDidlTracks(didl, nodes);
      }

      JSONObject meta = obj.optJSONObject("meta");
      if (meta != null) {
        if (meta.has("totalMatches")) {
          totalMatches = Integer.parseInt(meta.getString("totalMatches"));
        }
      }
      if (totalMatches == -1) {
        totalMatches = size;
      }
    } catch (Exception e) {
      Log.e(TAG, "Error creating didl", e);
      return null;
    }

    try {
      Log.d(TAG, "search returned " + size);
      String result = new DIDLParser().generate(didl);
      Log.d(TAG, "returning didl.");
      return new BrowseResult(result, size, totalMatches);
    } catch (Exception e) {
      Log.e(TAG, "Error generating didl", e);
      return null;
    }
  }
Example #13
0
 /**
  * Constructs a List of Rate objects from a RateInfos JSONObject.
  *
  * @param object The JSONObject which holds a RateInfos field which holds an array of
  *     RateInformation objects.
  * @return A fully constructed Rate list.
  */
 public static List<Rate> parseFromRateInformations(final JSONObject object) {
   final String rateInformationId = "RateInfos";
   if (object.optJSONArray(rateInformationId) != null) {
     final JSONArray rateInformations = object.optJSONArray(rateInformationId);
     return parseRates(rateInformations);
   } else if (object.optJSONObject(rateInformationId) != null) {
     final JSONObject rateInformation = object.optJSONObject(rateInformationId);
     return parseRates(rateInformation);
   }
   // if neither of the if/else above, then this was a sabre response that
   // requires ANOTHER call to get the rate information but that is handled
   // by the RoomAvailability request, so we do nothing with the rates.
   return Collections.singletonList(null);
 }
  public ArrayList<Actor> getActorID(String actorIN) {

    ArrayList<Actor> returnActors = new ArrayList<Actor>();
    JSONObject obj = new JSONObject(actorIN);

    JSONArray actors = obj.optJSONArray("results");

    int actor_id = 0;
    String actor_name = "";

    // "Actors" - Extraction
    if (actors != null) {
      for (int i = 0; i < actors.length(); i++) {
        actor_id = actors.optJSONObject(i).optInt("id");
        actor_name = actors.optJSONObject(i).optString("name");
        Actor toAdd = new Actor(actor_name, actor_id);
        returnActors.add(toAdd);

        /*				TEST
        				________________________________________
        */
        //				System.out.println(toAdd.actorID);
        //				System.out.println(toAdd.actorName);
        //				System.out.println(actor_id);
        //				System.out.println(actor_name);
      }
    }
    return returnActors;
  }
  /**
   * Deserialize the Sheet
   *
   * @param sheetJSON
   * @return
   * @throws Exception
   */
  private Sheet deserializeSheet(JSONObject sheetJSON) throws Exception {
    String name = sheetJSON.getString(WorkSheetSerializationUtils.NAME);
    JSONObject header = sheetJSON.optJSONObject(WorkSheetSerializationUtils.HEADER);
    String layout = sheetJSON.optString(WorkSheetSerializationUtils.LAYOUT);
    JSONObject footer = sheetJSON.optJSONObject(WorkSheetSerializationUtils.FOOTER);

    JSONObject filtersJSON = sheetJSON.optJSONObject(WorkSheetSerializationUtils.FILTERS);
    List<Filter> filters = deserializeSheetFilters(filtersJSON);
    FiltersPosition position = FiltersPosition.TOP;
    if (filtersJSON != null) {
      position =
          FiltersPosition.valueOf(
              filtersJSON.getString(WorkSheetSerializationUtils.POSITION).toUpperCase());
    }

    JSONArray filtersOnDomainValuesJSON =
        sheetJSON.optJSONArray(WorkSheetSerializationUtils.FILTERS_ON_DOMAIN_VALUES);
    List<Attribute> filtersOnDomainValues =
        deserializeSheetFiltersOnDomainValues(filtersOnDomainValuesJSON);

    logger.debug("Deserializing sheet " + name);
    SheetContent content = deserializeContent(sheetJSON);
    logger.debug("Sheet " + name + " deserialized successfully");

    return new Sheet(
        name, layout, header, filters, position, content, filtersOnDomainValues, footer);
  }
Example #16
0
  @Override
  public Response handle(HttpRequest request) throws JSONException {
    SelendroidLogger.log("execute script command");
    JSONObject payload = getPayload(request);
    String script = payload.getString("script");
    JSONArray args = payload.optJSONArray("args");
    Object value = null;
    try {
      if (args.length() > 0) {
        value = getSelendroidDriver(request).executeScript(script, args);
      } else {
        value = getSelendroidDriver(request).executeScript(script);
      }
    } catch (UnsupportedOperationException e) {
      return new SelendroidResponse(getSessionId(request), 13, e);
    }
    if (value instanceof String) {
      String result = (String) value;
      if (result.contains("value")) {
        JSONObject json = new JSONObject(result);
        int status = json.optInt("status");
        if (0 != status) {
          return new SelendroidResponse(
              getSessionId(request), status, new SelendroidException(json.optString("value")));
        }
        if (json.isNull("value")) {
          return new SelendroidResponse(getSessionId(request), null);
        } else {
          return new SelendroidResponse(getSessionId(request), json.get("value"));
        }
      }
    }

    return new SelendroidResponse(getSessionId(request), value);
  }
Example #17
0
 private void parseCategories(JSONArray categoryRootArray) {
   categoriesConcatenated = "";
   for (int i = 0; i < categoryRootArray.length(); i++) {
     JSONObject jsoCategory;
     try {
       jsoCategory = categoryRootArray.getJSONObject(i);
       JSONArray jsaSubCategories = jsoCategory.optJSONArray("children");
       if (jsaSubCategories.length() > 0) {
         parseCategories(jsaSubCategories);
       } else // this category is a leaf
       {
         String leafCategoryKey = jsoCategory.optString("key");
         String leafCategoryName =
             MainActivity.translationManager.getTranslation(
                 TranslationManager.MAP_NAME_CATEGORIES, leafCategoryKey);
         categoryLeafNames.add(leafCategoryName);
       }
     } catch (Exception e) {
       e.printStackTrace();
     }
   }
   boolean firstCategoryAdded = false;
   for (int i = 0; i < categoryLeafNames.size(); i++) {
     if (!firstCategoryAdded) {
       categoriesConcatenated = categoryLeafNames.get(i);
       firstCategoryAdded = true;
     } else categoriesConcatenated += ", " + categoryLeafNames.get(i);
   }
 }
Example #18
0
  public Map<String, List<JSONObject>> getAllCms() throws Exception {
    Map<String, List<JSONObject>> resultMap = new HashMap<String, List<JSONObject>>();
    int[] minMaxIds = getMinAndMaxIds();
    logger.debug("minMaxIds: " + Arrays.toString(minMaxIds));
    int length = 500;
    JSONArray cmsResultArray = null;
    for (int i = minMaxIds[0]; i < minMaxIds[1]; i += length) {
      cmsResultArray = loadCmsByPkCms(i, (i + length - 1), length);
      if (cmsResultArray != null) {
        for (int j = 0; j < cmsResultArray.length(); j++) {
          JSONObject cmsObj = cmsResultArray.getJSONObject(j);
          JSONArray cmsKeyword = cmsObj.optJSONArray("keywords");

          addJSONObjectToList(cmsObj.optString("title"), cmsObj, resultMap);
          if (cmsKeyword != null) {
            for (int k = 0; k < cmsKeyword.length(); k++) {
              addJSONObjectToList(cmsKeyword.optString(k), cmsObj, resultMap);
            }
          }
        }
      }
    }

    return resultMap;
  }
Example #19
0
  public List<String> getWeatherDetails() {
    DailyWeatherData[] dailyWeather = null;
    List<String> stringWeather = new ArrayList<String>();
    try {
      int numberOfDays = weatherData.getInt("cnt");
      dailyWeather = new DailyWeatherData[numberOfDays];

      JSONArray weather = weatherData.optJSONArray("list");
      if (weather == null) return stringWeather;
      for (int i = 0; i < numberOfDays; i++) {
        JSONObject day = weather.getJSONObject(i);
        DailyWeatherData data = new DailyWeatherData();
        double max = day.getJSONObject("temp").getDouble("max");
        double min = day.getJSONObject("temp").getDouble("min");
        if (!isMetric) {
          max = covertMetricToImperialTemperature(max);
          min = covertMetricToImperialTemperature(min);
        }

        data.setMax(max);
        data.setMin(min);
        data.setWeather(day.getJSONArray("weather").getJSONObject(0).getString("main"));
        data.setDate(day.getString("dt"));
        dailyWeather[i] = data;
        stringWeather.add(data.toString());
        Log.i(LOG_TAG, data.toString());
      }

    } catch (JSONException e) {
      Log.e(LOG_TAG, "JSON Exception", e);
    }
    return stringWeather;
  }
 private MediaConstraints constraintsFromJSON(String jsonString) throws JSONException {
   if (jsonString == null) {
     return null;
   }
   MediaConstraints constraints = new MediaConstraints();
   JSONObject json = new JSONObject(jsonString);
   JSONObject mandatoryJSON = json.optJSONObject("mandatory");
   if (mandatoryJSON != null) {
     JSONArray mandatoryKeys = mandatoryJSON.names();
     if (mandatoryKeys != null) {
       for (int i = 0; i < mandatoryKeys.length(); ++i) {
         String key = mandatoryKeys.getString(i);
         String value = mandatoryJSON.getString(key);
         constraints.mandatory.add(new MediaConstraints.KeyValuePair(key, value));
       }
     }
   }
   JSONArray optionalJSON = json.optJSONArray("optional");
   if (optionalJSON != null) {
     for (int i = 0; i < optionalJSON.length(); ++i) {
       JSONObject keyValueDict = optionalJSON.getJSONObject(i);
       String key = keyValueDict.names().getString(0);
       String value = keyValueDict.getString(key);
       constraints.optional.add(new MediaConstraints.KeyValuePair(key, value));
     }
   }
   return constraints;
 }
Example #21
0
  private int getCmsId(String orderBy) {

    Map<String, String> params = new LinkedHashMap<String, String>();

    params.put("pn", "1");
    params.put("pl", "2");
    params.put("fd", "title desc cmsurl thumburl publishtime");
    params.put("ob", orderBy);
    params.put("cl", "search_result");

    JSONObject resource = NovaMiddleResource.search("cms", "cms", "", params);

    if (resource == null || resource.isNull("results")) {
      for (int i = 0; i < 5; i++) {
        resource = NovaMiddleResource.search("cms", "cms", "", params);
        if (resource != null && !resource.isNull("results")) {
          break;
        }
        try {
          Thread.sleep(1000);
        } catch (InterruptedException e) {
          e.printStackTrace();
        }
      }
    }

    JSONArray showArray = resource.optJSONArray("results");
    if (!JSONUtil.isEmpty(showArray)) {
      return showArray.optJSONObject(0).optInt("cmsid");
    }
    return 0;
  }
    @Override
    public void onSuccess(JSONObject response) {
      JSONArray array = response.optJSONArray("list");

      List<User> usersToInsert = parseUsers(array);
      for (int i = 0; i < usersToInsert.size(); i++) {
        KidsLogger.d(
            LOG_TAG, String.format("Getting user : %s ", usersToInsert.get(i).getScreenName()));
        if (usersToInsert.get(i).getScreenName().equals("null")) {
          KidsLogger.d(
              LOG_TAG, String.format("Removing user : %s ", usersToInsert.get(i).getScreenName()));
          usersToInsert.remove(i);
        }
      }

      if (!insertNewUsers(usersToInsert)) {
        mCallback.onFailure(new IOException("Impossible to insert users in db."));
        return;
      }

      if (response.optBoolean("has_more") && response.optInt("page") != 0) {
        fetchPage(response.optInt("page") + 1);
      } else {
        deleteOutdatedUsers();
        mCallback.onSuccess(mFetchedUsers);
      }
    }
  /** Unpacks the response from remote TF manager into this object. */
  @Override
  protected CommandResult unpackResponseFromJson(JSONObject json) throws JSONException {
    Status status = Status.NOT_ALLOCATED;
    FreeDeviceState state = FreeDeviceState.AVAILABLE;
    String statusString = json.getString(STATUS);
    try {
      status = CommandResult.Status.valueOf(statusString);
    } catch (IllegalArgumentException e) {
      throw new JSONException(String.format("unrecognized status '%s'", statusString));
    }

    String errorDetails = json.optString(INVOCATION_ERROR, null);
    String freeDeviceString = json.optString(FREE_DEVICE_STATE, null);
    if (freeDeviceString != null) {
      try {
        state = FreeDeviceState.valueOf(freeDeviceString);
      } catch (IllegalArgumentException e) {
        throw new JSONException(String.format("unrecognized state '%s'", freeDeviceString));
      }
    }

    Map<String, String> runMetricsMap = null;
    JSONArray jsonRunMetricsArray = json.optJSONArray(RUN_METRICS);
    if (jsonRunMetricsArray != null && jsonRunMetricsArray.length() > 0) {
      ImmutableMap.Builder<String, String> mapBuilder = new ImmutableMap.Builder<String, String>();
      for (int i = 0; i < jsonRunMetricsArray.length(); i++) {
        JSONObject runMetricJson = jsonRunMetricsArray.getJSONObject(i);
        final String key = runMetricJson.getString(RUN_METRICS_KEY);
        final String value = runMetricJson.getString(RUN_METRICS_VALUE);
        mapBuilder.put(key, value);
      }
      runMetricsMap = mapBuilder.build();
    }
    return new CommandResult(status, errorDetails, state, runMetricsMap);
  }
Example #24
0
  public static RepostList parse(String jsonString) {
    if (TextUtils.isEmpty(jsonString)) {
      return null;
    }

    RepostList reposts = new RepostList();
    try {
      JSONObject jsonObject = new JSONObject(jsonString);
      reposts.previous_cursor = jsonObject.optString("previous_cursor", "0");
      reposts.next_cursor = jsonObject.optString("next_cursor", "0");
      reposts.total_number = jsonObject.optInt("total_number", 0);

      JSONArray jsonArray = jsonObject.optJSONArray("reposts");
      if (jsonArray != null && jsonArray.length() > 0) {
        int length = jsonArray.length();
        reposts.repostsList = new ArrayList<Reposts>(length);
        for (int ix = 0; ix < length; ix++) {
          reposts.repostsList.add(Reposts.parse(jsonArray.getJSONObject(ix)));
        }
      }
    } catch (JSONException e) {
      e.printStackTrace();
    }

    return reposts;
  }
Example #25
0
  /**
   * Constructs a Rate from a JSONObject.
   *
   * @param rateInformationJson The JSONObject holding the data to construct this object with.
   */
  public Rate(final JSONObject rateInformationJson) {

    final List<Room> localRooms;
    final JSONObject roomGroupJson = rateInformationJson.optJSONObject("RoomGroup");
    if (roomGroupJson != null && roomGroupJson.optJSONArray("Room") != null) {
      final JSONArray roomJson = roomGroupJson.optJSONArray("Room");
      localRooms = new ArrayList<Room>(roomJson.length());
      for (int i = 0; i < roomJson.length(); i++) {
        localRooms.add(new Room(roomJson.optJSONObject(i)));
      }
    } else if (roomGroupJson != null && roomGroupJson.optJSONObject("Room") != null) {
      localRooms = Collections.singletonList(new Room(roomGroupJson.optJSONObject("Room")));
    } else {
      localRooms = Collections.emptyList();
    }

    final JSONObject chargeableObject = rateInformationJson.optJSONObject("ChargeableRateInfo");
    final JSONObject convertedObject = rateInformationJson.optJSONObject("ConvertedRateInfo");

    chargeable = new RateInformation(chargeableObject);
    converted = convertedObject == null ? null : new RateInformation(convertedObject);

    promo = rateInformationJson.optBoolean("@promo");
    roomGroup = Collections.unmodifiableList(localRooms);
  }
  @Override
  protected void setView(View view, String key, Object value) {
    if (null == view || null == key) {
      return;
    }
    if ("addList".equals(key)) {
      JSONObject data = (JSONObject) value;
      JSONArray dataArray = data.optJSONArray("recordList");

      // cache record to sqlite --start by Teddy 17th July
      List<JSONObject> tmpList = new ArrayList<JSONObject>();
      // cache record to sqlite --end by Teddy 17th July

      for (int i = 0; i < dataArray.length(); i++) {
        recordDataList.add(dataArray.optJSONObject(i));
        tmpList.add(dataArray.optJSONObject(i));
      }
      hasMore = data.optBoolean("hasMore");
      adapter.setHasMore(hasMore);
      adapter.notifyDataSetChanged();

      // cache record to sqlite --start by Teddy 17th July
      if (tmpList != null && tmpList.size() > 0) {
        new CacheRecordThread().start();
      }
      // cache record to sqlite --end by Teddy 17th July
    }
    super.setView(view, key, value);
  }
  public CommentsGetInfoResponseBean(String response) {
    super(response);
    // TODO Auto-generated constructor stub
    if (response == null) {
      return;
    }

    try {
      JSONObject obj = new JSONObject(response);
      JSONArray array = obj.optJSONArray(CommentInfo.KEY_COMMENTS);
      if (array != null) {
        comments = new ArrayList<CommentInfo>();
        int size = array.length();
        for (int i = 0; i < size; i++) {
          CommentInfo info = new CommentInfo();
          info.parse(array.optJSONObject(i));
          if (info != null) {
            comments.add(info);
          }
        }
      }
    } catch (JSONException e) {
      e.printStackTrace();
    } catch (NetworkException e) {
      e.printStackTrace();
    }
  }
 public void refresh(String result) {
   freshProducts.clear();
   productAdapter.notifyDataSetChanged();
   if (result.length() > 0) {
     JSONObject object;
     try {
       object = new JSONObject(result);
       if (object.optString("state").equalsIgnoreCase("SUCCESS")) {
         JSONArray array = object.optJSONArray("dataList");
         if (array != null) {
           for (int i = 0; i < array.length(); i++) {
             freshProducts.add(new ModelLocalService(array.optJSONObject(i)));
           }
           if (freshProducts.size() > 0) {
             int colums = freshProducts.size();
             gridView.setLayoutParams(
                 new LinearLayout.LayoutParams(
                     colums * HomeData.columWidth, LinearLayout.LayoutParams.MATCH_PARENT));
             gridView.setColumnWidth(HomeData.columWidth);
             gridView.setStretchMode(GridView.NO_STRETCH);
             gridView.setNumColumns(colums);
             productAdapter.notifyDataSetChanged();
           }
         }
       }
     } catch (JSONException e) {
       e.printStackTrace();
     }
   }
   if (freshProducts.isEmpty()) {
     getView().setVisibility(View.GONE);
   } else {
     getView().setVisibility(View.VISIBLE);
   }
 }
 @Override
 public void onStart() {
   super.onStart();
   Log.d("SVF", "Called onStart in StoriesViewFragment");
   user = ValuesAndUtil.getInstance().loadUserData(getActivity().getApplicationContext());
   topics = user.optJSONArray("topics");
 }
Example #30
0
 /**
  * The json-based constructor for this object.
  *
  * @param jsonRoom The JSONObject representing this room.
  */
 public Room(final JSONObject jsonRoom) {
   this.occupancy =
       new RoomOccupancy(
           jsonRoom.optInt("numberOfAdults"),
           parseChildAgeArray(jsonRoom.optJSONArray("childAges")));
   this.rateKey = jsonRoom.optString("rateKey");
 }