コード例 #1
0
ファイル: APIHandler.java プロジェクト: kyeoh/tales-core
  private void databases(HttpServletResponse response) {

    try {

      JSONArray json = new JSONArray();

      for (String dbName : DBUtils.getLocalDBNames()) {

        JSONArray tables = new JSONArray();
        for (String tableName : DBUtils.getTableNames(new TemplateLocalhostConnection(), dbName)) {

          JSONObject table = new JSONObject();
          table.put("table", tableName);
          table.put(
              "size", DBUtils.getTableCount(new TemplateLocalhostConnection(), dbName, tableName));
          tables.add(table);
        }

        JSONObject database = new JSONObject();
        database.put("name", dbName);
        database.put("tables", tables);
        json.add(database);
      }

      response.setContentType("application/json");
      response.setStatus(HttpServletResponse.SC_OK);
      response.getWriter().println(json);

    } catch (Exception e) {
      new TalesException(new Throwable(), e);
    }
  }
コード例 #2
0
ファイル: UserService.java プロジェクト: runningship/makesite
 private JSONArray getChildrenOfGroup(Integer groupId, String _site) {
   List<Group> groups =
       dao.listByParams(Group.class, "from Group where parentId = ? and _site=?", groupId, _site);
   JSONArray arr = new JSONArray();
   for (Group g : groups) {
     JSONObject jobj = new JSONObject();
     jobj.put("name", g.name);
     jobj.put("id", g.id);
     jobj.put("type", "group");
     jobj.put("key", "group_" + g.id);
     jobj.put("isParent", true);
     JSONArray children = getChildrenOfGroup(g.id, _site);
     if (!children.isEmpty()) {
       jobj.put("children", children);
     }
     arr.add(jobj);
   }
   List<Map> users =
       dao.listAsMap(
           "select u.name as name , u.id as id from User u , UserGroup ug where u.id = ug.uid and ug.gid=? and u._site=?",
           groupId,
           _site);
   for (Map u : users) {
     JSONObject jobj = new JSONObject();
     jobj.put("name", u.get("name"));
     jobj.put("id", u.get("id"));
     jobj.put("key", "user_" + u.get("id"));
     jobj.put("type", "user");
     arr.add(jobj);
   }
   return arr;
 }
コード例 #3
0
  public JSONObject mappingElementsUsedInMapping() {
    JSONObject result = new JSONObject();
    JSONArray used = new JSONArray();
    JSONArray not_used = new JSONArray();
    JSONArray parent_used = new JSONArray();

    JSONObject mappings = this.getTargetDefinition();
    Map<String, MappingElement> map = this.inputSchema.getMap();
    Collection<String> list = MappingSummary.getMappedXPathList(mappings);

    Iterator<String> keys = map.keySet().iterator();

    while (keys.hasNext()) {
      String id = keys.next();
      String xpath = map.get(id).getXPath();
      for (String xp : list) {
        if (xp.length() > xpath.length() && xp.indexOf(xpath) > -1) {
          parent_used.add(id);
          break;
        }
      }
      if (list.contains(xpath)) {
        used.add(id);

      } else {
        not_used.add(id);
      }
    }
    return result
        .element("used", used)
        .element("not_used", not_used)
        .element("parent_used", parent_used);
  }
コード例 #4
0
  private JSONArray getAlbumTreeFromList(List<Album> albumList, String parentId) {
    JSONArray results = new JSONArray();

    if ("-1".equals(parentId)) {
      JSONObject allAlbum = new JSONObject();
      allAlbum.put("id", "allPicture");
      allAlbum.put("text", "所有图片");
      allAlbum.put("leaf", Boolean.valueOf(true));
      results.add(allAlbum);

      JSONObject album = new JSONObject();
      album.put("id", "0");
      album.put("text", "我的相册");
      album.put("leaf", Boolean.valueOf(false));
      results.add(album);
    } else if (albumList != null) {
      for (int i = 0; i < albumList.size(); i++) {
        JSONObject albumNode = new JSONObject();
        albumNode.put("id", ((Album) albumList.get(i)).getAlbumId());
        albumNode.put("text", ((Album) albumList.get(i)).getAlbumName());
        albumNode.put("leaf", Constants.ISLEAF_MAP.get(((Album) albumList.get(i)).getIsleaf()));
        results.add(albumNode);
      }
    }

    return results;
  }
