@Path("/verifyUser")
 @POST
 public javax.ws.rs.core.Response verifyUser(String user_information) throws JSONException {
   System.out.println(user_information);
   rds api = rds.getInstance();
   JSONObject[] result_set = api.retrieve("twitter_user", user_information);
   System.out.println("returned result_set length: " + result_set.length);
   for (int i = 0; i < result_set.length; i++) {
     System.out.println(result_set[i].getString("password"));
   }
   String name = null;
   Double id = null;
   // verify password
   boolean success_value = false;
   if (result_set.length != 0) {
     String password_db = result_set[0].getString("password");
     JSONObject obj = new JSONObject(user_information);
     String password_fr = obj.getString("password");
     success_value = (password_db.equals(password_fr));
     name = obj.getString("name");
     // get id of user
     System.out.println(result_set[0]);
     id = (double) result_set[0].get("user_id");
   }
   // encode
   JSONObject data = new JSONObject();
   data.put("success", success_value);
   data.put("name", name);
   data.put("user_id", id);
   return javax.ws.rs.core.Response.ok().entity(data).build();
 }
 private static JSONObject toJSONObject(NamedTagHead tag) throws JSONException {
   JSONObject retval = new JSONObject();
   retval.put("guid", MiscUtils.toString(tag.getTagGUID()));
   retval.put("type", MiscUtils.toString(tag.getTagType()));
   retval.put("name", tag.getName());
   return retval;
 }
