private MediaConstraints constraintsFromJSON(String jsonString) throws JSONException {
   if (jsonString == null) {
     return null;
   }
   MediaConstraints constraints = new MediaConstraints();
   JSONObject json = new JSONObject(jsonString);
   JSONObject mandatoryJSON = json.optJSONObject("mandatory");
   if (mandatoryJSON != null) {
     JSONArray mandatoryKeys = mandatoryJSON.names();
     if (mandatoryKeys != null) {
       for (int i = 0; i < mandatoryKeys.length(); ++i) {
         String key = mandatoryKeys.getString(i);
         String value = mandatoryJSON.getString(key);
         constraints.mandatory.add(new MediaConstraints.KeyValuePair(key, value));
       }
     }
   }
   JSONArray optionalJSON = json.optJSONArray("optional");
   if (optionalJSON != null) {
     for (int i = 0; i < optionalJSON.length(); ++i) {
       JSONObject keyValueDict = optionalJSON.getJSONObject(i);
       String key = keyValueDict.names().getString(0);
       String value = keyValueDict.getString(key);
       constraints.optional.add(new MediaConstraints.KeyValuePair(key, value));
     }
   }
   return constraints;
 }
Esempio n. 2
0
 private Session parseJson(final String json) {
   Session session = null;
   try {
     JSONObject jsonObject = new JSONObject(json);
     session = new Session();
     session.setIp(jsonObject.optString("ip"));
     session.setDomain(jsonObject.optString("domain"));
     session.setPath(jsonObject.optString("path"));
     session.setUserAgent(jsonObject.optString("userAgent"));
     session.setDateTime(parseDateFormat.parse(jsonObject.optString("dateTime")));
     Map<String, BasicClientCookie> cookies = new HashMap<String, BasicClientCookie>();
     JSONObject cookiesObject = jsonObject.optJSONObject("cookies");
     JSONArray cookieArray = cookiesObject.names();
     if (cookieArray != null) {
       for (int i = 0; i < cookieArray.length(); i++) {
         JSONObject cookieObject = cookiesObject.getJSONObject(cookieArray.getString(i));
         BasicClientCookie cookie =
             new BasicClientCookie(
                 cookieObject.optString("name"), cookieObject.optString("value"));
         cookie.setDomain(cookieObject.optString("domain"));
         cookies.put(cookieArray.getString(i), cookie);
       }
     }
     session.setCookies(cookies);
   } catch (JSONException e) {
     e.printStackTrace();
   } catch (ParseException e) {
     e.printStackTrace();
   }
   return session;
 }
Esempio n. 3
0
  public static void reflectJsonObject(Object model, JSONObject jsonObj) throws JSONException {
    Class<?> modelClass = model.getClass();
    JSONArray names = jsonObj.names();

    if (names != null) {
      for (int i = 0; i < names.length(); i++) {

        String name = names.getString(i);

        try {
          Field field = ReflectionHelper.getFieldInHierarchy(modelClass, name);

          if (field.getType() == List.class) {
            processListField(model, field, jsonObj.getJSONArray(name));

          } else {
            processSingleField(model, field, jsonObj, name);
          }

        } catch (NoSuchFieldException e) {
          Log.w(JsonReflector.class.getName(), "Can not locate field named " + name);

        } catch (IllegalAccessException e) {
          Log.w(JsonReflector.class.getName(), "Can not access field named " + name);

        } catch (InstantiationException e) {
          Log.w(
              JsonReflector.class.getName(),
              "Can not create an instance of the type defined in the field named " + name);
        }
      }
    }
  }
 public boolean isTagsPresent(String data, JSONObject tags) {
   if (tags == null) return true;
   else {
     int index;
     JSONArray names = tags.names();
     try {
       JSONObject jsonData = new JSONObject(data);
       JSONObject dataTags = new JSONObject(jsonData.getString("tags"));
       for (index = 0; index < names.length(); index++) {
         String name = names.getString(index);
         JSONArray dataTagArray = dataTags.getJSONArray(name);
         JSONArray tagArray = tags.getJSONArray(name);
         boolean isFound = false;
         for (int iteri = 0; iteri < tagArray.length(); iteri++) {
           for (int iterj = 0; iterj < dataTagArray.length(); iterj++) {
             if (tagArray.getString(iteri).contentEquals(dataTagArray.getString(iterj)))
               isFound = true;
           }
         }
         if (dataTagArray.length() * tagArray.length() == 0) isFound = true;
         if (!isFound) return false;
       }
     } catch (JSONException e) {
       e.printStackTrace();
     }
   }
   return true;
 }
