/** * 实际解析协议模板 * * @param protocol * @param template * @return */ @SuppressWarnings("unchecked") public <T extends GeneratedMessage> T parseProtocol(HawkProtocol protocol, T template) { if (protocol != null && template != null) { try { T pbProtocol = template; Parser<T> parser = (Parser<T>) parsers.get(template.getClass().getName()); if (parser == null) { parser = (Parser<T>) template.getClass().getField("PARSER").get(template); parsers.put(template.getClass().getName(), parser); } if (protocol.getSize() > 0) { pbProtocol = parser.parseFrom(protocol.getOctets().getBuffer().array(), 0, protocol.getSize()); } logProtocolBuilder(protocol, pbProtocol); return pbProtocol; } catch (Exception e) { HawkException.catchException(e); // 抛出运行时异常 throw new RuntimeException("protocol parse exception: " + protocol.getType()); } } return null; }
/** * 记录协议日志 * * @param builder */ public void logProtocolBuilder(HawkProtocol protocol, Object builder) { if (HawkApp.getInstance() != null && builder != null && HawkApp.getInstance().isDebug()) { logger.info( "protocol: {}, size: {}, crc: {}, pb: \r\n{}", new Object[] { protocol.getType(), protocol.getSize(), protocol.getCrc(), builder.toString() }); } }
/** * 实际解析协议模板 * * @param protocol * @return */ public HawkPacket parsePacket(HawkProtocol protocol) { if (protocol != null) { try { HawkPacket packet = createPacket(protocol.getType()); if (packet != null) { packet.unmarshal(protocol.getOctets()); return packet; } // 协议存根不存在 throw new RuntimeException("packet stub illegal: " + protocol.getType()); } catch (Exception e) { HawkException.catchException(e); // 抛出运行时异常 throw new RuntimeException("packet parse exception: " + protocol.getType()); } } return null; }
/** * 实际解析协议模板 * * @param protocol * @param template * @return */ @SuppressWarnings("unchecked") public <T extends GeneratedMessage> T parseFromJson(HawkProtocol protocol, T template) { if (protocol != null && template != null) { try { T pbProtocol = template; if (protocol.getSize() > 0) { String pbJson = new String(protocol.getOctets().getBuffer().array(), 0, protocol.getSize()); GeneratedMessage.Builder<?> builder = (Builder<?>) template.newBuilderForType(); JsonFormat.merge(pbJson, builder); pbProtocol = (T) builder.build(); } logProtocolBuilder(protocol, pbProtocol); return pbProtocol; } catch (Exception e) { HawkException.catchException(e); // 抛出运行时异常 throw new RuntimeException("protocol parse exception: " + protocol.getType()); } } return null; }