/**
  * Removes all properties from "valueObject" where the value matches the corresponding value in
  * "defaultValueObject".
  *
  * @return <code>true</code> of the two objects are completely equal and no properties remain in
  *     "valueObject". This means that the valueObject itself MAY be removed. Return value <code>
  *     false</code> means that not all properties are equal (but nevertheless, some properties may
  *     have been removed from valueObject).
  */
 protected boolean filterDefaultObject(JSONObject valueObject, JSONObject defaultValueObject) {
   boolean sameKeys =
       CollectionUtility.equalsCollection(valueObject.keySet(), defaultValueObject.keySet());
   for (Iterator it = valueObject.keys(); it.hasNext(); ) {
     String prop = (String) it.next();
     Object subValue = valueObject.opt(prop);
     Object subDefaultValue = defaultValueObject.opt(prop);
     boolean valueEqualToDefaultValue = checkValueEqualToDefaultValue(subValue, subDefaultValue);
     if (valueEqualToDefaultValue) {
       // Property value value is equal to the static default value -> remove the property
       it.remove();
     } else {
       // Special case: Check if there is a "pseudo" default value, which will not
       // be removed itself, but might have sub-properties removed.
       subDefaultValue = defaultValueObject.opt("~" + prop);
       checkValueEqualToDefaultValue(subValue, subDefaultValue);
     }
   }
   // Even more special case: If valueObject is now empty and it used to have the same keys as
   // the defaultValueObject, it is considered equal to the default value and MAY be removed.
   if (valueObject.length() == 0 && sameKeys) {
     return true;
   }
   return false;
 }
  /**
   * 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 #3
0
 public static Visible parse(JSONObject jsonObject) {
   if (jsonObject == null) {
     return null;
   }
   Visible obj = new Visible(jsonObject);
   obj.type = Result.parseInteger(jsonObject.opt("type"));
   obj.listId = Result.parseInteger(jsonObject.opt("list_id"));
   return obj;
 }
Example #4
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 #5
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;
  }
 public void filter(JSONObject json, String objectType) {
   if (json == null || objectType == null) {
     return;
   }
   List<String> objectTypeHierarchy = m_objectTypeHierarchyFlat.get(objectType);
   if (objectTypeHierarchy == null) {
     // Remove model variant and try again
     objectType = objectType.replaceAll("\\..*", "");
     objectTypeHierarchy = m_objectTypeHierarchyFlat.get(objectType);
   }
   if (objectTypeHierarchy == null) {
     // Unknown type, no default values
     return;
   }
   for (String t : objectTypeHierarchy) {
     for (Iterator it = json.keys(); it.hasNext(); ) {
       String prop = (String) it.next();
       Object value = json.opt(prop);
       if (checkPropertyValueEqualToDefaultValue(t, prop, value)) {
         // Property value value is equal to the static default value -> remove the property
         it.remove();
       }
     }
   }
 }
 protected void importDefaults(JSONObject jsonDefaults) {
   if (jsonDefaults == null) {
     return;
   }
   for (Iterator it = jsonDefaults.keys(); it.hasNext(); ) {
     String type = (String) it.next();
     JSONObject jsonProperties = jsonDefaults.optJSONObject(type);
     for (Iterator it2 = jsonProperties.keys(); it2.hasNext(); ) {
       String prop = (String) it2.next();
       Object value = jsonProperties.opt(prop);
       // Add to map
       Map<String, Object> propMap = m_defaults.get(type);
       if (propMap == null) {
         propMap = new HashMap<>();
         m_defaults.put(type, propMap);
       }
       Object oldValue = propMap.get(prop);
       if (value instanceof JSONObject && oldValue instanceof JSONObject) {
         // Combine
         JsonObjectUtility.mergeProperties((JSONObject) oldValue, (JSONObject) value);
       } else {
         // Override (cannot be combined)
         propMap.put(prop, value);
       }
     }
   }
 }
  // Returns either a JSONObject or JSONArray representation of the 'key' property of 'jsonObject'.
  public static Object getStringPropertyAsJSON(
      JSONObject jsonObject, String key, String nonJSONPropertyKey) throws JSONException {
    Object value = jsonObject.opt(key);
    if (value != null && value instanceof String) {
      JSONTokener tokener = new JSONTokener((String) value);
      value = tokener.nextValue();
    }

    if (value != null && !(value instanceof JSONObject || value instanceof JSONArray)) {
      if (nonJSONPropertyKey != null) {
        // Facebook sometimes gives us back a non-JSON value such as
        // literal "true" or "false" as a result.
        // If we got something like that, we present it to the caller as
        // a GraphObject with a single
        // property. We only do this if the caller wants that behavior.
        jsonObject = new JSONObject();
        jsonObject.putOpt(nonJSONPropertyKey, value);
        return jsonObject;
      } else {
        throw new FacebookException("Got an unexpected non-JSON object.");
      }
    }

    return value;
  }
Example #9
0
  /**
   * Overrides values in base data and returns a new object as the merged result.
   *
   * @param baseData
   * @param overrides
   * @return merged result
   */
  public static JSONObject merge(final JSONObject baseData, final JSONObject overrides) {
    if (baseData == null) {
      return merge(new JSONObject(), overrides);
    }
    // copy existing values so we don't leak mutable references
    final JSONObject result = createJSONObject(baseData.toString());
    // TODO: maybe do the same for overrides?

    if (overrides == null || overrides.length() == 0) {
      // JSONObject.getNames() on empty object returns null so early exit here
      return result;
    }
    try {
      for (String key : JSONObject.getNames(overrides)) {
        Object val = overrides.opt(key);
        if (val instanceof JSONObject) {
          val = merge(result.optJSONObject(key), (JSONObject) val);
        }
        result.put(key, val);
      }
    } catch (Exception ex) {
      log.warn(ex, "Error merging objects from:", overrides, "- to:", baseData);
    }
    return result;
  }