Esempio n. 5
0
  @POST
  @Path("/getSavedSearches")
  @Consumes(MediaType.APPLICATION_FORM_URLENCODED)
  @Produces("application/json")
  public String getSavedSearches(@FormParam("user") String user) {

    JSONArray queryList = new JSONArray();

    System.out.println(user);

    CouchConnection couch = new CouchConnection("http://localhost:5984/", "savedsearches/");

    JSONObject viewDocument = new JSONObject();
    JSONArray searches = new JSONArray();
    JSONArray keys = new JSONArray();
    boolean existingViews = true;
    try {
      viewDocument = new JSONObject(couch.queryDB(user));
      keys = viewDocument.names();
      System.out.println(keys.toString());
    } catch (Exception e) {
      existingViews = false;
    }

    return keys.toString();
  }
  @Override
  public void onComplete(String response, Object state) {
    try {
      JSONObject json = new JSONObject(response);

      if (json.has("data") && !json.isNull("data")) {
        JSONObject data = json.getJSONArray("data").getJSONObject(0);

        // Permissions are keys
        JSONArray names = data.names();

        ArrayList<String> current = new ArrayList<String>();

        for (int i = 0; i < names.length(); i++) {

          // If we're ON we're on
          String permission = names.getString(i);
          int status = data.getInt(permission);

          if (status == 1) {
            // ON
            current.add(permission);
          }
        }

        String[] values = current.toArray(new String[current.size()]);

        Arrays.sort(values); // Sort for binary searching

        onSuccess(values);
      }
    } catch (JSONException e) {
      onError(new SocializeException(e));
    }
  }
  private String convertJSONtoString(JSONObject json) {
    StringBuilder result = new StringBuilder();

    if (json != null) {
      JSONArray names = json.names();
      if (names != null) {
        boolean first = true;
        int size = names.length();
        for (int i = 0; i < size; i++) {
          try {
            String key = names.getString(i);

            if (first) {
              result.append("?");
              first = false;
            } else {
              result.append("&");
            }

            String value = json.getString(key);
            result.append(key).append("=").append(value);
          } catch (JSONException e) {
            e.printStackTrace();
            return null;
          }
        }
      }
    }

    return result.toString();
  }
  public Professor[] JsonProfessores() {
    JSONArray jsonArray = null;

    Professor[] professores;
    professores = new Professor[2000];
    JSONObject jsonobjectresult = null;

    try {

      JSONObject jsonObject = new JSONObject(json);
      String tamanho = jsonObject.getString("totalCount");
      JSONArray jsonresult = jsonObject.getJSONArray("result");
      for (int i = 0; i < Integer.parseInt(tamanho); i++) {
        professores[i] = new Professor();
      }
      for (int i = 0; i < Integer.parseInt(tamanho); i++) {
        JSONObject professor = jsonresult.getJSONObject(i);
        professores[i].setUsuarioMatricula(professor.getString("usuarioMatricula"));
        professores[i].setUsuarioEmail(professor.getString("usuarioEmail"));

        professores[i].setUsuarioCargo(professor.getString("usuarioCargo"));
        if (professor.names().toString().contains("usuarioNome")) {
          professores[i].setUsuarioNome(professor.getString("usuarioNome"));
        }
      }
    } catch (Exception e) {
      e.printStackTrace();
    }
    {
    }
    return professores;
  }
