org.tio.utils.json.Json Java Examples

The following examples show how to use org.tio.utils.json.Json. 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: DisruptorClientConsumer.java    From md_blockchain with Apache License 2.0 6 votes vote down vote up
@Override
public void receive(BaseEvent baseEvent) throws Exception {
    BlockPacket blockPacket = baseEvent.getBlockPacket();
    Byte type = blockPacket.getType();
    AbstractBlockHandler<?> blockHandler = handlerMap.get(type);
    if (blockHandler == null) {
        return;
    }

    //消费消息
    BaseBody baseBody = Json.toBean(new String(blockPacket.getBody()), BaseBody.class);
    //logger.info("收到来自于<" + baseBody.getAppId() + ">针对msg<" + baseBody.getResponseMsgId() + ">的回应");

    String appId = baseBody.getAppId();
    if (StrUtil.equals(AppId.value, appId)) {
        //是本机
        //return;
    }

    blockHandler.handler(blockPacket, baseEvent.getChannelContext());
}
 
Example #2
Source File: FetchBlockResponseHandler.java    From md_blockchain with Apache License 2.0 6 votes vote down vote up
@Override
public Object handler(BlockPacket packet, RpcBlockBody rpcBlockBody, ChannelContext channelContext) {
    logger.info("收到来自于<" + rpcBlockBody.getAppId() + ">的回复,Block为:" + Json.toJson(rpcBlockBody));

    Block block = rpcBlockBody.getBlock();
    //如果为null,说明对方也没有该Block
    if (block == null) {
        logger.info("对方也没有该Block");
    } else {
        //此处校验传过来的block的合法性,如果合法,则更新到本地,作为next区块
        CheckerManager checkerManager = ApplicationContextProvider.getBean(CheckerManager.class);
        RpcCheckBlockBody rpcCheckBlockBody = checkerManager.check(block);
        //校验通过,则存入本地DB,保存新区块
        if (rpcCheckBlockBody.getCode() == 0) {
            ApplicationContextProvider.publishEvent(new AddBlockEvent(block));
            //继续请求下一块
            BlockPacket blockPacket = NextBlockPacketBuilder.build();
            ApplicationContextProvider.getBean(PacketSender.class).sendGroup(blockPacket);
        }
    }

    return null;
}
 
Example #3
Source File: NextBlockRequestHandler.java    From md_blockchain with Apache License 2.0 6 votes vote down vote up
@Override
public Object handler(BlockPacket packet, RpcSimpleBlockBody rpcBlockBody, ChannelContext channelContext) {
    logger.info("收到来自于<" + rpcBlockBody.getAppId() + ">的<请求下一Block>消息,请求者的block hash为:" + Json.toJson
            (rpcBlockBody.getHash()));
    //传来的Block,如果为null,说明发起方连一个Block都没有
    String hash = rpcBlockBody.getHash();

    //查询自己的next block hash,返回给对方,让对方搜集2f+1后确定哪个是对的
    Block nextBlock = ApplicationContextProvider.getBean(DbBlockManager.class).getNextBlockByHash(hash);
    String nextHash = null;
    if (nextBlock != null) {
        nextHash = nextBlock.getHash();
    }
    RpcNextBlockBody respBody = new RpcNextBlockBody(nextHash, hash);
    respBody.setResponseMsgId(rpcBlockBody.getMessageId());
    BlockPacket blockPacket = new PacketBuilder<RpcNextBlockBody>().setType(PacketType
            .NEXT_BLOCK_INFO_RESPONSE).setBody(respBody).build();
    Aio.send(channelContext, blockPacket);
    logger.info("回复给<" + rpcBlockBody.getAppId() + ">,我的nextBlock是" + respBody.toString());

    return null;
}
 
Example #4
Source File: AbstractBlockHandler.java    From md_blockchain with Apache License 2.0 5 votes vote down vote up
@Override
public Object handler(BlockPacket packet, ChannelContext channelContext) throws Exception {
	String jsonStr;
	T bsBody = null;
	if (packet.getBody() != null) {
		jsonStr = new String(packet.getBody(), Const.CHARSET);
		bsBody = Json.toBean(jsonStr, bodyClass());
	}

	return handler(packet, bsBody, channelContext);
}
 
