Example #1
0
 @Override
 protected Void doInBackground(Void... params) {
   try {
     JSONParser jsonParser = new JSONParser(LoginActivity.this);
     JSONStringer jsonData =
         new JSONStringer()
             .object()
             .key("email")
             .value(etForgotPass.getText().toString())
             .endObject();
     String[] data;
     data =
         jsonParser.sendPostReq(
             Constants.api_ip + Constants.api_forgot_password, jsonData.toString());
     responseCode = Integer.valueOf(data[0]);
     if (responseCode == 200) {
       jObj = new JSONObject(data[1]);
       flag = JSONData.getBoolean(jObj, "flag");
       message = JSONData.getString(jObj, "message");
     }
   } catch (Exception e) {
     e.printStackTrace();
   }
   return null;
 }
 /**
  * 生成 JSON Description Array String
  *
  * @param description Description String
  * @return JSON String
  */
 @SuppressLint("DefaultLocale")
 public static String GenerateJSONDescription(String description) {
   if (description != null) {
     if (description.length() > 0 && !description.contains("null")) {
       JSONStringer jsonStringer = new JSONStringer();
       try {
         jsonStringer.array();
         for (String item : description.split("#")) {
           String[] part = item.split(":");
           jsonStringer.object();
           jsonStringer
               .key("id")
               .value(
                   part.length > 0
                       ? part[0].replaceAll("(?i)bit", "").replaceFirst("^0+(?!$)", "")
                       : "");
           jsonStringer.key("value").value(part.length > 1 ? part[1] : "");
           jsonStringer.endObject();
         }
         jsonStringer.endArray();
       } catch (JSONException e) {
         e.printStackTrace();
       }
       return jsonStringer.toString();
     } else {
       return "";
     }
   } else {
     return "";
   }
 }
 public static String stringWithObject(Object value) {
   String contentString = "";
   JSONStringer js = new JSONStringer();
   serialize(js, value);
   contentString = js.toString();
   return contentString;
 }
  /**
   * @param e
   * @param response
   */
  private void getError(Exception e, HttpServletResponse response) {
    PrintWriter print;
    // Do not display database or other system errors to the client
    final String errormessage = "A System Error Occurred, Contact the Administrator";

    try {
      print = response.getWriter();
      response.setContentType("text/javascript");
      StringBuffer toPrint = new StringBuffer();
      StringBuffer toPrint2 = new StringBuffer();
      toPrint.append("{ \"result\":");

      JSONStringer stringer = new JSONStringer();
      stringer.object();
      stringer.key("error");
      // stringer.value(e.getClass().toString() + ":" + e.getMessage());
      stringer.value(errormessage);
      stringer.endObject();
      toPrint.append(stringer.toString());
      toPrint2.append(e.getClass().toString() + ":" + e.getMessage() + "\n");

      StackTraceElement[] stack = e.getStackTrace();
      for (int i = 0; i < stack.length; i++) {
        toPrint2.append(stack[i].toString() + "\n");
      }
      toPrint.append("}");
      print.write(toPrint.toString());
      logger.error(toPrint2.toString());
    } catch (IOException e1) {
      e1.printStackTrace();
    } catch (JSONException e2) {
      e2.printStackTrace();
    }
  }
Example #5
0
 /**
  * Encodes this object as a compact JSON string, such as:
  *
  * <pre>{"query":"Pizza","locations":[94043,90210]}</pre>
  */
 @Override
 public String toString() {
   try {
     JSONStringer stringer = new JSONStringer();
     writeTo(stringer);
     return stringer.toString();
   } catch (JSONException e) {
     return null;
   }
 }
Example #6
0
  private JSONObject send(JSONStringer data) throws UnknownHostException, IOException {

    Socket s = new Socket(_host, _port);

    s.getOutputStream().write(data.toString().getBytes());

    JSONObject o = new JSONObject(new JSONTokener(s.getInputStream()));

    s.close();

    return o;
  }
Example #7
0
 @Override
 public String toJSONString() {
   JSONStringer stringer = new JSONStringer();
   try {
     stringer.object();
     this.toJSONString(stringer);
     stringer.endObject();
   } catch (JSONException e) {
     e.printStackTrace();
     System.exit(-1);
   }
   return stringer.toString();
 }
Example #8
0
 /**
  * Encodes {@code data} as a JSON string. This applies quotes and any necessary character
  * escaping.
  *
  * @param data the string to encode. Null will be interpreted as an empty string.
  */
 public static String quote(String data) {
   if (data == null) {
     return "\"\"";
   }
   try {
     JSONStringer stringer = new JSONStringer();
     stringer.open(JSONStringer.Scope.NULL, "");
     stringer.value(data);
     stringer.close(JSONStringer.Scope.NULL, JSONStringer.Scope.NULL, "");
     return stringer.toString();
   } catch (JSONException e) {
     throw new AssertionError();
   }
 }
