예제 #1
0
  public static ModelAndView Render(
      Object obj, String jsonpCallback, HttpServletResponse response) {
    PrintWriter out = null;
    try {
      StringBuffer jsonp = new StringBuffer();
      if (StringUtils.isBlank(jsonpCallback)) {
        jsonp.append(JsonUtil.Object2JsonStr(obj));
        response.setContentType("application/json");
      } else {
        jsonp.append(jsonpCallback + "(" + JsonUtil.Object2JsonStr(obj) + ")");
        response.setContentType("application/javascript");
      }
      response.setCharacterEncoding("utf-8");
      Pattern p = Pattern.compile("[\u4e00-\u9fa5]");
      Matcher m = p.matcher(jsonp.toString());
      StringBuffer res = new StringBuffer();
      while (m.find()) {
        m.appendReplacement(res, "\\" + toUnicode(m.group()));
      }
      m.appendTail(res);

      out = response.getWriter();
      out.write(res.toString());
    } catch (Exception e) {
      e.printStackTrace();
    } finally {
      if (null != out) out.close();
    }

    return null;
  }
예제 #2
0
 public UserCacheRecord next() {
   try {
     UserCacheRecord returnBean = null;
     while (returnBean == null && this.storageKeyIterator.hasNext()) {
       UserCacheService.StorageKey key = this.storageKeyIterator.next();
       returnBean = userCacheService.readStorageKey(key);
       if (returnBean != null) {
         if (returnBean.getCacheTimestamp() == null) {
           LOGGER.debug(
               PwmConstants.REPORTING_SESSION_LABEL,
               "purging record due to missing cache timestamp: "
                   + JsonUtil.serialize(returnBean));
           userCacheService.removeStorageKey(key);
         } else if (TimeDuration.fromCurrent(returnBean.getCacheTimestamp())
             .isLongerThan(settings.getMaxCacheAge())) {
           LOGGER.debug(
               PwmConstants.REPORTING_SESSION_LABEL,
               "purging record due to old age timestamp: " + JsonUtil.serialize(returnBean));
           userCacheService.removeStorageKey(key);
         } else {
           return returnBean;
         }
       }
     }
   } catch (LocalDBException e) {
     throw new IllegalStateException(
         "unexpected iterator traversal error while reading LocalDB: " + e.getMessage());
   }
   return null;
 }
예제 #3
0
  /**
   * test json fill bean
   *
   * @throws JSONException
   */
  @Test
  public void testJsonFillBean() throws JSONException {
    MessageInfo fromMsg = BaseTest.getMessageInfo();
    JSONObject jsonObject = JsonUtil.toJSONObjectFromBean(fromMsg);
    Assert.assertEquals(55555555555555L, jsonObject.get("messageId"));
    Assert.assertEquals("some msg", jsonObject.get("messageSubject"));
    Assert.assertEquals((short) 8, jsonObject.get("messageSubjectLength"));
    // Assert.assertEquals(new JSONObject(new Content(1, "哈哈噢噢,who am i?")),
    // jsonObject.get("messageContent"));
    Assert.assertEquals(true, jsonObject.get("success"));
    Assert.assertEquals((Long) 10L, jsonObject.get("messageSize"));
    Assert.assertEquals((Short) (short) 20, jsonObject.get("messageSize2"));

    jsonObject = JsonUtil.toJSONObject(jsonObject.toString());
    MessageInfo msg = new MessageInfo();
    JsonUtil.fillBeanFromJSONObject(msg, jsonObject, true);
    Assert.assertEquals(55555555555555L, msg.getMessageId());
    Assert.assertEquals("some msg", msg.getMessageSubject());
    Assert.assertEquals((short) 8, msg.getMessageSubjectLength());
    Assert.assertEquals(new Content(1, "哈哈噢噢,who am i?"), msg.getMessageContent());
    Assert.assertEquals(true, msg.getSuccess());
    Assert.assertEquals((Long) 10L, msg.getMessageSize());
    Assert.assertEquals((Short) (short) 20, msg.getMessageSize2());
    Assert.assertEquals(2, msg.getRecipientList().size());
    Assert.assertEquals(BaseTest.getRecipient(), msg.getRecipientList().get(0));
    Assert.assertEquals(BaseTest.getRecipient2(), msg.getRecipientList().get(1));
  }
 public JsonObject toJson() {
   return JsonLoader.createObjectBuilder()
       .add("name", name)
       .add("factoryClassName", factoryClassName)
       .add("params", JsonUtil.toJsonObject(params))
       .add("extraProps", JsonUtil.toJsonObject(extraProps))
       .build();
 }