コード例 #5
0
ファイル: Inventaire.java プロジェクト: vitiok123/inf4375_tp2
  private String jsonArtistes(Map<String, Artiste> artistes) {
    Map<String, Artiste> artistesTrie = new TreeMap<String, Artiste>(artistes);
    JSONObject jsonResultat = new JSONObject();
    JSONArray jsonArtistes = new JSONArray();
    for (String nome : artistesTrie.keySet()) {
      Artiste artiste = artistesTrie.get(nome);
      JSONObject jsonArtiste = new JSONObject();
      jsonArtiste.put("nom", nome);
      JSONArray jsonAlbums = new JSONArray();
      for (Integer annee : artiste.getAlbums().keySet()) {
        Album album = artiste.getAlbums().get(annee);
        JSONObject newAlbum = new JSONObject();
        newAlbum.put("id", album.getId());
        newAlbum.put("titre", album.getTitre());
        newAlbum.put("annee", album.getAnnee());
        newAlbum.put("qte", album.getQuantite());
        jsonAlbums.add(newAlbum);
      }
      jsonArtiste.accumulate("albums", jsonAlbums);
      jsonArtistes.add(jsonArtiste);
    }
    jsonResultat.accumulate("artistes", jsonArtistes);

    return jsonResultat.toString(2);
  }
コード例 #6
0
  @Override
  public void syncSharedConnectorSettings(
      final long apiKeyId, final SharedConnector sharedConnector) {
    JSONObject jsonSettings = new JSONObject();
    if (sharedConnector.filterJson != null)
      jsonSettings = JSONObject.fromObject(sharedConnector.filterJson);
    // get calendars, add new configs for new calendars...
    // we use the data in the connector settings, which have either just been synched (see
    // UpdateWorker's syncSettings)
    // or were synched  when the connector was last updated; in either cases, we know that the data
    // is up-to-date
    final GoogleCalendarConnectorSettings connectorSettings =
        (GoogleCalendarConnectorSettings) settingsService.getConnectorSettings(apiKeyId);
    final List<CalendarConfig> calendars = connectorSettings.calendars;

    JSONArray sharingSettingsCalendars = new JSONArray();
    if (jsonSettings.has("calendars"))
      sharingSettingsCalendars = jsonSettings.getJSONArray("calendars");
    there:
    for (CalendarConfig calendarConfig : calendars) {
      for (int i = 0; i < sharingSettingsCalendars.size(); i++) {
        JSONObject sharingSettingsCalendar = sharingSettingsCalendars.getJSONObject(i);
        if (sharingSettingsCalendar.getString("id").equals(calendarConfig.id)) continue there;
      }
      JSONObject sharingConfig = new JSONObject();
      sharingConfig.accumulate("id", calendarConfig.id);
      sharingConfig.accumulate("summary", calendarConfig.summary);
      sharingConfig.accumulate("description", calendarConfig.description);
      sharingConfig.accumulate("shared", false);
      sharingSettingsCalendars.add(sharingConfig);
    }

    // and remove configs for deleted notebooks - leave others untouched
    JSONArray settingsToDelete = new JSONArray();
    there:
    for (int i = 0; i < sharingSettingsCalendars.size(); i++) {
      JSONObject sharingSettingsCalendar = sharingSettingsCalendars.getJSONObject(i);
      for (CalendarConfig calendarConfig : calendars) {
        if (sharingSettingsCalendar.getString("id").equals(calendarConfig.id)) continue there;
      }
      settingsToDelete.add(sharingSettingsCalendar);
    }
    for (int i = 0; i < settingsToDelete.size(); i++) {
      JSONObject toDelete = settingsToDelete.getJSONObject(i);
      for (int j = 0; j < sharingSettingsCalendars.size(); j++) {
        if (sharingSettingsCalendars
            .getJSONObject(j)
            .getString("id")
            .equals(toDelete.getString("id"))) {
          sharingSettingsCalendars.remove(j);
        }
      }
    }
    jsonSettings.put("calendars", sharingSettingsCalendars);
    String toPersist = jsonSettings.toString();
    coachingService.setSharedConnectorFilter(sharedConnector.getId(), toPersist);
  }
コード例 #7
0
  // 子节点列表
  @RequestMapping(value = "/path/list")
  public void getChildren(HttpServletRequest request, HttpServletResponse response) {
    String searchPath = request.getParameter("searchPath"); // 搜索路径

    /*
     * 第一层 searchPath =/content/* 第二层 searchPath
     * =/content/folder[@name='总经理组']/*
     */
    CRNConnect connection = this.getConnect(); // cognos8连接
    if (connection != null) {

      try {

        JSONArray result = new JSONArray(); // 返回结果
        if (searchPath != null) { // 非根节点
          BaseClass[] queryList = cognos8Service.getChildren(connection, searchPath); // 查询子节点

          if (queryList != null && queryList.length > 0) {

            for (BaseClass c : queryList) {
              result.add(
                  new JSONObject()
                      .element("searchPath", c.getSearchPath().getValue())
                      // searchPath
                      .element("name", c.getDefaultName().getValue())
                      // 节点名称
                      .element("isexpand", false)
                      // 不自动展开
                      .element("children", new JSONArray())
                      // 类型
                      .element("className", c.getClass().getName())
                      .element("id", c.getStoreID().getValue().getValue())); // ID
            }
          }
        } else { // 根节点
          result.add(
              new JSONObject()
                  .element("searchPath", "/content")
                  // searchPath
                  .element("name", "公共文件夹")
                  // 节点名称
                  .element("isexpand", false)
                  // 不自动展开
                  .element("children", new JSONArray())
                  // 类型
                  .element("className", "com.cognos.developer.schemas.bibus._3.Folder")
                  .element("id", "-1"));
        }

        response.getWriter().print(result.toString());
      } catch (Exception e) {
        // TODO Auto-generated catch block
        logger.error("", e);
      }
    }
  }