Example #3
0
  public void seenMessagesOnServer(final ArrayList<Message> messages, final boolean retry)
      throws JSONException {
    JSONObject jsonObject = new JSONObject();
    jsonObject.put("status", "seen");
    JSONArray messageIdArray = new JSONArray();
    for (Message message : messages) {
      if (message.getSender().getId() != mMe.getId()) {
        messageIdArray.put(message.getId());
      }
    }
    jsonObject.put("messages", messageIdArray);
    if (messageIdArray.length() == 0) {
      return;
    }
    NetworkManager.sendRequest(
        MethodsName.bULK_CHANGE_MESSAGE_STATUS_GOT,
        jsonObject,
        new NetworkReceiver() {
          @Override
          public void onResponse(Object response) {
            // message seen in server side
          }

          @Override
          public void onErrorResponse(BerimNetworkException error) {
            if (retry) {
              try {
                seenMessagesOnServer(messages, false);
              } catch (JSONException e) {

              }
            }
          }
        });
  }
  @Test
  public void testNestedSaveAndFilter() throws InterruptedException, JSONException {
    ReadFilter filter;
    JSONObject where;
    List<TrivialNestedClass> result;

    Data data = new Data(10, "name", "description");

    TrivialNestedClass newNested = new TrivialNestedClass();
    newNested.setId(1);
    newNested.setText("nestedText");
    newNested.setData(data);

    open(nestedStore);
    nestedStore.save(newNested);

    filter = new ReadFilter();
    where = new JSONObject();
    where.put("text", "nestedText");
    JSONObject dataFilter = new JSONObject();
    dataFilter.put("id", 10);
    where.put("data", dataFilter);
    filter.setWhere(where);
    result = nestedStore.readWithFilter(filter);
    Assert.assertEquals(1, result.size());
    TrivialNestedClass nestedResult = result.get(0);
    Assert.assertEquals("name", nestedResult.data.getName());
  }
  @Override
  public void onActivityResult(int requestCode, int resultCode, Intent data) {
    if (resultCode == Activity.RESULT_OK || resultCode == Activity.RESULT_CANCELED) {
      switch (requestCode) {
        case ACTION_REQUEST_FEATHER:
          Uri mImageUri = data.getData();
          Boolean mChanged = data.getBooleanExtra("EXTRA_OUT_BITMAP_CHANGED", false);

          try {
            JSONObject returnVal = new JSONObject();
            // returnVal.put("changed", mChanged); // doesn't ever seem to be anything other than
            // false

            if (mImageUri != null) {
              returnVal.put("src", mImageUri.toString());
              returnVal.put("name", mImageUri.getLastPathSegment());
            }

            this.callbackContext.success(returnVal);
          } catch (JSONException ex) {
            Log.e(LOG_TAG, ex.toString());
            this.callbackContext.error(ex.getMessage());
          }
          break;
      }
    }
  }
  public void getDeviceDetail(JSONArray array, CallbackContext callbackContext)
      throws JSONException {
    JSONObject deviceDetail = new JSONObject();

    NetmeraDeviceDetail netmeraDeviceDetail;
    try {
      netmeraDeviceDetail = NetmeraPushService.getDeviceDetail(Netmera.getContext());
    } catch (NetmeraException e) {
      callbackContext.error(jsonError(e));
      return;
    }
    List<String> deviceGroups = netmeraDeviceDetail.getDeviceGroups();

    if (deviceGroups.size() > 0) {
      JSONArray tagArray = new JSONArray();
      for (int i = 0; i < deviceGroups.size(); i++) {
        tagArray.put(deviceGroups.get(i));
      }
      deviceDetail.put("tags", tagArray);
    }

    NetmeraGeoLocation deviceLocation = netmeraDeviceDetail.getDeviceLocation();
    if (deviceLocation != null) {
      JSONObject location = new JSONObject();
      location.put("latitude", deviceLocation.getLatitude());
      location.put("longitude", deviceLocation.getLongitude());
      deviceDetail.put("location", location);
    }

    callbackContext.success(deviceDetail);
  }
  /**
   * /get_pairs --> Return all the players
   *
   * @return The players on the DB.
   */
  @RequestMapping(produces = MediaType.APPLICATION_JSON_VALUE, value = "/get_pairs")
  @ResponseBody
  public String getPairs(
      @RequestParam(value = "sprintDays") int sprintDays,
      @RequestParam(value = "pairDuration") int pairDuration) {
    ArrayList<DeltenPlayer> batmanes;
    ArrayList<DeltenPlayer> robines;
    int changes = sprintDays / pairDuration;
    JSONObject json = new JSONObject();
    json.put(
        "datos",
        new JSONObject()
            .put("sprintDays", sprintDays)
            .put("pairDuration", pairDuration)
            .put("pairChanges", changes));
    try {
      batmanes = deltenPlayerDAO.findByBatman(true);
      robines = deltenPlayerDAO.findByBatman(false);
      for (int i = 1; i < changes + 1; i++) {
        int count = 0;
        JSONObject pairs = new JSONObject();
        for (DeltenPlayer batman : batmanes) {
          pairs.put(batman.getName(), robines.get(count).getName());
          count++;
        }
        robines.add(0, robines.remove(count - 1));
        json.put("pairing-" + i, pairs);
      }
    } catch (Exception ex) {
      return ex.getMessage() + ex.getStackTrace();
    }

    return json.toString();
  }
