/**
   * Get the JSON data for the Case Study
   *
   * @return boolean indicates whether the case study data is loaded
   */
  private boolean cacheJSON() {
    if (this.getType().equals("LOCAL")) {
      try {
        JSONobj = (new JSONObject(this.loadJSONFromAsset(this.getLocation())));
        Iterator<String> iter = JSONobj.keys();
        this.id = iter.next();

        JSONobj = JSONobj.getJSONObject(this.id);
      } catch (JSONException e) {
        e.printStackTrace();
      }
      return true;
    } else if (this.getType().equals("DISK")) {
      try {
        JSONobj = (new JSONObject(this.loadJSONFromStorage(this.getLocation())));
        Iterator<String> iter = JSONobj.keys();
        this.id = iter.next();

        JSONobj = JSONobj.getJSONObject(this.id);
      } catch (JSONException e) {
        e.printStackTrace();
      }
      return true;
    } else {
      return false;
    }
  }
  /**
   * Gets a map property deserialized values from the cache or from the underlying JSONObject
   *
   * @param property the property name
   * @param typeClass the type of JSONResponse contained in the property
   * @return the map of json response style objects associated to this property in the JSON response
   */
  @SuppressWarnings("unchecked")
  private Map<String, ?> getMap(String property, Class<?> typeClass) {
    Map<String, Object> map = null;
    if (!propertyMap.containsKey(property)) {
      JSONObject jsonMap = delegate.optJSONObject(property);
      if (jsonMap != null) {
        map = new LinkedHashMap<String, Object>(jsonMap.length());

        while (jsonMap.keys().hasNext()) {
          String key = (String) jsonMap.keys().next();
          JSONObject jsonObject = jsonMap.optJSONObject(key);
          try {
            Object response = typeClass.newInstance();
            ((JSONResponse) response).fromJSON(jsonObject);
            map.put(key, response);
          } catch (JSONException e) {
            throw new RuntimeException(e);
          } catch (InstantiationException e) {
            throw new RuntimeException(e);
          } catch (IllegalAccessException e) {
            throw new RuntimeException(e);
          }
        }
        propertyMap.put(property, map);
      }
    } else {
      map = (Map<String, Object>) propertyMap.get(property);
    }
    return map;
  }
 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);
       }
     }
   }
 }
