Example #1
0
    public void assertMatch(JSONObject json) {
      assertEquals(mPayloadType, json.optInt("type"));
      assertEquals(mClockRate, json.optInt("clockRate"));
      assertEquals(mEncodingName, json.optString("encodingName"));
      if (mChannels > 0) {
        assertEquals(mChannels, json.optInt("channels"));
      }
      if (mNackPli != null) {
        json.has("nackpli");
        assertEquals((boolean) mNackPli, json.optBoolean("nackpli"));
      }
      if (mNack != null) {
        json.has("nack");
        assertEquals((boolean) mNack, json.optBoolean("nack"));
      }
      if (mCcmFir != null) {
        json.has("ccmfir");
        assertEquals((boolean) mCcmFir, json.optBoolean("ccmfir"));
      }
      JSONObject jsonParameters = json.optJSONObject("parameters");
      if (mParameters != null) {
        assertNotNull(jsonParameters);
        assertEquals(mParameters.size(), jsonParameters.length());

        for (Map.Entry<String, Object> parameter : mParameters.entrySet()) {
          assertTrue(jsonParameters.has(parameter.getKey()));
          assertEquals(parameter.getValue(), jsonParameters.opt(parameter.getKey()));
        }
      } else {
        assertTrue(jsonParameters == null || jsonParameters.length() == 0);
      }
    }
Example #2
0
  @Override
  public void action(final Event<JSONObject> event) throws EventException {
    final JSONObject data = event.getData();
    LOGGER.log(
        Level.DEBUG,
        "Processing an event[type={0}, data={1}] in listener[className={2}]",
        new Object[] {event.getType(), data, CommentSender.class.getName()});
    try {
      if (data.optBoolean(Common.FROM_CLIENT)) {
        return;
      }

      final JSONObject originalArticle = data.getJSONObject(Article.ARTICLE);

      if (!originalArticle.optBoolean(Article.ARTICLE_SYNC_TO_CLIENT)) {
        return;
      }

      final LatkeBeanManager beanManager = Lifecycle.getBeanManager();
      final UserQueryService userQueryService = beanManager.getReference(UserQueryService.class);

      final String authorId = originalArticle.optString(Article.ARTICLE_AUTHOR_ID);
      final JSONObject author = userQueryService.getUser(authorId);
      final String clientURL = author.optString(UserExt.USER_B3_CLIENT_ADD_COMMENT_URL);

      if (Strings.isEmptyOrNull(clientURL)) {
        return;
      }

      final JSONObject originalComment = data.getJSONObject(Comment.COMMENT);
      final String commenterId = originalComment.optString(Comment.COMMENT_AUTHOR_ID);
      final JSONObject commenter = userQueryService.getUser(commenterId);

      final HTTPRequest httpRequest = new HTTPRequest();
      httpRequest.setURL(new URL(clientURL));
      httpRequest.setRequestMethod(HTTPRequestMethod.PUT);
      final JSONObject requestJSONObject = new JSONObject();
      final JSONObject comment =
          new JSONObject(
              originalComment,
              new String[] {Comment.COMMENT_AUTHOR_EMAIL, Comment.COMMENT_CONTENT, Keys.OBJECT_ID});

      comment.put(Comment.COMMENT_T_AUTHOR_NAME, commenter.optString(User.USER_NAME));
      comment.put(UserExt.USER_B3_KEY, author.optString(UserExt.USER_B3_KEY));
      comment.put(Comment.COMMENT_T_AUTHOR_URL, commenter.optString(User.USER_URL));
      comment.put(
          Comment.COMMENT_ON_ARTICLE_ID,
          originalArticle.optString(Article.ARTICLE_CLIENT_ARTICLE_ID));
      comment.put(Comment.COMMENT_T_SYMPHONY_ID, originalArticle.optString(Keys.OBJECT_ID));

      requestJSONObject.put(Comment.COMMENT, comment);
      httpRequest.setPayload(requestJSONObject.toString().getBytes("UTF-8"));

      urlFetchService.fetchAsync(httpRequest);
    } catch (final Exception e) {
      LOGGER.log(Level.ERROR, "Sends a comment to client error: {0}", e.getMessage());
    }

    LOGGER.log(Level.DEBUG, "Sent a comment to client");
  }