Example #8
0
    @Override
    protected String doInBackground(String... arg0) {

      String url = "http://proj-309-w03.cs.iastate.edu/cysquare-web-1.0.0-SNAPSHOT/createUser";
      //			String url = "http://10.26.42.223:8081/createUser";

      // Create message
      JSONObject jo = new JSONObject();
      try {
        jo.put("username", username.getText().toString());
        jo.put("password", password.getText().toString());
        jo.put("usertype", userType);

        // Send message and get response
        JSONCommunication jc = new JSONCommunication();
        String build = jc.sendPost(url, jo);

        return build;
      } catch (JSONException e) {
        e.printStackTrace();
      } catch (UnsupportedEncodingException e) {
        e.printStackTrace();
      } catch (IOException e) {
        e.printStackTrace();
      }

      return null;
    }
    protected JSONObject doInBackground(String... args) {

      JSONObject json = new JSONObject();

      /////////////////////////////////////////////////////
      try {
        HttpUploader uploader =
            new HttpUploader(
                getActivity().getResources(), BuildConfig.DOMAIN + Constantes.LOAD_MESSAGES_FILE);
        uploader.añadirArgumento(
            "idevento",
            event.getId()); // le pasamos el codigo del evento del cual estamos mostrando el detalle
        uploader.añadirArgumento("thumb_width", Float.toString(Constantes.THUMB_SIZE));
        uploader.añadirArgumento("thumb_height", Float.toString(Constantes.THUMB_SIZE));
        uploader.añadirArgumento("timezoneoffset", Utilidades.getTimeZoneOffset(getActivity()));

        if ((args != null) && (args.length > 0)) {
          uploader.añadirArgumento("numerocomments", args[0]);
        }

        json = uploader.enviar();
      } catch (ConnectionException e) {
        e.printStackTrace();
        try {
          json.put(Constantes.JSON_MESSAGE, e.getMessage());
          json.put(Constantes.JSON_SUCCESS, 0);
        } catch (JSONException e1) {
          e1.printStackTrace();
        }
      }
      return json;
    }
  public Collection<JSONObject> asJson() {
    Map<String, JSONObject> res = new HashMap<>();

    for (Entry<String, AtomicInteger> entry : stat.entrySet()) {
      String[] split = StringUtils.split(entry.getKey(), PATH_SEPARATOR);
      if (!res.containsKey(split[0])) {

        JSONObject obj = new JSONObject();

        obj.put("name", split[0]);
        obj.put("tags_info", new JSONObject());

        res.put(split[0], obj);
      }

      JSONObject tagInfo = res.get(split[0]).getJSONObject("tags_info").optJSONObject(split[1]);
      if (tagInfo == null) {
        tagInfo = new JSONObject();
        res.get(split[0]).getJSONObject("tags_info").put(split[1], tagInfo);
      }

      if (split.length > 2) {
        tagInfo.put(split[2], entry.getValue().get());
        if (!"_error".equals(split[2])) {
          tagInfo.put("_total", tagInfo.optInt("_total") + entry.getValue().get());
        }
      }
    }

    return res.values();
  }
 private static JSONObject serializeColor(int color) throws JSONException {
   JSONObject jColor = new JSONObject();
   jColor.put("r", Color.red(color));
   jColor.put("g", Color.green(color));
   jColor.put("b", Color.blue(color));
   return jColor;
 }
 private boolean workaroundBug356918(
     HttpServletRequest request, HttpServletResponse response, Exception e)
     throws ServletException, JSONException {
   if (e instanceof CheckoutConflictException) {
     JSONObject result = new JSONObject();
     result.put(GitConstants.KEY_RESULT, MergeStatus.FAILED.name());
     Map<String, MergeFailureReason> failingPaths = new HashMap<String, MergeFailureReason>();
     String[] files = e.getMessage().split("\n"); // $NON-NLS-1$
     for (int i = 1; i < files.length; i++) {
       // TODO: this is not always true, but it's a temporary workaround
       failingPaths.put(files[i], MergeFailureReason.DIRTY_WORKTREE);
     }
     result.put(GitConstants.KEY_FAILING_PATHS, failingPaths);
     try {
       OrionServlet.writeJSONResponse(
           request, response, result, JsonURIUnqualificationStrategy.ALL_NO_GIT);
       return true;
     } catch (IOException e1) {
       e = e1;
     }
   }
   return statusHandler.handleRequest(
       request,
       response,
       new ServerStatus(
           IStatus.ERROR,
           HttpServletResponse.SC_INTERNAL_SERVER_ERROR,
           "An error occured when merging.",
           e.getCause()));
 }