Example #4
0
  /**
   * Compares 2 JSON objects. It compares the actual JSON data, and considers a NULL or
   * non-specified value for a key equivalent to an absence of key (i.e. "{key:null}" is considered
   * equivalent to "{}"). Not that values are not coerced for comparison, so "{key:10}" isn't
   * equivalent to "{key:'10'}".
   *
   * @param left The first JSON data to compare
   * @param right The JSON data to compare to {@link left}
   * @return true if the 2 JSON data are equivalent per the above description, false otherwise
   */
  public static boolean areDataEquivalent(final JSONObject left, final JSONObject right) {
    if ((left == null) || (right == null)) {
      return (left == right); // whether both null or not
    }

    // special simple case
    if (left.toString().equals(right.toString())) return true;

    // else, perform a full comparison :
    final String[] keysToCompare =
        new String[left.length() + right.length()]; // will contain all keys to compare
    @SuppressWarnings("unchecked")
    final Iterator<String> leftKeysIt = left.keys();
    // copy keys to a common array (O(n)) :
    int i = 0;
    for (; leftKeysIt.hasNext(); ++i) keysToCompare[i] = leftKeysIt.next();
    @SuppressWarnings("unchecked")
    final Iterator<String> rightKeysIt = right.keys();
    for (; rightKeysIt.hasNext(); ++i) keysToCompare[i] = rightKeysIt.next();
    // sort keys (O(n logn)) :
    Arrays.sort(keysToCompare);
    // compare left and right for each key (O(n)) :
    for (i = 0; i < keysToCompare.length; ++i) {
      if ((i > 0) && (keysToCompare[i].equals(keysToCompare[i - 1])))
        // already checked this key
        continue;

      final String key = keysToCompare[i];
      Object leftObj;
      try {
        leftObj = (left.has(key)) ? left.get(key) : JSONObject.NULL;
      } catch (final JSONException jE) {
        throw new JSONRuntimeException(
            jE); // shouldn't happen as we check for has() before calling get()
      }
      Object rightObj;
      try {
        rightObj = (right.has(key)) ? right.get(key) : JSONObject.NULL;
      } catch (final JSONException jE) {
        throw new JSONRuntimeException(
            jE); // shouldn't happen as we check for has() before calling get()
      }

      // compare sub-objects :
      if ((leftObj instanceof JSONObject) && (rightObj instanceof JSONObject)) {
        if (!(areDataEquivalent((JSONObject) leftObj, (JSONObject) rightObj))) return false;
      } else {
        if (!leftObj.equals(rightObj)) return false; // they're not equivalent
      }
      // Android's JSONArray overrides equals() so no need for special case for it
    }

    // didn't return false yet, objects are equal :
    return true;
  }
 @SuppressWarnings("unchecked")
 @Override
 protected void doPut(HttpServletRequest req, HttpServletResponse resp)
     throws ServletException, IOException {
   traceRequest(req);
   IEclipsePreferences node = getNode(req, resp, true);
   if (node == null) return;
   String key = req.getParameter("key");
   try {
     if (key != null) {
       node.put(key, req.getParameter("value"));
     } else {
       JSONObject newNode = new JSONObject(new JSONTokener(req.getReader()));
       node.clear();
       for (Iterator<String> it = newNode.keys(); it.hasNext(); ) {
         key = it.next();
         node.put(key, newNode.getString(key));
       }
     }
     prefRoot.flush();
     resp.setStatus(HttpServletResponse.SC_NO_CONTENT);
   } catch (Exception e) {
     handleException(
         resp, NLS.bind("Failed to store preferences for {0}", req.getRequestURL()), e);
     return;
   }
 }
  @SuppressWarnings("static-access")
  @Override
  protected void onPostExecute(String result) {
    super.onPostExecute(result);
    this.result = result;

    LogUtils.d(result); // TODO

    if (!StringUtil.isEmptyString(result)) {
      try {
        this.jsonResult = MyGson.getInstance().fromJson(result, BaseResult.class);
      } catch (Exception e) {
        this.jsonResult = Constants.JSON_ERROR;
        e.printStackTrace();
      }
    } else {
      this.jsonResult = Constants.SERVER_ERROR;
    }
    try {
      JSONObject jo = new JSONObject(result).getJSONObject("resultParm");
      Map<String, String> map = new HashMap<String, String>();
      Iterator<String> keys = jo.keys();

      while (keys.hasNext()) {
        String k = keys.next();
        map.put(k, jo.getString(k));
      }
      this.jsonResult.setResultParam(map);
    } catch (Exception e) {
      e.printStackTrace();
    }
    if (dataReturnListener != null) {
      dataReturnListener.onDataReturn(Tasktag, jsonResult, result);
    }
  }