Example #3
0
  protected static Colony fromJSON(JSONObject json) throws JSONException {
    Colony colony = new Colony(json.getString("id"));
    colony.setX(json.getDouble("x"));
    colony.setY(json.getDouble("y"));

    colony.setAttribute("census.visited", json.optBoolean("visited", false));
    colony.setAttribute("census.active", json.optBoolean("active", false));

    final Object updatedObject = json.opt("modified");
    if (updatedObject == null
        || JSONObject.NULL.equals(updatedObject)
        || !(updatedObject instanceof String)) {
      // Set to now
      colony.setUpdateTime(DateTime.now());
    } else {
      try {
        final DateTime updatedTime =
            ISODateTimeFormat.dateTimeParser().parseDateTime((String) updatedObject);
        colony.setUpdateTime(updatedTime);
      } catch (IllegalArgumentException e) {
        // Could not parse time
        // Set to now
        colony.setUpdateTime(DateTime.now());
      }
    }
    return colony;
  }
  private boolean handlePost(HttpServletRequest request, HttpServletResponse response, String path)
      throws IOException, JSONException, ServletException, URISyntaxException, CoreException {
    Path p = new Path(path);
    if (p.segment(0).equals("file")) { // $NON-NLS-1$
      // handle adding new remote
      // expected path: /git/remote/file/{path}
      return addRemote(request, response, path);
    } else {
      JSONObject requestObject = OrionServlet.readJSONRequest(request);
      boolean fetch = Boolean.parseBoolean(requestObject.optString(GitConstants.KEY_FETCH, null));
      String srcRef = requestObject.optString(GitConstants.KEY_PUSH_SRC_REF, null);
      boolean tags = requestObject.optBoolean(GitConstants.KEY_PUSH_TAGS, false);
      boolean force = requestObject.optBoolean(GitConstants.KEY_FORCE, false);

      // prepare creds
      GitCredentialsProvider cp = GitUtils.createGitCredentialsProvider(requestObject);

      // if all went well, continue with fetch or push
      if (fetch) {
        return fetch(request, response, cp, path, force);
      } else if (srcRef != null) {
        return push(request, response, path, cp, srcRef, tags, force);
      } else {
        return statusHandler.handleRequest(
            request,
            response,
            new ServerStatus(
                IStatus.ERROR,
                HttpServletResponse.SC_BAD_REQUEST,
                "Only Fetch:true is currently supported.",
                null));
      }
    }
  }
Example #5
0
  private static void populateEventFromJSON(AccessibilityEvent event, JSONObject message) {
    final JSONArray textArray = message.optJSONArray("text");
    if (textArray != null) {
      for (int i = 0; i < textArray.length(); i++) event.getText().add(textArray.optString(i));
    }

    event.setContentDescription(message.optString("description"));
    event.setEnabled(message.optBoolean("enabled", true));
    event.setChecked(message.optBoolean("checked"));
    event.setPassword(message.optBoolean("password"));
    event.setAddedCount(message.optInt("addedCount", -1));
    event.setRemovedCount(message.optInt("removedCount", -1));
    event.setFromIndex(message.optInt("fromIndex", -1));
    event.setItemCount(message.optInt("itemCount", -1));
    event.setCurrentItemIndex(message.optInt("currentItemIndex", -1));
    event.setBeforeText(message.optString("beforeText"));
    if (Versions.feature14Plus) {
      event.setToIndex(message.optInt("toIndex", -1));
      event.setScrollable(message.optBoolean("scrollable"));
      event.setScrollX(message.optInt("scrollX", -1));
      event.setScrollY(message.optInt("scrollY", -1));
    }
    if (Versions.feature15Plus) {
      event.setMaxScrollX(message.optInt("maxScrollX", -1));
      event.setMaxScrollY(message.optInt("maxScrollY", -1));
    }
  }