コード例 #8
0
  /**
   * 将用户分配的权限转换成主菜单的JSON数据,输出到前台
   *
   * @param authorizedFuncs 用户分配的功能权限
   * @param funcType 主菜单
   * @return
   */
  private String convertFuncsToMenu(List<FuncModel> authorizedFuncs, Integer funcType) {
    System.setProperty("java.util.Arrays.useLegacyMergeSort", "true");
    Collections.sort(
        authorizedFuncs,
        new Comparator<FuncModel>() {
          public int compare(FuncModel obj1, FuncModel obj2) {

            return obj2.getMenuSort() - obj1.getMenuSort();
          }
        });
    String webPath = getRequest().getContextPath();

    /** 查找数据库的主菜单的顶级菜单项记录,然后将功能权限作为子菜单加入到顶级菜单中,如果顶级菜单下没有权限,将忽略不显示 */
    String hsql =
        "from FuncModel where parentId = ? and funcType = ? and deleted = ? order by menuSort";
    List<FuncModel> subSysFuncs =
        this.getBaseService().query(hsql, new Object[] {Integer.valueOf(-1), 1, false});
    JSONArray jsonArray = new JSONArray();
    for (FuncModel func : subSysFuncs) {
      List<FuncModel> childSysFuns = findChidFuncByParentId(func.getEntityId(), authorizedFuncs);
      JSONObject menuItem = new JSONObject();
      menuItem.put("id", "" + func.getEntityId());
      menuItem.put("text", func.getDescr());
      menuItem.put("icon", func.getIcon());
      JSONObject attributes = new JSONObject();
      attributes.put("url", func.getUrl());
      menuItem.put("attributes", attributes);

      JSONArray childMenuItems = new JSONArray();
      for (FuncModel childSysFunc : childSysFuns) {
        JSONObject childItem = new JSONObject();
        childItem.put("id", "" + childSysFunc.getEntityId());
        childItem.put("text", childSysFunc.getDescr());

        childItem.put("icon", childSysFunc.getIcon());
        String url = "";
        if (!StringUtil.isEmpty(childSysFunc.getUrl())) {
          url = webPath + "/" + func.getUrl() + "/" + childSysFunc.getUrl();
        }

        attributes = new JSONObject();
        attributes.put("url", url);
        childItem.put("attributes", attributes);
        childMenuItems.add(childItem);
      }
      if (childMenuItems.size() > 0) {
        menuItem.put("menu", childMenuItems);
        jsonArray.add(menuItem); // 如果父菜单下没有子菜单,就不显示在前台
      } else if (isAuthorized(func)) {
        jsonArray.add(menuItem);
      }
    }

    return jsonArray.toString();
  }
コード例 #9
0
ファイル: SysRightsListAction.java プロジェクト: zhfy/server
  public String execute() throws Exception {
    response.setCharacterEncoding("UTF-8");
    int count = sysRightsService.findAllCount();
    sysRightsList = sysRightsService.finsSysRightsByPage(page, rows);
    try {
      JSONObject json = new JSONObject();
      JSONArray jsonItems = new JSONArray();
      List list = sysRightsService.findSysRightsListByPaentId(0); // 父板块为0的子版快号
      Iterator it = list.iterator();
      while (it.hasNext()) {
        SysRights sysRights = (SysRights) it.next();
        Map map = new HashMap();
        map.put("sysRightsId", sysRights.getSysRightsId());
        map.put("sysRightsName", sysRights.getSysRightsName());
        map.put("className", sysRights.getClassName());
        map.put("type", sysRights.getType());
        map.put("status", sysRights.getStatus());
        List sonList =
            sysRightsService.findSysRightsListByPaentId(sysRights.getSysRightsId()); // 获得编号
        Iterator it2 = sonList.iterator();

        JSONObject sonJson = new JSONObject();
        JSONArray sonJsonItem = new JSONArray();
        while (it2.hasNext()) {
          SysRights sysRights2 = (SysRights) it2.next();
          Map map2 = new HashMap();
          map2.put("sysRightsId", sysRights2.getSysRightsId());
          map2.put("sysRightsName", sysRights2.getSysRightsName());
          map2.put("className", sysRights2.getClassName());
          map2.put("type", sysRights2.getType());
          map2.put("status", sysRights2.getStatus());
          sonJsonItem.add(map);
        }

        map.put("children", sonJsonItem);
        jsonItems.add(map);
      }
      json.put("total", count);
      json.put("rows", jsonItems);
      PrintWriter out = response.getWriter();
      out.write(json.toString());

      out.flush();
      out.close();

    } catch (Exception e) {

      e.printStackTrace();
    }
    return null;
  }