Example #7
0
 public static Bundle Json2Bundle(JSONObject json) {
   Bundle mBundle = new Bundle();
   @SuppressWarnings("unchecked")
   Iterator<String> iter = json.keys();
   Object value;
   while (iter.hasNext()) {
     String key = iter.next();
     try {
       value = json.get(key);
       if (Boolean.class.isInstance(value)) {
         mBundle.putBoolean(key, (Boolean) value);
       } else if (Double.class.isInstance(value)) {
         mBundle.putDouble(key, (Double) value);
       } else if (Integer.class.isInstance(value)) {
         mBundle.putInt(key, (Integer) value);
       } else if (Long.class.isInstance(value)) {
         mBundle.putLong(key, (Long) value);
       } else if (JSONObject.class.isInstance(value)) {
         mBundle.putBundle(key, Json2Bundle((JSONObject) value));
       } else {
         mBundle.putString(key, json.getString(key));
       }
     } catch (JSONException e) {
       e.printStackTrace();
     }
   }
   return mBundle;
 }
  /** Positive test case for listUsers method with optional parameters. */
  @Test(
      groups = {"wso2.esb"},
      description = "tsheets {listUsers} integration test with optional parameters.")
  public void testListUsersWithOptionalParameters() throws IOException, JSONException {

    esbRequestHeadersMap.put("Action", "urn:listUsers");
    RestResponse<JSONObject> esbRestResponse =
        sendJsonRestRequest(proxyUrl, "POST", esbRequestHeadersMap, "esb_listUsers_optional.json");

    JSONObject esbUsers = esbRestResponse.getBody().getJSONObject("results").getJSONObject("users");

    String apiEndPoint =
        connectorProperties.getProperty("apiUrl") + "/api/v1/users?page=2&per_page=1";
    RestResponse<JSONObject> apiRestResponse =
        sendJsonRestRequest(apiEndPoint, "GET", apiRequestHeadersMap);

    JSONObject apiUsers = apiRestResponse.getBody().getJSONObject("results").getJSONObject("users");

    Iterator<String> esbUserKeySet = esbUsers.keys();

    Assert.assertEquals(apiUsers.length(), esbUsers.length());

    while (esbUserKeySet.hasNext()) {

      String userKey = esbUserKeySet.next();
      JSONObject esbUser = esbUsers.getJSONObject(userKey);
      JSONObject apiUser = apiUsers.getJSONObject(userKey);

      Assert.assertEquals(apiUser.getString("first_name"), esbUser.getString("first_name"));
      Assert.assertEquals(apiUser.getString("last_name"), esbUser.getString("last_name"));
      Assert.assertEquals(apiUser.getString("username"), esbUser.getString("username"));
      Assert.assertEquals(apiUser.getString("email"), esbUser.getString("email"));
    }
  }
  private static Education parseEducation(JSONObject educationObject) throws JSONException {
    Education.Builder education = new Education.Builder();

    for (@SuppressWarnings("unchecked") Iterator<String> educationIter = educationObject.keys();
        educationIter.hasNext(); ) {

      String educationKey = educationIter.next();
      if (educationKey.equals("id")) {
        education.setId(educationObject.getString(educationKey));

      } else if (educationKey.equals("degree")) {
        education.setDegree(educationObject.getString(educationKey));

      } else if (educationKey.equals("institution")) {
        education.setInstitution(educationObject.getString(educationKey));

      } else if (educationKey.equals("start_date")) {
        education.setStartDate(educationObject.getString(educationKey));

      } else if (educationKey.equals("end_date")) {
        education.setEndDate(educationObject.getString(educationKey));

      } else if (educationKey.equals("website")) {
        education.setWebsite(educationObject.getString(educationKey));
      }
    }
    return education.build();
  }
 private void getSavedDevices() {
   JSONObject jsonObject = new JSONObject();
   String file = readFromFile();
   if (file != null) {
     try {
       jsonObject = new JSONObject(file);
     } catch (JSONException e) {
       e.printStackTrace();
     }
     // List<iBeaconInfo> devices = new ArrayList<iBeaconInfo>();
     Iterator<String> iter = jsonObject.keys();
     while (iter.hasNext()) {
       String hash = iter.next();
       try {
         JSONObject tempObject = (JSONObject) jsonObject.get(hash);
         String nickname = tempObject.getString("nickname");
         // HashMap<String,String> tempMap = new HashMap<String, String>();
         // tempMap.put(hash,nickname);
         mHashNicknames.put(hash, nickname);
       } catch (JSONException e) {
         e.printStackTrace();
       }
     }
     Log.v(TAG, mHashNicknames.toString());
   }
 }
  private OpenGraphObject buildOpenGraphObject(JSONObject actionParams) throws JSONException {
    JSONObject jsonObject = actionParams.getJSONObject("object");

    OpenGraphObject object = OpenGraphObject.Factory.createForPost(jsonObject.getString("type"));
    object.setTitle(jsonObject.getString("title"));
    object.setDescription(jsonObject.getString("description"));

    if (jsonObject.has("url")) {
      object.setUrl(jsonObject.getString("url"));
    }

    object.setImageUrls(Arrays.asList(jsonObject.getString("image")));

    JSONObject dataObject = jsonObject.getJSONObject("data");

    @SuppressWarnings("unchecked")
    Iterator<String> keys = (Iterator<String>) dataObject.keys();

    while (keys.hasNext()) {
      String key = keys.next();

      object.getData().setProperty(key, dataObject.get(key));
    }

    return object;
  }
Example #12
0
  @SuppressWarnings("rawtypes")
  private void generateHeaderRow(
      HSSFWorkbook workBook, Sheet sheet, JSONArray columnConfigJSONObject) {

    CellStyle center = workBook.createCellStyle();
    center.setAlignment(HSSFCellStyle.ALIGN_CENTER);
    int columnType = Cell.CELL_TYPE_STRING;
    String col = null, text = null;
    short width = 15;
    sheet.setDefaultColumnWidth(width);
    Row headerRow = createRow(sheet, headerRowNum);
    for (short i = 0; i < columnConfigJSONObject.length(); i++) {
      JSONObject headerObj = columnConfigJSONObject.getJSONObject(i);
      for (Iterator iterator = headerObj.keys(); iterator.hasNext(); ) {
        String key = (String) iterator.next();
        if ("columnType".equals(key)) {
          //					if(isNumber(headerObj.getString(key))) {
          //						columnType = Cell.CELL_TYPE_NUMERIC;
          //					}
        } else {
          col = key;
          text = headerObj.getString(key);
        }
      }

      headerIdArray.add(col);

      Cell cell = createCell(headerRow, i, columnType);
      cell.setCellValue(new HSSFRichTextString(text));
      cell.setCellStyle(center);
    }
  }