Example #10
0
 public void json(JSONObject jsonObject) {
   Iterator keys = jsonObject.keys();
   while (keys.hasNext()) {
     String next = (String) keys.next();
     json(next, jsonObject.opt(next));
   }
 }
  public void testNull() throws Exception {
    jsonobject = new JSONObject("{\"message\":\"null\"}");
    assertFalse(jsonobject.isNull("message"));
    assertEquals("null", jsonobject.getString("message"));

    jsonobject = new JSONObject("{\"message\":null}");
    assertTrue(jsonobject.isNull("message"));

    jsonobject.put("message2", JSONObject.NULL);
    assertTrue(jsonobject.isNull("message2"));

    jsonobject.put("message2", (Object) null);
    assertEquals(null, jsonobject.opt("message2"));

    jsonobject.put("message3", (Object) null);
    assertEquals(null, jsonobject.opt("message3"));
  }
Example #12
0
  protected Point getActionPosition(JSONObject properties) {
    Integer x = (Integer) properties.opt("x");
    Integer y = (Integer) properties.opt("y");
    String elementId = (String) properties.opt("element");

    // Check the request either has an element or coordinates
    Preconditions.checkState(elementId != null || (x != null && y != null));

    Point elementLocation =
        (elementId == null) ? new Point(0, 0) : getElementFromCache(elementId).getLocation();

    if (x != null && y != null) {
      return new Point(elementLocation.getX() + x, elementLocation.getY() + y);
    }

    return elementLocation;
  }
Example #13
0
 @Override
 public long readLongField(final String id) {
   final Object value = instance.opt(id);
   if (value == null) {
     return 0;
   } else {
     return Long.valueOf((String) value);
   }
 }
Example #14
0
 /**
  * Construct a JSONObject from a subset of another JSONObject. An array of strings is used to
  * identify the keys that should be copied. Missing keys are ignored.
  *
  * @param jo A JSONObject.
  * @param names An array of strings.
  * @throws JSONException
  * @exception JSONException If a value is a non-finite number or if a name is duplicated.
  */
 public JSONObject(JSONObject jo, String[] names) {
   this();
   for (final String name : names) {
     try {
       this.putOnce(name, jo.opt(name));
     } catch (final Exception ignore) {
     }
   }
 }
Example #15
0
 /**
  * Construct a JSONObject from a subset of another JSONObject. An array of strings is used to
  * identify the keys that should be copied. Missing keys are ignored.
  *
  * @param jo A JSONObject.
  * @param names An array of strings.
  * @throws JSONException
  * @exception JSONException If a value is a non-finite number or if a name is duplicated.
  */
 public JSONObject(JSONObject jo, String[] names) {
   this();
   for (int i = 0; i < names.length; i += 1) {
     try {
       putOnce(names[i], jo.opt(names[i]));
     } catch (Exception ignore) {
     }
   }
 }
    @Override
    protected String doInBackground(String... params) {

      try {
        inputJson.accumulate("claimCode", Redeemcode);
        // inputJson.accumulate("voucherId",);

        outputJson =
            URLconnectionService.getWebServiceData(
                url, null, AppConstants.GET_REQUEST, gmail, password);
        // prefManager.createMessageBuffer(AppConstants.SIGHNIN_JSON,outputJson.toString());
        message = outputJson.opt("message").toString();
        code = outputJson.opt("code").toString();

      } catch (Exception e) {
      }
      return null;
    }
