Java Code Examples for com.alibaba.fastjson.JSONObject#getObject()

The following examples show how to use com.alibaba.fastjson.JSONObject#getObject() . You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
Source File: PojoBindingTest.java    From actframework with Apache License 2.0 6 votes vote down vote up
@Test
public void testMapPojoBinding() throws Exception {
    url("/pojo/fooMap").get(
            "fooMap.x.id", "abc",
            "fooMap.x.bar.id", "xyz",
            "fooMap.y.id", "a123",
            "fooMap.y.bar.id", "a000"
    );
    String body = resp().body().string();
    JSONObject json = JSONObject.parseObject(body);
    Foo x = json.getObject("x", Foo.class);
    eq("abc", x.getId());
    eq("xyz", x.getBar().getId());
    Foo y = json.getObject("y", Foo.class);
    eq("a000", y.getBar().getId());
}
 
Example 2
Source File: EsColumnSyncManager.java    From DataLink with Apache License 2.0 6 votes vote down vote up
/**
 * 获取索引所对应的参数
 *
 * @param json
 * @return
 */
private static void toIndexPropMap(JSONObject json, Map<String, String> propMap) {
    Iterator it = json.keySet().iterator();
    while (it.hasNext()) {
        String key = (String) it.next();
        Object object = json.getObject(key, Object.class);
        if (key.equals("properties")) {
            JSONObject propJson = json.getJSONObject(key);
            Iterator propIt = propJson.keySet().iterator();
            while (propIt.hasNext()) {
                String prop = (String) propIt.next();
                JSONObject valJson = propJson.getJSONObject(prop);
                String type = valJson.getString("type");
                propMap.put(prop, type);
            }
        } else if (object instanceof JSONObject) {
            toIndexPropMap((JSONObject) object, propMap);
        }
    }
}
 
Example 3
Source File: AddressUtils.java    From NutzSite with Apache License 2.0 6 votes vote down vote up
public static String getRealAddressByIP(String ip) {
    String address = "XX XX";
    // 内网不查询
    if (IpUtils.internalIp(ip)) {
        return "内网IP";
    }
    try {
        Response rspStr = Http.get(IP_URL + "?ip=" + ip, 5 * 1000);
        if (!rspStr.isOK()) {
            log.error("获取地理位置异常 {}", ip);
            return address;
        }
        JSONObject obj = JSONObject.parseObject(rspStr.getContent());
        JSONObject data = obj.getObject("data", JSONObject.class);
        String region = data.getString("region");
        String city = data.getString("city");
        address = region + " " + city;
    } catch (Exception e) {
        log.error("IP查询失败:" + ip + e.getMessage());
    }
    return address;
}
 
Example 4
Source File: BaseOperationAdapter.java    From java-unified-sdk with Apache License 2.0 6 votes vote down vote up
private <T> T parseJSONObject(JSONObject jsonObject) {
  if (jsonObject.containsKey(ATTR_OP) && jsonObject.containsKey(ATTR_FIELD)) {
    String op = jsonObject.getString(ATTR_OP);
    String field = jsonObject.getString(ATTR_FIELD);
    boolean isFinal = jsonObject.containsKey(ATTR_FINAL)? jsonObject.getBoolean(ATTR_FINAL) : false;

    OperationBuilder.OperationType opType = OperationBuilder.OperationType.valueOf(op);

    Object obj = jsonObject.containsKey(ATTR_OBJECT) ? jsonObject.get(ATTR_OBJECT) : null;
    Object parsedObj = getParsedObject(obj);

    ObjectFieldOperation result = OperationBuilder.gBuilder.create(opType, field, parsedObj);
    ((BaseOperation)result).isFinal = isFinal;

    if (jsonObject.containsKey(ATTR_SUBOPS) && result instanceof CompoundOperation) {
      List<JSONObject> subOps = jsonObject.getObject(ATTR_SUBOPS, List.class);
      for (JSONObject o : subOps) {
        result.merge((BaseOperation)parseJSONObject(o));
      }
    }

    return (T) result;
  }
  return (T) new NullOperation("Null", null);
}
 
Example 5
Source File: AddressUtils.java    From DimpleBlog with Apache License 2.0 6 votes vote down vote up
/**
 * call taobao api will get error like <code>{"msg":"the request over max qps for user ,the accessKey=public","code":4}</code>
 * this method has deprecated.
 *
 * @param ip ip location
 * @return location info
 */