Example #13
0
 private synchronized boolean extractJSON(String inResult) {
   boolean bSuccess;
   bSuccess = false;
   try {
     PaytmUtility.debugLog("Parsing JSON");
     JSONObject Obj = new JSONObject(inResult);
     Iterator<String> Keys = Obj.keys();
     PaytmUtility.debugLog("Appending Key Value pairs");
     PaytmUtility.debugLog(
         "Send All Checksum Response Parameters to PG "
             + this.mbSendAllChecksumResponseParametersToPGServer);
     while (Keys.hasNext()) {
       String Key = (String) Keys.next();
       String Value = Obj.getString(Key);
       Key = Key.trim();
       PaytmUtility.debugLog(
           new StringBuilder(String.valueOf(Key)).append(" = ").append(Value).toString());
       if (Key.equals(CHECKSUMHASH)) {
         this.mParams.putString(Key, Value);
       } else if (this.mbSendAllChecksumResponseParametersToPGServer) {
         this.mParams.putString(Key, Value);
       }
       if (Key.equals(PAYT_STATUS) && Value.equals(SUCCESS)) {
         bSuccess = true;
       }
     }
   } catch (Exception inEx) {
     PaytmUtility.debugLog(
         "Some exception occurred while extracting the checksum from CAS Response.");
     PaytmUtility.printStackTrace(inEx);
   }
   return bSuccess;
 }
  @SuppressWarnings({"unchecked", "rawtypes"})
  public FullDistrictModel parse(JSONObject json) throws JSONException {
    if (null == json) {
      return null;
    }

    strMD5 = json.optString("md5", "");
    if (!ToolUtil.isEmptyList(json, "fullDistrict")) {
      JSONObject data = json.getJSONObject("fullDistrict");
      if (null != data) {
        Iterator<String> iter = data.keys();
        while (iter.hasNext()) {
          ProvinceModel model = new ProvinceModel();
          String key = iter.next();
          model.parse(data.getJSONObject(key));
          mProvnceModels.add(model);
        }

        Collections.sort(
            mProvnceModels,
            new Comparator() {
              @Override
              public int compare(Object one, Object another) {
                ProvinceModel a = (ProvinceModel) one;
                ProvinceModel b = (ProvinceModel) another;
                return ToolUtil.compareInt(a.getProvinceSortId(), b.getProvinceSortId());
              }
            });
      }
    }

    return null;
  }
Example #15
0
  public static Map<String, Object> getMap(
      JSONObject object, String key, Map<String, Object> fallback) {
    JSONObject data = key == null ? object : getObject(object, key, null);
    if (data == null) {
      return null;
    }

    try {
      HashMap<String, Object> result = new HashMap<String, Object>();

      Iterator<?> keyIterator = data.keys();
      while (keyIterator.hasNext()) {
        String current = (String) keyIterator.next();

        Object value = data.get(current);
        if (value instanceof JSONObject) {
          value = getMap(data, current, null);
        } else if (value instanceof JSONArray) {
          value = getCollection(data, current, null);
        }

        result.put(current, value);
      }
      return result;
    } catch (JSONException e) {
      return null;
    }
  }