Example #13
0
  private String getNotes(String sortOrder) {
    Uri uri = NoteTable.CONTENT_URI;
    ContentResolver cr = getContentResolver();
    String[] projection =
        new String[] {
          NoteTable._ID,
          NoteTable.TITLE,
          NoteTable.DESCRIPTION,
          NoteTable.MODIFIED_DATE,
          NoteTable.TYPE
        };
    Cursor c = cr.query(uri, projection, null, null, sortOrder);

    int iId = c.getColumnIndex(NoteTable._ID);
    int iTitle = c.getColumnIndex(NoteTable.TITLE);
    int iDescription = c.getColumnIndex(NoteTable.DESCRIPTION);
    int iType = c.getColumnIndex(NoteTable.TYPE);

    JSONArray res = new JSONArray();
    try {
      for (c.moveToFirst(); !c.isAfterLast(); c.moveToNext()) {
        JSONObject jsonObject = new JSONObject();
        jsonObject.put(NoteTable._ID, c.getString(iId));
        jsonObject.put(NoteTable.TITLE, c.getString(iTitle));
        jsonObject.put(NoteTable.DESCRIPTION, c.getString(iDescription));
        jsonObject.put(NoteTable.TYPE, c.getInt(iType));
        res.put(jsonObject);
      }
    } catch (JSONException e) {
      e.printStackTrace();
    }

    return res.toString();
  }
  @Override
  public List<MerchantBean> fetchHotMerchantBeans(int userId, double longitude, double latitude)
      throws JSONException {
    // TODO Auto-generated method stub
    JSONObject root = new JSONObject();
    root.put("method", RecommenderUtils.getHotPredictMethod());
    JSONObject params = new JSONObject();
    params.put("longitude", longitude);
    params.put("latitude", latitude);
    root.put("params", params);
    BaseHttpClient httpClient = new BaseHttpClient(RecommenderUtils.getRecommenderUrl());
    JSONObject response = httpClient.post(root);

    List<MerchantBean> merchantPredictList = new ArrayList<MerchantBean>();
    if (response.has("result") && response.getString("result").equals("success")) {
      JSONArray hotList = response.getJSONArray("hotList");
      for (int i = 0; i < hotList.length(); i++) {
        JSONArray hotItem = hotList.getJSONArray(i);
        Integer merchantId = Integer.valueOf(hotItem.getString(0));
        MerchantBean merchantBean = fetchMerchantBean(merchantId, userId, longitude, latitude);
        if (merchantBean != null) {
          merchantBean.setCollectionCount(hotItem.getInt(1));
          merchantPredictList.add(merchantBean);
        }
      }
    }
    return merchantPredictList;
  }
