Пример #1
0
  public SGeneric(
      JSONObject element, LinearLayout layout, MainActivity.TabSectionFragment fragment) {
    super(element, layout, fragment);

    if (element.containsKey("action")) this.command = (String) element.get("action");
    else throw new IllegalArgumentException("SCheckBox has no action defined");

    if (this.element.containsKey("label")) this.label = Utils.localise(element.get("label"));

    if (element.containsKey("default")) this.original = element.get("default");

    if (element.containsKey("inputType")) this.inputType = (String) element.get("inputType");

    /** Add a description element inside our own with the same JSON object */
    if (element.containsKey("description"))
      descriptionObj = new SDescription(element, layout, fragment);

    if (element.containsKey("title")) titleObj = new STitleBar(element, layout, fragment);

    resumeTask =
        new Runnable() {
          @Override
          public void run() {
            try {
              refreshValue();
            } catch (ElementFailureException e) {
              Utils.createElementErrorView(e);
            }
          }
        };

    ActionValueNotifierHandler.register(this);
  }
Пример #2
0
  @Test
  public void DecodingJsonText() throws ParseException {
    System.out.println("=======decode=======");

    String s = "[0,{'1':{'2':{'3':{'4':[5,{'6':7}]}}}}]";
    Object obj = JSONValue.parse(s);
    JSONArray array = (JSONArray) obj;
    System.out.println("======the 2nd element of array======");
    System.out.println(array.get(1));
    System.out.println();

    JSONObject obj2 = (JSONObject) array.get(1);
    System.out.println("======field \"1\"==========");
    System.out.println(obj2.get("1"));

    s = "{}";
    obj = JSONValue.parse(s);
    System.out.println(obj);

    s = "{\"key\":\"Value\"}";
    // JSONValue.parseStrict()
    // can be use to be sure that the input is wellformed
    obj = JSONValue.parseStrict(s);
    JSONObject obj3 = (JSONObject) obj;
    System.out.println("====== Object content ======");
    System.out.println(obj3.get("key"));
    System.out.println();
  }
Пример #3
0
  public SLiveLabel(
      JSONObject element, LinearLayout layout, MainActivity.TabSectionFragment fragment) {
    super(element, layout, fragment);

    if (element.containsKey("action")) this.command = (String) element.get("action");
    else throw new IllegalArgumentException("SSeekBar has no action defined");

    if (element.containsKey("refresh")) {
      refreshInterval = (Integer) element.get("refresh");
      if (refreshInterval != 0 && refreshInterval < 50) refreshInterval = 50;
    }

    if (element.containsKey("style")) style = (String) element.get("style");

    resumeTask =
        new Runnable() {
          @Override
          public void run() {
            try {
              liveLabel.setText(Utils.runCommand(command).replace("@n", "\n"));
              if (refreshInterval > 0) Synapse.handler.postDelayed(this, refreshInterval);
            } catch (Exception e) {
              liveLabel.setText(e.getMessage());
            }
          }
        };

    /** Add a description element inside our own with the same JSON object */
    if (element.containsKey("description"))
      descriptionObj = new SDescription(element, layout, fragment);

    if (element.containsKey("title")) titleObj = new STitleBar(element, layout, fragment);
  }