Example #6
0
  @Override
  public void parseJson(String jsonStr) {
    JSONObject jsonObject = getJsonObject(jsonStr);
    this.setAge(jsonObject.optString("age"));
    this.setImgUrl(jsonObject.optString("avatar"));
    this.setNickname(jsonObject.optString("nickname"));
    this.setHeight(jsonObject.optString("height"));
    this.setOnline(jsonObject.optInt("online"));
    this.setImgUrl(jsonObject.optString("avatar"));
    this.setUid(jsonObject.optLong("uid"));
    this.setProvince(jsonObject.optString("province"));
    this.setCity(jsonObject.optString("city"));
    this.setGrade(jsonObject.optInt("grade"));
    this.gender = jsonObject.optInt("gender");

    this.hasLocalTag = jsonObject.optBoolean("hasLocalTag");
    if (hasLocalTag) {
      this.localTag = new LocateTag();
      localTag.parseJson(jsonObject.optString("localTag"));
    }
    this.score = jsonObject.optInt("score");
    this.lat = jsonObject.optDouble("lat");
    this.lng = jsonObject.optDouble("lng");
    this.distance = LocationMgr.getDistance(lng, lat);
    this.certify_level = jsonObject.optInt("certify_level");
    this.setFollowed(jsonObject.optBoolean("following"));
    this.setTm(jsonObject.optString("tm"));
    JSONObject JsonStatus = jsonObject.optJSONObject("status");
    if (JsonStatus != null) {
      this.setShow(JsonStatus.optString("show"));
    }
  }
  /**
   * Creates a new instance of a GameItem with the given data
   *
   * @param inventory The inventory this item is contained in
   * @param itemData The data specifying this item
   * @throws WebApiException on Web API errors
   */
  public GameItem(GameInventory inventory, JSONObject itemData) throws SteamCondenserException {
    this.inventory = inventory;

    try {
      this.defindex = itemData.getInt("defindex");
      this.backpackPosition = (int) itemData.getLong("inventory") & 0xffff;
      this.count = itemData.getInt("quantity");
      this.craftable = !itemData.optBoolean("flag_cannot_craft");
      this.id = itemData.getInt("id");
      this.itemClass = this.getSchemaData().getString("item_class");
      this.itemSet =
          this.inventory
              .getItemSchema()
              .getItemSets()
              .get(this.getSchemaData().optString("item_set"));
      this.level = itemData.getInt("level");
      this.name = this.getSchemaData().getString("item_name");
      this.preliminary = (itemData.getLong("inventory") & 0x40000000) != 0;
      this.originalId = itemData.getInt("original_id");
      this.quality = this.inventory.getItemSchema().getQualities().get(itemData.getInt("quality"));
      this.tradeable = !itemData.optBoolean("flag_cannot_trade");
      this.type = this.getSchemaData().getString("item_type_name");

      if (itemData.has("origin")) {
        this.origin = this.inventory.getItemSchema().getOrigins().get(itemData.getInt("origin"));
      }

      JSONArray attributesData = this.getSchemaData().optJSONArray("attributes");
      if (attributesData == null) {
        attributesData = new JSONArray();
      }
      if (itemData.has("attributes")) {
        JSONArray itemAttributes = itemData.getJSONArray("attributes");
        for (int i = 0; i < itemAttributes.length(); i++) {
          attributesData.put(itemAttributes.get(i));
        }
      }

      this.attributes = new ArrayList<JSONObject>();
      for (int i = 0; i < attributesData.length(); i++) {
        JSONObject attributeData = attributesData.getJSONObject(i);
        Object attributeKey = attributeData.opt("defindex");
        if (attributeKey == null) {
          attributeKey = attributeData.opt("name");
        }

        if (attributeKey != null) {
          JSONObject schemaAttributeData =
              inventory.getItemSchema().getAttributes().get(attributeKey);
          for (String key : JSONObject.getNames(schemaAttributeData)) {
            attributeData.put(key, schemaAttributeData.get(key));
          }
          this.attributes.add(attributeData);
        }
      }
    } catch (JSONException e) {
      throw new WebApiException("Could not parse JSON data.", e);
    }
  }
Example #8
0
 private IGPSObject parseWATCH(final JSONObject json) {
   IGPSObject gps;
   final WatchObject watch = new WatchObject();
   watch.setEnable(json.optBoolean("enable", true));
   watch.setDump(json.optBoolean("json", false));
   gps = watch;
   return gps;
 }
Example #9
0
 private void assertRtcpMux(JSONObject mediaDescription, boolean rtcpMux) {
   JSONObject rtcp = mediaDescription.optJSONObject("rtcp");
   if (rtcpMux) {
     assertNotNull(rtcp);
     assertTrue(rtcp.optBoolean("mux", false));
   } else {
     assertTrue(rtcp == null || !rtcp.optBoolean("mux", false));
   }
 }