예제 #5
0
  private static List<UserIdentity> readAllUsersFromLdap(
      final PwmApplication pwmApplication, final String searchFilter, final int maxResults)
      throws ChaiUnavailableException, ChaiOperationException, PwmUnrecoverableException,
          PwmOperationalException {
    final UserSearchEngine userSearchEngine = new UserSearchEngine(pwmApplication, null);
    final UserSearchEngine.SearchConfiguration searchConfiguration =
        new UserSearchEngine.SearchConfiguration();
    searchConfiguration.setEnableValueEscaping(false);
    searchConfiguration.setSearchTimeout(
        Long.parseLong(
            pwmApplication.getConfig().readAppProperty(AppProperty.REPORTING_LDAP_SEARCH_TIMEOUT)));

    if (searchFilter == null) {
      searchConfiguration.setUsername("*");
    } else {
      searchConfiguration.setFilter(searchFilter);
    }

    LOGGER.debug(
        PwmConstants.REPORTING_SESSION_LABEL,
        "beginning UserReportService user search using parameters: "
            + (JsonUtil.serialize(searchConfiguration)));

    final Map<UserIdentity, Map<String, String>> searchResults =
        userSearchEngine.performMultiUserSearch(
            searchConfiguration, maxResults, Collections.<String>emptyList());
    LOGGER.debug(
        PwmConstants.REPORTING_SESSION_LABEL,
        "user search found " + searchResults.size() + " users for reporting");
    final List<UserIdentity> returnList = new ArrayList<>(searchResults.keySet());
    Collections.shuffle(returnList);
    return returnList;
  }
예제 #6
0
 private static String buildTiposContaJson() {
   List<Tipo> tipos = new ArrayList<Tipo>();
   for (ContaTipo contaTipo : ContaTipo.values()) {
     tipos.add(new TipoUtil.Tipo("" + contaTipo.getId(), contaTipo.getDescricao()));
   }
   return JsonUtil.toJson(tipos);
 }
예제 #7
0
  public static boolean uploadFile(
      String url, String uploadKey, File file, Map<String, String> params) {
    // TODO httpClient连接关闭问题需要考虑
    try {
      HttpPost httppost = new HttpPost("http://www.new_magic.com/service.php");

      MultipartEntity reqEntity = new MultipartEntity();
      reqEntity.addPart(uploadKey, new FileBody(file));
      for (Map.Entry<String, String> entry : params.entrySet()) {
        StringBody value = new StringBody(entry.getValue());
        reqEntity.addPart(entry.getKey(), value);
      }

      httppost.setEntity(reqEntity);
      HttpResponse response = httpClient.execute(httppost);
      int statusCode = response.getStatusLine().getStatusCode();

      if (statusCode == HttpStatus.SC_OK) {
        HttpEntity resEntity = response.getEntity();
        String body = EntityUtils.toString(resEntity);
        EntityUtils.consume(resEntity);

        Map<String, Object> responseMap = JsonUtil.parseJson(body, Map.class);
        if (responseMap.containsKey("code") && responseMap.get("code").equals(10000)) {
          return true;
        }
      }
    } catch (Exception e) {
      log.error("", e);
    }
    return false;
  }
 /** Constructor, parses from a JSON response String. */
 public ReadResponse(InternalResponse resp) {
   super(resp);
   try {
     JSONObject rootJsonObj = new JSONObject(resp.getContent());
     Response.withMeta(this, rootJsonObj);
     JSONObject respJson = rootJsonObj.getJSONObject(Constants.RESPONSE);
     Object dataObj = respJson.get(Constants.QUERY_DATA);
     if (dataObj instanceof JSONArray) {
       data = JsonUtil.data(respJson.getJSONArray(Constants.QUERY_DATA));
     } else if (dataObj instanceof JSONObject) {
       data.add(JsonUtil.toMap((JSONObject) dataObj));
     }
   } catch (JSONException e) {
     throw new RuntimeException(e);
   }
 }