Пример #4
0
  /**
   * @param queryString is a simple query of 4 types (assault, murder, robbery, rape) e.g.
   *     assault>300&&rape<10
   * @return List<CityCrime> of CityCrime objects
   */
  public List<CityCrime> filterByViolentType(String queryString) {
    Configuration config = Configuration.builder().options(Option.AS_PATH_LIST).build();
    String formatted = formatQueryString("totals.violent", queryString);
    List<String> foundPaths =
        JsonPath.using(config).parse(rawData).read("$[*].data[?(" + formatted + ")]");
    List<CityCrime> resultList = new ArrayList<CityCrime>();

    // Regex:::create matcher object to get the parent
    for (String path : foundPaths) {
      String pattern = "\\$\\[\\d+\\]"; // root

      // Create a Pattern object
      Pattern r = Pattern.compile(pattern);
      CityCrime cityCrime = new CityCrime();

      Matcher m = r.matcher(path);
      if (m.find()) {
        JSONObject rawObj = JsonPath.read(rawData, m.group(0));
        cityCrime.setDepartment((String) rawObj.get("department"));
        cityCrime.setState((String) rawObj.get("state"));

        JSONObject reportObj = JsonPath.read(rawData, path);
        List<Report> reports = new ArrayList<Report>();
        reports.add(new Report(reportObj));
        cityCrime.setReport(reports);
      }
      resultList.add(cityCrime);
    }
    return resultList;
  }
  public static Manifest manifestFromJSonObject(JSONObject parsedObject) {
    String versionStr = "";
    String guid = "";
    String urlRoot = "";

    Object tmp = parsedObject.get(ManifestConstants.VERSION);
    if (null != tmp) {
      versionStr = tmp.toString();
    }

    tmp = parsedObject.get(ManifestConstants.GUID);
    if (null != tmp) {
      guid = tmp.toString();
    }
    tmp = parsedObject.get(ManifestConstants.URLROOT);
    if (null != tmp) {
      urlRoot = tmp.toString();
    }

    Manifest toReturn = new Manifest(Util.intFromStringWithoutThrow(versionStr), guid, urlRoot);

    tmp = parsedObject.get(ManifestConstants.ENTRIES);
    if (tmp instanceof JSONArray) {
      JSONArray entries = (JSONArray) tmp;
      for (Object tmpEntry : entries) {
        if (tmpEntry instanceof JSONObject) {
          Entry e = entryFromJsonObject((JSONObject) tmpEntry);
          if (null != e) {
            toReturn.addEntry(e);
          }
        }
      }
    }
    return toReturn;
  }
Пример #6
0
  @ResponseBody
  @RequestMapping(value = "modify", method = RequestMethod.POST)
  public String modify(HttpServletRequest request, HttpServletResponse response) {
    JSONObject json = FormRequestUtil.parseData(request);

    Object _id = json.get("id");
    if (_id == null) {
      response.setStatus(HttpStatus.BAD_REQUEST.value());
      return "媒体Id不能为空";
    }

    int id = Integer.parseInt(_id.toString());
    Media media = service.getById(id);
    if (media != null) {
      String desc = (String) json.get("desc");
      String logourl = (String) json.get("logourl");
      String siteurl = (String) json.get("siteurl");
      if (StringUtils.isNotBlank(desc)) {
        media.setDesc(desc);
      }
      if (StringUtils.isNotBlank(logourl)) {
        media.setLogourl(logourl);
      }
      if (StringUtils.isNotBlank(siteurl)) {
        media.setSiteurl(siteurl);
      }

      return media.toJson().toJSONString();
    } else {
      response.setStatus(HttpStatus.NOT_FOUND.value());
      return "媒体[id=" + _id + "]不存在";
    }
  }
Пример #7
0
 private Double getKelvinsTemp(String cityId) throws Exception, ParseException {
   String url = baseUrl.replaceFirst("CITY_ID", cityId);
   String json = URLConnectionReader.getText(url);
   JSONParser p = new JSONParser(JSONParser.MODE_PERMISSIVE);
   JSONObject o1 = (JSONObject) p.parse(json);
   o1 = (JSONObject) o1.get("main");
   Number kelvins = (Number) o1.get("temp");
   return kelvins.doubleValue();
 }
 private static Entry entryFromJsonObject(JSONObject object) {
   String file = object.get(ManifestConstants.FILE).toString();
   String hash = object.get(ManifestConstants.HASH).toString();
   String time = object.get(ManifestConstants.TIME).toString();
   String size = object.get(ManifestConstants.SIZE).toString();
   String type = object.get(ManifestConstants.TYPE).toString();
   EntryStatus statType = EntryStatus.valueOf(type);
   return new Entry(
       file,
       hash,
       Util.longFromStringWithoutThrow(time),
       Util.longFromStringWithoutThrow(size),
       statType);
 }