コード例 #10
0
ファイル: FeedbackController.java プロジェクト: caocf/Hera
 @RequestMapping()
 public void select(HttpServletRequest request, HttpServletResponse response) {
   try {
     response.setContentType("text/html;charset=UTF-8");
     request.setCharacterEncoding("UTF-8");
     super.initializePagingSortingFiltering(request);
     //
     Map<String, Object> params = new HashMap<String, Object>();
     params.put("pagination.pageSize", getPageSize());
     params.put("pagination.currentPage", getPageNo());
     //
     JSONObject json = VLivesCaller.HTTP.USER_FEEDBACK_READ.invoke(null, params);
     //
     JSONArray ja = new JSONArray();
     for (Object obj : json.getJSONArray("list").toArray()) {
       JSONObject jsObj = (JSONObject) obj;
       JSONObject jt = (JSONObject) jsObj.get("user");
       String str = jsObj.getString("user");
       if (jt == null || "null".equals(str)) {
         jsObj.remove("user");
         JSONObject jn = new JSONObject();
         jn.put("name", "匿名");
         jn.put("mobile", "");
         jsObj.put("user", jn);
         ja.add(jsObj);
       } else {
         str = jt.getString("name");
         if (str == null || "null".equals(str)) {
           jt.put("name", "匿名");
         }
         ja.add(jsObj);
       }
     }
     //
     if ("true".equals(json.getString("success"))) {
       String result =
           makeSuccessArrayString(
               json.getJSONObject("pagination").getString("count"), ja.toString());
       response.getWriter().write(result);
     } else {
       responseMessage(response, json.getString("msg"), false);
     }
   } catch (RuntimeException e) {
     e.printStackTrace();
     responseMessage(response, "系统错误<br />请检查配置后重试", false);
   } catch (Exception e) {
     e.printStackTrace();
     responseMessage(response, "查询反馈信息列表失败", false);
   }
 }
コード例 #11
0
ファイル: Field.java プロジェクト: RG9/jira-client
  /**
   * Converts an iterable type to a JSON array.
   *
   * @param iter Iterable type containing field values
   * @param type Name of the item type
   * @param custom Name of the custom type
   * @return a JSON-encoded array of items
   */
  public static JSONArray toArray(Iterable iter, String type, String custom) throws JiraException {
    JSONArray results = new JSONArray();

    if (type == null) throw new JiraException("Array field metadata is missing item type");

    for (Object val : iter) {
      Operation oper = null;
      Object realValue = null;
      Object realResult = null;

      if (val instanceof Operation) {
        oper = (Operation) val;
        realValue = oper.value;
      } else realValue = val;

      if (type.equals("component")
          || type.equals("group")
          || type.equals("user")
          || type.equals("version")) {

        JSONObject itemMap = new JSONObject();

        if (realValue instanceof ValueTuple) {
          ValueTuple tuple = (ValueTuple) realValue;
          itemMap.put(tuple.type, tuple.value.toString());
        } else itemMap.put(ValueType.NAME.toString(), realValue.toString());

        realResult = itemMap;
      } else if (type.equals("option")
          || (type.equals("string")
              && custom != null
              && (custom.equals("com.atlassian.jira.plugin.system.customfieldtypes:multicheckboxes")
                  || custom.equals(
                      "com.atlassian.jira.plugin.system.customfieldtypes:multiselect")))) {

        realResult = new JSONObject();
        ((JSONObject) realResult).put(ValueType.VALUE.toString(), realValue.toString());
      } else if (type.equals("string")) realResult = realValue.toString();

      if (oper != null) {
        JSONObject operMap = new JSONObject();
        operMap.put(oper.name, realResult);
        results.add(operMap);
      } else results.add(realResult);
    }

    return results;
  }
コード例 #12
0
  private static JSONObject extractAvgTrtData(
      Map<Integer, TreeMap<String, AvgTransactionResponseTime>> graphData,
      HashSet<String> transactions) {
    HashMap<String, ArrayList<Number>> averageTRTData = new HashMap<String, ArrayList<Number>>(0);
    JSONObject graphDataSet = new JSONObject();

    JSONArray labels = new JSONArray();

    for (String transaction : transactions) {
      averageTRTData.put(transaction, new ArrayList<Number>(0));
    }

    for (Map.Entry<Integer, TreeMap<String, AvgTransactionResponseTime>> result :
        graphData.entrySet()) {
      labels.add(result.getKey());

      for (String transaction : transactions) {
        if (!result.getValue().containsKey(transaction)) {
          averageTRTData.get(transaction).add(null);
          // TODO:change to null
          continue;
        }
        averageTRTData
            .get(transaction)
            .add((result.getValue()).get(transaction).getActualValueAvg());
      }
    }

    graphDataSet.put(LABELS, labels);
    JSONArray datasets = createGraphDatasets(averageTRTData);
    graphDataSet.put(SERIES, datasets);
    return graphDataSet;
  }
