/**
  * 生成 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 "";
   }
 }
 @Override
 public void toJSONString(JSONStringer stringer) throws JSONException {
   super.toJSONString(stringer);
   stringer.key(Members.COLUMN_IDX.name()).value(m_columnIndex);
   stringer.key(Members.TABLE_NAME.name()).value(m_tableName);
   stringer.key(Members.COLUMN_NAME.name()).value(m_columnName);
   stringer.key(Members.COLUMN_ALIAS.name()).value(m_columnAlias);
 }
  /**
   * @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();
    }
  }
Exemple #4
0
  private void encodeFeature(Feature f) throws JSONException {
    builder.object();
    builder.key("type").value("Feature");
    // builder.key("id").value(f.getID());
    builder.key("geometry");

    IGeometry g = f.getGeometry();
    encodeGeometry(g);

    builder.key("properties");
    builder.object();
    // TODO encode Feature
    // f.toJSON(builder);
    builder.endObject();
    builder.endObject();
  }
Exemple #5
0
  private void encodeFeatureCollection(FeatureCollection c) throws JSONException {
    builder.object();
    builder.key("type").value("FeatureCollection");
    builder.key("features");
    builder.array();

    Enumeration e = c.getFeatures().elements();

    while (e.hasMoreElements()) {
      Feature f = (Feature) e.nextElement();
      encodeFeature(f);
    }

    builder.endArray();
    builder.endObject();
  }
Exemple #6
0
 void writeTo(JSONStringer stringer) throws JSONException {
   stringer.object();
   for (Map.Entry<String, Object> entry : nameValuePairs.entrySet()) {
     stringer.key(entry.getKey()).value(entry.getValue());
   }
   stringer.endObject();
 }
Exemple #7
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();
  }
Exemple #8
0
 private void encodeBoundingBox(Extent env) throws JSONException {
   builder.key("bbox");
   builder.array();
   builder.value(env.getMinX());
   builder.value(env.getMinY());
   builder.value(env.getMaxX());
   builder.value(env.getMaxY());
   builder.endArray();
 }
Exemple #9
0
  private void encodeGeometry(IGeometry g) throws JSONException {

    builder.object();
    builder.key("type");
    String name = getGeometryName(g);
    if (name != null) {
      builder.value(name);
      if (name.compareTo("Point") == 0) {
        builder.key("coordinates");
        encodeCoordinate((Point) g);
      } else if (name.compareTo("MultiPoint") == 0) {
        MultiPoint mp = (MultiPoint) g;
        builder.key("coordinates");
        builder.array();
        for (int i = 0; i < mp.getNumPoints(); i++) {
          encodeCoordinate(((MultiPoint) g).getPoint(i));
        }
        builder.endArray();
      }
    }
    builder.endObject();
  }
  public String getJSONEncodedParams() {
    try {
      JSONStringer json = new JSONStringer().object();

      for (String key : params.keySet()) {
        json.key(key).value(params.get(key));
      }

      return URLEncoder.encode(json.endObject().toString(), "UTF-8");
    } catch (Exception e) {
      e.printStackTrace();
    }

    return null;
  }
  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();
  }
Exemple #12
0
 /**
  * 序列化Map
  *
  * @param js json对象
  * @param map map对象
  */
 private static void serializeMap(JSONStringer js, Map<?, ?> map) {
   try {
     js.object();
     @SuppressWarnings("unchecked")
     Map<String, Object> valueMap = (Map<String, Object>) map;
     Iterator<Map.Entry<String, Object>> it = valueMap.entrySet().iterator();
     while (it.hasNext()) {
       Map.Entry<String, Object> entry = (Map.Entry<String, Object>) it.next();
       js.key(entry.getKey());
       serialize(js, entry.getValue());
     }
     js.endObject();
   } catch (Exception e) {
     e.printStackTrace();
   }
 }
Exemple #13
0
  /**
   * 序列化对象
   *
   * @param js json对象
   * @param obj 待序列化对象
   */
  private static void serializeObject(JSONStringer js, Object obj) {
    try {
      js.object();
      Class<? extends Object> objClazz = obj.getClass();
      Method[] methods = objClazz.getDeclaredMethods();
      Field[] fields = objClazz.getDeclaredFields();
      for (Field field : fields) {
        try {
          String fieldType = field.getType().getSimpleName();
          String fieldGetName = parseMethodName(field.getName(), "get");
          if (!haveMethod(methods, fieldGetName)) {
            continue;
          }
          Method fieldGetMet = objClazz.getMethod(fieldGetName, new Class[] {});
          Object fieldVal = fieldGetMet.invoke(obj, new Object[] {});
          String result = null;
          if ("Date".equals(fieldType)) {
            SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss", Locale.US);
            result = sdf.format((Date) fieldVal);

          } else {
            if (null != fieldVal) {
              result = String.valueOf(fieldVal);
            }
          }
          js.key(field.getName());
          serialize(js, result);
        } catch (Exception e) {
          continue;
        }
      }
      js.endObject();
    } catch (Exception e) {
      e.printStackTrace();
    }
  }
  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();
  }
Exemple #15
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 encodeToString() {
      if (activityInfo != null) {
        try {
          // If it a launcher target, we only need component name, and user to
          // recreate this.
          return new JSONStringer()
              .object()
              .key(LAUNCH_INTENT_KEY)
              .value(launchIntent.toUri(0))
              .key(APP_SHORTCUT_TYPE_KEY)
              .value(true)
              .key(USER_HANDLE_KEY)
              .value(UserManagerCompat.getInstance(mContext).getSerialNumberForUser(user))
              .endObject()
              .toString();
        } catch (JSONException e) {
          Log.d(TAG, "Exception when adding shortcut: " + e);
          return null;
        }
      }

      if (launchIntent.getAction() == null) {
        launchIntent.setAction(Intent.ACTION_VIEW);
      } else if (launchIntent.getAction().equals(Intent.ACTION_MAIN)
          && launchIntent.getCategories() != null
          && launchIntent.getCategories().contains(Intent.CATEGORY_LAUNCHER)) {
        launchIntent.addFlags(
            Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_RESET_TASK_IF_NEEDED);
      }

      // This name is only used for comparisons and notifications, so fall back to activity
      // name if not supplied
      String name = ensureValidName(mContext, launchIntent, label).toString();
      Bitmap icon = data.getParcelableExtra(Intent.EXTRA_SHORTCUT_ICON);
      Intent.ShortcutIconResource iconResource =
          data.getParcelableExtra(Intent.EXTRA_SHORTCUT_ICON_RESOURCE);

      // Only encode the parameters which are supported by the API.
      try {
        JSONStringer json =
            new JSONStringer()
                .object()
                .key(LAUNCH_INTENT_KEY)
                .value(launchIntent.toUri(0))
                .key(NAME_KEY)
                .value(name);
        if (icon != null) {
          byte[] iconByteArray = ItemInfo.flattenBitmap(icon);
          json =
              json.key(ICON_KEY)
                  .value(
                      Base64.encodeToString(
                          iconByteArray, 0, iconByteArray.length, Base64.DEFAULT));
        }
        if (iconResource != null) {
          json = json.key(ICON_RESOURCE_NAME_KEY).value(iconResource.resourceName);
          json = json.key(ICON_RESOURCE_PACKAGE_NAME_KEY).value(iconResource.packageName);
        }
        return json.endObject().toString();
      } catch (JSONException e) {
        Log.d(TAG, "Exception when adding shortcut: " + e);
      }
      return null;
    }