Пример #1
0
  public static void printCollection(Iterable<? extends Message> messages, Appendable appendable)
      throws IOException {
    if (messages == null) throw new IllegalArgumentException("messages cannot be null");
    if (appendable == null) throw new IllegalArgumentException("messages cannot be null");

    // Start the Array
    appendable.append('[');
    boolean first = true;
    for (Message ml : messages) {
      // If this isn't the first item, prepend with a comma
      if (!first) appendable.append(',');
      first = false;

      JsonFormat.print(ml, appendable);
    }
    // Close the Array
    appendable.append(']');
  }
Пример #2
0
  /**
   * 实际解析协议模板
   *
   * @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;
  }