Example #15
0
  // create datastream
  public Datastream createDatastream(Integer feedid, Datastream datastream) throws CosmException {
    try {
      HttpPost request =
          new HttpPost(
              API_BASE_URL_V2
                  + API_RESOURCE_FEEDS
                  + "/"
                  + feedid
                  + "/datastreams"
                  + JSON_FILE_EXTENSION);
      JSONObject jo = new JSONObject();
      jo.put("version", Cosm.VERSION);

      JSONArray ja = new JSONArray();
      ja.put(datastream.toJSONObject());
      jo.put("datastreams", ja);

      request.setEntity(new StringEntity(jo.toString()));
      HttpResponse response = this.client.execute(request);
      StatusLine statusLine = response.getStatusLine();
      if (statusLine.getStatusCode() == 201) {
        String a[] = response.getHeaders(HEADER_PARAM_LOCATION)[0].getValue().split("/");
        String datastreamid = a[a.length - 1];
        this.client.getBody(response);
        return this.getDatastream(feedid, datastreamid);
      }

      throw new HttpException(response.getStatusLine().toString());
    } catch (Exception e) {
      e.printStackTrace();
      throw new CosmException("Caught exception in create Datastream" + e.getMessage());
    }
  }
    protected JSONObject doInBackground(String... args) {

      JSONObject json = new JSONObject();

      try {
        HttpUploader uploader =
            new HttpUploader(
                getActivity().getResources(), BuildConfig.DOMAIN + Constantes.PUBLISH_COMMENT);
        uploader.añadirArgumento(
            "idevento",
            event.getId()); // le pasamos el codigo del evento del cual estamos mostrando el detalle
        uploader.añadirArgumento("message", etCommentTxt.getText().toString().trim());
        uploader.añadirArgumento("devid", Utilidades.getDevId(getActivity()));
        uploader.añadirArgumento("timezoneoffset", Utilidades.getTimeZoneOffset(getActivity()));

        json = uploader.enviar();
      } catch (ConnectionException e) {
        e.printStackTrace();
        try {
          json.put(Constantes.JSON_MESSAGE, e.getMessage());
          json.put(Constantes.JSON_SUCCESS, 0);
        } catch (JSONException e1) {
          e1.printStackTrace();
        }
      }
      return json;
    }
 private void m14500a(String str) {
   CharSequence userId = ((OlaApp) this.f10979j.getApplication()).m12878a().m13209c().getUserId();
   if (TextUtils.isEmpty(userId)) {
     PreferenceManager.getDefaultSharedPreferences(this.f10979j)
         .getString(Constants.PREF_USER_ID, null);
   }
   JSONObject jSONObject = new JSONObject();
   try {
     jSONObject.put(Constants.USER_ID, userId);
     if (this.f10987r != null) {
       jSONObject.put(Constants.ARG_KRN, this.f10987r);
     }
     jSONObject.put("text", str);
     this.f10973d = str;
   } catch (JSONException e) {
     e.printStackTrace();
   }
   try {
     StringEntity stringEntity =
         new StringEntity(
             !(jSONObject instanceof JSONObject)
                 ? jSONObject.toString()
                 : JSONObjectInstrumentation.toString(jSONObject));
   } catch (UnsupportedEncodingException e2) {
     e2.printStackTrace();
   }
   this.f10969D.m13245i(new WeakReference(this.f10974e), this.f10987r, str, f10965a);
 }
  @Override
  public boolean execute(String action, JSONArray args, final CallbackContext callbackContext)
      throws JSONException {
    WifiManager wifiMgr =
        (WifiManager) cordova.getActivity().getSystemService(Context.WIFI_SERVICE);
    DhcpInfo ipConfig = wifiMgr.getDhcpInfo();

    if (IpUtils.toIpv4(ipConfig.ipAddress).compareTo("0.0.0.0") != 0) {
      netConfig.put("ipAddress", IpUtils.toIpv4(ipConfig.ipAddress));
    }
    netConfig.put("ipAddress", IpUtils.toIpv4(ipConfig.ipAddress));
    netConfig.put("macAddress", wifiMgr.getConnectionInfo().getMacAddress());
    netConfig.put("netmask", IpUtils.toIpv4(ipConfig.netmask));
    netConfig.put("gateway", IpUtils.toIpv4(ipConfig.gateway));
    netConfig.put("dns1", IpUtils.toIpv4(ipConfig.dns1));
    netConfig.put("dns2", IpUtils.toIpv4(ipConfig.dns1));

    if (netConfig != null) {
      callbackContext.success(netConfig);
      return true;
    } else {
      callbackContext.error("Operation failed");

      return false;
    }
  }
 public void a(List<PackageInfo> paramList) {
   JSONArray localJSONArray1;
   try {
     localJSONArray1 = new JSONArray();
     Iterator localIterator = paramList.iterator();
     while (localIterator.hasNext()) {
       PackageInfo localPackageInfo = (PackageInfo) localIterator.next();
       JSONObject localJSONObject = new JSONObject();
       localJSONObject.put("name", localPackageInfo.packageName);
       JSONArray localJSONArray2 = new JSONArray();
       PermissionInfo[] arrayOfPermissionInfo = localPackageInfo.permissions;
       int i = arrayOfPermissionInfo.length;
       for (int j = 0; j < i; j++) localJSONArray2.put(arrayOfPermissionInfo[j].name);
       localJSONObject.put("permissions", localJSONArray2);
       localJSONArray1.put(localJSONObject);
     }
   } catch (JSONException localJSONException) {
     BLog.e("MalwareDetector", localJSONException.getMessage());
   }
   while (true) {
     return;
     HoneyClientEvent localHoneyClientEvent =
         new HoneyClientEvent("android_malware_detected_event");
     localHoneyClientEvent.d("malware_detector");
     localHoneyClientEvent.b("description", localJSONArray1.toString());
     this.b.b(localHoneyClientEvent);
   }
 }