@Deprecated
public static String getRealAddressByIP(String ip) {
    String address = "XX XX";
    // 内网不查询
    if (IpUtils.internalIp(ip)) {
        return "内网IP";
    }
    String rspStr = HttpUtils.sendPost(IP_URL, "ip=" + ip);
    if (StringUtils.isEmpty(rspStr)) {
        log.error("获取地理位置异常 {}", ip);
        return address;
    }
    JSONObject obj = JSON.parseObject(rspStr);
    JSONObject data = obj.getObject("data", JSONObject.class);
    String region = data.getString("region");
    String city = data.getString("city");
    address = region + " " + city;
    return address;
}
 
Example 6
Source File: AddressUtils.java    From LuckyFrameWeb with GNU Affero General Public License v3.0 6 votes vote down vote up
public static String getRealAddressByIP(String ip)
{
    String address = "XX XX";
    // 内网不查询
    if (IpUtils.internalIp(ip))
    {
        return "内网IP";
    }
    if (LuckyFrameConfig.isAddressEnabled())
    {
        String rspStr = HttpUtils.sendPost(IP_URL, "ip=" + ip);
        if (StringUtils.isEmpty(rspStr))
        {
            log.error("获取地理位置异常 {}", ip);
            return address;
        }
        JSONObject obj = JSONObject.parseObject(rspStr);
        JSONObject data = obj.getObject("data", JSONObject.class);
        String region = data.getString("region");
        String city = data.getString("city");
        address = region + " " + city;
    }
    return address;
}
 
Example 7
Source File: NodeManageController.java    From redis-manager with Apache License 2.0 6 votes vote down vote up
@RequestMapping(value = "/getConfigCurrentValue", method = RequestMethod.POST)
@ResponseBody
public Result getConfigCurrentValue(@RequestBody JSONObject jsonObject) {
    Cluster cluster = jsonObject.getObject("cluster", Cluster.class);
    String configKey = jsonObject.getString("configKey");
    List<RedisNode> redisNodeList = redisService.getRealRedisNodeList(cluster);
    List<JSONObject> configList = new ArrayList<>(redisNodeList.size());
    redisNodeList.forEach(redisNode -> {
        Map<String, String> configMap = redisService.getConfig(redisNode, cluster.getRedisPassword(), configKey);
        JSONObject config = new JSONObject();
        config.put("redisNode", RedisUtil.getNodeString(redisNode));
        if (configMap != null) {
            config.put("configValue", configMap.get(configKey));
        }
        configList.add(config);
    });
    return Result.successResult(configList);
}
 
Example 8
Source File: FastjsonSerializer.java    From jboot with Apache License 2.0 6 votes vote down vote up
@Override
public Object deserialize(byte[] bytes) {
    if (bytes == null || bytes.length == 0) {
        return null;
    }
    String json = new String(bytes);
    JSONObject jsonObject = JSON.parseObject(json);
    Class clazz = null;
    try {
        clazz = Class.forName(jsonObject.getString("clazz"));
    } catch (ClassNotFoundException e) {
        LOG.error(e.toString(), e);
        return null;
    }
    return jsonObject.getObject("object", clazz);
}
 
Example 9
Source File: AddOrUpdateCardGroupAction.java    From Almost-Famous with MIT License 5 votes vote down vote up
@Override
public Resoult execute(JSONObject jsonObject, HttpServletRequest request, HttpServletResponse response) {
    Integer schoolId = jsonObject.getInteger("schoolId");
    CardGroup cardGroup = jsonObject.getObject("cardGroup", CardGroup.class);
    // 新增或修改
    ErrorCode code = schoolService.updateCardGroup(rid, schoolId, cardGroup);
    return Resoult.error(RegisterProtocol.ADD_OR_UPDATE_CARD_GROUP_RESP, code, "");
}
 