Example #10
0
 public ao a(Z paramZ, JSONObject paramJSONObject) throws JSONException {
   JSONObject localJSONObject1 = paramJSONObject.getJSONObject("app");
   String str1 = localJSONObject1.getString("identifier");
   String str2 = localJSONObject1.getString("status");
   String str3 = localJSONObject1.getString("url");
   String str4 = localJSONObject1.getString("reports_url");
   boolean bool1 = localJSONObject1.optBoolean("update_required", false);
   boolean bool2 = localJSONObject1.has("icon");
   c localc = null;
   if (bool2) {
     boolean bool3 = localJSONObject1.getJSONObject("icon").has("hash");
     localc = null;
     if (bool3) {
       JSONObject localJSONObject4 = localJSONObject1.getJSONObject("icon");
       localc =
           new c(
               localJSONObject4.getString("hash"),
               localJSONObject4.getInt("width"),
               localJSONObject4.getInt("height"));
     }
   }
   i locali = new i(str1, str2, str3, str4, bool1, localc);
   JSONObject localJSONObject2 = paramJSONObject.getJSONObject("settings");
   ar localar =
       new ar(
           localJSONObject2.optBoolean("collect_reports", true),
           localJSONObject2.optInt("cache_duration", 3600),
           localJSONObject2.optInt("log_buffer_size", 64000),
           localJSONObject2.optInt("max_chained_exception_depth", 8),
           localJSONObject2.optInt("max_custom_exception_events", 64),
           localJSONObject2.optInt("max_custom_key_value_pairs", 64),
           localJSONObject2.optInt("identifier_mask", 255),
           localJSONObject2.optBoolean("send_session_without_crash", false));
   JSONObject localJSONObject3 = paramJSONObject.getJSONObject("prompt");
   aj localaj =
       new aj(
           localJSONObject3.getBoolean("enabled"),
           localJSONObject3.optString("title", "Send Crash Report?"),
           localJSONObject3.optString(
               "message",
               "Looks like we crashed! Please help us fix the problem by sending a crash report."),
           localJSONObject3.optString("send_button_title", "Send"),
           localJSONObject3.optBoolean("show_cancel_button", true),
           localJSONObject3.optString("cancel_button_title", "Don't Send"),
           localJSONObject3.optBoolean("show_always_send_button", true),
           localJSONObject3.optString("always_send_button_title", "Always Send"));
   long l1 = localar.b();
   if (paramJSONObject.has("expires_at")) ;
   for (long l2 = paramJSONObject.getLong("expires_at"); ; l2 = paramZ.a() + l1 * 1000L)
     return new ao(l2, locali, localar, localaj);
 }
  private void addMailboxList(JSONObject response) {
    JSONObject inbox = response.optJSONObject("inbox");
    if (inbox != null) {
      messageCount = inbox.optInt("message_count");
      unreadCount = inbox.optInt("unread_count");

      m_mailboxUnread.setText(String.valueOf(unreadCount));
      m_mailboxUnread.setVisibility(unreadCount > 0 ? View.VISIBLE : View.GONE);
      m_application.setMailUnreadCount(unreadCount);

      currentPage = inbox.optInt("page");
      JSONArray messages = inbox.optJSONArray("messages");
      if (messages != null) {
        for (int i = 0; i < messages.length(); i++) {
          JSONObject message = messages.optJSONObject(i);
          glitchMail mail = new glitchMail();

          mail.id = message.optInt("message_id");
          mail.currants = message.optInt("currants");
          mail.text = message.optString("text");
          if (mail.text.equalsIgnoreCase("null")) {
            mail.text = "";
          }
          mail.received = message.optLong("received");
          mail.replied = message.optInt("replied") == 1;
          mail.is_expedited = message.optBoolean("is_expedited");
          mail.is_read = message.optBoolean("is_read");

          JSONObject sender = message.optJSONObject("sender");
          if (sender != null) {
            mail.sender_tsid = sender.optString("tsid");
            mail.sender_label = sender.optString("label");
            mail.sender_avatar = sender.optString("singles_url");
          }

          JSONObject item = message.optJSONObject("item");
          if (item != null) {
            mail.item = new glitchMailItem();
            mail.item.tsid = item.optString("class_tsid");
            mail.item.name = item.optString("name");
            mail.item.count = item.optInt("count");
            mail.item.desc = item.optString("desc");
            mail.item.icon = item.optString("icon");
          }

          m_mailList.add(mail);
        }
      }
    }
  }
  public void onUserUpdated() {
    if (mUser == null) return;

    // Map to the profile view items in the layout
    mCommonItems = addItemsFromLayout((ViewGroup) findViewById(R.id.common_list));
    mTutorItems = addItemsFromLayout((ViewGroup) findViewById(R.id.tutor_list));

    loadAvailability();

    // Enable/disable tutor-only fields based on whether we are a tutor or not
    CheckBox isTutor = (CheckBox) findViewById(R.id.is_tutor_checkbox);
    isTutor.setOnCheckedChangeListener(this);
    isTutor.setChecked(mUser.optBoolean("tutor_flag"));
    Util.setGroupEnabled((ViewGroup) findViewById(R.id.tutor_list), mUser.optBoolean("tutor_flag"));
  }