Пример #9
0
  private void loadTableSpaces(JSONObject json, boolean override) {
    JSONObject spaces = (JSONObject) json.get(KEY_SPACES);

    if (spaces != null) {
      for (Map.Entry<String, Object> entry : spaces.entrySet()) {
        JSONObject spaceDetail = (JSONObject) entry.getValue();
        AddTableSpace(
            entry.getKey(),
            URI.create(spaceDetail.getAsString("uri")),
            Boolean.parseBoolean(spaceDetail.getAsString("default")),
            (JSONObject) spaceDetail.get(TABLESPACE_SPEC_CONFIGS_KEY),
            override);
      }
    }
  }
Пример #10
0
  @Test
  public void responseCanBeSerialized() {
    // Arrange:
    final JsonSerializer serializer = new JsonSerializer();
    final ErrorResponse response = new ErrorResponse(new TimeInstant(18), "badness", 500);

    // Act:
    response.serialize(serializer);
    final JSONObject jsonObject = serializer.getObject();

    // Assert:
    Assert.assertThat(jsonObject.get("timeStamp"), IsEqual.equalTo(18));
    Assert.assertThat(jsonObject.get("error"), IsEqual.equalTo("Internal Server Error"));
    Assert.assertThat(jsonObject.get("message"), IsEqual.equalTo("badness"));
    Assert.assertThat(jsonObject.get("status"), IsEqual.equalTo(500));
  }
Пример #11
0
 public void send(JSONObject cmd) {
   try {
     Method method = getClass().getMethod("process_" + cmd.get("_op"), JSONObject.class);
     method.invoke(this, cmd);
   } catch (Exception e) {
     e.printStackTrace();
   }
 }
  @Test
  public void descriptorCanBeSerialized() {
    // Arrange:
    final File file =
        new File(Paths.get(TEST_FILE_DIRECTORY.toString(), "blah").toString(), "foo.bar");
    final TEntityFileDescriptor descriptor = this.createDescriptor(file);

    // Act:
    final JSONObject jsonObject = JsonSerializer.serializeToJson(descriptor);

    // Assert:
    Assert.assertThat(jsonObject.size(), IsEqual.equalTo(2));
    Assert.assertThat(jsonObject.get(descriptor.getName().getLabel()), IsEqual.equalTo("foo"));
    Assert.assertThat(
        jsonObject.get("location"),
        IsEqual.equalTo(Paths.get(TEST_FILE_DIRECTORY.toString(), "blah", "foo.bar").toString()));
  }
Пример #13
0
  @Override
  public CamusWrapper<String> decode(byte[] payload) {
    long timestamp = 0;
    String payloadString;
    JSONObject jobj;
    // Need to specify Charset because the default might not be UTF-8.
    // Bug fix for https://jira.airbnb.com:8443/browse/PRODUCT-5551.
    payloadString = new String(payload, Charset.forName("UTF-8"));

    // Parse the payload into a JsonObject.
    try {
      jobj = (JSONObject) JSONValue.parse(payloadString);
    } catch (RuntimeException e) {
      log.error("Caught exception while parsing JSON string '" + payloadString + "'.");
      throw new RuntimeException(e);
    }

    // Attempt to read and parse the timestamp element into a long.
    if (jobj.get(timestampField) != null) {
      Object ts = jobj.get(timestampField);
      if (ts instanceof String) {
        try {
          timestamp = new SimpleDateFormat(timestampFormat).parse((String) ts).getTime();
        } catch (Exception e) {
          log.error("Could not parse timestamp '" + ts + "' while decoding JSON message.");
        }
      } else if (ts instanceof Long) {
        timestamp = (Long) ts;
      }
    }

    // If timestamp wasn't set in the above block,
    // then set it to current time.
    final long now = System.currentTimeMillis();
    if (timestamp == 0) {
      log.warn(
          "Couldn't find or parse timestamp field '"
              + timestampField
              + "' in JSON message, defaulting to current time.");
      timestamp = now;
    }

    return new CamusWrapper<String>(payloadString, timestamp);
  }
Пример #14
0
 public static void loadSections() {
   if (Utils.configSections == null) {
     JSONObject resultsJSONObject = Utils.getJSON();
     if (resultsJSONObject == null) {
       Synapse.currentEnvironmentState = Synapse.environmentState.JSON_FAILURE;
       return;
     }
     Utils.configSections = (JSONArray) resultsJSONObject.get("sections");
   }
 }