コード例 #13
0
  /**
   * 单选
   *
   * @return
   */
  public String single() {
    if (vo == null) {
      vo = new DepartmentSO();
    }
    vo.setPageNumber(1);
    vo.setObjectsPerPage(Integer.MAX_VALUE);
    List<Department> list = departmentDAO.getList(vo);

    if (list != null && list.size() > 0) {
      JSONArray array = new JSONArray();
      for (Department dep : list) {
        JSONObject json = new JSONObject();
        json.put("id", dep.getId());

        if (dep.getDepartment() == null) {
          json.put("pId", 0);
        } else {
          json.put("pId", dep.getDepartment().getId());
          json.put("open", true);
        }

        json.put("name", dep.getName());

        if (id != null) {
          if (id.equals(dep.getId())) {
            json.put("checked", true);
          }
        }

        array.add(json);
      }
      nodes = array.toString();
    }
    return Constants.SINGLE;
  }
コード例 #14
0
 public String getSuccessString(String API_CODE, JSONObject temp) {
   JSONArray jarray = new JSONArray();
   temp.put("status", "0");
   temp.put("msg", API_CODE + "00");
   jarray.add(temp);
   return jarray.toString();
 }
コード例 #15
0
  @Override
  protected void doGet(HttpServletRequest request, HttpServletResponse response)
      throws ServletException, IOException {

    // OutputStream out = response.getOutputStream();
    // Creating parameters
    String startTime = request.getParameter("startTime");
    String endTime = request.getParameter("endTime");
    System.out.println(startTime);
    // System.out.println(endTime);

    // Formating the time parameters into "yyyy-MM-dd HH:mm:ss"
    SimpleDateFormat sd = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
    String newStartTime = sd.format(new Date(startTime));
    System.out.println(newStartTime);

    // Formating the time parameters into "yyyy-MM-dd HH:mm:ss"
    SimpleDateFormat sd1 = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
    String newEndTime = sd1.format(new Date(endTime));
    System.out.println(newEndTime);

    // Creating json format ready to pass the parameters
    List<Station> listStation = getDataSet(newStartTime, newEndTime);
    JSONObject jsonObject = new JSONObject();
    jsonObject.put("listStation", listStation);

    JSONArray jsonArray = new JSONArray();
    jsonArray.add(jsonObject);
    PrintWriter out = response.getWriter();
    out.write(jsonArray.toString());
  }
コード例 #16
0
  /**
   * 将集合元素封装成json对象并返回
   *
   * @param list 要封装的数组集合
   * @param config 类在转换成json数据时遵循的一些配置规则
   * @param status 状态标识
   * @return json对象 返回json对象的内部格式如下:data中的内容就是list集合中的内容,count表示data中的条数,也就是list集合中数据数 { status:1,
   *     message:"ok", result:{ count:2, data:[
   *     {id:"2353sdkfhosdf",name:boat.jpg,type=1,savepath:"http://172.19.68.77:8080/zhushou/images/logo.jpg"},
   *     {id:"2353sdkfhosdf",name:boat.jpg,type=1,savepath:"http://172.19.68.77:8080/zhushou/images/logo.jpg"},
   *     <p>] } }
   */
  @Deprecated
  public static <T> JSONObject createJsonObject(List<T> list, JsonConfig config, MyStatus status) {

    // 整个json
    JSONObject jsonObject = new JSONObject();
    // result json
    JSONObject resultObject = new JSONObject();
    // 数组json
    JSONArray jsonArray = new JSONArray();

    int count = 0;
    if (list != null) {
      for (T entity : list) {
        JSONObject entityJson;
        if (config == null) entityJson = JSONObject.fromObject(entity);
        else entityJson = JSONObject.fromObject(entity, config);
        jsonArray.add(entityJson);
        count++;
      }
    }
    resultObject.put("count", count);
    resultObject.put("data", jsonArray);
    jsonObject.put("result", resultObject);

    JsonTool.putStatusJson(status, jsonObject);
    return jsonObject;
  }
コード例 #17
0
  /**
   * 终端命令菜单
   *
   * @return
   */
  private String terminalCommandMenuJson() {
    JSONArray jsonArray = new JSONArray();
    for (FuncModel root : authorizedFuncs) {
      // FuncModel root = (FuncModel) iterator.next();
      if (root.getParentId() != 900700 || root.getDeleted()) continue;

      JSONObject rootJsonObject = new JSONObject();
      rootJsonObject.put("id", "" + root.getEntityId());

      rootJsonObject.put("text", root.getDescr());
      rootJsonObject.put("icon", root.getIcon());
      /**
       * if (this.selectUserFuncsMap.containsKey(root.getId())) rootJsonObject.put("checked",
       * Boolean.valueOf(true)); else { rootJsonObject.put("checked", Boolean.valueOf(false)); }
       */
      JSONObject attributes = new JSONObject();
      attributes.put("funcName", root.getFuncName());
      // attributes.put("style", root.getStyle());
      rootJsonObject.put("attributes", attributes);

      List subGroupInfos = findSubSyssFuncByParnetId(root.getEntityId());

      genSubGroupsTreeJson(rootJsonObject, subGroupInfos);
      jsonArray.add(rootJsonObject);
    }
    return jsonArray.toString();
  }
