예제 #1
0
  private void writeHeaders(
      StompHeaderAccessor headers, Message<byte[]> message, DataOutputStream output)
      throws IOException {

    Map<String, List<String>> stompHeaders = headers.toStompHeaderMap();
    if (SimpMessageType.HEARTBEAT.equals(headers.getMessageType())) {
      logger.trace("Encoded heartbeat");
    } else if (logger.isDebugEnabled()) {
      logger.debug("Encoded STOMP command=" + headers.getCommand() + " headers=" + stompHeaders);
    }
    for (Entry<String, List<String>> entry : stompHeaders.entrySet()) {
      byte[] key = getUtf8BytesEscapingIfNecessary(entry.getKey(), headers);
      for (String value : entry.getValue()) {
        output.write(key);
        output.write(COLON);
        output.write(getUtf8BytesEscapingIfNecessary(value, headers));
        output.write(LF);
      }
    }
    if ((headers.getCommand() == StompCommand.SEND)
        || (headers.getCommand() == StompCommand.MESSAGE)
        || (headers.getCommand() == StompCommand.ERROR)) {

      output.write("content-length:".getBytes(UTF8_CHARSET));
      output.write(Integer.toString(message.getPayload().length).getBytes(UTF8_CHARSET));
      output.write(LF);
    }
  }
예제 #2
0
  /**
   * Encodes the given payload and headers into a {@code byte[]}.
   *
   * @param headers the headers
   * @param payload the payload
   * @return the encoded message
   */
  public byte[] encode(Map<String, Object> headers, byte[] payload) {
    Assert.notNull(headers, "'headers' is required");
    Assert.notNull(payload, "'payload' is required");
    try {
      ByteArrayOutputStream baos = new ByteArrayOutputStream(128 + payload.length);
      DataOutputStream output = new DataOutputStream(baos);

      if (SimpMessageType.HEARTBEAT.equals(SimpMessageHeaderAccessor.getMessageType(headers))) {
        logger.trace("Encoded heartbeat");
        output.write(StompDecoder.HEARTBEAT_PAYLOAD);
      } else {
        StompCommand command = StompHeaderAccessor.getCommand(headers);
        Assert.notNull(command, "Missing STOMP command: " + headers);
        output.write(command.toString().getBytes(StompDecoder.UTF8_CHARSET));
        output.write(LF);
        writeHeaders(command, headers, payload, output);
        output.write(LF);
        writeBody(payload, output);
        output.write((byte) 0);
      }

      return baos.toByteArray();
    } catch (IOException e) {
      throw new StompConversionException(
          "Failed to encode STOMP frame, headers=" + headers + ".", e);
    }
  }