Пример #15
0
  private Pair<String, Class<? extends Tablespace>> extractStorage(Map.Entry<String, Object> entry)
      throws ClassNotFoundException {

    String storageType = entry.getKey();
    JSONObject storageDesc = (JSONObject) entry.getValue();
    String handlerClass = (String) storageDesc.get(KEY_STORAGE_HANDLER);

    return new Pair<String, Class<? extends Tablespace>>(
        storageType, (Class<? extends Tablespace>) Class.forName(handlerClass));
  }
Пример #16
0
  @ResponseBody
  @RequestMapping(value = "create", method = RequestMethod.POST)
  public String add(HttpServletRequest request, HttpServletResponse response) {

    JSONObject json = FormRequestUtil.parseData(request);
    String name = (String) json.get("desc");
    if (name == null) {
      response.setStatus(HttpStatus.BAD_REQUEST.value());
      return "媒体名不能为空";
    }
    String siteUrl = (String) json.get("siteurl");
    String logoUrl = (String) json.get("logourl");

    Media media = new Media();
    media.setDesc(name);
    media.setSiteurl(siteUrl);
    media.setLogourl(logoUrl);
    service.insert(media);

    Media ret = service.findByName(name);
    return ret.toJson().toJSONString();
  }
Пример #17
0
  public static String localise(Object textObject) {
    if (textObject instanceof String) {
      return (String) textObject;
    } else if (textObject instanceof JSONObject) {
      JSONObject object = (JSONObject) textObject;
      String localeKey;

      if (object.containsKey(Utils.locale)) localeKey = Utils.locale;
      else if (object.containsKey(Utils.locale.substring(0, 2)))
        localeKey = Utils.locale.substring(0, 2);
      else localeKey = "en";

      return (String) object.get(localeKey);
    }

    return null;
  }
Пример #18
0
  private void loadStorages(JSONObject json) {
    JSONObject spaces = (JSONObject) json.get(KEY_STORAGES);

    if (spaces != null) {
      Pair<String, Class<? extends Tablespace>> pair = null;
      for (Map.Entry<String, Object> entry : spaces.entrySet()) {

        try {
          pair = extractStorage(entry);
        } catch (ClassNotFoundException e) {
          LOG.warn(e);
          continue;
        }

        TABLE_SPACE_HANDLERS.put(pair.getFirst(), pair.getSecond());
      }
    }
  }
Пример #19
0
  @ResponseBody
  @RequestMapping(value = "delete", method = RequestMethod.POST)
  public String delete(HttpServletRequest request, HttpServletResponse response) {
    JSONObject json = FormRequestUtil.parseData(request);

    Object _id = json.get("id");
    if (_id == null) {
      response.setStatus(HttpStatus.BAD_REQUEST.value());
      return "媒体Id不能为空";
    }

    int id = Integer.parseInt(_id.toString());
    Media media = service.getById(id);
    if (media != null) {
      service.delete(id);
      return media.toJson().toJSONString();
    } else {
      response.setStatus(HttpStatus.NOT_FOUND.value());
      return "媒体[id=" + _id + "]不存在";
    }
  }
 /* (non-Javadoc)
  * @see org.topicquests.model.api.node.IAirStruct#getEditComment()
  */
 @Override
 public String getEditComment() {
   return (String) data.get(IAirStruct.EDIT_COMMENT);
 }
 /* (non-Javadoc)
  * @see org.topicquests.model.api.node.IAirStruct#getLastEditDate()
  */
 @Override
 public String getLastEditDate() {
   return (String) data.get(IAirStruct.LAST_EDIT_DATE);
 }
 /* (non-Javadoc)
  * @see org.topicquests.model.api.node.IAirStruct#getText()
  */
 @Override
 public String getText() {
   return (String) data.get(IChildStruct.CONTEXT_LOCATOR);
 }
 @Override
 public String getCreatorId() {
   return (String) data.get(IAirStruct.CREATOR_ID);
 }