コード例 #18
0
ファイル: XshlfxLcReportAction.java プロジェクト: qw4wer/back
  public String searchxshlfxLcReport() throws Exception {

    // 步骤1:进行List的定义,直接对应于html页面的Table
    ArrayList<ReportShowTR> trList = new ArrayList();
    trList = (ArrayList<ReportShowTR>) request.getSession().getAttribute("trList");
    try {

      JSONArray jsonArray = new JSONArray();
      JSONObject jsonobj = new JSONObject();

      StringBuilder sb = new StringBuilder("");
      for (int i = 0; i < trList.size(); i++) {
        for (int j = 0; j < trList.get(i).getTdsCount(); j++) {
          jsonobj.put("xs" + j, trList.get(i).getTD(j).getXyValueText());
        }
        jsonArray.add(jsonobj);
      }
      Map<String, Object> json = new HashMap<String, Object>();
      json.put("rows", jsonArray); // rows键 存放每页记录 list
      result = JSONObject.fromObject(json); // 格式化result一定要是JSONObject
    } catch (Exception ex) {
      ex.printStackTrace();
    }

    return "suc";
  }
コード例 #19
0
ファイル: CheckFeeModAction.java プロジェクト: qw4wer/back
  public String myGetCheckFeeDateList() throws Exception {

    JSONArray jsonArray = new JSONArray();

    confirmCond = new ConfirmCond();
    confirmCond.setPropertyId(request.getParameter("propertyId"));

    List<Map<String, Object>> checkFeeDateList = confirmServices.checkFeeDateList(confirmCond);

    for (int i = 0; i < checkFeeDateList.size(); i++) {

      Map<String, Object> mapobject = checkFeeDateList.get(i);

      String checkfee_date =
          mapobject.get("checkfee_date") == null ? "" : mapobject.get("checkfee_date").toString();

      if (!CommonUtils.isStrEmpty(checkfee_date)) {

        Map<String, Object> json = new HashMap<String, Object>();
        json.put(
            "checkFeeDate",
            CommonUtils.getDateString(CommonUtils.getDateFromString(checkfee_date)));

        jsonArray.add(json);
      }
    }

    CustomerUtils.writeResponse(response, jsonArray.toString());

    return null;
  }
コード例 #20
0
ファイル: DocumentModelToJSON.java プロジェクト: mindis/nuxeo
 @Override
 public Object visit(MapProperty property, Object arg) throws PropertyException {
   Object value = null;
   if (property.isContainer()) {
     value = new JSONObject();
   } else {
     value = property.getValue();
   }
   if (property instanceof BlobProperty) {
     log.warn(
         "Property '"
             + property.getName()
             + "' ignored during serialization. Blob and blob related properties are not written to json object.");
   } else if (property.getParent() instanceof BlobProperty) {
     log.warn(
         "Property '"
             + property.getName()
             + "' ignored during serialization. Blob and blob related properties are not written to json object.");
   } else if (property.getParent().isList()) {
     ((JSONArray) arg).add(value);
   } else {
     try {
       ((JSONObject) arg).put(property.getField().getName().getPrefixedName(), value);
     } catch (JSONException e) {
       throw new PropertyException("Failed to put value", e);
     }
   }
   return value;
 }
コード例 #21
0
ファイル: View.java プロジェクト: alexkogon/jenkins
 @Override
 protected synchronized JSON data() {
   JSONArray r = new JSONArray();
   for (User u : modified) {
     UserInfo i = users.get(u);
     JSONObject entry =
         new JSONObject()
             .accumulate("id", u.getId())
             .accumulate("fullName", u.getFullName())
             .accumulate("url", u.getUrl())
             .accumulate(
                 "avatar",
                 i.avatar != null
                     ? i.avatar
                     : Stapler.getCurrentRequest().getContextPath()
                         + Functions.getResourcePath()
                         + "/images/"
                         + iconSize
                         + "/user.png")
             .accumulate("timeSortKey", i.getTimeSortKey())
             .accumulate("lastChangeTimeString", i.getLastChangeTimeString());
     AbstractProject<?, ?> p = i.getProject();
     if (p != null) {
       entry
           .accumulate("projectUrl", p.getUrl())
           .accumulate("projectFullDisplayName", p.getFullDisplayName());
     }
     r.add(entry);
   }
   modified.clear();
   return r;
 }