Example #16
0
  private static boolean resetStateFromJSON(
      JSONObject state, String targetListName, IItemStateApplier stateApplier) {
    if (!state.has(targetListName)) {
      return true;
    }

    SoomlaUtils.LogDebug(TAG, "Resetting state for " + targetListName);

    try {
      JSONObject itemsJSON = state.getJSONObject(targetListName);
      Iterator keysIter = itemsJSON.keys();
      while (keysIter.hasNext()) {
        String itemId = (String) keysIter.next();
        JSONObject itemValuesJSON = itemsJSON.getJSONObject(itemId);
        if (!stateApplier.applyState(itemId, itemValuesJSON)) {
          return false;
        }
      }
    } catch (JSONException e) {
      SoomlaUtils.LogError(
          TAG, "Unable to set state for " + targetListName + ". error: " + e.getLocalizedMessage());
      return false;
    }

    return true;
  }
 public void setPaletteCustomization(PaletteCustomization prefs) {
   try {
     JSONObject jsonObject = null;
     if (prefs != null) {
       jsonObject = new JSONObject();
       if (prefs.drawers != null) {
         jsonObject.put(PaletteCustomization.DRAWERS, prefs.drawers);
       }
       if (prefs.drawerEntries != null && prefs.drawerEntries.size() > 0) {
         jsonObject.put(PaletteCustomization.DRAWER_ENTRIES, prefs.drawerEntries);
       }
       if (prefs.entryProperties != null && prefs.entryProperties.size() > 0) {
         jsonObject.put(PaletteCustomization.ENTRY_PROPERTIES, prefs.entryProperties);
       }
     }
     if (jsonObject != null && jsonObject.keys().hasNext()) {
       setProperty(
           PALETTE_CUSTOMIZATION_SETTING,
           ServoyJSONObject.toString(jsonObject, false, false, false));
     } else {
       removeProperty(PALETTE_CUSTOMIZATION_SETTING);
     }
   } catch (JSONException e) {
     ServoyLog.logError("Could not save palette preferences", e);
   }
 }
  /**
   * Takes json string and parses it to map of dictionary references.
   *
   * @param jsonString - JSON string to be parsed
   */
  public void parseDicRef(String jsonString) {
    if (jsonString == null || jsonString.length() < 1) {
      return;
    }
    Map<String, String> dicRefTemp = new HashMap<>();
    JSONObject dicRefJson;
    try {
      dicRefJson = new JSONObject(jsonString);
    } catch (JSONException e) {
      Log.w(LOG_TAG, "getting parseJapaneseKeb()  initial expression failed: " + e.toString());
      return;
    }

    Iterator<?> keys = dicRefJson.keys();
    while (keys.hasNext()) {
      String key = (String) keys.next();
      String value;
      try {
        value = dicRefJson.getString(key);
        if (key != null && value != null) {
          dicRefTemp.put(key, value);
        }
      } catch (JSONException e) {
        Log.w(LOG_TAG, "parsing dicRef failed");
      }
    }
    if (dicRefTemp.size() > 0) {
      for (String key : dicRefTemp.keySet()) {
        addDicRef(key, dicRefTemp.get(key));
      }
    }
  }
Example #19
0
  @Override
  protected void onPostExecute(String result) {
    super.onPostExecute(result);
    try {
      JSONObject jsonObject = new JSONObject(result);
      JSONArray jsonArray = new JSONArray();
      Iterator iterator = jsonObject.keys();

      while (iterator.hasNext()) {
        String key = (String) iterator.next();
        if (key != "") {
          jsonArray.put(jsonObject.get(key));
          MyCurrencyObject object = new MyCurrencyObject();
          object.setNameId(key);
          object.setFullCountryName(jsonObject.get(key).toString());
          MyCurrencyObjArray.addCurrencyObj(object);
        }
      }
      MainActivity.countriesList.clear();
      for (int i = 0; i < jsonArray.length(); i++) {
        MainActivity.countriesList.add(jsonArray.get(i).toString());
      }
      complete.asyncComplete1(true);
    } catch (JSONException e) {
      e.printStackTrace();
    }
  }