Example 10
Source File: ChapterChallengeOverAction.java    From Almost-Famous with MIT License 5 votes vote down vote up
@Override
    public Resoult execute(JSONObject jsonObject, HttpServletRequest request, HttpServletResponse response) {
        Integer chapterId = jsonObject.getInteger("chapterId");
        Integer schoolId = jsonObject.getInteger("schoolId");
        Integer state = jsonObject.getInteger("state"); //失败 0

        JSONObject object = chapterService.challengeOver(rid, schoolId, chapterId, state);
        ErrorCode code = object.getObject("code", ErrorCode.class);
        String drop = object.getString("drop");
        if (code != ErrorCode.SERVER_SUCCESS) {
            return Resoult.error(RegisterProtocol.CHAPTER_CHALLENGE_OVER_RESP, code, "");
        }

        JSONObject data = new JSONObject();
        ConcurrentHashMap<Integer, Integer> map = new ConcurrentHashMap<>();
        String cutQuotes = Misc.cutQuotes(drop);
        List<HoldItem> holdItems = ItemMgr.dropItem(cutQuotes);
        List<PropBean> propList = GameUtils.getPropList(holdItems);
        data.put("drop", propList);

        //推送GM
        Resoult result = GameUtils.getActorCurrency(roleService.selectByRoleId(rid), rid);
        sendMessage.send(rid, result);
//        sendMessage.sendNow(rid);

        missionService.actorMissionMgr(missionService.getActorMissionById(rid), roleService.selectByRoleId(rid));
        //任务推送
//        missionService.noticeMission(rid);
        return Resoult.ok(RegisterProtocol.CHAPTER_CHALLENGE_OVER_RESP).responseBody(data);
    }
 
Example 11
Source File: AVObject.java    From java-unified-sdk with Apache License 2.0 5 votes vote down vote up
public AVObject apply(JSONObject object) throws Exception {
  if (null != object) {
    logger.d("batchUpdate result: " + object.toJSONString());
    Map<String, Object> lastResult = object.getObject(currentObjectId, Map.class);
    if (null != lastResult) {
      AVUtils.mergeConcurrentMap(serverData, lastResult);
      AVObject.this.onSaveSuccess();
    }
  }
  return AVObject.this;
}
 
Example 12
Source File: NodeManageController.java    From redis-manager with Apache License 2.0 5 votes vote down vote up
@RequestMapping(value = "/updateRedisConfig", method = RequestMethod.POST)
@ResponseBody
@OperationLog(type = OperationType.UPDATE, objType = OperationObjectType.REDIS_CONFIG)
public Result updateRedisConfig(@RequestBody JSONObject jsonObject) {
    Integer clusterId = jsonObject.getInteger("clusterId");
    RedisConfigUtil.RedisConfig redisConfig = jsonObject.getObject("redisConfig", RedisConfigUtil.RedisConfig.class);
    Cluster cluster = clusterService.getClusterById(clusterId);
    boolean result = redisService.setConfigBatch(cluster, redisConfig);
    return result ? Result.successResult() : Result.failResult();
}
 
Example 13
Source File: HswebResponseConvertSupport.java    From hsweb-framework with Apache License 2.0 4 votes vote down vote up
public Object tryConvertToObject(String json, Class type, OAuth2Response response) {
    if (json.startsWith("{")) {
        if (ResponseMessage.class.isAssignableFrom(type)) {
            return JSON.parseObject(json, type);
        }
        JSONObject message = JSON.parseObject(json, Feature.DisableFieldSmartMatch);
        //判断是否响应的为ResponseMessage
        if (message.size() <= responseMessageFieldSize
                && message.get("status") != null && message.get("timestamp") != null) {

            Integer status = message.getInteger("status");
            if (status != 200) {
                throw new BusinessException(message.getString("message"), status);
            }
            Object data = message.get("result");
            if (data == null) {
                return null;
            }
            //返回的是对象
            if (data instanceof JSONObject) {
                if (type == Authentication.class) {
                    return autzParser.apply(data);
                }
                return ((JSONObject) data).toJavaObject(type);
            }
            //返回的是集合
            if (data instanceof JSONArray) {
                if (type == Authentication.class) {
                    return ((JSONArray) data).stream().map(autzParser).collect(Collectors.toList());
                }
                return ((JSONArray) data).toJavaList(type);
            }
            //return data;
            return message.getObject("result", type);
        }
        if (springMvcErrorResponseKeys.containsAll(message.keySet())) {
            throw new OAuth2RequestException(ErrorType.SERVICE_ERROR, response);
        }
        return message.toJavaObject(type);
    } else if (json.startsWith("[")) {
        if (type == Authentication.class) {
            return (JSON.parseArray(json)).stream().map(autzParser).collect(Collectors.toList());
        }
        return JSON.parseArray(json, type);
    }
    return null;
}
 