예제 #9
0
  private void restBrowseLdap(final PwmRequest pwmRequest, final ConfigGuideBean configGuideBean)
      throws IOException, ServletException, PwmUnrecoverableException {
    final StoredConfigurationImpl storedConfiguration =
        StoredConfigurationImpl.copy(configGuideBean.getStoredConfiguration());
    if (configGuideBean.getStep() == STEP.LDAP_ADMIN) {
      storedConfiguration.resetSetting(PwmSetting.LDAP_PROXY_USER_DN, LDAP_PROFILE_KEY, null);
      storedConfiguration.resetSetting(PwmSetting.LDAP_PROXY_USER_PASSWORD, LDAP_PROFILE_KEY, null);
    }

    final Date startTime = new Date();
    final Map<String, String> inputMap =
        pwmRequest.readBodyAsJsonStringMap(PwmHttpRequestWrapper.Flag.BypassValidation);
    final String profile = inputMap.get("profile");
    final String dn = inputMap.containsKey("dn") ? inputMap.get("dn") : "";

    final LdapBrowser ldapBrowser = new LdapBrowser(storedConfiguration);
    final LdapBrowser.LdapBrowseResult result = ldapBrowser.doBrowse(profile, dn);
    ldapBrowser.close();

    LOGGER.trace(
        pwmRequest,
        "performed ldapBrowse operation in "
            + TimeDuration.fromCurrent(startTime).asCompactString()
            + ", result="
            + JsonUtil.serialize(result));

    pwmRequest.outputJsonResult(new RestResultBean(result));
  }
 public static Object deserialize(String json, String containerType, Class cls)
     throws ApiException {
   try {
     if ("list".equalsIgnoreCase(containerType) || "array".equalsIgnoreCase(containerType)) {
       return JsonUtil.deserializeToList(json, cls);
     } else if (String.class.equals(cls)) {
       if (json != null && json.startsWith("\"") && json.endsWith("\"") && json.length() > 1)
         return json.substring(1, json.length() - 1);
       else return json;
     } else {
       return JsonUtil.deserializeToObject(json, cls);
     }
   } catch (JsonParseException e) {
     throw new ApiException(500, e.getMessage());
   }
 }
예제 #11
0
  public static void main(String[] args) {
    ParamUtil paramUtil = new ParamUtil();

    paramUtil.setType("1");
    List<ConUtil> conUtilList = new ArrayList<ConUtil>();
    ConUtil conUtil = new ConUtil();
    conUtil.setArg("aaaa");
    conUtil.setMsg("bbbb");
    conUtil.setShortname("cccc");
    conUtil.setValue("dddd");

    conUtilList.add(conUtil);

    conUtil = new ConUtil();
    conUtil.setArg("eeee");
    conUtil.setMsg("rrrr");
    conUtil.setShortname("tttt");
    conUtil.setValue("yyyy");
    conUtilList.add(conUtil);

    paramUtil.setConUtilList(conUtilList);

    paramUtil.setTablename("444444444444");

    System.out.println(JsonUtil.buildNormalBinder().toJson(paramUtil));
  }
예제 #12
0
 private static String buildTiposUsuarioJson() {
   List<String> tipos = new ArrayList<String>();
   for (UsuarioTipo usuarioTipo : UsuarioTipo.values()) {
     tipos.add(usuarioTipo.name());
   }
   return JsonUtil.toJson(tipos.toArray(new String[0]));
 }
예제 #13
0
  public SearchResponse search(String index, String type, SearchRequest searchRequest)
      throws IOException {
    logger.debug("search [{}]/[{}], request [{}]", index, type, searchRequest);

    String path = "/";

    if (index != null) {
      path += index + "/";
    }
    if (type != null) {
      path += type + "/";
    }

    path += "_search";

    Map<String, String> params = new HashMap<>();
    if (searchRequest.getQuery() != null) {
      params.put("q", searchRequest.getQuery());
    }
    if (searchRequest.getFields() != null) {
      // If we never set elasticsearch behavior, it's time to do so
      if (FIELDS == null) {
        setElasticsearchBehavior();
      }
      params.put(FIELDS, String.join(",", (CharSequence[]) searchRequest.getFields()));
    }
    if (searchRequest.getSize() != null) {
      params.put("size", searchRequest.getSize().toString());
    }
    Response restResponse = client.performRequest("GET", path, params);
    SearchResponse searchResponse = JsonUtil.deserialize(restResponse, SearchResponse.class);

    logger.trace("search response: {}", searchResponse);
    return searchResponse;
  }