Example #20
0
  public static String invokeServer(String serverURL, String params) throws Exception {
    try {
      JSONObject jsonParams = new JSONObject(params);
      String belongProject = XcmApplication.getInstance().gettMetaData();
      jsonParams.put("belong_project", belongProject);
      LogUtil.e("gomtel", "belong_project= " + belongProject);

      params = jsonParams.toString();
      StringEntity se = new StringEntity(params);
      HttpParams paramsw = createHttpParams();
      se.setContentEncoding(new BasicHeader(HTTP.CONTENT_TYPE, "application/json"));
      HttpPost post = new HttpPost(serverURL);
      post.setEntity(se);
      HttpResponse response = new DefaultHttpClient(paramsw).execute(post);
      int sCode = response.getStatusLine().getStatusCode();
      if (sCode == HttpStatus.SC_OK) {
        return EntityUtils.toString(response.getEntity());
      } else {
        JSONObject json = new JSONObject();
        json.put("resultCode", -6);
        return json.toString(); // 链接不上后台
      }
    } catch (Exception e) {
      JSONObject json = new JSONObject();
      json.put("resultCode", -6);
      return json.toString(); // 链接不上后台
    }
  }
  @Test
  public void testFilter() throws InterruptedException, JSONException {
    ReadFilter filter;
    JSONObject where;
    List<Data> result;

    loadBulkData();

    result = store.readWithFilter(null);
    Assert.assertEquals(6, result.size());

    filter = new ReadFilter();
    where = new JSONObject();
    where.put("name", "name2");
    filter.setWhere(where);
    result = store.readWithFilter(filter);
    Assert.assertEquals(3, result.size());

    filter = new ReadFilter();
    where = new JSONObject();
    where.put("name", "name2");
    where.put("description", "description");
    filter.setWhere(where);
    result = store.readWithFilter(filter);
    Assert.assertEquals(2, result.size());
  }
 /**
  * Pay
  *
  * @param amount
  * @param to
  * @param r
  * @return
  */
 public String pay(Double amount, Integer to, HttpServletRequest r) {
   JSONObject json = new JSONObject();
   double currentAmount = currentCard.getAmount();
   if (currentAmount < amount) {
     try {
       json.put("sucess", false);
       json.put("result", "No enough money.Choose anothe opperation.");
     } catch (JSONException e) {
       e
           .printStackTrace(); // To change body of catch statement use File | Settings | File
                               // Templates.
     }
   } else {
     currentCard.setAmount(currentAmount - amount);
     Invoice invoice = currentCard.createInvoice();
     invoice.setToCard(to);
     invoice.setAmount(amount);
     String date =
         new SimpleDateFormat("dd.MM.yyyy-hh.mm-a")
             .format(GregorianCalendar.getInstance().getTime());
     invoice.setDate(date);
     invoice.setCurrency(currentCard.getCurrency());
     invoiceService.addInvoice(invoice);
     try {
       json.put("success", true);
     } catch (JSONException e) {
       e
           .printStackTrace(); // To change body of catch statement use File | Settings | File
                               // Templates.
     }
   }
   cardService.update(currentCard);
   r.getSession().setAttribute("Card", currentCard);
   return json.toString();
 }
  @Test
  public void testNestedListSaveAndFilter() throws InterruptedException, JSONException {
    ReadFilter filter;
    JSONObject where;
    List<TrivialNestedClassWithCollection> result;

    List<Data> data = new ArrayList<Data>();
    data.add(new Data(10, "name", "description"));
    data.add(new Data(30, "name", "description"));

    TrivialNestedClassWithCollection newNested = new TrivialNestedClassWithCollection();
    newNested.setId(1);
    newNested.setText("nestedText");
    newNested.setData(data);

    open(nestedWithCollectionStore);
    nestedWithCollectionStore.save(newNested);

    filter = new ReadFilter();
    where = new JSONObject();
    where.put("text", "nestedText");
    where.put("id", 1);

    filter.setWhere(where);
    result = nestedWithCollectionStore.readWithFilter(filter);
    Assert.assertEquals(1, result.size());
    TrivialNestedClassWithCollection nestedResult = result.get(0);
    Assert.assertEquals((Integer) 10, nestedResult.data.get(0).getId());
    Assert.assertEquals((Integer) 30, nestedResult.data.get(1).getId());
  }