Example #13
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
  public void selectKind(int kind) {
    this.kind = kind;
    JSONObject json = defMap.get(name);

    try {
      texture(json.getString("texture"));

      int width = json.getInt("width");

      TextureFilm film = new TextureFilm(texture, width, json.getInt("height"));

      bloodColor = json.optInt("bloodColor", 0xFFBB0000);
      levitating = json.optBoolean("levitating", false);
      framesInRow = texture.width / width;

      idle = readAnimation(json, "idle", film);
      run = readAnimation(json, "run", film);
      attack = readAnimation(json, "attack", film);
      die = readAnimation(json, "die", film);
      zap = attack.clone();

    } catch (Exception e) {
      GLog.w("Something bad happens when loading %s", name);
    }

    play(idle);
  }
  @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 void onDone(JSONObject paramJSONObject) {
   WebViewActivity.access$000(this$0, "onDone");
   this$0.setResult(-1);
   String str1 = paramJSONObject.optString("title");
   String str2 = paramJSONObject.optString("subtitle");
   boolean bool = paramJSONObject.optBoolean("has_details");
   try {
     paramJSONObject = paramJSONObject.getString("url");
     if (TextUtils.isEmpty(paramJSONObject)) {
       AppData.a("WEBVIEW", "No URL sent with onDone", new Object[0]);
       WebViewActivity.access$300(this$0, true);
       this$0.finish();
       return;
     }
   } catch (JSONException paramJSONObject) {
     AppData.a("WEBVIEW", "Unexpected result from onDone", new Object[0]);
     WebViewActivity.access$300(this$0, true);
     this$0.finish();
     return;
   }
   Intent localIntent = new Intent("android.intent.action.VIEW");
   localIntent.setData(Uri.parse(paramJSONObject));
   localIntent.putExtra("com.yelp.android.webview_done", true);
   localIntent.putExtra("com.yelp.android.webview_title", str1);
   localIntent.putExtra("com.yelp.android.webview_subtitle", str2);
   localIntent.putExtra("com.yelp.android.webview_has_details", bool);
   WebViewActivity.access$400(this$0);
   this$0.enableLoading();
   new ch("webview_done", new WebViewActivity.ForceDirtySessionCallback(this$0, localIntent))
       .execute(new Void[0]);
 }
  @JavascriptInterface
  public void logEvent(String json) {
    try {
      JSONObject event = new JSONObject(json);

      String name = event.getString(JS_KEY_EVENT_NAME);
      EventType eventType = convertEventType(event.getInt(JS_KEY_EVENT_CATEGORY));
      Map<String, String> eventAttributes =
          convertToMap(event.optJSONObject(JS_KEY_EVENT_ATTRIBUTES));

      int messageType = event.getInt(JS_KEY_EVENT_DATATYPE);
      switch (messageType) {
        case JS_MSG_TYPE_PE:
          MParticle.getInstance().logEvent(name, eventType, eventAttributes);
          break;
        case JS_MSG_TYPE_PV:
          MParticle.getInstance().logScreen(name, eventAttributes);
          break;
        case JS_MSG_TYPE_OO:
          MParticle.getInstance().setOptOut(event.optBoolean(JS_KEY_OPTOUT));
          break;
        case JS_MSG_TYPE_CR:
          MParticle.getInstance().logError(name, eventAttributes);
          break;
        case JS_MSG_TYPE_SE:
        case JS_MSG_TYPE_SS:
          // swallow session start and end events, the native SDK will handle those.
        default:
      }

    } catch (JSONException jse) {
      ConfigManager.log(MParticle.LogLevel.WARNING, String.format(errorMsg, jse.getMessage()));
    }
  }