Example 14
Source File: PayChannel4AlipayController.java    From xxpay-master with MIT License 4 votes vote down vote up
/**
 * 支付宝APP支付,生产签名及请求支付宝的参数(注:不会向支付宝发请求)
 * 文档: https://docs.open.alipay.com/204/105465/
 * @param jsonParam
 * @return
 */
@RequestMapping(value = "/pay/channel/ali_mobile")
public String doAliPayMobileReq(@RequestParam String jsonParam) {
    String logPrefix = "【支付宝APP支付下单】";
    JSONObject paramObj = JSON.parseObject(new String(MyBase64.decode(jsonParam)));
    PayOrder payOrder = paramObj.getObject("payOrder", PayOrder.class);
    String payOrderId = payOrder.getPayOrderId();
    String mchId = payOrder.getMchId();
    String channelId = payOrder.getChannelId();
    MchInfo mchInfo = mchInfoService.selectMchInfo(mchId);
    String resKey = mchInfo == null ? "" : mchInfo.getResKey();
    if("".equals(resKey)) return XXPayUtil.makeRetFail(XXPayUtil.makeRetMap(PayConstant.RETURN_VALUE_FAIL, "", PayConstant.RETURN_VALUE_FAIL, PayEnum.ERR_0001));
    PayChannel payChannel = payChannelService.selectPayChannel(channelId, mchId);
    alipayConfig.init(payChannel.getParam());
    AlipayClient client = new DefaultAlipayClient(alipayConfig.getUrl(), alipayConfig.getApp_id(), alipayConfig.getRsa_private_key(), AlipayConfig.FORMAT, AlipayConfig.CHARSET, alipayConfig.getAlipay_public_key(), AlipayConfig.SIGNTYPE);
    AlipayTradeAppPayRequest alipay_request = new AlipayTradeAppPayRequest();
    // 封装请求支付信息
    AlipayTradeAppPayModel model=new AlipayTradeAppPayModel();
    model.setOutTradeNo(payOrderId);
    model.setSubject(payOrder.getSubject());
    model.setTotalAmount(AmountUtil.convertCent2Dollar(payOrder.getAmount().toString()));
    model.setBody(payOrder.getBody());
    model.setProductCode("QUICK_MSECURITY_PAY");
    alipay_request.setBizModel(model);
    // 设置异步通知地址
    alipay_request.setNotifyUrl(alipayConfig.getNotify_url());
    // 设置同步地址
    alipay_request.setReturnUrl(alipayConfig.getReturn_url());
    String payParams = null;
    try {
        payParams = client.sdkExecute(alipay_request).getBody();
    } catch (AlipayApiException e) {
        e.printStackTrace();
    }
    payOrderService.updateStatus4Ing(payOrderId, null);
    _log.info("{}生成请求支付宝数据,payParams={}", logPrefix, payParams);
    _log.info("###### 商户统一下单处理完成 ######");
    Map<String, Object> map = XXPayUtil.makeRetMap(PayConstant.RETURN_VALUE_SUCCESS, "", PayConstant.RETURN_VALUE_SUCCESS, null);
    map.put("payOrderId", payOrderId);
    map.put("payParams", payParams);
    return XXPayUtil.makeRetData(map, resKey);
}
 