Example #5
Source File: TotalBlockInfoResponseHandler.java    From md_blockchain with Apache License 2.0 5 votes vote down vote up
@Override
public Object handler(BlockPacket packet, RpcBlockBody rpcBlockBody, ChannelContext channelContext) throws Exception {
    logger.info("收到<请求生成Block的回应>消息", Json.toJson(rpcBlockBody));

    //TODO check合法性
    //TODO response

    return null;
}
 
Example #6
Source File: TotalBlockInfoRequestHandler.java    From md_blockchain with Apache License 2.0 5 votes vote down vote up
@Override
public Object handler(BlockPacket packet, RpcBlockBody rpcBlockBody, ChannelContext channelContext) throws Exception {
    logger.info("收到<请求生成Block的回应>消息", Json.toJson(rpcBlockBody));

    //TODO check合法性
    //TODO response

    return null;
}
 
Example #7
Source File: DbBlockGenerator.java    From md_blockchain with Apache License 2.0 5 votes vote down vote up
/**
 * 数据库里添加一个新的区块
 *
 * @param addBlockEvent
 *         addBlockEvent
 */
@Order(1)
@EventListener(AddBlockEvent.class)
public synchronized void addBlock(AddBlockEvent addBlockEvent) {
    logger.info("开始生成本地block");
    Block block = (Block) addBlockEvent.getSource();
    String hash = block.getHash();
    //如果已经存在了,说明已经更新过该Block了
    if (dbStore.get(hash) != null) {
        return;
    }
    //校验区块
    if (checkerManager.check(block).getCode() != 0) {
        return;
    }

    //如果没有上一区块,说明该块就是创世块
    if (block.getBlockHeader().getHashPreviousBlock() == null) {
        dbStore.put(Constants.KEY_FIRST_BLOCK, hash);
    } else {
        //保存上一区块对该区块的key value映射
        dbStore.put(Constants.KEY_BLOCK_NEXT_PREFIX + block.getBlockHeader().getHashPreviousBlock(), hash);
    }
    //存入rocksDB
    dbStore.put(hash, Json.toJson(block));
    //设置最后一个block的key value
    dbStore.put(Constants.KEY_LAST_BLOCK, hash);

    logger.info("本地已生成新的Block");

    //同步到sqlite
    sqliteSync();
}
 
Example #8
Source File: Resps.java    From t-io with Apache License 2.0 5 votes vote down vote up
/**
 * Content-Type: application/json;charset=utf-8
 * @param request
 * @param body
 * @param charset
 * @return
 * @author tanyaowu
 */
public static HttpResponse json(HttpRequest request, Object body, String charset) {
	HttpResponse ret = null;
	if (body == null) {
		ret = string(request, "", charset, getMimeTypeStr(MimeType.TEXT_PLAIN_JSON, charset));
	} else {
		if (body.getClass() == String.class || ClassUtil.isBasicType(body.getClass())) {
			ret = string(request, body + "", charset, getMimeTypeStr(MimeType.TEXT_PLAIN_JSON, charset));
		} else {
			ret = string(request, Json.toJson(body), charset, getMimeTypeStr(MimeType.TEXT_PLAIN_JSON, charset));
		}
	}
	return ret;
}
 
Example #9
Source File: TestController.java    From FrameworkBenchmarks with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
@RequestPath(value = "json")
	public HttpResponse json(HttpRequest request) throws Exception {
		//更高性能的写法
		HttpResponse ret = new HttpResponse(request);
		ret.setBody(Json.toJson(new Message(HELLO_WORLD)).getBytes());
		ret.addHeader(HeaderName.Content_Type, HeaderValue.Content_Type.TEXT_PLAIN_JSON);
		return ret;
		
		//简便写法
//		return Resps.json(request, new Message(HELLO_WORLD));
	}
 
Example #10
Source File: BlockServerAioListener.java    From md_blockchain with Apache License 2.0 4 votes vote down vote up
@Override
public void onAfterSent(ChannelContext channelContext, Packet packet, boolean isSentSuccess) {
	log.info("onAfterSent channelContext:{}, packet:{}, isSentSuccess:{}", channelContext, Json.toJson(packet), isSentSuccess);
}
 
