Ejemplo n.º 1
0
 /**
  * 生成 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 "";
   }
 }
Ejemplo n.º 2
0
  /**
   * @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();
    }
  }
Ejemplo n.º 3
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();
  }
Ejemplo n.º 4
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();
 }
Ejemplo n.º 5
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();
 }
Ejemplo n.º 6
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();
   }
 }
Ejemplo n.º 7
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();
  }
Ejemplo n.º 8
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();
 }
Ejemplo n.º 9
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;
 }
Ejemplo n.º 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();
  }
Ejemplo n.º 11
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();
  }
Ejemplo n.º 12
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();
  }
Ejemplo n.º 14
0
  @Override
  public void generateJson(String prefix, PrintWriter pw, VWorkspace vWorkspace) {
    Workspace workspace = vWorkspace.getWorkspace();
    alignment = AlignmentManager.Instance().getAlignment(workspace.getId(), worksheetId);
    SemanticTypes types = worksheet.getSemanticTypes();
    Map<String, ColumnNode> hNodeIdTocolumnNodeMap = createColumnNodeMap();
    Map<String, SemanticTypeNode> hNodeIdToDomainNodeMap = createDomainNodeMap();

    JSONStringer jsonStr = new JSONStringer();
    try {
      JSONWriter writer = jsonStr.object();
      writer.key("worksheetId").value(worksheetId).key("updateType").value("SemanticTypesUpdate");

      writer.key(JsonKeys.Types.name());
      writer.array();
      // Iterate through all the columns
      for (HNodePath path : worksheet.getHeaders().getAllPaths()) {
        HNode node = path.getLeaf();
        String nodeId = node.getId();

        writer.object();

        // Check if a semantic type exists for the HNode
        SemanticType type = types.getSemanticTypeForHNodeId(nodeId);
        if (type != null && type.getConfidenceLevel() != SemanticType.ConfidenceLevel.Low) {
          writer
              .key(JsonKeys.HNodeId.name())
              .value(type.getHNodeId())
              .key(JsonKeys.SemanticTypesArray.name())
              .array();

          ColumnNode alignmentColumnNode = hNodeIdTocolumnNodeMap.get(type.getHNodeId());
          SemanticTypeNode domainNode = hNodeIdToDomainNodeMap.get(type.getHNodeId());

          if (alignmentColumnNode == null || domainNode == null) {
            logger.error(
                "Column node or domain node not found in alignment."
                    + " (This should not happen conceptually!):"
                    + type);
            continue;
          }

          // Add the primary semantic type
          writer
              .object()
              .key(JsonKeys.Origin.name())
              .value(type.getOrigin().name())
              .key(JsonKeys.ConfidenceLevel.name())
              .value(type.getConfidenceLevel().name())
              .key(JsonKeys.isPrimary.name())
              .value(true);

          // Add the RDF literal type to show in the text box
          String rdfLiteralType =
              alignmentColumnNode.getRdfLiteralType() == null
                  ? ""
                  : alignmentColumnNode.getRdfLiteralType().getDisplayName();
          String language =
              alignmentColumnNode.getLanguage() == null ? "" : alignmentColumnNode.getLanguage();
          writer.key(JsonKeys.rdfLiteralType.name()).value(rdfLiteralType);
          writer.key(JsonKeys.language.name()).value(language);

          //					String domainDisplayLabel = (domainNode.getLabel().getPrefix() != null &&
          // (!domainNode.getLabel().getPrefix().equals(""))) ?
          //							(domainNode.getLabel().getPrefix() + ":" + domainNode.getLocalId()) :
          // domainNode.getLocalId();
          if (!type.isClass()) {
            writer
                .key(JsonKeys.FullType.name())
                .value(type.getType().getUri())
                .key(JsonKeys.DisplayLabel.name())
                .value(type.getType().getDisplayName())
                .key(JsonKeys.DisplayRDFSLabel.name())
                .value(type.getType().getRdfsLabel())
                .key(JsonKeys.DisplayRDFSComment.name())
                .value(type.getType().getRdfsComment())
                .key(JsonKeys.DomainId.name())
                .value(domainNode.getId())
                .key(JsonKeys.DomainUri.name())
                .value(domainNode.getUri())
                .key(JsonKeys.DisplayDomainLabel.name())
                .value(domainNode.getDisplayId())
                .key(JsonKeys.DomainRDFSLabel.name())
                .value(domainNode.getRdfsLabel())
                .key(JsonKeys.DomainRDFSComment.name())
                .value(domainNode.getRdfsComment());
          } else {
            writer
                .key(JsonKeys.FullType.name())
                .value(domainNode.getId())
                .key(JsonKeys.DisplayLabel.name())
                .value(domainNode.getDisplayId())
                .key(JsonKeys.DisplayRDFSLabel.name())
                .value(domainNode.getRdfsLabel())
                .key(JsonKeys.DisplayRDFSComment.name())
                .value(domainNode.getRdfsComment())
                .key(JsonKeys.DomainId.name())
                .value("")
                .key(JsonKeys.DomainUri.name())
                .value("")
                .key(JsonKeys.DisplayDomainLabel.name())
                .value("")
                .key(JsonKeys.DomainRDFSLabel.name())
                .value("")
                .key(JsonKeys.DomainRDFSComment.name())
                .value("");
          }

          // Mark the special properties
          writer
              .key(JsonKeys.isMetaProperty.name())
              .value(isMetaProperty(type.getType(), alignmentColumnNode));

          writer.endObject();

          // Iterate through the synonym semantic types
          SynonymSemanticTypes synTypes = types.getSynonymTypesForHNodeId(nodeId);

          if (synTypes != null) {
            for (SemanticType synType : synTypes.getSynonyms()) {
              writer
                  .object()
                  .key(JsonKeys.HNodeId.name())
                  .value(synType.getHNodeId())
                  .key(JsonKeys.FullType.name())
                  .value(synType.getType().getUri())
                  .key(JsonKeys.Origin.name())
                  .value(synType.getOrigin().name())
                  .key(JsonKeys.ConfidenceLevel.name())
                  .value(synType.getConfidenceLevel().name())
                  .key(JsonKeys.DisplayLabel.name())
                  .value(synType.getType().getDisplayName())
                  .key(JsonKeys.DisplayRDFSLabel.name())
                  .value(synType.getType().getRdfsLabel())
                  .key(JsonKeys.DisplayRDFSComment.name())
                  .value(synType.getType().getRdfsComment())
                  .key(JsonKeys.isPrimary.name())
                  .value(false);
              if (!synType.isClass()) {
                writer
                    .key(JsonKeys.DomainUri.name())
                    .value(synType.getDomain().getUri())
                    .key(JsonKeys.DomainId.name())
                    .value("")
                    .key(JsonKeys.DisplayDomainLabel.name())
                    .value(synType.getDomain().getDisplayName())
                    .key(JsonKeys.DomainRDFSLabel.name())
                    .value(synType.getDomain().getRdfsLabel())
                    .key(JsonKeys.DomainRDFSComment.name())
                    .value(synType.getDomain().getRdfsComment());
              } else {
                writer
                    .key(JsonKeys.DomainId.name())
                    .value("")
                    .key(JsonKeys.DomainUri.name())
                    .value("")
                    .key(JsonKeys.DisplayDomainLabel.name())
                    .value("")
                    .key(JsonKeys.DomainRDFSLabel.name())
                    .value("")
                    .key(JsonKeys.DomainRDFSComment.name())
                    .value("");
              }
              writer.endObject();
            }
          }
          writer.endArray();
        } else {
          writer.key(JsonKeys.HNodeId.name()).value(nodeId);
          writer.key(JsonKeys.SemanticTypesArray.name()).array().endArray();
        }

        writer.endObject();
      }
      writer.endArray();
      writer.endObject();

      pw.print(writer.toString());
    } catch (JSONException e) {
      logger.error("Error occured while writing to JSON!", e);
    }
  }