Example 15
Source File: DepartmentTests.java    From hsweb-framework with Apache License 2.0 4 votes vote down vote up
@Test
public void testCrud() throws Exception {
    DepartmentEntity entity = entityFactory.newInstance(DepartmentEntity.class);
    //todo 设置测试属性
    entity.setName("test");
    entity.setCode("2");
    // test add data
    String requestBody = JSON.toJSONString(entity);
    JSONObject result = testPost("/department").setUp(setup -> setup.contentType(MediaType.APPLICATION_JSON).content(requestBody)).exec().resultAsJson();
    Assert.assertEquals(200, result.get("status"));
    String id = result.getString("result");
    Assert.assertNotNull(id);
    entity.setId(id);
    // test get data
    result = testGet("/department/" + id).exec().resultAsJson();
    entity = result.getObject("result", entityFactory.getInstanceType(DepartmentEntity.class));

    Assert.assertEquals(200, result.get("status"));
    Assert.assertNotNull(result.getJSONObject("result"));

    Assert.assertEquals(fastJsonHttpMessageConverter.converter(entity),
            fastJsonHttpMessageConverter.converter(result.getObject("result", entityFactory.getInstanceType(DepartmentEntity.class))));
    //todo 修改测试属性
    DepartmentEntity newEntity = entityFactory.newInstance(DepartmentEntity.class);
    newEntity.setName("test");

    result = testPut("/department/" + id)
            .setUp(setup ->
                    setup.contentType(MediaType.APPLICATION_JSON)
                            .content(JSON.toJSONString(newEntity)))
            .exec().resultAsJson();
    Assert.assertEquals(200, result.get("status"));

    result = testGet("/department/" + id).exec().resultAsJson();
    result = result.getJSONObject("result");
    Assert.assertNotNull(result);

    result = testDelete("/department/" + id).exec().resultAsJson();
    Assert.assertEquals(200, result.get("status"));

    result = testGet("/department/" + id).exec().resultAsJson();
    Assert.assertEquals(404, result.get("status"));
}
 
Example 16
Source File: PersonTests.java    From hsweb-framework with Apache License 2.0 4 votes vote down vote up
@Test
public void testCrud() throws Exception {
    PersonEntity entity = entityFactory.newInstance(PersonEntity.class);
    //todo 设置测试属性
    entity.setName("test");

    // test add data
    String requestBody = JSON.toJSONString(entity);
    JSONObject result = testPost("/person").setUp(setup -> setup.contentType(MediaType.APPLICATION_JSON).content(requestBody)).exec().resultAsJson();
    Assert.assertEquals(200, result.get("status"));
    String id = result.getString("result");
    Assert.assertNotNull(id);
    entity.setId(id);
    // test get data
    result = testGet("/person/" + id).exec().resultAsJson();
    entity = result.getObject("result", entityFactory.getInstanceType(PersonEntity.class));

    Assert.assertEquals(200, result.get("status"));
    Assert.assertNotNull(result.getJSONObject("result"));

    Assert.assertEquals(fastJsonHttpMessageConverter.converter(entity),
            fastJsonHttpMessageConverter.converter(result.getObject("result", entityFactory.getInstanceType(PersonEntity.class))));
    //todo 修改测试属性
    PersonEntity newEntity = entityFactory.newInstance(PersonEntity.class);
    newEntity.setName("test2");

    result = testPut("/person/" + id)
            .setUp(setup ->
                    setup.contentType(MediaType.APPLICATION_JSON)
                            .content(JSON.toJSONString(newEntity)))
            .exec().resultAsJson();
    Assert.assertEquals(200, result.get("status"));

    result = testGet("/person/" + id).exec().resultAsJson();
    result = result.getJSONObject("result");
    Assert.assertNotNull(result);

    result = testDelete("/person/" + id).exec().resultAsJson();
    Assert.assertEquals(200, result.get("status"));

    result = testGet("/person/" + id).exec().resultAsJson();
    Assert.assertEquals(404, result.get("status"));
}
 
Example 17
Source File: PositionTests.java    From hsweb-framework with Apache License 2.0 4 votes vote down vote up
@Test
public void testCrud() throws Exception {
   PositionEntity entity = entityFactory.newInstance(PositionEntity.class);
    //todo 设置测试属性
    entity.setName("test");

    // test add data
    String requestBody = JSON.toJSONString(entity);
    JSONObject result = testPost("/position").setUp(setup -> setup.contentType(MediaType.APPLICATION_JSON).content(requestBody)).exec().resultAsJson();
    Assert.assertEquals(200, result.get("status"));
    String id = result.getString("result");
    Assert.assertNotNull(id);
    entity.setId(id);
    // test get data
    result = testGet("/position/" + id).exec().resultAsJson();
    entity = result.getObject("result", entityFactory.getInstanceType(PositionEntity.class));

    Assert.assertEquals(200, result.get("status"));
    Assert.assertNotNull(result.getJSONObject("result"));

    Assert.assertEquals(fastJsonHttpMessageConverter.converter(entity),
            fastJsonHttpMessageConverter.converter(result.getObject("result", entityFactory.getInstanceType(PositionEntity.class))));
    //todo 修改测试属性
    PositionEntity newEntity = entityFactory.newInstance(PositionEntity.class);
    newEntity.setName("test");

    result = testPut("/position/" + id)
            .setUp(setup ->
                    setup.contentType(MediaType.APPLICATION_JSON)
                            .content(JSON.toJSONString(newEntity)))
            .exec().resultAsJson();
    Assert.assertEquals(200, result.get("status"));

    result = testGet("/position/" + id).exec().resultAsJson();
    result = result.getJSONObject("result");
    Assert.assertNotNull(result);

    result = testDelete("/position/" + id).exec().resultAsJson();
    Assert.assertEquals(200, result.get("status"));

    result = testGet("/position/" + id).exec().resultAsJson();
    Assert.assertEquals(404, result.get("status"));
}
 