Example #11
Source File: PacketBuilder.java    From md_blockchain with Apache License 2.0 4 votes vote down vote up
public BlockPacket build() {
    return new BlockPacket(type, Json.toJson(body));
}
 
Example #12
Source File: HttpServerStarter.java    From t-io with Apache License 2.0 4 votes vote down vote up
/**
 * 预访问第一版功能先上,后面再优化
 * 
 * @author tanyaowu
 */
public void preAccess() {
	if (httpConfig.isPageInClasspath()) {
		log.info("暂时只支持目录形式的预访问");
		return;
	}

	String pageRoot = httpConfig.getPageRoot();
	if (pageRoot == null) {
		return;
	}

	new Thread(new Runnable() {
		@Override
		public void run() {
			Map<String, Long> pathCostMap = new TreeMap<>();

			long start = System.currentTimeMillis();
			preAccess(pageRoot, pathCostMap);
			long end = System.currentTimeMillis();
			long iv = end - start;

			Map<Long, Set<String>> costPathsMap = new TreeMap<>(new Comparator<Long>() {
				@Override
				public int compare(Long o1, Long o2) {
					//倒序排序
					return Long.compare(o2, o1);
				}
			});
			Set<Entry<String, Long>> entrySet = pathCostMap.entrySet();
			for (Entry<String, Long> entry : entrySet) {
				try {
					Long cost = entry.getValue();
					String path = entry.getKey();
					Set<String> pathSet = costPathsMap.get(cost);
					if (pathSet == null) {
						pathSet = new TreeSet<>();
						costPathsMap.put(cost, pathSet);
					}
					boolean added = pathSet.add(path);
					if (!added) {
						log.error("可能重复访问了:{}", path);
					}
				} catch (Exception e) {
					log.error(e.toString(), e);
				}
			}

			log.info("预访问了{}个path,耗时:{}ms,访问详情:\r\n{}\r\n耗时排序:\r\n{}", pathCostMap.size(), iv, Json.toFormatedJson(pathCostMap), Json.toFormatedJson(costPathsMap));
		}
	}).start();

}
 
Example #13
Source File: TioClusterMessageListener.java    From t-io with Apache License 2.0 4 votes vote down vote up
public void onMessage(CharSequence channel, TioClusterVo tioClusterVo) {
	log.info("收到topic:{}, count:{}, tioClusterVo:{}", channel, RECEIVED_TOPIC_COUNT.incrementAndGet(), Json.toJson(tioClusterVo));
	String clientid = tioClusterVo.getClientId();
	if (StrUtil.isBlank(clientid)) {
		log.error("clientid is null");
		return;
	}
	if (Objects.equals(TioClusterVo.CLIENTID, clientid)) {
		log.info("自己发布的消息,忽略掉,{}", clientid);
		return;
	}

	Packet packet = tioClusterVo.getPacket();
	if (packet == null) {
		log.error("packet is null");
		return;
	}
	packet.setFromCluster(true);

	//发送给所有
	boolean isToAll = tioClusterVo.isToAll();
	if (isToAll) {
		Tio.sendToAll(tioConfig, packet);
	}

	//发送给指定组
	String group = tioClusterVo.getGroup();
	if (StrUtil.isNotBlank(group)) {
		Tio.sendToGroup(tioConfig, group, packet);
	}

	//发送给指定用户
	String userid = tioClusterVo.getUserid();
	if (StrUtil.isNotBlank(userid)) {
		Tio.sendToUser(tioConfig, userid, packet);
	}

	//发送给指定token
	String token = tioClusterVo.getToken();
	if (StrUtil.isNotBlank(token)) {
		Tio.sendToToken(tioConfig, token, packet);
	}

	//发送给指定ip
	String ip = tioClusterVo.getIp();
	if (StrUtil.isNotBlank(ip)) {
		Tio.sendToIp(tioConfig, ip, packet);
	}

	//发送给指定channelId
	String channelId = tioClusterVo.getChannelId();
	if (StrUtil.isNotBlank(channelId)) {
		Tio.sendToId(tioConfig, channelId, packet);
	}

	//发送给指定bsId
	String bsId = tioClusterVo.getBsId();
	if (StrUtil.isNotBlank(bsId)) {
		Tio.sendToBsId(tioConfig, bsId, packet);
	}
}