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);
      }
    }
  @Test
  public void test_CreateSimpleWithObjectProp() {
    String classId = simpleClassId;

    ds.begin(ReadWrite.WRITE);
    try {
      Ontology ont = Ontology.loadOntology(ds, testOntologyName);
      JSONObject values = new JSONObject();

      String[] propValue = new String[1];
      propValue[0] = existingInstanceId;
      values.put(idChar + objectPropId, new JSONArray(propValue));

      OntologyInstance instance = ont.createInstance(classId, values);

      JSONObject rep = instance.getJSONRepresentation();

      assertTrue("JSON Rep: " + rep, rep.length() == values.length());
      assertTrue(
          "Instance does not have expected data property and value: " + rep,
          rep.has(idChar + objectPropId)
              && rep.optJSONArray(idChar + objectPropId).length() == 1
              && rep.optJSONArray(idChar + objectPropId).optString(0).equals(propValue[0]));
      ds.commit();
    } catch (JSONException e) {
      ds.abort();
      fail(e.getMessage());
    } finally {
      ds.end();
    }
  }
  /** 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"));
    }
  }
  @Test
  public void testUpdate() {

    ds.begin(ReadWrite.WRITE);
    try {
      Ontology ont = Ontology.loadOntology(ds, testOntologyName);

      JSONObject values = new JSONObject();

      OntologyInstance instance = ont.createInstance(simpleClassId, values);

      JSONObject rep = instance.getJSONRepresentation();

      assertTrue(rep.length() == 0);

      // Add DataProperty

      values.put(idChar + dataPropId, new JSONArray("[test]"));

      instance.update(values);

      rep = instance.getJSONRepresentation();

      assertTrue(rep.length() == 1);
      assertTrue(rep.toString().equals(values.toString()));

      ds.commit();
    } catch (JSONException e) {
      ds.abort();
      fail(e.getMessage());
    } finally {
      ds.end();
    }
  }
  private void assertVariantDetailLevel(
      VariantDetailLevel detailLevel, JSONObject result, int nVariants) {
    if (detailLevel.equals(VariantDetailLevel.NONE)) {
      Assert.assertEquals(0, result.length());
    } else {
      Assert.assertEquals(1, result.length());
      JSONArray variants = result.getJSONArray("variants");
      // Ensure expected number of variants
      Assert.assertEquals(nVariants, variants.length());

      for (int i = 0; i < nVariants; i++) {
        JSONObject v = variants.getJSONObject(i);
        Assert.assertNotNull(v);

        if (detailLevel.equals(VariantDetailLevel.FULL)) {
          // Ensure full variant details displayed
          Assert.assertTrue(v.length() > 4);

          Assert.assertTrue(v.getDouble("score") > 0);
          Assert.assertFalse(v.getString("chrom").isEmpty());
          Assert.assertTrue(v.getInt("position") > 0);
          Assert.assertFalse(v.getString("ref").isEmpty());
          Assert.assertFalse(v.getString("alt").isEmpty());
          Assert.assertFalse(v.getString("type").isEmpty());
        } else if (detailLevel.equals(VariantDetailLevel.LIMITED)) {
          // Ensure limited variant details displayed
          Assert.assertEquals(2, v.length());
          Assert.assertTrue(v.getDouble("score") > 0);
          Assert.assertFalse(v.getString("type").isEmpty());
        }
      }
    }
  }
Example #6
0
  public List<JsonData> getData(String jsonString) {
    jsonDatas = new ArrayList<>();

    try {
      Log.e("TestJsonString", jsonString);
      JSONArray array = new JSONArray(jsonString); // 最外层为[],用JSONArray

      for (int i = 0; i < array.length(); i++) {
        jsonData = new JsonData();

        JSONObject object = array.getJSONObject(i);
        jsonData.setId(object.getString("id"));
        jsonData.setTitle(object.getString("title"));
        jsonData.setUrl(object.getString("url"));
        jsonData.setContent(object.getString("content"));
        jsonData.setContent_rendered(object.getString("content_rendered"));
        jsonData.setReplies(object.getString("replies"));

        JSONObject memberObject = object.getJSONObject("member"); // number节点
        for (int j = 0; j < memberObject.length(); j++) {

          // JSONObject memberObject = memberObject.getJSONObject(j);
          jsonData.setMember_id(memberObject.getString("id"));
          jsonData.setMember_username(memberObject.getString("username"));
          jsonData.setMember_tagline(memberObject.getString("tagline"));
          jsonData.setMember_avatar_mini(memberObject.getString("avatar_mini"));
          jsonData.setMember_avatar_normal(memberObject.getString("avatar_normal"));
          jsonData.setMember_avatar_large(memberObject.getString("avatar_large"));
        }

        JSONObject nodeObject = object.getJSONObject("node"); // node节点
        for (int x = 0; x < nodeObject.length(); x++) {

          // JSONObject nodeObject = nodeArray.getJSONObject(x);
          jsonData.setNode_id(nodeObject.getString("id"));
          jsonData.setNode_name(nodeObject.getString("name"));
          jsonData.setNode_title(nodeObject.getString("title"));
          jsonData.setNode_title_alternative(nodeObject.getString("title_alternative"));
          jsonData.setNode_url(nodeObject.getString("url"));
          jsonData.setNode_topics(nodeObject.getString("topics"));
          jsonData.setNode_avartar_mini(nodeObject.getString("avatar_mini"));
          jsonData.setNode_avartar_normal(nodeObject.getString("avatar_normal"));
          jsonData.setNode_avatar_large(nodeObject.getString("avatar_large"));
        }

        jsonData.setCreated(object.getString("created"));
        jsonData.setLast_modified(object.getString("last_modified"));
        jsonData.setLast_touched(object.getString("last_touched"));

        jsonDatas.add(jsonData);
        Log.e("test_json", jsonDatas.toString());
      }

    } catch (Exception e) {
      e.printStackTrace();
    }

    return jsonDatas;
  }
Example #7
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;
  }
Example #8
0
 @Override
 public void mGetInfo(String content) {
   super.mGetInfo(content);
   List<ShopBean> list = new ArrayList<ShopBean>();
   ShopBean sBean = null;
   JSONObject json;
   try {
     json = new JSONObject(content);
     JSONObject zjson = null;
     for (int i = 0; i < json.length(); i++) {
       zjson = json.getJSONObject("shop" + (i + 1));
       sBean = new ShopBean();
       sBean.shopId = zjson.getInt("shopId");
       sBean.bAccount = zjson.getString("account");
       sBean.shopImg = zjson.getString("shopImg");
       sBean.shopName = zjson.getString("shopName");
       sBean.shopTime = zjson.getString("shopTime");
       sBean.shopAddress = zjson.getString("shopAddr");
       sBean.by = zjson.getInt("by");
       this.maxPage = zjson.getInt("sumPage");
       JSONObject sjson = new JSONObject(zjson.getString("sunday"));
       JSONObject ojson = null;
       List<SundayShopBean> slist = new ArrayList<SundayShopBean>();
       SundayShopBean ssbean = null;
       for (int j = 0; j < sjson.length(); j++) {
         ojson = sjson.getJSONObject("sun" + (j + 1));
         ssbean = new SundayShopBean();
         ssbean.tcType = ojson.getInt("tcType");
         ssbean.discount = ojson.getDouble("discount");
         ssbean.color = ojson.getString("color");
         ssbean.payNum = ojson.getInt("payNum");
         ssbean.lastNum = ojson.getInt("lastNum");
         ssbean.sundayId = ojson.getInt("sundayId");
         slist.add(ssbean);
       }
       sBean.dayType = slist;
       list.add(sBean);
     }
   } catch (JSONException e) {
     e.printStackTrace();
   }
   Collections.sort(
       list,
       new Comparator<Object>() {
         public int compare(Object a, Object b) {
           int one = ((ShopBean) a).by;
           int two = ((ShopBean) b).by;
           return one - two;
         }
       });
   Sources.SUNDAYINFO.addAll(list);
   mod.mSuccess();
 }
Example #9
0
    public Feed build() {
      // add properties if needed
      if (mProperties.length() > 0) {
        mBundle.putString(Parameters.PROPERTIES, mProperties.toString());
      }

      // add actions if needed
      if (mActions.length() > 0) {
        mBundle.putString(Parameters.ACTIONS, mActions.toString());
      }

      return new Feed(this);
    }
  @SmallTest
  @MediumTest
  @LargeTest
  public void testMapClear() throws JSONException {
    JSONObject jsonObject = new JSONObject();
    jsonObject.put("hello", "world");

    GraphObject graphObject = GraphObject.Factory.create(jsonObject);

    assertEquals(1, jsonObject.length());

    graphObject.asMap().clear();

    assertEquals(0, jsonObject.length());
  }
Example #11
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;
  }
  @Test
  public void testAString() throws Exception {
    FileLoggerMock mockFileLogger = setFileLoggerInstanceField(activity);
    LogPersister.setContext(activity);
    LogPersister.setLogLevel(LEVEL.DEBUG);
    Logger logger = Logger.getLogger("package");
    LogPersister.setAnalyticsCapture(true);

    logger.analytics("message", null);

    waitForNotify(logger);

    JSONArray jsonArray = mockFileLogger.getAccumulatedLogCalls();
    JSONObject jsonObject = jsonArray.getJSONObject(0);

    // jsonObject should have a fixed number of key/value pairs
    assertEquals(
        "resulting jsonobject in file has wrong number of key/value pairs", 6, jsonObject.length());
    // verify the key/value pairs
    assertTrue(
        jsonObject.has(TIMESTAMP_KEY)); // don't test the value, as it may differ from current
    assertEquals("package", jsonObject.get(PACKAGE_KEY));
    // WARN
    assertEquals("ANALYTICS", jsonObject.get(LEVEL_KEY));
    assertEquals("message", jsonObject.get(MESSAGE_KEY));
    // ensure no exception is thrown by parsing the threadid value:
    assertFalse(jsonObject.getLong(THREADID_KEY) == 0);
  }
  public IpLocationInfo decodeMessage(String message) {
    try {
      Log.d(TAG, "Parsing: " + message);
      ipLocationInfo = new IpLocationInfo();

      JSONObject jObject;
      jObject = new JSONObject(message);

      // extract location fields from JSON
      String value = getJsonValue(jObject, IpLocationInfo.KEY_IP);
      ipLocationInfo.setIp(value);

      if (jObject.length() > 1) {
        // only do these when querying location info
        value = getJsonValue(jObject, IpLocationInfo.KEY_LATITUDE);
        ipLocationInfo.setLatitude(value);
        value = getJsonValue(jObject, IpLocationInfo.KEY_LONGITUDE);
        ipLocationInfo.setLongitude(value);
        value = getJsonValue(jObject, IpLocationInfo.KEY_COUNTRY);
        ipLocationInfo.setCountry(value);
        value = getJsonValue(jObject, IpLocationInfo.KEY_CITY);
        ipLocationInfo.setCity(value);
        value = getJsonValue(jObject, IpLocationInfo.KEY_REGION);
        ipLocationInfo.setRegion(value);
        value = getJsonValue(jObject, IpLocationInfo.KEY_TIMEZONE);
        ipLocationInfo.setTimezone(value);
      }

    } catch (Exception e) {
      Log.e(TAG, "decodeMessage: exception during parsing - ", e);
      e.printStackTrace();
      return null;
    }
    return ipLocationInfo;
  }
Example #14
0
    @Override
    protected String doInBackground(String... params) {
      String result = "";
      try {
        HttpClient httpclient = new DefaultHttpClient();
        System.out.println("Result::" + "http://www.google.com/ig/calculator?q=" + params[0]);
        HttpPost httppost = new HttpPost("http://www.google.com/ig/calculator?q=" + params[0]);
        // httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
        HttpResponse response = httpclient.execute(httppost);
        HttpEntity entity = response.getEntity();
        InputStream is = entity.getContent();

        BufferedReader reader = new BufferedReader(new InputStreamReader(is, "iso-8859-1"), 8);
        StringBuilder sb = new StringBuilder();
        String line = null;
        while ((line = reader.readLine()) != null) {
          sb.append(line);
        }
        is.close();

        String output = sb.toString();
        System.out.println("output::" + output);
        JSONObject jobj = new JSONObject(output);
        System.out.println(jobj + "arrlen::" + jobj.length());
        String foo = jobj.get("lhs").toString();
        result = jobj.get("rhs").toString();
        System.out.println(foo + "::" + result + "RESULT : -" + output + "-");
        return result;

      } catch (Exception e) {
        System.out.println("Error parsing data " + e.toString());
      }

      return result;
    }
  @Test
  public void writeJSONWithSelectedFieldsAddsSelectedValues() throws ComponentLookupException {
    Map<String, String> map = new LinkedHashMap<String, String>();
    map.put(STATUS_KEY, "1");
    String pubmedID = "pubmed:0001";
    map.put("solved__pubmed_id", pubmedID);
    String geneID = "ABC1";
    map.put("solved__gene_id", geneID);
    String notes = "some notes about the solved case";
    map.put("solved__notes", notes);
    PatientData<String> patientData = new DictionaryPatientData<String>(DATA_NAME, map);
    doReturn(patientData).when(this.patient).getData(DATA_NAME);
    JSONObject json = new JSONObject();
    Collection<String> selectedFields = new LinkedList<>();
    selectedFields.add(STATUS_KEY);
    selectedFields.add("solved__notes");

    this.mocker.getComponentUnderTest().writeJSON(this.patient, json, selectedFields);

    JSONObject container = json.getJSONObject(DATA_NAME);
    Assert.assertEquals(2, container.length());
    Assert.assertEquals(STATUS_SOLVED, container.get("status"));
    Assert.assertEquals(notes, container.get("notes"));
    Assert.assertFalse(container.has("pubmed_id"));
    Assert.assertFalse(container.has("gene"));
  }
 /**
  * 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;
 }
Example #17
0
  private void parseResponse(JSONObject responseData) {
    if (responseData != null && responseData.length() > 0) {
      // mCategoryLinearLayout.removeAllViews();
      try {
        JSONArray categoryArray = responseData.getJSONArray("DATA");
        if (categoryArray.length() > 0) {
          mCategoryList = new ArrayList<Category>();
          categoryStringList = new String[categoryArray.length()];

          for (int i = 0; i < categoryArray.length(); i++) {
            Category catItem = new Category();
            catItem.setCategoryId(categoryArray.getJSONObject(i).getString("cat_id"));
            catItem.setCategoryName(categoryArray.getJSONObject(i).getString("cat_name"));
            catItem.setCategoryImage(categoryArray.getJSONObject(i).getString("cat_image"));
            catItem.setCategroyDiscription(categoryArray.getJSONObject(i).getString("cat_desc"));

            mCategoryList.add(catItem);
            categoryStringList[i] = catItem.getCategoryName().toUpperCase();
          }
        }

        mCategoryAdapter = new CategoryAdapter(mContext, mCategoryList);
        mCategoryListView.setAdapter(mCategoryAdapter);

      } catch (JSONException e) {
        e.printStackTrace();
      }
    }
  }
Example #18
0
  private static List<Geocache> parseCaches(final JSONObject response) {
    try {
      // Check for empty result
      final String result = response.getString("results");
      if (StringUtils.isBlank(result) || StringUtils.equals(result, "[]")) {
        return Collections.emptyList();
      }

      // Get and iterate result list
      final JSONObject cachesResponse = response.getJSONObject("results");
      if (cachesResponse != null) {
        final List<Geocache> caches = new ArrayList<Geocache>(cachesResponse.length());
        @SuppressWarnings("unchecked")
        final Iterator<String> keys = cachesResponse.keys();
        while (keys.hasNext()) {
          final String key = keys.next();
          final Geocache cache = parseSmallCache(cachesResponse.getJSONObject(key));
          if (cache != null) {
            caches.add(cache);
          }
        }
        return caches;
      }
    } catch (final JSONException e) {
      Log.e("OkapiClient.parseCachesResult", e);
    }
    return Collections.emptyList();
  }
  /**
   * 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;
  }
Example #20
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);
  }
  public static ArrayList<ContentProviderOperation> quoteJsonToContentVals(String JSON)
      throws JSONException {
    ArrayList<ContentProviderOperation> batchOperations = new ArrayList<>();
    JSONObject jsonObject = null;
    JSONArray resultsArray = null;
    ContentProviderOperation cpo = null;

    jsonObject = new JSONObject(JSON);
    if (jsonObject != null && jsonObject.length() != 0) {
      jsonObject = jsonObject.getJSONObject(QUERY);
      int count = Integer.parseInt(jsonObject.getString(COUNT));
      if (count == 1) {
        jsonObject = jsonObject.getJSONObject(RESULTS).getJSONObject(QUOTE);
        cpo = buildBatchOperation(jsonObject);
        if (cpo != null) {
          batchOperations.add(cpo);
        }

      } else {
        resultsArray = jsonObject.getJSONObject(RESULTS).getJSONArray(QUOTE);

        if (resultsArray != null && resultsArray.length() != 0) {
          for (int i = 0; i < resultsArray.length(); i++) {
            jsonObject = resultsArray.getJSONObject(i);
            cpo = buildBatchOperation(jsonObject);
            if (cpo != null) {
              batchOperations.add(cpo);
            }
          }
        }
      }
    }

    return batchOperations;
  }
 public JsonBackedSuggestionExtras(String json) throws JSONException {
   mExtras = new JSONObject(json);
   mColumns = new ArrayList<String>(mExtras.length());
   Iterator<String> it = mExtras.keys();
   while (it.hasNext()) {
     mColumns.add(it.next());
   }
 }
 public void sendGeofenceInfo() {
   Storage.turnLocationsToJson();
   JSONObject geofenceInfo = Storage.getGeofenceInfo();
   if (geofenceInfo.length() != 0) {
     String userID = ClientAuthentication.getClientId();
     new SendStoreGeofenceInfoRequest().execute(userID, geofenceInfo.toString());
   }
 }
  @Test
  public void testMergeIntoLocalFailedDirtyWorkTree() throws Exception {
    // clone a repo
    createWorkspace(SimpleMetaStore.DEFAULT_WORKSPACE_NAME);
    String workspaceId = workspaceIdFromLocation(workspaceLocation);
    JSONObject project =
        createProjectOrLink(workspaceLocation, getMethodName().concat("Project"), null);
    IPath clonePath = getClonePath(workspaceId, project);
    clone(clonePath);

    // get project metadata
    WebRequest request = getGetRequest(project.getString(ProtocolConstants.KEY_CONTENT_LOCATION));
    WebResponse response = webConversation.getResponse(request);
    assertEquals(HttpURLConnection.HTTP_OK, response.getResponseCode());
    project = new JSONObject(response.getText());
    JSONObject gitSection = project.getJSONObject(GitConstants.KEY_GIT);
    String gitHeadUri = gitSection.getString(GitConstants.KEY_HEAD);
    String gitRemoteUri = gitSection.getString(GitConstants.KEY_REMOTE);

    // add a parallel commit in secondary clone and push it to the remote
    JSONObject project2 =
        createProjectOrLink(workspaceLocation, getMethodName().concat("Project2"), null);
    IPath clonePath2 = getClonePath(workspaceId, project2);
    clone(clonePath2);

    // get project2 metadata
    request = getGetRequest(project2.getString(ProtocolConstants.KEY_CONTENT_LOCATION));
    response = webConversation.getResponse(request);
    assertEquals(HttpURLConnection.HTTP_OK, response.getResponseCode());
    project2 = new JSONObject(response.getText());
    JSONObject gitSection2 = project2.getJSONObject(GitConstants.KEY_GIT);
    String gitRemoteUri2 = gitSection2.getString(GitConstants.KEY_REMOTE);

    JSONObject testTxt = getChild(project2, "test.txt");
    modifyFile(testTxt, "change in secondary");
    addFile(testTxt);
    commitFile(testTxt, "commit on branch", false);

    ServerStatus pushStatus = push(gitRemoteUri2, 1, 0, Constants.MASTER, Constants.HEAD, false);
    assertEquals(true, pushStatus.isOK());

    // modify on master and try to merge
    testTxt = getChild(project, "test.txt");
    modifyFile(testTxt, "dirty");

    JSONObject masterDetails = getRemoteBranch(gitRemoteUri, 1, 0, Constants.MASTER);
    String masterLocation = masterDetails.getString(ProtocolConstants.KEY_LOCATION);
    fetch(masterLocation);
    JSONObject merge = merge(gitHeadUri, Constants.DEFAULT_REMOTE_NAME + "/" + Constants.MASTER);

    MergeStatus mergeResult = MergeStatus.valueOf(merge.getString(GitConstants.KEY_RESULT));
    assertEquals(MergeStatus.FAILED, mergeResult);
    JSONObject failingPaths = merge.getJSONObject(GitConstants.KEY_FAILING_PATHS);
    assertEquals(1, failingPaths.length());
    assertEquals(
        MergeFailureReason.DIRTY_WORKTREE,
        MergeFailureReason.valueOf(failingPaths.getString("test.txt")));
  }
Example #25
0
  public static ChatTopic buildRecord(String result) throws JSONException {

    ChatTopic target = new ChatTopic();
    JSONObject json = new JSONObject(result);
    if (json.length() != 0) {
      target = parseJson(json);
    }
    return target;
  }
  @Override
  public void sendMessage(final JSONObject message, final ResponseListener<Object> listener) {
    if (message == null || message.length() == 0) {
      Util.postError(listener, new ServiceCommandError(0, "Cannot send an Empty Message", null));
      return;
    }

    sendP2PMessage(message, listener);
  }
Example #27
0
 ///////////////////////////// PRODUCT API//////////////////////////////////
 public List<Product> listProducts(String query, int page, int perpage) throws Exception {
   String params = "?page=" + page + "&per_page=" + perpage;
   if (query != null && !query.isEmpty()) params += "&query=" + query;
   JSONObject response = requestGet(userid, token, null, "products.json" + params);
   Log.e("Jumlah anak response", response.length() + "");
   Log.e("Jumlah name response", response.names().length() + "");
   String message = response.getString("message");
   Log.e("Jumlah anak message", message + "");
   return null;
 }
Example #28
0
  @Override
  protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_ue);

    try {
      String jsResult = new Ue().getAllUE();
      JSONObject jObject = new JSONObject(jsResult);
      String[] web = new String[jObject.length()];
      Integer[] imageId = new Integer[jObject.length()];
      for (int i = 0; i < jObject.length(); i++) {
        JSONObject json_data = jObject.optJSONObject("" + i);
        String title = json_data.getJSONObject("ue").getString("Nom");
        web[i] = title;
        imageId[i] = R.drawable.cours;
      }
      Log.i("res", "Amine");
      ListView mListView = (ListView) findViewById(R.id.listView2);
      mListView.setAdapter(new ListAdapter(this, web, imageId));

      mListView.setOnItemClickListener(
          new OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> arg0, View arg1, int arg2, long arg3) {
              // TODO Auto-generated method stub
              TextView v = (TextView) arg1.findViewById(R.id.txt);
              try {
                Intent i = new Intent(UEActivity.this, MainActivity.class);
                i.putExtra("Nom", v.getText());
                startActivity(i);
              } catch (Exception e) {
                // TODO Auto-generated catch block
                Toast.makeText(getApplicationContext(), e.getMessage(), Toast.LENGTH_LONG).show();
              }
              //
            }
          });

    } catch (Exception e) {
      // TODO Auto-generated catch block
      e.printStackTrace();
    }
  }
  /** Positive test case for listJobCodes method with optional parameters. */
  @Test(
      groups = {"wso2.esb"},
      dependsOnMethods = {"testAddJobCodesWithMandatoryParameters"},
      description = "tsheets {listJobCodes} integration test with optional parameters.")
  public void testListJobCodesWithOptionalParameters() throws IOException, JSONException {

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

    JSONObject esbJobCodes =
        esbRestResponse.getBody().getJSONObject("results").getJSONObject("jobcodes");

    int esbJobCodesCount = esbJobCodes.length();

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

    JSONObject apiJobCodes =
        apiRestResponse.getBody().getJSONObject("results").getJSONObject("jobcodes");

    int apiJobCodesCount = esbJobCodes.length();

    Assert.assertEquals(apiJobCodesCount, esbJobCodesCount);

    Iterator<String> esbJobCodesKeySet = esbJobCodes.keys();

    while (esbJobCodesKeySet.hasNext()) {

      String jobCodeKey = esbJobCodesKeySet.next();
      JSONObject esbJobCode = esbJobCodes.getJSONObject(jobCodeKey);
      JSONObject apiJobCode = apiJobCodes.getJSONObject(jobCodeKey);

      Assert.assertEquals(apiJobCode.getString("id"), esbJobCode.getString("id"));
      Assert.assertEquals(apiJobCode.getString("created"), esbJobCode.getString("created"));
      Assert.assertEquals(
          apiJobCode.getString("last_modified"), esbJobCode.getString("last_modified"));
    }
  }
  @Test
  public void writeJSONWithSelectedFieldsReturnsWhenGetDataReturnsNull()
      throws ComponentLookupException {
    doReturn(null).when(this.patient).getData(DATA_NAME);
    JSONObject json = new JSONObject();
    Collection<String> selectedFields = new LinkedList<>();

    this.mocker.getComponentUnderTest().writeJSON(this.patient, json, selectedFields);

    Assert.assertEquals(0, json.length());
  }