Esempio n. 9
0
        @Override
        public void handleMessage(Message msg) {
          String friendsListResponse = (String) msg.obj;
          try {
            jObj = new JSONObject(friendsListResponse);
          } catch (JSONException e1) {
            e1.printStackTrace();
          }

          if (!jObj.isNull("message")) {
            // they are not registered OR they entered incorrect username/password
            Toast.makeText(getApplicationContext(), "You have no friends =(", Toast.LENGTH_LONG)
                .show();
          } else {
            try {
              jObj = new JSONObject(friendsListResponse);
              jObj.names();
              Log.d(TAG, "Names 1: " + jObj.names().toString());
              jArray = jObj.getJSONArray("Friends");
              Log.d(TAG, "Friends: " + jArray.toString());
              // jObj.names();
              Log.d(TAG, "Names 2: " + jObj.names().toString());
              // jArray = jObj.getJSONArray("Friend");
              // Log.d(TAG, "Array 0: " + jArray.getString(0).toString());

              for (int i = 0; i < jArray.length(); ++i) {
                String temp = jArray.getString(i).toString();
                JSONObject friend = new JSONObject(temp);
                String thisFriend = friend.getString("Friend");
                Log.d(TAG, "Friend " + i + ": " + thisFriend);
                friendList.add(thisFriend);
              }
              // friendList.get(0).toString();
              friendAdapter =
                  new ExtendedArrayAdapter(
                      getApplicationContext(), R.layout.simple_list_item_1, friendList);
              friendListview.setAdapter(friendAdapter);
              friendListview.setVisibility(View.VISIBLE);
            } catch (JSONException e) {
              e.printStackTrace();
            }
            // Toast.makeText(getApplicationContext(), "The Friends List Response was : " +
            // friendsListResponse + ".", Toast.LENGTH_LONG).show();
          }
        }
Esempio n. 10
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;
 }
Esempio n. 11
0
  @Test
  public void shouldReturnListOfChangeLogsForNewFieldValueToExistingChild() throws JSONException {
    Child oldChild = new Child("id", "user", "{'gender' : 'male', 'name' : 'old-name'}");
    Child updatedChild =
        new Child(
            "id", "user", "{'gender' : 'male','nationality' : 'Indian', 'name' : 'new-name'}");
    List<Child.History> histories = updatedChild.changeLogs(oldChild);

    JSONObject changesMap = (JSONObject) histories.get(0).get(CHANGES);
    JSONObject fromTo = (JSONObject) changesMap.get("nationality");

    assertThat(histories.size(), is(2));
    assertThat(changesMap.names().get(0).toString(), is("nationality"));
    assertThat(fromTo.get(FROM).toString(), is(""));
    assertThat(fromTo.get(TO).toString(), is("Indian"));

    changesMap = (JSONObject) histories.get(1).get(CHANGES);
    fromTo = (JSONObject) changesMap.get("name");

    assertThat(changesMap.names().get(0).toString(), is("name"));
    assertThat(fromTo.get(FROM).toString(), is("old-name"));
    assertThat(fromTo.get(TO).toString(), is("new-name"));
  }
Esempio n. 12
0
  public void shouldReturnListOfChangeLogsBasedOnChanges() throws JSONException {
    Child oldChild = new Child("id", "user", "{'name' : 'old-name'}");
    Child updatedChild = new Child("id", "user", "{'name' : 'updated-name'}");
    List<Child.History> histories = updatedChild.changeLogs(oldChild);

    JSONObject changesMap = (JSONObject) histories.get(0).get(CHANGES);
    HashMap fromTo = (HashMap) changesMap.get("name");

    assertThat(histories.size(), is(1));
    assertThat(histories.get(0).get(USER_NAME).toString(), is(updatedChild.getOwner()));
    assertThat(changesMap.names().get(0).toString(), is("name"));
    assertThat(fromTo.get(FROM).toString(), is("old-name"));
    assertThat(fromTo.get(TO).toString(), is("updated-name"));
  }