Example #18
0
 private IGPSObject parseSUBFRAME(final JSONObject json) throws ParseException {
   IGPSObject gps;
   final SUBFRAMEObject subframe = new SUBFRAMEObject();
   subframe.setDevice(json.optString("device", null));
   subframe.setMSBs(json.optInt("TOW17"));
   subframe.setSatelliteNumber(json.optInt("tSV"));
   subframe.setSubframeNumber(json.optInt("frame"));
   subframe.setScaled(json.optBoolean("scaled", false));
   subframe.setPageid(json.optInt("pageid"));
   if (json.has("system_message")) {
     subframe.setSystemMessage(json.optString("system_message"));
   } else if (json.has(ALMANACObject.NAME)) {
     subframe.setAlmanac((ALMANACObject) this.parse(json.optJSONObject(ALMANACObject.NAME)));
   } else if (json.has(EPHEM1Object.NAME)) {
     subframe.setEphem1((EPHEM1Object) this.parse(json.optJSONObject(EPHEM1Object.NAME)));
   } else if (json.has(EPHEM2Object.NAME)) {
     subframe.setEphem2((EPHEM2Object) this.parse(json.optJSONObject(EPHEM2Object.NAME)));
   } else if (json.has(EPHEM3Object.NAME)) {
     subframe.setEphem3((EPHEM3Object) this.parse(json.optJSONObject(EPHEM3Object.NAME)));
   } else if (json.has(ERDObject.NAME)) {
     subframe.setErd((ERDObject) this.parse(json.optJSONObject(ERDObject.NAME)));
   } else if (json.has(HEALTHObject.NAME)) {
     subframe.setHealth((HEALTHObject) this.parse(json.optJSONObject(HEALTHObject.NAME)));
   } else if (json.has(HEALTH2Object.NAME)) {
     subframe.setHealth2((HEALTH2Object) this.parse(json.optJSONObject(HEALTH2Object.NAME)));
   } else if (json.has(IONOObject.NAME)) {
     subframe.setIono((IONOObject) this.parse(json.optJSONObject(IONOObject.NAME)));
   } else {
     AbstractResultParser.LOG.error("Unknown subframe: {}", json.toString());
   }
   gps = subframe;
   return gps;
 }
 @Override
 public boolean importValue(JSONObject json, String key, SharedPreferences.Editor editor) {
   final Preference preference = supportedMap.get(key);
   if (preference == null || !preference.exportable()) return false;
   switch (preference.type()) {
     case BOOLEAN:
       editor.putBoolean(key, json.optBoolean(key, preference.defaultBoolean()));
       break;
     case INT:
       editor.putInt(key, json.optInt(key, preference.defaultInt()));
       break;
     case LONG:
       editor.putLong(key, json.optLong(key, preference.defaultLong()));
       break;
     case FLOAT:
       editor.putFloat(key, (float) json.optDouble(key, preference.defaultFloat()));
       break;
     case STRING:
       editor.putString(key, json.optString(key, preference.defaultString()));
       break;
     default:
       break;
   }
   return true;
 }
  // Handle actionbar menu actions
  public void onSaveButton(MenuItem item) {
    try {
      // Look up the address field and add the lat/lon
      if (!mUser.isNull("loc_address") && !mUser.optString("loc_address").isEmpty()) {
        Geocoder g = new Geocoder(this, Locale.US);
        List<Address> result = g.getFromLocationName(mUser.optString("loc_address"), 1);

        if (!result.isEmpty()) {
          mUser.put("loc_lat", result.get(0).getLatitude());
          mUser.put("loc_lon", result.get(0).getLongitude());

          Log.d(TAG, "Put lat: " + result.get(0).getLatitude());
          Log.d(TAG, "Put lon: " + result.get(0).getLongitude());
        }
      }

      // Don't send picture if we didn't update it
      if (!mUser.optBoolean("picture_updated")) {
        mUser.remove("picture");
      }

      // Save all items to our user object and send it to the database
      saveAllItems();
      mUser.put("action", "update_user");
      new DatabaseRequest(mUser, this, this, true);
    } catch (JSONException e) {
      Log.e(TAG, e.toString(), e);
    } catch (IOException e) {
      Log.e(TAG, e.toString(), e);
    }
  }
  @Override
  public JSONObject getFileForLocalURL(
      LocalFilesystemURL inputURL, String path, JSONObject options, boolean directory)
      throws FileExistsException, IOException, TypeMismatchException, EncodingException,
          JSONException {
    if (options != null && options.optBoolean("create")) {
      throw new UnsupportedOperationException("Assets are read-only");
    }

    // Check whether the supplied path is absolute or relative
    if (directory && !path.endsWith("/")) {
      path += "/";
    }

    LocalFilesystemURL requestedURL;
    if (path.startsWith("/")) {
      requestedURL = localUrlforFullPath(normalizePath(path));
    } else {
      requestedURL = localUrlforFullPath(normalizePath(inputURL.path + "/" + path));
    }

    // Throws a FileNotFoundException if it doesn't exist.
    getFileMetadataForLocalURL(requestedURL);

    boolean isDir = isDirectory(requestedURL.path);
    if (directory && !isDir) {
      throw new TypeMismatchException("path doesn't exist or is file");
    } else if (!directory && isDir) {
      throw new TypeMismatchException("path doesn't exist or is directory");
    }

    // Return the directory
    return makeEntryForURL(requestedURL);
  }
 public PluginResult dispatch(DatabaseActionDispatcher.Context paramContext)
   throws Throwable
 {
   JSONObject localJSONObject = getOptions(paramContext);
   Object localObject1 = getToUpdate(paramContext);
   boolean bool = false;
   if (localJSONObject != null)
     bool = localJSONObject.optBoolean("isRefresh");
   ReplaceAction localReplaceAction;
   if ((localObject1 instanceof JSONObject))
     localReplaceAction = new ReplaceAction((JSONObject)localObject1, bool, null);
   try
   {
     while (true)
     {
       Object localObject3 = paramContext.performWritableDatabaseAction(localReplaceAction);
       localObject2 = localObject3;
       if (!(localObject2 instanceof Integer))
         break;
       return new PluginResult(PluginResult.Status.OK, ((Integer)localObject2).intValue());
       localReplaceAction = new ReplaceAction((JSONArray)localObject1, bool, null);
     }
     return new JacksonSerializedPluginResult(PluginResult.Status.ERROR, (JSONArray)localObject2);
   }
   catch (Throwable localThrowable)
  /**
   * Update prefs that depend on home panels state.
   *
   * <p>This includes the prefs that keep track of whether bookmarks or history are enabled, which
   * are used to control the visibility of the corresponding menu items.
   */
  private void updatePrefsFromConfig(JSONArray panelsArray) {
    final SharedPreferences prefs = GeckoSharedPrefs.forProfile(mContext);
    if (!prefs.contains(HomeConfig.PREF_KEY_BOOKMARKS_PANEL_ENABLED)
        || !prefs.contains(HomeConfig.PREF_KEY_HISTORY_PANEL_ENABLED)) {

      final String bookmarkType = PanelType.BOOKMARKS.toString();
      final String historyType = PanelType.COMBINED_HISTORY.toString();
      try {
        for (int i = 0; i < panelsArray.length(); i++) {
          final JSONObject panelObj = panelsArray.getJSONObject(i);
          final String panelType = panelObj.optString(PanelConfig.JSON_KEY_TYPE, null);
          if (panelType == null) {
            break;
          }
          final boolean isDisabled = panelObj.optBoolean(PanelConfig.JSON_KEY_DISABLED, false);
          if (bookmarkType.equals(panelType)) {
            prefs
                .edit()
                .putBoolean(HomeConfig.PREF_KEY_BOOKMARKS_PANEL_ENABLED, !isDisabled)
                .apply();
          } else if (historyType.equals(panelType)) {
            prefs.edit().putBoolean(HomeConfig.PREF_KEY_HISTORY_PANEL_ENABLED, !isDisabled).apply();
          }
        }
      } catch (JSONException e) {
        Log.e(LOGTAG, "Error fetching panel from config to update prefs");
      }
    }
  }
  /**
   * Create a notification as the visible part to be able to put the service in a foreground state.
   *
   * @return A local ongoing notification which pending intent is bound to the main activity.
   */
  @SuppressLint("NewApi")
  @SuppressWarnings("deprecation")
  private Notification makeNotification() {
    JSONObject settings = BackgroundMode.getSettings();
    Context context = getApplicationContext();
    String pkgName = context.getPackageName();
    Intent intent = context.getPackageManager().getLaunchIntentForPackage(pkgName);

    Notification.Builder notification =
        new Notification.Builder(context)
            .setContentTitle(settings.optString("title", "Title"))
            .setContentText(settings.optString("text", "Content"))
            .setTicker(settings.optString("ticker", "Ticker"))
            .setOngoing(true)
            .setSmallIcon(getIconResId());

    if (intent != null && settings.optBoolean("resume")) {

      PendingIntent contentIntent =
          PendingIntent.getActivity(
              context, NOTIFICATION_ID, intent, PendingIntent.FLAG_CANCEL_CURRENT);

      notification.setContentIntent(contentIntent);
    }

    if (Build.VERSION.SDK_INT < 16) {
      // Build notification for HoneyComb to ICS
      return notification.getNotification();
    } else {
      // Notification for Jellybean and above
      return notification.build();
    }
  }
  public static StatusList parse(String jsonString) {
    if (TextUtils.isEmpty(jsonString)) {
      return null;
    }

    StatusList statuses = new StatusList();
    try {
      JSONObject jsonObject = new JSONObject(jsonString);
      statuses.hasvisible = jsonObject.optBoolean("hasvisible", false);
      statuses.previous_cursor = jsonObject.optString("previous_cursor", "0");
      statuses.next_cursor = jsonObject.optString("next_cursor", "0");
      statuses.total_number = jsonObject.optInt("total_number", 0);

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

    return statuses;
  }
  public UserSmart(JSONObject objUser) {
    super();
    this.checkInId = objUser.optInt("checkin_id");
    this.userId = objUser.optInt("id");
    this.nickName = objUser.optString("nickname");
    this.statusText = objUser.optString("status_text");
    this.photo = objUser.optString("photo");
    this.majorJobCategory = objUser.optString("major_job_category");
    this.minorJobCategory = objUser.optString("minor_job_category");
    this.headLine = objUser.optString("headline");

    if (!objUser.optString("filename").equals("")) this.fileName = objUser.optString("filename");
    else if (!objUser.optString("imageUrl").equals(""))
      this.fileName = objUser.optString("imageUrl");
    else if (Constants.debugLog)
      Log.d(
          "UserSmart",
          "Warning, could not parse user image URL with keys 'filename' or 'imageUrl'...");

    this.lat = objUser.optDouble("lat");
    this.lng = objUser.optDouble("lng");
    this.checkedIn = objUser.optInt("checked_in");
    this.foursquareId = objUser.optString("foursquare");
    this.venueName = objUser.optString("venue_name");
    this.venueId = objUser.optInt("venue_id");
    this.checkInCount = objUser.optInt("checkin_count");
    this.skills = objUser.optString("skills");
    this.sponsorNickname = objUser.optString("sponsorNickname");
    if (this.sponsorNickname.equalsIgnoreCase("") == false) {
      Log.d("UserSmart", "Sponsor: %s" + this.sponsorNickname);
      int test = 5;
      int test2 = test;
    }
    this.met = objUser.optBoolean("met");
  }
    @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);
      }
    }