Example #9
0
 /**
  * Main method to encode geometries.
  *
  * @param o The object to encode: It can be one of: <code>Feature</code> <code>FeatureCollection
  *     </code> <code>Point</code> <code>MultiPoint</code>
  * @return The GeoJSON String with the object encoded
  * @throws JSONException
  */
 public String encode(Object o) throws JSONException {
   if (o instanceof Feature) {
     encodeFeature((Feature) o);
   } else if (o instanceof FeatureCollection) {
     encodeFeatureCollection((FeatureCollection) o);
   } else if (o instanceof Point) {
     encodeGeometry((Point) o);
   } else if (o instanceof MultiPoint) {
     encodeGeometry((MultiPoint) o);
   } else {
     // TODO
     // throw exception;
   }
   return builder.toString();
 }
Example #10
0
  public String marshal() throws JSONException {

    JSONStringer stringer = new JSONStringer();

    stringer.object();
    stringer.key("scope").value(this.scope);
    if (this.callbackUrl != null) {
      stringer.key("callbackUrl").value(this.callbackUrl);
    }
    if (this.returnUrl != null) {
      stringer.key("returnUrl").value(this.returnUrl);
    }
    stringer.key("deadline").value(this.deadline);
    stringer.endObject();

    return stringer.toString();
  }
Example #11
0
 public String toJSONString() {
   final JSONStringer json = new JSONStringer();
   try {
     if (messageParts.size() == 1) {
       latest().writeJson(json);
     } else {
       json.object().key("text").value("").key("extra").array();
       for (final MessagePart part : messageParts) {
         part.writeJson(json);
       }
       json.endArray().endObject();
     }
   } catch (final JSONException e) {
     throw new RuntimeException("invalid message");
   }
   return json.toString();
 }