コード例 #22
0
 public void myBuyedStore() throws IOException {
   id = Integer.parseInt(ServletActionContext.getRequest().getParameter("id"));
   List<GoodStore> listgoostore = goodStoreService.getMyBuyedStore(id);
   for (GoodStore goodStore : listgoostore) {
     JSONObject jsonObj = new JSONObject();
     Goods good = goodsService.getGoods(goodStore.getGoodId());
     jsonObj.put("goodStoreid", goodStore.getGoodStoreid());
     jsonObj.put("title", good.getTitle());
     jsonObj.put(
         "addTime", goodStore.getAddtime() == null ? "" : sdf1.format(goodStore.getAddtime()));
     jsonObj.put("price", good.getPrice() * goodStore.getCount());
     jsonObj.put("count", goodStore.getCount());
     jsonObj.put("id", goodStore.getGoodId());
     List<Image> listimage = imageServiceImpl.getimage(goodStore.getGoodId(), 3);
     Image image = new Image();
     if (listimage.size() > 0) {
       image.setImageUrl(IpMain.IP + listimage.get(1).getImageUrl());
     } else {
       image.setImageUrl("");
     }
     jsonObj.put("imgUrl", image);
     array.add(jsonObj);
   }
   m.put("msg", array);
   ServletActionContext.getResponse().getWriter().write(JSON.toJSONString(m));
 }
コード例 #23
0
ファイル: APIHandler.java プロジェクト: kyeoh/tales-core
  private void errors(HttpServletResponse response) {

    try {

      // gets the errors
      JSONArray array = new JSONArray();

      for (Log log : LogsDB.getErrors(Globals.DASHBOARD_MAX_ERRORS)) {

        JSONObject obj = new JSONObject();
        obj.put("added", log.getAdded().toString());
        obj.put("id", log.getId());
        obj.put("publicDNS", log.getPublicDNS());
        obj.put("pid", log.getPid());
        obj.put("logType", log.getLogType());
        obj.put("methodPath", log.getMethodPath());
        obj.put("lineNumber", log.getLineNumber());

        array.add(obj);
      }

      // response
      response.setContentType("application/json");
      response.setStatus(HttpServletResponse.SC_OK);
      response.getWriter().println(array);

    } catch (Exception e) {
      new TalesException(new Throwable(), e);
    }
  }
コード例 #24
0
  public String getCodeJson(MobileServerConfig mobileServerConfig, Document doc, String urlPara) {
    String json = "";

    JSONObject jsonObjectResult = new JSONObject();

    try {
      List<Code> list = GetCodeCache();

      if (list != null && list.size() > 0) {
        JSONArray jsonArray = new JSONArray();

        for (Code code : list) {
          JSONObject jsonObjectData = new JSONObject();

          jsonObjectData.put("codeName", code.getCodeName());
          jsonObjectData.put("description", code.getDescription());
          jsonObjectData.put("category", code.getCategory());

          jsonArray.add(jsonObjectData);
        }

        jsonObjectResult.put("result", "1");
        jsonObjectResult.put("data", jsonArray);
      }
    } catch (Exception e) {
      // TODO: handle exception
      jsonObjectResult.put("result", "0");
      jsonObjectResult.put("message", e.getMessage());
    }

    json = jsonObjectResult.toString();

    return json;
  }
コード例 #25
0
  private static JSONObject extractVuserResult(Map<Integer, TreeMap<String, Integer>> graphData) {
    JSONObject graphDataSet;
    graphDataSet = new JSONObject();
    JSONArray labels = new JSONArray();

    HashMap<String, ArrayList<Number>> vUserState = new HashMap<String, ArrayList<Number>>(0);
    vUserState.put("Passed", new ArrayList<Number>(0));
    vUserState.put("Failed", new ArrayList<Number>(0));
    vUserState.put("Stopped", new ArrayList<Number>(0));
    vUserState.put("Error", new ArrayList<Number>(0));
    for (Map.Entry<Integer, TreeMap<String, Integer>> run : graphData.entrySet()) {
      Number tempVUserCount = run.getValue().get("Count");
      if (tempVUserCount != null && tempVUserCount.intValue() > 0) {
        labels.add(run.getKey());
        vUserState.get("Passed").add(run.getValue().get("Passed"));
        vUserState.get("Failed").add(run.getValue().get("Failed"));
        vUserState.get("Stopped").add(run.getValue().get("Stopped"));
        vUserState.get("Error").add(run.getValue().get("Error"));
      }
    }

    graphDataSet.put(LABELS, labels);
    graphDataSet.put(SERIES, createGraphDatasets(vUserState));
    return graphDataSet;
  }
コード例 #26
0
ファイル: CdfTemplates.java プロジェクト: pmalves/cde
  private void loadFiles(final IBasicFile[] jsonFiles, final JSONArray result, final String type)
      throws IOException {

    Arrays.sort(
        jsonFiles,
        new Comparator<IBasicFile>() {

          @Override
          public int compare(IBasicFile file1, IBasicFile file2) {
            if (file1 == null && file2 == null) {
              return 0;
            } else {
              return file1.getFullPath().toLowerCase().compareTo(file2.getFullPath().toLowerCase());
            }
          }
        });

    IReadAccess access = CdeEnvironment.getPluginSystemReader(SYSTEM_CDF_DD_TEMPLATES);

    for (int i = 0; i < jsonFiles.length; i++) {
      final JSONObject template = new JSONObject();

      String imgResourcePath = resoureUrl + "unknown.png";

      if (access.fileExists(jsonFiles[i].getName().replace(".cdfde", ".png"))) {
        imgResourcePath = resoureUrl + jsonFiles[i].getName().replace(".cdfde", ".png");
      }

      template.put("img", imgResourcePath);
      template.put("type", type);
      template.put("structure", JsonUtils.readJsonFromInputStream(jsonFiles[i].getContents()));
      result.add(template);
    }
  }