Example #28
0
  @Override
  public void handleMessage(String event, JSONObject message) {
    if (!"TextSelection:DraggingHandle".equals(event)) {
      return;
    }

    mSuppressCompositions = message.optBoolean("dragging", false);
  }
 // Return the constraints specified for |type| of "audio" or "video" in
 // |mediaConstraintsString|.
 private String getAVConstraints(String type, String mediaConstraintsString) throws JSONException {
   JSONObject json = new JSONObject(mediaConstraintsString);
   // Tricky handling of values that are allowed to be (boolean or
   // MediaTrackConstraints) by the getUserMedia() spec.  There are three
   // cases below.
   if (!json.has(type) || !json.optBoolean(type, true)) {
     // Case 1: "audio"/"video" is not present, or is an explicit "false"
     // boolean.
     return null;
   }
   if (json.optBoolean(type, false)) {
     // Case 2: "audio"/"video" is an explicit "true" boolean.
     return "{\"mandatory\": {}, \"optional\": []}";
   }
   // Case 3: "audio"/"video" is an object.
   return json.getJSONObject(type).toString();
 }
  private boolean test(Actions.EventExpecter expecter) {
    final JSONObject eventData;
    try {
      eventData = new JSONObject(expecter.blockForEventData());
    } catch (Exception ex) {
      // Log and ignore
      getAsserter().ok(false, "JS Test", "Error decoding data " + ex);
      return false;
    }

    if (eventData.has("result")) {
      getAsserter().ok(eventData.optBoolean("result"), "JS Test", eventData.optString("msg"));
    }

    EventDispatcher.sendResponse(eventData, new JSONObject());
    return eventData.optBoolean("done", false);
  }