Пример #24
0
  public void process_init(JSONObject cmd) {
    int side = Integer.parseInt(cmd.get("_side") + "");

    ArrayList<ObjectRock> rocks = new ArrayList<ObjectRock>();
    ArrayList<ObjectFlag> flags = new ArrayList<ObjectFlag>();
    ArrayList<ObjectUnit> units = new ArrayList<ObjectUnit>();

    // Rocks
    JSONArray ja = (JSONArray) cmd.get("mapDump");
    for (Object o : ja) {
      JSONObject jo = (JSONObject) o;
      rocks.add(
          new ObjectRock(Integer.parseInt(jo.get("x") + ""), Integer.parseInt(jo.get("y") + "")));
    }

    // Flags
    ja = (JSONArray) cmd.get("flags");
    for (Object o : ja) {
      JSONObject jo = (JSONObject) o;
      flags.add(
          new ObjectFlag(
              Integer.parseInt(jo.get("id") + ""),
              Integer.parseInt(jo.get("x") + ""),
              Integer.parseInt(jo.get("y") + "")));
    }

    // Units
    ja = (JSONArray) cmd.get("units");
    for (Object o : ja) {
      JSONObject jo = (JSONObject) o;
      units.add(
          new ObjectUnit(
              Integer.parseInt(jo.get("id") + ""),
              jo.get("type") + "",
              Integer.parseInt(jo.get("x") + ""),
              Integer.parseInt(jo.get("y") + "")));
    }

    _sides
        .get(side)
        .processInit(
            this,
            side,
            Integer.parseInt(cmd.get("mapSizeX") + ""),
            Integer.parseInt(cmd.get("mapSizeY") + ""),
            rocks,
            flags,
            units);

    sendReady(side);
  }
Пример #25
0
  public void process_tick(JSONObject cmd) {
    int side = Integer.parseInt(cmd.get("_side") + "");

    ArrayList<EventBoom> eventBoomList = new ArrayList<EventBoom>();
    ArrayList<EventCoins> eventCoinsList = new ArrayList<EventCoins>();
    ArrayList<EventFlag> eventFlagList = new ArrayList<EventFlag>();
    ArrayList<EventUnitBuild> eventUnitBuildList = new ArrayList<EventUnitBuild>();
    ArrayList<EventUnitFire> eventUnitFireList = new ArrayList<EventUnitFire>();
    ArrayList<EventUnitHide> eventUnitHideList = new ArrayList<EventUnitHide>();
    ArrayList<EventUnitHit> eventUnitHitList = new ArrayList<EventUnitHit>();
    ArrayList<EventUnitMove> eventUnitMoveList = new ArrayList<EventUnitMove>();
    ArrayList<EventUnitRotateTurret> eventUnitRotateTurrerList =
        new ArrayList<EventUnitRotateTurret>();
    ArrayList<EventUnitShow> eventUnitShowList = new ArrayList<EventUnitShow>();

    JSONArray eventsJ = (JSONArray) cmd.get("events");
    for (Object o : eventsJ) {
      JSONObject jo = (JSONObject) o;
      String event = jo.get("event") + "";

      if (event.equals(EventUnitMove.EVENT)) {
        eventUnitMoveList.add(
            new EventUnitMove(
                Integer.parseInt(jo.get("unitId") + ""),
                Integer.parseInt(jo.get("toX") + ""),
                Integer.parseInt(jo.get("toY") + "")));
      } else if (event.equals(EventUnitShow.EVENT)) {
        eventUnitShowList.add(
            new EventUnitShow(
                Integer.parseInt(jo.get("unitId") + ""),
                Integer.parseInt(jo.get("side") + ""),
                jo.get("type") + "",
                Integer.parseInt(jo.get("x") + ""),
                Integer.parseInt(jo.get("y") + ""),
                Boolean.parseBoolean(jo.get("isArmed") + ""),
                Boolean.parseBoolean(jo.get("isMobile") + "")));
      } else if (event.equals(EventUnitHide.EVENT)) {
        eventUnitHideList.add(new EventUnitHide(Integer.parseInt(jo.get("unitId") + "")));
      } else if (event.equals(EventUnitFire.EVENT)) {
        eventUnitFireList.add(new EventUnitFire(Integer.parseInt(jo.get("unitId") + "")));
      } else if (event.equals(EventBoom.EVENT)) {
        eventBoomList.add(
            new EventBoom(Integer.parseInt(jo.get("x") + ""), Integer.parseInt(jo.get("y") + "")));
      } else if (event.equals(EventUnitRotateTurret.EVENT)) {
        eventUnitRotateTurrerList.add(
            new EventUnitRotateTurret(
                Integer.parseInt(jo.get("unitId") + ""),
                Integer.parseInt(jo.get("turretLook") + "")));
      } else if (event.equals(EventUnitHit.EVENT)) {
        eventUnitHitList.add(
            new EventUnitHit(
                Integer.parseInt(jo.get("unitId") + ""),
                Boolean.parseBoolean(jo.get("isArmed") + ""),
                Boolean.parseBoolean(jo.get("isMobile") + ""),
                Boolean.parseBoolean(jo.get("isAlive") + "")));
      } else if (event.equals(EventFlag.EVENT)) {
        eventFlagList.add(
            new EventFlag(
                Integer.parseInt(jo.get("id") + ""),
                Integer.parseInt(jo.get("side") + ""),
                Integer.parseInt(jo.get("state") + "")));
      } else if (event.equals(EventCoins.EVENT)) {
        eventCoinsList.add(new EventCoins(Integer.parseInt(jo.get("coins") + "")));
      } else if (event.equals(EventUnitBuild.EVENT)) {
        eventUnitBuildList.add(
            new EventUnitBuild(
                Integer.parseInt(jo.get("unitId") + ""),
                jo.get("type") + "",
                Integer.parseInt(jo.get("x") + ""),
                Integer.parseInt(jo.get("y") + "")));
      }
    }

    _sides
        .get(side)
        .processTick(
            new WorldTick(
                side,
                eventBoomList,
                eventCoinsList,
                eventFlagList,
                eventUnitBuildList,
                eventUnitFireList,
                eventUnitHideList,
                eventUnitHitList,
                eventUnitMoveList,
                eventUnitRotateTurrerList,
                eventUnitShowList));

    sendReady(side);
  }