Example 18
Source File: AuthorizationSettingTests.java    From hsweb-framework with Apache License 2.0 4 votes vote down vote up
@Test
public void testCrud() throws Exception {
    AuthorizationSettingEntity entity = entityFactory.newInstance(AuthorizationSettingEntity.class);
    //todo 设置测试属性
    entity.setId("test");
    entity.setType(AuthorizationSettingTypeSupplier.SETTING_TYPE_USER);
    entity.setSettingFor("test");
    entity.setDescribe("测试");

    // test add data
    String requestBody = JSON.toJSONString(entity);
    JSONObject result = testPost("/autz-setting").setUp(setup -> setup.contentType(MediaType.APPLICATION_JSON).content(requestBody)).exec().resultAsJson();
    Assert.assertEquals(200, result.get("status"));
    String id = result.getString("result");
    Assert.assertNotNull(id);
    entity.setId(id);
    // test get data
    result = testGet("/autz-setting/" + id).exec().resultAsJson();
    entity = result.getObject("result", entityFactory.getInstanceType(AuthorizationSettingEntity.class));

    Assert.assertEquals(200, result.get("status"));
    Assert.assertNotNull(result.getJSONObject("result"));

    Assert.assertEquals(fastJsonHttpMessageConverter.converter(entity),
            fastJsonHttpMessageConverter.converter(result.getObject("result", entityFactory.getInstanceType(AuthorizationSettingEntity.class))));
    //todo 修改测试属性
    AuthorizationSettingEntity newEntity = entityFactory.newInstance(AuthorizationSettingEntity.class);
    newEntity.setId("test");
    newEntity.setDescribe("测试2");
    result = testPut("/autz-setting/" + id)
            .setUp(setup ->
                    setup.contentType(MediaType.APPLICATION_JSON)
                            .content(JSON.toJSONString(newEntity)))
            .exec().resultAsJson();
    Assert.assertEquals(200, result.get("status"));

    result = testGet("/autz-setting/" + id).exec().resultAsJson();
    result = result.getJSONObject("result");
    Assert.assertNotNull(result);

    result = testDelete("/autz-setting/" + id).exec().resultAsJson();
    Assert.assertEquals(200, result.get("status"));

    result = testGet("/autz-setting/" + id).exec().resultAsJson();
    Assert.assertEquals(404, result.get("status"));
}
 