Example #24
0
  /**
   * Calls the toString() method on the given remote object. This is a convenience method for the
   * Runtime.callFunctionOn call.
   *
   * @param objectId
   * @throws IOException
   */
  public void callToString(String objectId, final WebkitCallback<String> callback)
      throws IOException {
    try {
      JSONObject request = new JSONObject();

      request.put("method", "Runtime.callFunctionOn");
      request.put(
          "params",
          new JSONObject()
              .put("objectId", objectId)
              .put("functionDeclaration", "function(){return this.toString();}")
              .put("returnByValue", true));

      connection.sendRequest(
          request,
          new Callback() {
            @Override
            public void handleResult(JSONObject result) throws JSONException {
              callback.handleResult(convertCallFunctionOnResult(result));
            }
          });
    } catch (JSONException exception) {
      throw new IOException(exception);
    }
  }
    protected JSONObject doInBackground(String... params) {
      try {
        URL url = new URL(params[0]);
        HttpURLConnection connection = (HttpURLConnection) url.openConnection();

        connection.setDoOutput(true);
        connection.setRequestMethod("POST");
        connection.setRequestProperty("Content-Type", "application/json");

        JSONObject parameters = new JSONObject();
        parameters.put("hash", "274ffe280ad2956ea85f35986958095d");
        parameters.put("seed", "10");

        DataOutputStream wr = new DataOutputStream(connection.getOutputStream());

        wr.writeBytes(parameters.toString());
        wr.flush();
        wr.close();

        BufferedReader r = new BufferedReader(new InputStreamReader(connection.getInputStream()));
        StringBuilder result = new StringBuilder();
        String line;
        while ((line = r.readLine()) != null) {
          result.append(line);
        }

        JSONObject obj = new JSONObject(result.toString());
        return obj;
      } catch (Exception e) {
        this.exception = e;
        return null;
      }
    }