Esempio n. 13
0
  private void setupBundle(final View view, final JSONObject publisherData, final String bundleid) {

    final JSONObject bundleData = publisherData.optJSONObject(bundleid);
    if (bundleData != null && bundleData.names().length() > 0) {
      log.info("config found for", bundleid);
      final Bundle bundle = addBundle(view, bundleid);
      mergeBundleConfiguration(bundle, bundleData, null);
    } else {
      log.warn("config not found for", bundleid, "- removing bundle.");
      // We have to remove the bundle...
      // TODO: check if we really want to remove the bundle from view since it could be template
      // view???
      view.removeBundle(bundleid);
    }
  }
Esempio n. 14
0
  /**
   * Load the url into the webview.
   *
   * @param url
   * @param props Properties that can be passed in to the Cordova activity (i.e. loadingDialog,
   *     wait, ...)
   * @throws JSONException
   */
  public void loadUrl(String url, JSONObject props) throws JSONException {
    LOG.d("App", "App.loadUrl(" + url + "," + props + ")");
    int wait = 0;
    boolean openExternal = false;
    boolean clearHistory = false;

    // If there are properties, then set them on the Activity
    HashMap<String, Object> params = new HashMap<String, Object>();
    if (props != null) {
      JSONArray keys = props.names();
      for (int i = 0; i < keys.length(); i++) {
        String key = keys.getString(i);
        if (key.equals("wait")) {
          wait = props.getInt(key);
        } else if (key.equalsIgnoreCase("openexternal")) {
          openExternal = props.getBoolean(key);
        } else if (key.equalsIgnoreCase("clearhistory")) {
          clearHistory = props.getBoolean(key);
        } else {
          Object value = props.get(key);
          if (value == null) {

          } else if (value.getClass().equals(String.class)) {
            params.put(key, (String) value);
          } else if (value.getClass().equals(Boolean.class)) {
            params.put(key, (Boolean) value);
          } else if (value.getClass().equals(Integer.class)) {
            params.put(key, (Integer) value);
          }
        }
      }
    }

    // If wait property, then delay loading

    if (wait > 0) {
      try {
        synchronized (this) {
          this.wait(wait);
        }
      } catch (InterruptedException e) {
        e.printStackTrace();
      }
    }
    this.webView.showWebPage(url, openExternal, clearHistory, params);
  }
 static Map<String, Object> convertJSONObjectToHashMap(JSONObject jsonObject) {
   HashMap<String, Object> map = new HashMap<String, Object>();
   JSONArray keys = jsonObject.names();
   for (int i = 0; i < keys.length(); ++i) {
     String key;
     try {
       key = keys.getString(i);
       Object value = jsonObject.get(key);
       if (value instanceof JSONObject) {
         value = convertJSONObjectToHashMap((JSONObject) value);
       }
       map.put(key, value);
     } catch (JSONException e) {
     }
   }
   return map;
 }
Esempio n. 16
0
  private static Pair toPairs(JSONObject json) throws JSONException {
    Pair list = Pair.EMPTY;

    JSONArray names = json.names();

    for (int i = 0; i < names.length(); i++) {
      String name = names.getString(i);
      Object item = json.get(name);

      if (item instanceof JSONArray) item = JSONHelper.toList((JSONArray) item);
      else if (item instanceof JSONObject) item = JSONHelper.toPairs((JSONObject) item);

      list = new Pair(new Pair(name, item), list);
    }

    return new Pair(new Pair(Symbol.QUOTE, new Pair(list, Pair.EMPTY)), Pair.EMPTY);
  }