Пример #26
0
  public void parseJSON(String singleLine) {
    JSONObject json = (JSONObject) JSONValue.parse(singleLine);
    JSONArray jry = (JSONArray) json.get("statuses");
    if (jry == null) {
      return;
    }

    for (Object jry1 : jry) {
      JSONObject obj, pobj;
      obj = (JSONObject) jry1;
      pobj = (JSONObject) obj.get("user");
      JsonTweet jt = new JsonTweet(obj.get("id_str").toString(), pobj.get("id_str").toString());
      jt.setText(obj.get("text").toString());
      jt.setRetweetCount(obj.get("retweet_count").toString());
      jt.setFavoriteCount(obj.get("favorite_count").toString());
      if (obj.get("contributors") != null) {
        jt.setContributors(obj.get("contributors").toString());
      }
      jt.setLang(obj.get("lang").toString());
      if (obj.get("geo") != null) {
        jt.setGeo(obj.get("geo").toString());
      }
      jt.setSource(obj.get("source").toString());
      jt.setCreatedAt(obj.get("created_at").toString());
      if (obj.get("place") != null) {
        jt.setPlace(obj.get("place").toString());
      }
      jt.setRetweeted(obj.get("retweeted").toString());
      jt.setTruncated(obj.get("truncated").toString());
      jt.setFavorited(obj.get("favorited").toString());
      if (obj.get("coordinates") != null) {
        jt.setCoordinates(obj.get("coordinates").toString());
      }
      JsonTweetUser jtu = jt.getUser();
      jtu.setLocation(pobj.get("location").toString());
      jtu.setDefaultProfile(pobj.get("default_profile").toString());
      jtu.setBackgroundTile(pobj.get("profile_background_tile").toString());
      jtu.setStatusesCount(pobj.get("statuses_count").toString());
      jtu.setLang(pobj.get("lang").toString());
      jtu.setFollowing(pobj.get("following").toString());
      jtu.setProtected(pobj.get("protected").toString());
      jtu.setFavoriteCount(pobj.get("favourites_count").toString());
      jtu.setDescription(pobj.get("description").toString());
      jtu.setVerified(pobj.get("verified").toString());
      jtu.setContributorsEnabled(pobj.get("contributors_enabled").toString());
      jtu.setname(pobj.get("name").toString());
      jtu.setCreatedAt(pobj.get("created_at").toString());
      jtu.setTranslationEnabled(pobj.get("is_translation_enabled").toString());
      jtu.setDefaultProfileImg(pobj.get("default_profile_image").toString());
      jtu.setFollowerCount(pobj.get("followers_count").toString());
      if (pobj.get("has_extended_profile") != null) {
        jtu.setExtendedProfile(pobj.get("has_extended_profile").toString());
      }
      jtu.setProfileImg(pobj.get("profile_image_url_https").toString());
      jtu.setGeoEnabled(pobj.get("geo_enabled").toString());
      jtu.setProfileBackgroundImg(pobj.get("profile_background_image_url_https").toString());
      if (pobj.get("url") != null) {
        jtu.setUrl(pobj.get("url").toString());
      }
      if (pobj.get("utc_offset") != null) {
        jtu.setUtcOffset(pobj.get("utc_offset").toString());
      }
      if (pobj.get("time_zone") != null) {
        jtu.setTimeZone(pobj.get("time_zone").toString());
      }
      if (pobj.get("notifications") != null) {
        jtu.setNotifications(pobj.get("notifications").toString());
      }
      jtu.setFiendCount(pobj.get("friends_count").toString());
      jtu.setScreenName(pobj.get("screen_name").toString());
      jtu.setListedCount(pobj.get("listed_count").toString());
      jtu.setIsTranslator(pobj.get("is_translator").toString());
      tweets.add(jt);
    }
  }