예제 #14
0
  public void TestRedis() {
    RedisTemplate<String, String> jedisTemplate =
        (RedisTemplate<String, String>) SpringUtils.getBean("jedisTemplate");
    jedisTemplate.setValueSerializer(new StringRedisSerializer());
    Long size = jedisTemplate.opsForList().size(MsgListName);

    if (0L == size) return;
    //		// show the Hashmap 's value
    Map<Object, Object> hm = jedisTemplate.opsForHash().entries("Sender_Rules_HashMap");
    for (Entry<Object, Object> entry : hm.entrySet()) {
      System.out.println(entry.getKey());
    }
    for (int i = 0; i < 1; i++) {
      String json = jedisTemplate.opsForList().rightPop(MsgListName);
      AlarmMsgEntity entity = JsonUtil.getInstance().json2Obj(json, AlarmMsgEntity.class);
      // if has key then wait next time to alarm
      if (jedisTemplate.hasKey(entity.getRedisKey())) continue;
      System.out.println(entity.getRedisKey());

      if (jedisTemplate.opsForHash().hasKey("Sender_Rules_HashMap", entity.getRedisKey())) {
        System.out.println("find one .................");
        AlarmSenderEntity ae =
            (AlarmSenderEntity)
                jedisTemplate.opsForHash().get("Sender_Rules_HashMap", entity.getRedisKey());
        if (ae.getSendType().equals("短信")) {
          System.out.println("sends messages for alarm!");
          jedisTemplate.expire(entity.getRedisKey(), 5, TimeUnit.MINUTES);
        }
      }
    }
  }
예제 #15
0
 private void updateCacheFromLdap()
     throws ChaiUnavailableException, ChaiOperationException, PwmOperationalException,
         PwmUnrecoverableException {
   LOGGER.debug(
       PwmConstants.REPORTING_SESSION_LABEL,
       "beginning process to updating user cache records from ldap");
   if (status != STATUS.OPEN) {
     return;
   }
   cancelFlag = false;
   reportStatus = new ReportStatusInfo(settings.getSettingsHash());
   reportStatus.setInProgress(true);
   reportStatus.setStartDate(new Date());
   try {
     final Queue<UserIdentity> allUsers = new LinkedList<>(getListOfUsers());
     reportStatus.setTotal(allUsers.size());
     while (status == STATUS.OPEN && !allUsers.isEmpty() && !cancelFlag) {
       final Date startUpdateTime = new Date();
       final UserIdentity userIdentity = allUsers.poll();
       try {
         if (updateCachedRecordFromLdap(userIdentity)) {
           reportStatus.setUpdated(reportStatus.getUpdated() + 1);
         }
       } catch (Exception e) {
         String errorMsg =
             "error while updating report cache for " + userIdentity.toString() + ", cause: ";
         errorMsg +=
             e instanceof PwmException
                 ? ((PwmException) e).getErrorInformation().toDebugStr()
                 : e.getMessage();
         final ErrorInformation errorInformation;
         errorInformation = new ErrorInformation(PwmError.ERROR_REPORTING_ERROR, errorMsg);
         LOGGER.error(PwmConstants.REPORTING_SESSION_LABEL, errorInformation.toDebugStr());
         reportStatus.setLastError(errorInformation);
         reportStatus.setErrors(reportStatus.getErrors() + 1);
       }
       reportStatus.setCount(reportStatus.getCount() + 1);
       reportStatus.getEventRateMeter().markEvents(1);
       final TimeDuration totalUpdateTime = TimeDuration.fromCurrent(startUpdateTime);
       if (settings.isAutoCalcRest()) {
         avgTracker.addSample(totalUpdateTime.getTotalMilliseconds());
         Helper.pause(avgTracker.avgAsLong());
       } else {
         Helper.pause(settings.getRestTime().getTotalMilliseconds());
       }
     }
     if (cancelFlag) {
       reportStatus.setLastError(
           new ErrorInformation(
               PwmError.ERROR_SERVICE_NOT_AVAILABLE, "report cancelled by operator"));
     }
   } finally {
     reportStatus.setFinishDate(new Date());
     reportStatus.setInProgress(false);
   }
   LOGGER.debug(
       PwmConstants.REPORTING_SESSION_LABEL,
       "update user cache process completed: " + JsonUtil.serialize(reportStatus));
 }
 public static String serialize(Object obj) throws ApiException {
   try {
     if (obj != null) return JsonUtil.serialize(obj);
     else return null;
   } catch (Exception e) {
     throw new ApiException(500, e.getMessage());
   }
 }