Example #12
0
 public JSONStringer generateDeviceJSON(Context context, boolean isFirst, String userAccount) {
   LocationUtils location = new LocationUtils(context);
   JSONStringer deviceJson = new JSONStringer();
   try {
     deviceJson.object();
     deviceJson.key("deviceid");
     //            deviceJson.value(getsDeviceIdSHA1());
     deviceJson.value(getPseudoID());
     deviceJson.key("useraccount");
     deviceJson.value(userAccount); // /TODO
     deviceJson.key("devicename");
     deviceJson.value(sDeviceManufacturer);
     deviceJson.key("devicetype");
     deviceJson.value("1"); // 1手机
     deviceJson.key("deviceos");
     deviceJson.value(2000); // Android
     deviceJson.key("devicemac");
     deviceJson.value(WLAN_MAC);
     deviceJson.key("devicephonenum");
     deviceJson.value(TEL);
     deviceJson.key("deviceislock");
     deviceJson.value(0);
     deviceJson.key("deviceisdel");
     deviceJson.value(0);
     deviceJson.key("deviceinittime");
     Date date = new Date();
     deviceJson.value(date.getTime()); // TODO 日期格式 long型
     deviceJson.key("devicevalidperiod");
     deviceJson.value(365); // //TODO 暂定365天有效。服务器需要支持修改
     deviceJson.key("deviceisillegal");
     deviceJson.value(0);
     deviceJson.key("deviceisactive");
     deviceJson.value(isFirst ? 1 : 0); // 第一台设备不做peer校验,直接注册
     deviceJson.key("deviceislogout");
     deviceJson.value(0);
     deviceJson.key("deviceeaster");
     deviceJson.value(userAccount);
     deviceJson.key("bakstr1");
     deviceJson.value(location.getLocation()); // TODO 目前是经度+空格+纬度
     deviceJson.endObject();
     Log.d(TAG, "JSON-----" + deviceJson.toString());
   } catch (JSONException e) {
     e.printStackTrace();
   }
   return deviceJson;
 }
  public String saveMap(String action, MapViewModel map) {
    String returnVal = null;
    try {
      // POST request to <service>/SaveCrop
      String s = svcUri + action;
      HttpPost request = new HttpPost(svcUri + action);
      request.setHeader("Accept", "application/json");
      request.setHeader("Content-type", "application/json");
      request.setHeader("User-Agent", "Fiddler");

      // Build JSON string
      JSONStringer mapJson =
          new JSONStringer()
              .object()
              .key("map")
              .object()
              .key("mapid")
              .value(0)
              .key("longitude")
              .value(map.getLongitude())
              .key("latitude")
              .value(map.getLatitude())
              .key("field_fk")
              .value(map.getFieldId())
              .endObject()
              .endObject();
      StringEntity entity = new StringEntity(mapJson.toString());

      request.setEntity(entity);

      // Send request to WCF service
      DefaultHttpClient httpClient = new DefaultHttpClient();
      HttpResponse response = httpClient.execute(request);
      HttpEntity httpEntity = response.getEntity();
      returnVal = EntityUtils.toString(httpEntity);
    } catch (Exception e) {
      e.printStackTrace();
    }
    return returnVal;
  }
  /**
   * Returns the JSON text for the wrapped JSON object or representation.
   *
   * @return The JSON text.
   * @throws JSONException
   */
  private String getJsonText() throws JSONException {
    String result = null;

    if (this.jsonValue != null) {
      if (this.jsonValue instanceof JSONArray) {
        JSONArray jsonArray = (JSONArray) this.jsonValue;

        if (isIndenting()) {
          result = jsonArray.toString(getIndentingSize());
        } else {
          result = jsonArray.toString();
        }
      } else if (this.jsonValue instanceof JSONObject) {
        JSONObject jsonObject = (JSONObject) this.jsonValue;

        if (isIndenting()) {
          result = jsonObject.toString(getIndentingSize());
        } else {
          result = jsonObject.toString();
        }
      } else if (this.jsonValue instanceof JSONStringer) {
        JSONStringer jsonStringer = (JSONStringer) this.jsonValue;
        result = jsonStringer.toString();
      } else if (this.jsonValue instanceof JSONTokener) {
        JSONTokener jsonTokener = (JSONTokener) this.jsonValue;
        result = jsonTokener.toString();
      }
    } else if (this.jsonRepresentation != null) {
      try {
        result = this.jsonRepresentation.getText();
      } catch (IOException e) {
        throw new JSONException(e);
      }
    }

    return result;
  }
  private String inventoryToJson(Inventory inventory) throws JSONException {
    JSONStringer json = new JSONStringer().object();

    json.key("purchaseMap").array();
    for (Map.Entry<String, Purchase> entry : inventory.getPurchaseMap().entrySet()) {
      json.array();
      json.value(entry.getKey());
      json.value(purchaseToJson(entry.getValue()));
      json.endArray();
    }
    json.endArray();

    json.key("skuMap").array();
    for (Map.Entry<String, SkuDetails> entry : inventory.getSkuMap().entrySet()) {
      json.array();
      json.value(entry.getKey());
      json.value(skuDetailsToJson(entry.getValue()));
      json.endArray();
    }
    json.endArray();

    json.endObject();
    return json.toString();
  }