Example #17
0
 /**
  * Creates a new {@code JSONObject} by copying mappings for the listed names from the given
  * object. Names that aren't present in {@code copyFrom} will be skipped.
  */
 public JSONObject(JSONObject copyFrom, String[] names) throws JSONException {
   this();
   for (String name : names) {
     Object value = copyFrom.opt(name);
     if (value != null) {
       nameValuePairs.put(name, value);
     }
   }
 }
Example #18
0
 private HashMap<String, String> parseJsonToMap(JSONObject clientInfo) {
   HashMap<String, String> map = new HashMap<>();
   Iterator<String> keysItr = clientInfo.keys();
   while (keysItr.hasNext()) {
     String key = keysItr.next();
     String value = String.valueOf(clientInfo.opt(key));
     map.put(key, value);
   }
   return map;
 }
 /* package */ Map<String, Object> convertJSONObjectToMap(JSONObject object) {
   Map<String, Object> outputMap = new HashMap<>();
   Iterator<String> it = object.keys();
   while (it.hasNext()) {
     String key = it.next();
     Object value = object.opt(key);
     outputMap.put(key, decode(value));
   }
   return outputMap;
 }
  private void freightUI(JSONObject jsonObject) throws JSONException {

    ls_data.clear();

    JSONArray array = jsonObject.getJSONArray("data");

    int size = array.length();
    if (size == 0) {
      CodeUtil.toast(COBaseFragment.this.getActivity(), "没有订单");
      if (ls_data.size() == 0) {
        setReloadAvailable();
      } else {
        setReloadGone();
      }
      adapter.notifyDataSetChanged();
      return;
    }

    for (int i = 0; i < size; i++) {

      JSONObject object = array.getJSONObject(i);
      OrderBaseAdapter.OrderInfo info = new OrderBaseAdapter.OrderInfo();
      CodeUtil.doOrderCommonDo(object, info);

      info.isValid = object.getBoolean("isvalid");
      info.isPayOnline = object.getBoolean("isPayOln");

      // 是否有效
      if (!info.isValid) {
        info.cause = object.getString("cause");

        // 是否在线付款了
        if (info.isPayOnline) {
          info.refundStatus = object.getInt("status");
        }

      } else {

        if (object.opt("category") == null) {
          info.status = 5;
          info.out_time = DateUtil.getHourAndMinute(object.getString("sendtime"));

        } else {
          info.status = object.optInt("category");
          if (info.status == 5) {
            info.out_time = DateUtil.getHourAndMinute(object.getString("sendtime"));
          }
        }
      }
      ls_data.add(info);
    }

    setReloadGone();
    adapter.notifyDataSetChanged();
  }
  @Override
  public void onQuery(Query query) throws DeadlineExceededException {
    JSONObject parameters = query.getParameters();
    Object monthId = parameters.opt("monthid");
    Object yearId = parameters.opt("yearid");
    if (monthId == null || yearId == null) {
      throw new RuntimeException("Please Select Month Year.");
    }

    String yearName =
        EmployeeSalaryGenerationServlet.getYearName((long) Translator.integerValue(yearId));
    String fromDateString = yearName + "-" + monthId + "-1";
    Date fromDate = Translator.dateValue(fromDateString);
    Date toDate = DataTypeUtilities.getMonthLastDate(fromDate);
    String toDateString = EmployeeSalaryGenerationServlet.getDateInString(toDate);
    String filter = "date>='" + fromDateString + "' AND date<='" + toDateString + "'";
    query.addFilter(filter);

    JSONArray filters = query.getFilters();
    LogUtility.writeLog("parameters >> " + parameters + " << filters >> " + filters);
  }
Example #22
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 #23
0
 private ConfigurationMetadataItem parseItem(JSONObject json) {
   ConfigurationMetadataItem item = new ConfigurationMetadataItem();
   item.setId(json.getString("name"));
   item.setType(json.optString("type", null));
   String description = json.optString("description", null);
   item.setDescription(description);
   item.setShortDescription(extractShortDescription(description));
   item.setDefaultValue(readItemValue(json.opt("defaultValue")));
   item.setDeprecated(json.optBoolean("deprecated", false));
   item.setSourceType(json.optString("sourceType", null));
   item.setSourceMethod(json.optString("sourceMethod", null));
   return item;
 }
  protected Object parseResponseData(String content)
      throws JSONException, RequestRejectedException {
    final JSONObject r = new JSONObject(content);
    if (!r.getBoolean("success")) {
      throw new RequestRejectedException(r.optString("code"), r.optString("message"));
    }

    Object data = r.opt("data");
    if (data == JSONObject.NULL) {
      return null;
    }
    return data;
  }