Esempio n. 17
0
      @Override
      public List<String> handleResponse(HttpResponse response)
          throws ClientProtocolException, IOException {

        String JSONResponse = new BasicResponseHandler().handleResponse(response);
        try {

          JSONObject responseObject = (JSONObject) new JSONTokener(JSONResponse).nextValue();

          JSONArray values = responseObject.names();
          JSONArray weather = responseObject.toJSONArray(values);

          for (int idx = 0; idx < weather.length(); idx++) {

            JSONObject weatherObj = weather.getJSONObject(idx);

            // result
            result.add(
                NAME
                    + ": "
                    + weatherObj.get(NAME)
                    + "\n"
                    + "\n"
                    + LATITUDE
                    + ": "
                    + weatherObj.getString(LATITUDE)
                    + "\n"
                    + "\n"
                    + LONGITUDE
                    + ": "
                    + weatherObj.get(LONGITUDE)
                    + " F'"
                    + "\n"
                    + "\n"
                    + AREA
                    + ": "
                    + weatherObj.get(AREA));
          }

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

        return result;
      }
  /**
   * This method is used to parse JSON to get revision ID TODO Need to find a way to make this and
   * the above methods more generic
   *
   * @param response
   * @return
   */
  public static String parseRevisionJson(String response) {
    String revisionID = null;

    try {
      JSONObject jsonObject = new JSONObject(response);
      JSONObject queryObject = jsonObject.getJSONObject("query");
      JSONObject pagesObject = queryObject.getJSONObject("pages");

      String id = pagesObject.names().get(0).toString();
      JSONObject pageID = pagesObject.getJSONObject(id);
      JSONArray revisionsArray = pageID.getJSONArray("revisions");
      revisionID = revisionsArray.getJSONObject(0).getString("revid");

    } catch (JSONException e) {
      // TODO: handle exception
    }
    return revisionID;
  }
  /**
   * Helper to read json string representing field name-value map
   *
   * @param jsonTextField
   * @return
   */
  private Map<String, Object> parseFieldMap(int jsonTextField) {
    String fieldsString = ((EditText) findViewById(jsonTextField)).getText().toString();
    if (fieldsString.length() == 0) {
      return null;
    }

    try {
      JSONObject fieldsJson = new JSONObject(fieldsString);
      Map<String, Object> fields = new HashMap<String, Object>();
      JSONArray names = fieldsJson.names();
      for (int i = 0; i < names.length(); i++) {
        String name = (String) names.get(i);
        fields.put(name, fieldsJson.get(name));
      }
      return fields;

    } catch (Exception e) {
      printHeader("Could not parse: " + fieldsString);
      printException(e);
      return null;
    }
  }
  public ArrayList<Map<String, String>> JSON(String url, Context context) {
    ArrayList<Map<String, String>> lista = new ArrayList<Map<String, String>>();

    JSONObject myJSON = new JSONObject();
    JSONArray names = null;
    String restWebServerResponse = getInternet(context, url);
    if (restWebServerResponse != "seminternet") {
      try {
        JSONArray myJSONArray = new JSONArray(restWebServerResponse);
        for (int i = 0; i < myJSONArray.length(); i++) {
          Map<String, String> data = new HashMap<String, String>();
          myJSON = new JSONObject(myJSONArray.getString(i));
          names = myJSON.names();
          for (int j = 0; j < names.length(); j++) {
            Log.i("JSON Items", names.getString(j) + ", " + myJSON.getString(names.getString(j)));
            data.put(names.getString(j), myJSON.getString(names.getString(j)));
          }
          data.put("internet", "true");
          lista.add(data);
        }
        Log.i("JSON Lista", lista.toString());
      } catch (JSONException e) {
        Log.e("JSON", e.getMessage());
      }
    } else {
      Map<String, String> data = new HashMap<String, String>();
      data.put("internet", "false");
      lista.add(data);
    }
    if (lista.size() > 0) {
      return lista;
    } else {
      Map<String, String> data = new HashMap<String, String>();
      data.put("internet", "false");
      lista.add(data);
      return lista;
    }
  }
 @Override
 protected Void doInBackground(Void... arg0) {
   JSONObject fbFeed = JSONParser.getJSONObjectfromURL(mUrl);
   try {
     if (fbFeed.get("link") == JSONObject.NULL) {
       publishProgress("Facebook feed not found");
     } else {
       JSONArray fbFeedEntries = fbFeed.getJSONArray("entries");
       for (int i = 0; i < fbFeedEntries.length(); i++) {
         HashMap<String, String> fbMap = new HashMap<String, String>();
         JSONObject obj = fbFeedEntries.getJSONObject(i);
         JSONArray objFieldNames = obj.names();
         for (int j = 0; j < objFieldNames.length(); j++) {
           String fieldName = objFieldNames.getString(j);
           if (obj.has(fieldName)) fbMap.put(fieldName, obj.getString(fieldName));
         }
         fbMap.put("id", String.valueOf(i));
         if (obj.has("published")) {
           try {
             SimpleDateFormat curFormater = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ssZ");
             SimpleDateFormat postFormater = new SimpleDateFormat("MMMM dd, yyyy 'at' h:mm a");
             Date dateObj = curFormater.parse(obj.getString("published"));
             String pubDate = postFormater.format(dateObj);
             fbMap.put("date", pubDate);
           } catch (java.text.ParseException e) {
             Log.e(FacebookFeedActivity.class.toString(), "Error parsing date: " + e.toString());
           }
         }
         mFeedData.add(fbMap);
       }
     }
   } catch (JSONException e) {
     Log.e(
         FacebookFeedActivity.class.toString(), "Error parsing facebook feed: " + e.toString());
   }
   return null;
 }
Esempio n. 22
0
 public Pair keys(JSONObject json) throws JSONException {
   return JSONHelper.toList(json.names());
 }
Esempio n. 23
0
  public void handle(HttpRequest request, HttpResponse response, HttpContext argument)
      throws HttpException, IOException {
    if (BasicAuthHelper.isAuthenticated(request) == false) {
      BasicAuthHelper.unauthedResponse(response);

      return;
    }

    response.setStatusCode(HttpStatus.SC_OK);

    if (request instanceof HttpEntityEnclosingRequest) {
      HttpEntityEnclosingRequest enclosingRequest = (HttpEntityEnclosingRequest) request;

      HttpEntity entity = enclosingRequest.getEntity();

      String entityString = EntityUtils.toString(entity);

      Uri u = Uri.parse("http://localhost/?" + entityString);

      JSONObject arguments = null;

      try {
        arguments = new JSONObject(URLDecoder.decode(u.getQueryParameter("json"), "UTF-8"));
      } catch (JSONException e) {
        LogManager.getInstance(this._context).logException(e);

        response.setStatusCode(HttpStatus.SC_INTERNAL_SERVER_ERROR);

        StringEntity body = new StringEntity(e.toString());
        body.setContentType("text/plain");

        response.setEntity(body);

        return;
      }

      if (arguments != null) {
        try {
          JavaScriptEngine engine = new JavaScriptEngine(this._context);

          String action = arguments.getString("action");

          if ("fetch".equals(action)) {
            if (arguments.has("keys")) {
              JSONObject result = new JSONObject();
              result.put("status", "success");

              JSONArray keys = arguments.getJSONArray("keys");

              JSONObject values = new JSONObject();

              for (int i = 0; i < keys.length(); i++) {
                String key = keys.getString(i);

                String value = engine.fetchString(key);

                values.put(key, value);
              }

              result.put("values", values);

              StringEntity body = new StringEntity(result.toString(2));
              body.setContentType("application/json");

              response.setEntity(body);

              return;
            }
          } else if ("put".equals(action)) {
            JSONArray names = arguments.names();

            for (int i = 0; i < names.length(); i++) {
              String name = names.getString(i);

              if ("action".equals(name) == false) {
                String value = arguments.getString(name);

                if (value != null) engine.persistString(name, value);
              }
            }

            JSONObject result = new JSONObject();
            result.put("status", "success");

            StringEntity body = new StringEntity(result.toString(2));
            body.setContentType("application/json");

            response.setEntity(body);

            return;
          }
        } catch (JSONException e) {
          LogManager.getInstance(this._context).logException(e);

          response.setStatusCode(HttpStatus.SC_INTERNAL_SERVER_ERROR);

          StringEntity body = new StringEntity(e.toString());
          body.setContentType("text/plain");

          response.setEntity(body);

          return;
        }
      }
    }

    response.setStatusCode(HttpStatus.SC_INTERNAL_SERVER_ERROR);

    StringEntity body = new StringEntity(this._context.getString(R.string.error_malformed_request));
    body.setContentType("text/plain");

    response.setEntity(body);
  }
Esempio n. 24
0
 public static boolean isEmptyObject(JSONObject object) {
   return object.names() == null;
 }