Example #16
0
 /**
  * 将对象转换成Json字符串
  *
  * @param obj
  * @return json类型字符串
  */
 public static String toJSON(Object obj) {
   JSONStringer js = new JSONStringer();
   serialize(js, obj);
   return js.toString();
 }
  protected void doGet(HttpServletRequest request, HttpServletResponse response)
      throws ServletException, IOException {
    String q = request.getParameter("q");
    String simple = request.getParameter("simple");
    String test = request.getParameter("test");
    boolean isTest = false;
    if (test != null && test.equals("true")) {
      isTest = true;
    }
    PrintWriter w = response.getWriter();
    if (q != null) {
      // 지원사항을 알려준다.
      response.setCharacterEncoding("utf-8");
      response.setStatus(HttpServletResponse.SC_OK);
      response.setContentType("application/json;");

      String[] collectionNameList = service.getCollectionNameList();
      boolean[] status = service.getCollectionStatus();

      JSONStringer stringer = new JSONStringer();
      try {
        stringer.array();
        if (collectionNameList != null) {
          for (int i = 0; i < collectionNameList.length; i++) {
            stringer.object().key("name").value(collectionNameList[i]);
            if (isTest) {
              stringer.key("status").value(true);
            } else {
              stringer.key("status").value(status[i]);
            }
            stringer.endObject();
          }
        }
        stringer.endArray();
        //    			logger.debug("stringer = "+stringer);
        w.println(stringer.toString());
      } catch (JSONException e) {
        throw new ServletException("JSONException 발생", e);
      }
    } else {
      String callback = request.getParameter("jsoncallback");

      response.setCharacterEncoding("utf-8");
      response.setStatus(HttpServletResponse.SC_OK);

      if (RESULT_TYPE == JSONP_TYPE) {
        response.setContentType("text/javascript;");
      } else {
        response.setContentType("application/json;");
      }
      String[] collectionNameList = service.getCollectionNameList();
      boolean[] status = service.getCollectionStatus();
      RealTimeCollectionStatistics[] statistics = service.getCollectionStatisticsList();
      RealTimeCollectionStatistics globalCollectionStatistics =
          service.getGlobalCollectionStatistics();
      // 결과생성
      JSONStringer stringer = new JSONStringer();
      try {
        //
        // 간략정보
        //
        if (simple != null) {
          if (isTest) {
            stringer.object();
            int hit = r.nextInt(30) + 1;
            stringer.key("h").value(r.nextInt(30) + 1);
            stringer.key("fh").value(r.nextInt(hit > 5 ? 5 : hit));
            int ta = r.nextInt(50) + 1;
            stringer.key("ta").value(ta + 1);
            stringer.key("tx").value(ta + r.nextInt(20) + 1);
            stringer.endObject();
          } else {
            // 컬렉션 통합 정보를 리턴한다.
            //	    				if(collectionNameList != null){
            //	    					int hit = 0;
            //	    					int failHit = 0;
            //	    					int avgTime = 0;
            //	    					int maxTime = 0;
            //	    					int count = 0;
            //	    					for (int i = 0; i < collectionNameList.length; i++) {
            //	    						if(status[i]){
            //	    							count++;
            //	    							hit += statistics[i].getHitPerUnitTime();
            //	    							failHit += statistics[i].getFailHitPerUnitTime();
            //	    							avgTime += statistics[i].getMeanResponseTime();
            //	    							if(statistics[i].getMaxResponseTime() > maxTime){
            //	    								maxTime = statistics[i].getMaxResponseTime();
            //	    							}
            //	    						}
            //	    					}
            //	    				}
            stringer.object();
            stringer.key("h").value(globalCollectionStatistics.getHitPerUnitTime());
            stringer.key("fh").value(globalCollectionStatistics.getFailHitPerUnitTime());
            stringer.key("ach").value(globalCollectionStatistics.getAccumulatedHit());
            stringer.key("acfh").value(globalCollectionStatistics.getAccumulatedFailHit());
            stringer.key("ta").value(globalCollectionStatistics.getMeanResponseTime());
            stringer.key("tx").value(globalCollectionStatistics.getMaxResponseTime());
            stringer.endObject();
          }
        } else {
          //
          // 컬렉션별 상세정보
          //
          stringer.array();
          if (collectionNameList != null) {
            for (int i = 0; i < collectionNameList.length; i++) {
              if (status[i]) {
                stringer.object().key("c").value(collectionNameList[i]);
                if (isTest) {
                  int hit = r.nextInt(10) + 1;
                  stringer.key("h").value(hit);
                  stringer.key("fh").value(r.nextInt(hit > 3 ? 3 : hit));
                  stringer.key("ta").value(r.nextInt(100) + 1);
                  stringer.key("tx").value(r.nextInt(50) + r.nextInt(20) + 1);
                } else {
                  stringer.key("h").value(statistics[i].getHitPerUnitTime());
                  stringer.key("fh").value(statistics[i].getFailHitPerUnitTime());
                  stringer.key("ach").value(statistics[i].getAccumulatedHit());
                  stringer.key("acfh").value(statistics[i].getAccumulatedFailHit());
                  stringer.key("ta").value(statistics[i].getMeanResponseTime());
                  stringer.key("tx").value(statistics[i].getMaxResponseTime());
                }
                stringer.endObject();
              }
            }
          }
          stringer.endArray();
        }
      } catch (JSONException e) {
        throw new ServletException("JSONException 발생", e);
      }

      // JSONP는 데이터 앞뒤로 function명으로 감싸준다.
      if (RESULT_TYPE == JSONP_TYPE) {
        w.write(callback + "(");
      }

      // 정보를 보내준다.
      w.write(stringer.toString());

      if (RESULT_TYPE == JSONP_TYPE) {
        w.write(");");
      }
    }
    w.close();
  }