Example #25
0
  public void handleOp(JSONObject opPayload, Cache<Object, Object> cache, ChannelHandlerContext ctx)
      throws JSONException {
    String opCode = (String) opPayload.get(OpHandler.OP_CODE);
    String key = (String) opPayload.opt(OpHandler.KEY);
    String[] onEvents = (String[]) opPayload.opt("onEvents");
    CacheListener listener = listeners.get(cache);

    if (key == null) {
      // If key not specified... notify on all...
      key = "*";
    }

    if (listener == null) {
      synchronized (this) {
        listener = listeners.get(cache);
        if (listener == null) {
          listener = new CacheListener();
          listeners.put(cache, listener);
          cache.addListener(listener);
        }
      }
    }

    String[] keyTokens = key.split(",");
    for (String keyToken : keyTokens) {
      ChannelNotifyParams notifyParams =
          new ChannelNotifyParams(ctx.getChannel(), keyToken, onEvents);

      if (opCode.equals("notify")) {
        listener.addChannel(notifyParams);
        // And push the value to the channel (if it's not wildcard)...
        if (!keyToken.equals("*")) {
          ChannelUtils.pushCacheValue(keyToken, cache, ctx);
        }
      } else if (opCode.equals("unnotify")) {
        listener.removeChannel(notifyParams);
      }
    }
  }
  public void testOpt() throws Exception {
    try {
      jsonobject = new JSONObject(jsonstring);
      Object o = null;

      o = jsonobject.opt("value0");
      assertNull(o);

      o = jsonobject.opt("value1");
      assertNotNull(o);
      assertTrue(o instanceof String);
      assertEquals(o, "john");

      o = jsonobject.opt("value2");
      assertNotNull(o);
      assertTrue(o instanceof Integer);
      assertEquals(o, 18);

      o = jsonobject.opt("value3");
      assertNotNull(o);
      assertTrue(o instanceof Double);
      assertEquals(o, 18.81);

      o = jsonobject.opt("value4");
      assertNotNull(o);
      assertTrue(o instanceof Boolean);
      assertEquals(o, true);

      o = jsonobject.opt("value6");
      assertNotNull(o);
      assertTrue(o == JSONObject.NULL);

      o = jsonobject.opt("object");
      assertNotNull(o);
      assertTrue(o instanceof JSONObject);
      assertEquals(((JSONObject) o).opt("id"), 123);

      o = jsonobject.opt("array");
      assertNotNull(o);
      assertTrue(o instanceof JSONArray);
      JSONArray a = (JSONArray) o;
      assertEquals(3, a.length());

    } catch (Exception t) {
      fail(t.toString());
    }
  }
  private Map<String, Set<String>> getProperties(JSONObject jo) throws JSONException {
    Map<String, Set<String>> result = new HashMap<String, Set<String>>();

    for (Iterator i = jo.keys(); i.hasNext(); ) {
      String key = (String) i.next();
      JSONArray arr = (JSONArray) jo.opt(key);
      Set set = new HashSet<String>();
      result.put(key, set);

      for (int j = 0; j < arr.length(); j++) {
        set.add(arr.getString(j));
      }
    }

    return result;
  }
 @SuppressWarnings("unchecked")
 private static String json2String(JSONObject params) {
   String content = "";
   for (Iterator<String> iterator = params.keys(); iterator.hasNext(); ) {
     String key = iterator.next();
     if (!TextUtils.isEmpty(content)) {
       content += "&";
     }
     try {
       content += key + "=" + URLEncoder.encode(params.opt(key).toString(), "UTF-8");
     } catch (Exception e) {
       e.printStackTrace();
     }
   }
   return content;
 }
Example #29
0
  protected void setData(JSONObject jsonObject, boolean disableChecks) {
    Iterator<?> it = jsonObject.keys();
    while (it.hasNext()) {
      String key = (String) it.next();
      Object value = jsonObject.opt(key);
      if (Parse.isInvalidKey(key)) {
        setReservedKey(key, value);
      } else {
        put(key, ParseDecoder.decode(value), disableChecks);
      }
    }

    this.isDirty = false;
    this.operations.clear();
    this.dirtyKeys.clear();
  }
Example #30
0
  public static GeckoBundle fromJSONObject(final JSONObject obj) throws JSONException {
    if (obj == null || obj == JSONObject.NULL) {
      return null;
    }

    final String[] keys = new String[obj.length()];
    final Object[] values = new Object[obj.length()];

    final Iterator<String> iter = obj.keys();
    for (int i = 0; iter.hasNext(); i++) {
      final String key = iter.next();
      keys[i] = key;
      values[i] = fromJSONValue(obj.opt(key));
    }
    return new GeckoBundle(keys, values);
  }