Example #20
0
  @SuppressWarnings("rawtypes")
  public KCClassParser(String jsonStr) {
    try {
      JSONObject json = new JSONObject(jsonStr);
      mJSClzName = json.get(CLZ).toString();
      mJSMethodName = json.get(METHOD).toString();
      if (json.has(ARGS)) {
        mArgsJSON = json.getJSONObject(ARGS);
        Iterator it = mArgsJSON.keys();
        while (it.hasNext()) {
          String key = (String) it.next();
          if (key != null) {
            Object value = mArgsJSON.get(key);
            if (KCJSNull.isNull(value)) value = new KCJSNull();
            KCArg arg = null;

            if (key.equals(KCJSDefine.kJS_callbackId)) {
              arg = new KCArg(key, new KCJSCallback(value.toString()), KCJSCallback.class);
            } else {
              arg = new KCArg(key, value);
            }
            mArgList.addArg(arg);
          }
        }
      }
    } catch (JSONException e) {
      KCLog.e(e);
    }
  }
  /**
   * Creating a File object from a json string
   *
   * @param jsonString the json string
   * @return the File object
   * @throws JSONException
   */
  public static File parseFile(String jsonString) throws JSONException {
    File.Builder mendeleyFile = new File.Builder();

    JSONObject documentObject = new JSONObject(jsonString);

    for (@SuppressWarnings("unchecked") Iterator<String> keysIter = documentObject.keys();
        keysIter.hasNext(); ) {

      String key = keysIter.next();
      if (key.equals("id")) {
        mendeleyFile.setId(documentObject.getString(key));

      } else if (key.equals("document_id")) {
        mendeleyFile.setDocumentId(documentObject.getString(key));

      } else if (key.equals("mime_type")) {
        mendeleyFile.setMimeType(documentObject.getString(key));

      } else if (key.equals("file_name")) {
        mendeleyFile.setFileName(documentObject.getString(key));

      } else if (key.equals("filehash")) {
        mendeleyFile.setFileHash(documentObject.getString(key));

      } else if (key.equals("size")) {
        mendeleyFile.setFileSize(documentObject.getInt(key));
      }
    }

    return mendeleyFile.build();
  }
 void _ui(String params, int cbIndex) {
   String action = null;
   Bundle parameters = new Bundle();
   try {
     JSONObject jsonObject = new JSONObject(params);
     action = jsonObject.getString("method");
     Iterator iterator = jsonObject.keys();
     String key = null;
     String value = null;
     while (iterator.hasNext()) {
       key = (String) iterator.next();
       Object object = jsonObject.get(key);
       if (object instanceof String) {
         value = (String) object;
         if (key.compareTo("method") != 0) parameters.putString(key, value);
       } else if (object instanceof Integer) {
         parameters.putInt(key, ((Integer) object).intValue());
       } else if (object instanceof Boolean) {
         parameters.putBoolean(key, ((Boolean) object).booleanValue());
       } else if (object instanceof Double) {
         parameters.putDouble(key, ((Double) object).doubleValue());
       } else {
         Log.v(TAG, "other type:" + object.toString());
       }
     }
   } catch (JSONException e) {
     e.printStackTrace();
   }
   WebDialog uiDialog =
       (new WebDialog.Builder(mActivity, Session.getActiveSession(), action, parameters))
           .setOnCompleteListener(new WebDialogListener(cbIndex))
           .build();
   uiDialog.show();
 }
  public List<TagBean> getGSONMsgList() throws WeiboException {

    String json = getMsgListJson();
    List<TagBean> tagBeanList = new ArrayList<TagBean>();

    try {
      JSONArray array = new JSONArray(json);
      int size = array.length();
      for (int i = 0; i < size; i++) {
        TagBean bean = new TagBean();
        JSONObject jsonObject = array.getJSONObject(i);
        Iterator<String> iterator = jsonObject.keys();
        while (iterator.hasNext()) {
          String key = iterator.next();
          if (key.equalsIgnoreCase("weight")) {
            String value = jsonObject.optString(key);
            bean.setWeight(value);
          } else {
            String value = jsonObject.optString(key);
            bean.setId(Integer.valueOf(key));
            bean.setName(value);
          }
        }
        tagBeanList.add(bean);
      }

    } catch (JSONException e) {
      AppLogger.e(e.getMessage());
    }

    return tagBeanList;
  }
 /**
  * Gets a {@link JSONObject} containing the post data supplied with the current request as
  * key-value pairs appended with the instrumentation data.
  *
  * <p>* @param instrumentationData {@link ConcurrentHashMap} with instrumentation values
  *
  * @return A {@link JSONObject} containing the post data supplied with the current request as
  *     key-value pairs and the instrumentation meta data.
  */
 public JSONObject getPostWithInstrumentationValues(
     ConcurrentHashMap<String, String> instrumentationData) {
   JSONObject extendedPost = new JSONObject();
   try {
     // Add original parameters
     if (params_ != null) {
       JSONObject originalParams = new JSONObject(params_.toString());
       Iterator<String> keys = originalParams.keys();
       while (keys.hasNext()) {
         String key = keys.next();
         extendedPost.put(key, originalParams.get(key));
       }
     }
     // Append instrumentation metadata
     if (instrumentationData.size() > 0) {
       JSONObject instrObj = new JSONObject();
       Set<String> keys = instrumentationData.keySet();
       try {
         for (String key : keys) {
           instrObj.put(key, instrumentationData.get(key));
           instrumentationData.remove(key);
         }
         extendedPost.put(Defines.Jsonkey.Branch_Instrumentation.getKey(), instrObj);
       } catch (JSONException ignore) {
       }
     }
   } catch (JSONException ignore) {
   } catch (ConcurrentModificationException ex) {
     extendedPost = params_;
   }
   return extendedPost;
 }
  /**
   * Create and show a simple notification containing the received GCM message.
   *
   * @param message GCM message received.
   */
  private void sendNotification(String message, String extra) {
    Intent intent = new Intent("com.ibm.bluebridge.pushnotification");
    try {
      JSONObject data = new JSONObject(extra);
      Iterator<String> itr = data.keys();
      while (itr.hasNext()) {
        String key = itr.next();
        intent.putExtra(key, data.getString(key));
      }
    } catch (JSONException e) {
      Log.e(TAG, "Cannot parse data, no extra set to Notification");
    }
    intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
    PendingIntent pendingIntent =
        PendingIntent.getActivity(this, 0 /* Request code */, intent, PendingIntent.FLAG_ONE_SHOT);

    Uri defaultSoundUri = RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION);
    NotificationCompat.Builder notificationBuilder =
        new NotificationCompat.Builder(this)
            .setSmallIcon(R.mipmap.logo)
            .setContentTitle("BlueBridge")
            .setContentText(message)
            .setAutoCancel(true)
            .setSound(defaultSoundUri)
            .setContentIntent(pendingIntent);

    NotificationManager notificationManager =
        (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);

    notificationManager.notify(0 /* ID of notification */, notificationBuilder.build());
  }
  /**
   * Checks if is scope valid.
   *
   * @param scope the scope
   * @param response the response
   * @return true, if is scope valid
   */
  private boolean isScopeValid(String scope, String response) {
    boolean isValid = true;
    JSONObject obj;
    try {
      obj = new JSONObject(response);

      if (obj.toString().equals("{}")) {
        System.out.println("No claims have not null values in the scope : " + scope);
        return true;
      }

      Iterator keys = obj.keys();
      List xmlScopeList = scopes.get(scope).getClaims().getClaimValues();

      while (keys.hasNext()) {
        String key = (String) keys.next();
        if (!xmlScopeList.contains(key)) {
          log.info("Response contains a claim value that is not belongs to scope " + scope);
          isValid = false;
          break;
        }
      }
    } catch (JSONException e) {
      e.printStackTrace();
      return false;
    }
    return isValid;
  }
 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();
       }
     }
   }
 }
  @SuppressWarnings("unchecked")
  public MobeelizerJsonEntity(final String json) throws JSONException {
    JSONObject jsonObject = new JSONObject(json);
    model = jsonObject.getString("model");
    guid = jsonObject.getString("guid");

    if (jsonObject.has("owner")) {
      owner = jsonObject.getString("owner");
    }

    if (jsonObject.has("conflictState")) {
      conflictState = ConflictState.valueOf(jsonObject.getString("conflictState"));
    } else {
      conflictState = ConflictState.NO_IN_CONFLICT;
    }

    if (jsonObject.has("fields")) {
      JSONObject jsonFields = jsonObject.getJSONObject("fields");
      Iterator<String> keys = jsonFields.keys();
      fields = new HashMap<String, String>();

      while (keys.hasNext()) {
        String key = keys.next();
        fields.put(key, jsonFields.isNull(key) ? null : jsonFields.getString(key));
      }
    }
  }
  public static Bundle convertToBundle(JSONObject jsonObject) throws JSONException {
    Bundle bundle = new Bundle();
    @SuppressWarnings("unchecked")
    Iterator<String> jsonIterator = jsonObject.keys();
    while (jsonIterator.hasNext()) {
      String key = jsonIterator.next();
      Object value = jsonObject.get(key);
      if (value == null || value == JSONObject.NULL) {
        // Null is not supported.
        continue;
      }

      // Special case JSONObject as it's one way, on the return it would be Bundle.
      if (value instanceof JSONObject) {
        bundle.putBundle(key, convertToBundle((JSONObject) value));
        continue;
      }

      Setter setter = SETTERS.get(value.getClass());
      if (setter == null) {
        throw new IllegalArgumentException("Unsupported type: " + value.getClass());
      }
      setter.setOnBundle(bundle, key, value);
    }

    return bundle;
  }
 /**
  * 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;
 }