コード例 #27
0
  private static JSONObject extractPercentileTransactionSet(
      Map<Integer, TreeMap<String, PercentileTransactionWholeRun>> graphData,
      HashSet<String> transactions) {
    JSONObject graphDataSet = new JSONObject();
    JSONArray labels = new JSONArray();

    HashMap<String, ArrayList<Number>> percentileTrtData =
        new HashMap<String, ArrayList<Number>>(0);
    for (String transaction : transactions) {
      percentileTrtData.put(transaction, new ArrayList<Number>(0));
    }

    for (Map.Entry<Integer, TreeMap<String, PercentileTransactionWholeRun>> result :
        graphData.entrySet()) {
      labels.add(result.getKey());

      for (String transaction : transactions) {
        if (!result.getValue().containsKey(transaction)) {
          percentileTrtData.get(transaction).add(null);
          // TODO:change to null
          continue;
        }
        percentileTrtData
            .get(transaction)
            .add((result.getValue()).get(transaction).getActualValue());
      }
    }

    graphDataSet.put(LABELS, labels);
    graphDataSet.put(SERIES, createGraphDatasets(percentileTrtData));

    return graphDataSet;
  }
コード例 #28
0
 /**
  * 从数据库查询信息供写文件使用
  *
  * @return JSONArray
  */
 public JSONArray loadInfo() {
   JSONArray jsonArray = new JSONArray();
   try {
     List<Asset> assetList = assetService.findAllAssetList();
     for (int i = 0; i < assetList.size(); i++) {
       JSONObject jsonObject = new JSONObject();
       Asset asset = new Asset();
       asset = assetList.get(i);
       jsonObject.put("number", asset.getNumber());
       jsonObject.put("name", asset.getName());
       jsonObject.put("uses", asset.getUses());
       jsonObject.put("category", asset.getCategory());
       jsonObject.put(
           "entryTime", new SimpleDateFormat("yyyy-MM-dd").format(asset.getEntryTime()));
       jsonObject.put("status", asset.getStatus());
       jsonObject.put("remarks", asset.getRemarks());
       jsonObject.put(
           "edit",
           "<a href='javascript:void(0)' onclick='editAsset("
               + '"'
               + asset.getId()
               + '"'
               + ")'>编辑</>/<a href='javascript:void(0)' onclick='deleteAsset("
               + '"'
               + asset.getId()
               + '"'
               + ")'>删除</>");
       jsonArray.add(jsonObject);
     }
   } catch (Exception e) {
     e.printStackTrace();
   }
   return jsonArray;
 }
コード例 #29
0
  @RequestMapping(value = "/gotoData", method = RequestMethod.GET)
  public String gotoData(HttpServletRequest request, HttpServletResponse response)
      throws Exception {
    User user = (User) request.getSession().getAttribute("user");
    // 设计返回数据是的数组
    JSONArray sendjsonarray = new JSONArray();
    Map returnmap = new HashMap();
    if (user == null) {
      returnmap.put("statics", "0");
    } else {

      // 设计保存在缓存中的数据内容
      Map sessionmap = new HashMap();
      // 通过ip  时间    host  区分登陆的是不是一个人
      Usersession se = new Usersession();
      se.setAddtime(new Timestamp(new Date().getTime()));
      se.setIp(request.getHeader("X-Real-IP"));
      se.setUser(user);
      se.save();
      returnmap.put("statics", "1");
      returnmap.put("id", se.getUsersessionid());
      returnmap.put("userid", user.getUserid());
    }

    JSONObject jsonObject = JSONObject.fromObject(returnmap);
    sendjsonarray.add(0, jsonObject);
    response.getWriter().print("jsonp={'returns':" + sendjsonarray + "}");
    return null;
  }
コード例 #30
0
ファイル: DocumentModelToJSON.java プロジェクト: mindis/nuxeo
  @Override
  public Object visit(ScalarProperty property, Object arg) throws PropertyException {
    if (property.getParent() instanceof BlobProperty) {
      log.warn(
          "Property '"
              + property.getName()
              + "' ignored during serialization. Blob and blob related properties are not written to json object.");
      return null;
    }

    // convert values if needed
    Serializable value = property.getValue();
    if (value instanceof Calendar) {
      value = dateFormat.format(((Calendar) value).getTime());
    }
    // build json
    if (property.getParent().isList()) {
      ((JSONArray) arg).add(value);
    } else {
      try {
        ((JSONObject) arg).put(property.getField().getName().getPrefixedName(), value);
      } catch (JSONException e) {
        throw new PropertyException("Failed to put value", e);
      }
    }
    return null;
  }