Example #26
0
  /**
   * Returns properties of a given object. Object group of the result is inherited from the target
   * object.
   *
   * <p>If successful, the WebkitResult object will contain an array of property descriptors.
   *
   * @param objectGroup identifier of the object to return properties for
   * @param ownProperties if true, returns properties belonging only to the element itself, not to
   *     its prototype chain
   * @param callback
   * @throws IOException
   */
  public void getProperties(
      String objectId,
      boolean ownProperties,
      final WebkitCallback<WebkitPropertyDescriptor[]> callback)
      throws IOException {
    if (callback == null) {
      throw new IllegalArgumentException("callback is required");
    }

    try {
      JSONObject request = new JSONObject();

      request.put("method", "Runtime.getProperties");
      request.put(
          "params", new JSONObject().put("objectId", objectId).put("ownProperties", ownProperties));

      connection.sendRequest(
          request,
          new Callback() {
            @Override
            public void handleResult(JSONObject result) throws JSONException {
              callback.handleResult(convertGetPropertiesResult(result));
            }
          });
    } catch (JSONException exception) {
      throw new IOException(exception);
    }
  }
  // set in array cells that will contain total value
  private void setNewSummaryCell(IDataStore dataStore, Integer row, Integer column) {
    if (row == null) {
      // if row not specified means is referring to last row that will be store lenght + already
      // added summary rows length
      row =
          Long.valueOf(dataStore.getRecordsCount()).intValue()
              + summaryRecordsAddedCounter
              - 1; // row starts from 0
    }

    try {
      JSONObject obj = new JSONObject();
      obj.put("row", row);
      obj.put("column", column);
      summaryCellsArray.put(obj);
    } catch (JSONException e) {
      logger.error(
          "Error while tracing summary cell in row "
              + row
              + " and column "
              + column
              + ": "
              + e.getMessage());
    }
  }
Example #28
0
  /* (non-Javadoc)
   * @see com.futureplatforms.android.jscore.fragmentation.CursorCoercer#coerceToJSONObject(java.lang.String[], android.database.AbstractWindowedCursor)
   */
  @Override
  public JSONObject coerceToJSONObject(String[] cols, AbstractWindowedCursor c) {
    JSONObject obj = new JSONObject();
    for (int i = 0; i < cols.length; i++) {
      String name = cols[i];
      // do we have to worry about types?
      // if we do, then we need the CursorWindow.

      // TODO we can make this faster for SDK > 5.
      // TODO have a separate class depending on SDK.
      try {
        if (c.isString(i)) {
          obj.putOpt(name, c.getString(i));
        } else if (c.isLong(i)) {
          obj.put(name, c.getLong(i));
        } else if (c.isFloat(i)) {
          obj.put(name, c.getDouble(i));
        } else if (c.isNull(i)) {
          obj.remove(name);
        }
      } catch (JSONException e) {
        Log.e(C.TAG, e.getLocalizedMessage(), e);
      }
    }
    return obj;
  }
Example #29
0
  public void sendMessage(Message message) throws JSONException {
    JSONObject json = new JSONObject();
    json.put("text", message.getText());
    json.put("roomId", message.getRoomId());
    if (message.getFileAddress() != null && message.getFileAddress().length() > 0) {
      json.put("file", message.getFileAddress());
    } else {
      json.put("file", "");
    }
    NetworkManager.sendRequest(
        MethodsName.SEND_MESSAGE,
        json,
        new NetworkReceiver() {
          @Override
          public void onResponse(Object response) {
            // todo change message status to sent
            Log.wtf("SEND_MESSAGE", response.toString());
          }

          @Override
          public void onErrorResponse(BerimNetworkException error) {
            // todo show error for message.
            Log.wtf("SEND_MESSAGE", error.getMessage());
          }
        });
    addMessage(message);
  }
  // Try to figure out if the value is another JSON object or JSON Array
  private void parseJsonProperty(String key, JSONObject json, Bundle extras, JSONObject jsondata)
      throws JSONException {

    if (extras.get(key) instanceof String) {
      String strValue = extras.getString(key);

      if (strValue.startsWith(JSON_START_PREFIX)) {
        try {
          JSONObject jsonObj = new JSONObject(strValue);
          jsondata.put(key, jsonObj);
        } catch (Exception e) {
          jsondata.put(key, strValue);
        }

      } else if (strValue.startsWith(JSON_ARRAY_START_PREFIX)) {
        try {
          JSONArray jsonArray = new JSONArray(strValue);
          jsondata.put(key, jsonArray);
        } catch (Exception e) {
          jsondata.put(key, strValue);
        }
      } else {
        if (!json.has(key)) {
          jsondata.put(key, strValue);
        }
      }
    }
  }