예제 #17
0
 public Map getEnv() {
   if (env == null) {
     // parse env
     String _env = request.getParameter("env");
     if (_env != null && _env.length() > 0 && _env.startsWith("{")) {
       env = JsonUtil.toMap(_env);
     }
   }
   return env;
 }
예제 #18
0
  public void putMapping(String index, String type, String mapping) throws IOException {
    logger.debug("put mapping [{}/{}]", index, type);

    StringEntity entity = new StringEntity(mapping, Charset.defaultCharset());
    Response restResponse =
        client.performRequest(
            "PUT", "/" + index + "/_mapping/" + type, Collections.emptyMap(), entity);
    Map<String, Object> responseAsMap = JsonUtil.asMap(restResponse);
    logger.trace("put mapping response: {}", responseAsMap);
  }
예제 #19
0
 private void saveTempData() {
   try {
     final String jsonInfo = JsonUtil.serialize(reportStatus);
     pwmApplication.writeAppAttribute(PwmApplication.AppAttribute.REPORT_STATUS, jsonInfo);
   } catch (Exception e) {
     LOGGER.error(
         PwmConstants.REPORTING_SESSION_LABEL,
         "error writing cached report dredge info into memory: " + e.getMessage());
   }
 }
예제 #20
0
  public static void main(String[] args) {
    //        HttpUtil.postXml("http://127.0.0.1:8090/trade/order/payment/callback/wechat_notify",
    // "<xml>\n" +
    //                "   <appid><![CDATA[wx2421b1c4370ec43b]]></appid>\n" +
    //                "   <attach><![CDATA[支付测试]]></attach>\n" +
    //                "   <bank_type><![CDATA[CFT]]></bank_type>\n" +
    //                "   <fee_type><![CDATA[CNY]]></fee_type>\n" +
    //                "   <is_subscribe><![CDATA[Y]]></is_subscribe>\n" +
    //                "   <mch_id><![CDATA[10000100]]></mch_id>\n" +
    //                "   <nonce_str><![CDATA[5d2b6c2a8db53831f7eda20af46e531c]]></nonce_str>\n" +
    //                "   <openid><![CDATA[oUpF8uMEb4qRXf22hE3X68TekukE]]></openid>\n" +
    //                "   <out_trade_no><![CDATA[1409811653]]></out_trade_no>\n" +
    //                "   <result_code><![CDATA[SUCCESS]]></result_code>\n" +
    //                "   <return_code><![CDATA[SUCCESS]]></return_code>\n" +
    //                "   <sign><![CDATA[B552ED6B279343CB493C5DD0D78AB241]]></sign>\n" +
    //                "   <sub_mch_id><![CDATA[10000100]]></sub_mch_id>\n" +
    //                "   <time_end><![CDATA[20140903131540]]></time_end>\n" +
    //                "   <total_fee>1</total_fee>\n" +
    //                "   <trade_type><![CDATA[JSAPI]]></trade_type>\n" +
    //                "
    // <transaction_id><![CDATA[1004400740201409030005092168]]></transaction_id>\n" +
    //                "</xml>");

    List<NameValuePair> params = new ArrayList<NameValuePair>();
    params.add(new BasicNameValuePair("topic", "user-add-msg"));
    Map<String, Object> data = new HashMap<String, Object>();
    data.put("user_id", 92L);
    params.add(new BasicNameValuePair("data", JsonUtil.toJson(data)));

    String response = HttpUtil.post("http://115.236.182.108:7081/YDX-ERP/message/notify", params);
    System.out.println("response:" + response);

    params = new ArrayList<NameValuePair>();
    params.add(new BasicNameValuePair("topic", "trade-pay-msg"));
    data = new HashMap<String, Object>();
    data.put("user_id", 75L);
    data.put("order_uid", "1_75_976");
    data.put("pay_status", 1);
    params.add(new BasicNameValuePair("data", JsonUtil.toJson(data)));

    response = HttpUtil.post("http://115.236.182.108:7081/YDX-ERP/message/notify", params);
    System.out.println("response:" + response);
  }