Example 19
Source File: OrganizationalTests.java    From hsweb-framework with Apache License 2.0 4 votes vote down vote up
@Test
public void testCrud() throws Exception {
    OrganizationalEntity entity = entityFactory.newInstance(OrganizationalEntity.class);
    //todo 设置测试属性
    entity.setName("test");

    // test add data
    String requestBody = JSON.toJSONString(entity);
    JSONObject result = testPost("/department").setUp(setup -> setup.contentType(MediaType.APPLICATION_JSON).content(requestBody)).exec().resultAsJson();
    Assert.assertEquals(200, result.get("status"));
    String id = result.getString("result");
    Assert.assertNotNull(id);
    entity.setId(id);
    // test get data
    result = testGet("/department/" + id).exec().resultAsJson();
    entity = result.getObject("result", entityFactory.getInstanceType(OrganizationalEntity.class));

    Assert.assertEquals(200, result.get("status"));
    Assert.assertNotNull(result.getJSONObject("result"));

    Assert.assertEquals(fastJsonHttpMessageConverter.converter(entity),
            fastJsonHttpMessageConverter.converter(result.getObject("result", entityFactory.getInstanceType(OrganizationalEntity.class))));
    //todo 修改测试属性
    OrganizationalEntity newEntity = entityFactory.newInstance(OrganizationalEntity.class);
    newEntity.setName("test");

    result = testPut("/department/" + id)
            .setUp(setup ->
                    setup.contentType(MediaType.APPLICATION_JSON)
                            .content(JSON.toJSONString(newEntity)))
            .exec().resultAsJson();
    Assert.assertEquals(200, result.get("status"));

    result = testGet("/department/" + id).exec().resultAsJson();
    result = result.getJSONObject("result");
    Assert.assertNotNull(result);

    result = testDelete("/department/" + id).exec().resultAsJson();
    Assert.assertEquals(200, result.get("status"));

    result = testGet("/department/" + id).exec().resultAsJson();
    Assert.assertEquals(404, result.get("status"));
}
 
Example 20
Source File: DictionaryTests.java    From hsweb-framework with Apache License 2.0 4 votes vote down vote up
@Test
public void testCrud() throws Exception {
    DictionaryEntity entity = entityFactory.newInstance(DictionaryEntity.class);
    //todo 设置测试属性
    entity.setName("test");
    entity.setCreatorId("admin");
    entity.setCreateTime(System.currentTimeMillis());
    entity.setId("test");
    entity.setDescribe("test");
    entity.setClassifiedId("test");
    entity.setStatus(DataStatus.STATUS_ENABLED);
    String json = "[" +
            "{'value':'1','text':'水果','children':" +
            "[" +
            "{'value':'101','text':'苹果'," +
            "'children':[" +
            "{'value':'10102','text':'红富士'}" +
            ",{'value':'10103','text':'青苹果'}" +
            //使用表达式进行解析
            ",{'value':'10105','text':'其他苹果'" +
            ",'textExpression':'${#value}[${#context[otherApple]}]'" +
            ",'valueExpression':'${(#context.put(\\'otherApple\\',#pattern.split(\"[ \\\\[ \\\\]]\")[1])==null)?#value:#value}'" +
            "}" +
            "]}" +
            ",{'value':'102','text':'梨子'}]" +
            "}" +
            ",{'value':'2','text':'蔬菜'}" +
            "]";

    List<DictionaryItemEntity> itemEntities = JSON.parseArray(json, DictionaryItemEntity.class);
    entity.setItems(itemEntities);
    // test add data
    String requestBody = JSON.toJSONString(entity);
    JSONObject result = testPost("/dictionary").setUp(setup -> setup.contentType(MediaType.APPLICATION_JSON).content(requestBody)).exec().resultAsJson();
    Assert.assertEquals(200, result.get("status"));
    String id = result.getString("result");
    Assert.assertNotNull(id);
    entity.setId(id);
    // test get data
    result = testGet("/dictionary/" + id).exec().resultAsJson();
    entity = result.getObject("result", entityFactory.getInstanceType(DictionaryEntity.class));

    Assert.assertEquals(200, result.get("status"));
    Assert.assertNotNull(result.getJSONObject("result"));

    Assert.assertEquals(fastJsonHttpMessageConverter.converter(entity),
            fastJsonHttpMessageConverter.converter(result.getObject("result", entityFactory.getInstanceType(DictionaryEntity.class))));
    //todo 修改测试属性
    DictionaryEntity newEntity = entityFactory.newInstance(DictionaryEntity.class);
    newEntity.setName("test");

    result = testPut("/dictionary/" + id)
            .setUp(setup ->
                    setup.contentType(MediaType.APPLICATION_JSON)
                            .content(JSON.toJSONString(newEntity)))
            .exec().resultAsJson();
    Assert.assertEquals(200, result.get("status"));

    result = testGet("/dictionary/" + id).exec().resultAsJson();
    result = result.getJSONObject("result");
    Assert.assertNotNull(result);

    result = testDelete("/dictionary/" + id).exec().resultAsJson();
    Assert.assertEquals(200, result.get("status"));

    result = testGet("/dictionary/" + id).exec().resultAsJson();
    Assert.assertEquals(404, result.get("status"));
}