Example #18
0
 /**
  * Encodes this object as a human readable JSON string for debugging, such as:
  *
  * <pre>
  * {
  *     "query": "Pizza",
  *     "locations": [
  *         94043,
  *         90210
  *     ]
  * }</pre>
  *
  * @param indentSpaces the number of spaces to indent for each level of nesting.
  */
 public String toString(int indentSpaces) throws JSONException {
   JSONStringer stringer = new JSONStringer(indentSpaces);
   writeTo(stringer);
   return stringer.toString();
 }
  // *****************************************************************************
  // Save Contact using HTTP PUT method with singleContactUrl.
  // If Id is zero(0) a new Contact will be added.
  // If Id is non-zero an existing Contact will be updated.
  // HTTP POST could be used to add a new Contact but the ContactService knows
  // an Id of zero means a new Contact so in this case the HTTP PUT is used.
  // *****************************************************************************
  public Integer SaveContact(Contact saveContact) {
    Integer statusCode = 0;
    HttpResponse response;

    try {
      boolean isValid = true;

      // Data validation goes here

      if (isValid) {

        // POST request to <service>/SaveVehicle
        HttpPut request = new HttpPut(singleContactUrl + saveContact.getId());
        request.setHeader("User-Agent", "dev.ronlemire.contactClient");
        request.setHeader("Accept", "application/json");
        request.setHeader("Content-type", "application/json");

        // Build JSON string
        JSONStringer contact =
            new JSONStringer()
                .object()
                .key("Id")
                .value(Integer.parseInt(saveContact.getId()))
                .key("FirstName")
                .value(saveContact.getFirstName())
                .key("LastName")
                .value(saveContact.getLastName())
                .key("Email")
                .value(saveContact.getEmail())
                .endObject();
        StringEntity entity = new StringEntity(contact.toString());

        request.setEntity(entity);

        // Send request to WCF service
        DefaultHttpClient httpClient = new DefaultHttpClient();
        response = httpClient.execute(request);

        Log.d("WebInvoke", "Saving : " + response.getStatusLine().getStatusCode());

        // statusCode =
        // Integer.toString(response.getStatusLine().getStatusCode());
        statusCode = response.getStatusLine().getStatusCode();

        if (saveContact.getId().equals("0")) {
          // New Contact.Id is in buffer
          HttpEntity responseEntity = response.getEntity();
          char[] buffer = new char[(int) responseEntity.getContentLength()];
          InputStream stream = responseEntity.getContent();
          InputStreamReader reader = new InputStreamReader(stream);
          reader.read(buffer);
          stream.close();
          statusCode = Integer.parseInt(new String(buffer));
        } else {
          statusCode = response.getStatusLine().getStatusCode();
        }
      }

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

    return statusCode;
  }
Example #20
0
    @Override
    protected Void doInBackground(Void... params) {
      JSONParser jParser = new JSONParser(context);

      try {
        if (type == 1) {
          jsonStringer =
              new JSONStringer()
                  .object()
                  .key("email")
                  .value(email)
                  .key("password")
                  .value(pass)
                  .endObject();
          data =
              jParser.sendPostReqLogin(
                  Constants.api_v1 + Constants.api_login, jsonStringer.toString());
        } else if (type == 2) {
          jsonStringer =
              new JSONStringer()
                  .object()
                  .key("facebook_id")
                  .value(user_id)
                  .key("first_name")
                  .value(firstName)
                  .key("email")
                  .value(email)
                  .key("image")
                  .value(imageUrl)
                  .endObject();
          data =
              jParser.sendPostReqLogin(
                  Constants.api_v1 + Constants.api_facebook_login, jsonStringer.toString());
        } else if (type == 3) {
          jsonStringer =
              new JSONStringer()
                  .object()
                  .key("google_id")
                  .value(user_id)
                  .key("first_name")
                  .value(firstName)
                  .key("email")
                  .value(email)
                  .key("image")
                  .value(imageUrl)
                  .endObject();
          data =
              jParser.sendPostReqLogin(
                  Constants.api_v1 + Constants.api_google_login, jsonStringer.toString());
        }
        responseCode = Integer.parseInt(data[0]);
        if (responseCode == 200) {
          jsonObjects = new JSONObject(data[1]);
          message = JSONData.getString(jsonObjects, "message");
          flag = JSONData.getBoolean(jsonObjects, "flag");
          if (flag) {
            JSONObject dataObj = jsonObjects.getJSONObject("data");
            UserDataPreferences.saveToken(LoginActivity.this, dataObj.getString("token"));
            UserDataPreferences.saveUserInfo(LoginActivity.this, dataObj.toString());
            Calendar calendar = Calendar.getInstance();
            UserDataPreferences.saveLoginDate(LoginActivity.this, calendar.getTimeInMillis());

            final int cartCount =
                Integer.parseInt(
                    dataObj.has("cart_count")
                        ? (dataObj.isNull("cart_count") ? "0" : dataObj.getString("cart_count"))
                        : "0");
            if (cartCount > 0) {
              UserDataPreferences.saveCartCount(LoginActivity.this, cartCount);
            }
          }
        }
      } catch (Exception e) {
        e.printStackTrace();
      }
      return null;
    }