예제 #21
0
  public void testEncode() throws Exception {
    JsonObject jso =
        JsonParser.fromString("{name:'bleujin', age:20, loc:{city:'seoul'}, color:['red', 'blue']}")
            .getAsJsonObject();

    Map<String, Object> map = (Map<String, Object>) JsonUtil.toSimpleObject(jso);
    assertEquals("bleujin", map.get("name"));
    assertEquals(20L, map.get("age"));
    assertEquals("seoul", ((Map) map.get("loc")).get("city"));
    assertEquals("red", ((List) map.get("color")).get(0));
  }
예제 #22
0
  public void index(String index, String type, String id, String json) throws IOException {
    logger.debug("put document [{}/{}/{}]", index, type, id);

    StringEntity entity = new StringEntity(json, Charset.defaultCharset());
    Response restResponse =
        client.performRequest(
            "PUT", "/" + index + "/" + type + "/" + id, Collections.emptyMap(), entity);
    Map<String, Object> responseAsMap = JsonUtil.asMap(restResponse);

    logger.trace("put document response: {}", responseAsMap);
  }
예제 #23
0
파일: HttpSend.java 프로젝트: Jeanwin/study
 /**
  * put方式远程获取数据
  *
  * @param url
  * @param param
  * @return
  */
 public static String put(String url, Object param) {
   HttpPut put = new HttpPut(url);
   try {
     put.setEntity(new StringEntity(JsonUtil.toJson(param)));
     HttpResponse response = new DefaultHttpClient().execute(put);
     return send(response);
   } catch (Exception e) {
     e.printStackTrace();
   }
   return null;
 }
예제 #24
0
 public Object[] getArgs() {
   // parse arguments
   if (args == null) {
     String parm = request.getParameter("args");
     if (parm != null && parm.length() > 0) {
       if (!parm.startsWith("[")) throw new RuntimeException("args must be enclosed with []");
       args = JsonUtil.toObjectArray(parm);
     }
   }
   return args;
 }
예제 #25
0
 public String findVersion() throws IOException {
   logger.debug("findVersion()");
   String version;
   Response restResponse = client.performRequest("GET", "/");
   Map<String, Object> responseAsMap = JsonUtil.asMap(restResponse);
   logger.trace("get server response: {}", responseAsMap);
   Object oVersion = extractFromPath(responseAsMap, "version").get("number");
   version = (String) oVersion;
   logger.debug("findVersion() -> [{}]", version);
   return version;
 }
예제 #26
0
  public void waitForHealthyIndex(String index) throws IOException {
    logger.debug("wait for yellow health on index [{}]", index);

    Response restResponse =
        client.performRequest(
            "GET",
            "/_cluster/health/" + index,
            Collections.singletonMap("wait_for_status", "yellow"));
    Map<String, Object> responseAsMap = JsonUtil.asMap(restResponse);

    logger.trace("health response: {}", responseAsMap);
  }