Пример #27
0
  private Object getObject(String path) {
    this.hitCache = false;
    if (cache.containsKey(path)) {
      this.hitCache = true;
      return cache.get(path);
    }
    String[] params = path.split("\\.");
    JSONObject json = this.root;
    JSONArray jsonArray = null;
    String currentPath = "";
    for (int i = 0; i < params.length - 1; i++) {
      String param = params[i];
      if (cachePolicy.equals(CachePolicy.CACHE_ALL_LEVELS)) {
        if (!currentPath.isEmpty()) {
          currentPath += ".";
        }
        currentPath += param;
      }
      if (param.startsWith("$")) {
        if (jsonArray == null) {
          throw new JSONOperationErrorException("Not illegal syntax at this place: " + param);
        }
        int index = getIndex(param);
        json = (JSONObject) jsonArray.get(index);
        jsonArray = null;
      } else if (param.contains("[")) {
        int find = param.indexOf("[");
        String newParam = param.substring(0, find);
        String s = param.substring(find + 1, param.indexOf("]"));
        if (s.isEmpty()) {
          jsonArray = (JSONArray) json.get(newParam);
          json = null;
        } else {
          int index = Integer.parseInt(s);
          json = (JSONObject) ((JSONArray) json.get(newParam)).get(index);
          jsonArray = null;
        }
      } else {
        Object obj = json.get(param);
        if (obj instanceof JSONObject) {
          json = (JSONObject) obj;
          jsonArray = null;
        } else if (obj instanceof JSONArray) {
          jsonArray = (JSONArray) obj;
          json = null;
        } else if (obj == null) {
          throw new IllegalStateException("json object is null");
        } else {
          throw new IllegalStateException(
              "json object ('" + param + "') has wrong type: " + obj.getClass());
        }
      }
      if (cachePolicy.equals(CachePolicy.CACHE_ALL_LEVELS)) {
        saveToCache(currentPath, json);
      }
    }
    String name = params[params.length - 1];

    Object value;
    if (name.startsWith("$")) {
      if (jsonArray == null) {
        throw new JSONOperationErrorException("Not illegal syntax at this place: " + name);
      }
      int index = getIndex(name);
      value = jsonArray.get(index);
    } else {
      value = json.get(name);
    }

    saveToCache(path, value);

    return value;
  }