예제 #27
0
  public void testFindElement() throws Exception {
    JsonObject jso =
        JsonParser.fromString("{name:'bleujin', age:20, loc:{city:'seoul'}, color:['red', 'blue']}")
            .getAsJsonObject();

    assertEquals("bleujin", JsonUtil.findElement(jso, "name").getAsString());
    assertEquals(20, JsonUtil.findElement(jso, "age").getAsInt());

    assertEquals("seoul", JsonUtil.findElement(jso, "loc.city").getAsString());
    assertEquals(true, JsonUtil.findElement(jso, "loc.city").isJsonPrimitive());

    assertEquals(true, JsonUtil.findElement(jso, "Name") != null);
    assertEquals(true, JsonUtil.findElement(jso, "un") == null);
    assertEquals(true, JsonUtil.findElement(jso, "loc.un") == null);

    assertEquals(true, JsonUtil.findSimpleObject(jso, "loc.city").equals("seoul"));
    assertEquals(true, JsonUtil.findSimpleObject(jso, "loc.notfound") == null);
  }
  @RequestMapping(value = "queryAccountInformationChangeList")
  public @ResponseBody Pagination queryAccountInformationChangeList(
      @RequestParam(required = false) String page,
      @RequestParam(required = false) String rows,
      HttpSession session,
      String paramJsonMap,
      String sort,
      String order) {
    Pagination pagination = new Pagination();
    if (!StringUtils.isBlank(page)) {
      pagination.setPage(Integer.valueOf(page));
    }
    if (!StringUtils.isBlank(rows)) {
      pagination.setPageSize(Integer.valueOf(rows));
    }
    // 添加权限查询
    List<String> authList = SpringSecurityUtils.getAuthList(session);
    String sqlsid = "";
    if (authList.size() > 0) {
      for (String e : authList) {
        if (sqlsid != null) {
          sqlsid = sqlsid + "'" + e + "'" + ",";
        } else {
          sqlsid = "'" + e + "'" + ",";
        }
      }
      sqlsid = sqlsid.substring(0, sqlsid.length() - 1);
    }

    System.out.println(sqlsid);
    System.out.println(sqlsid);
    System.out.println(sqlsid);
    System.out.println(sqlsid);
    Map<String, String> pramMap = new HashMap<String, String>();

    pramMap.put("authList", sqlsid);
    pramMap.put("sort", sort);
    pramMap.put("order", order);

    if (!"".equals(paramJsonMap) && paramJsonMap != null) {
      Map<String, String> temp = JsonUtil.getObject(paramJsonMap);
      String businessNumber = temp.get("businessNumber");
      String name = temp.get("name");
      pramMap.put("businessNumber", businessNumber);
      pramMap.put("name", name);
    }

    pagination = modifyCatdAppService.queryAccountInformationChangeList(pagination, pramMap);

    return pagination;
  }
    @Override
    protected String doInBackground(String... urls) {

      JSONObject jsonObject = new JSONObject();
      try {
        jsonObject.accumulate("comment", urls[1]);
        jsonObject.accumulate("post_id", urls[2]);
        jsonObject.accumulate("username", UserDataHolder.getInstance().getUsername());
      } catch (JSONException e) {
        e.printStackTrace();
      }

      return JsonUtil.POST(urls[0], jsonObject);
    }
예제 #30
0
  /**
   * test to json
   *
   * @throws JSONException
   */
  @Test
  public void testToJson() throws JSONException {
    MessageInfo msg = BaseTest.getMessageInfo();
    JSONObject jsonObject = JsonUtil.toJSONObjectFromBean(msg);
    Assert.assertEquals(55555555555555L, jsonObject.get("messageId"));
    Assert.assertEquals("some msg", jsonObject.get("messageSubject"));
    Assert.assertEquals((short) 8, jsonObject.get("messageSubjectLength"));
    // Assert.assertEquals(new JSONObject(new Content(1, "哈哈噢噢,who am i?")),
    // jsonObject.get("messageContent"));
    Assert.assertEquals(true, jsonObject.get("success"));
    Assert.assertEquals((Long) 10L, jsonObject.get("messageSize"));
    Assert.assertEquals((Short) (short) 20, jsonObject.get("messageSize2"));

    jsonObject = JsonUtil.toJSONObject(jsonObject.toString());
    Assert.assertEquals(55555555555555L, jsonObject.get("messageId"));
    Assert.assertEquals("some msg", jsonObject.get("messageSubject"));
    Assert.assertEquals((byte) 8, jsonObject.get("messageSubjectLength"));
    // Assert.assertEquals(new JSONObject(new Content(1, "哈哈噢噢,who am i?")),
    // jsonObject.get("messageContent"));
    Assert.assertEquals(true, jsonObject.get("success"));
    Assert.assertEquals((Byte) (byte) 10, jsonObject.get("messageSize"));
    Assert.assertEquals((Byte) (byte) 20, jsonObject.get("messageSize2"));
  }