Class Message

java.lang.Object
org.eclipse.californium.core.coap.Message
Direct Known Subclasses:
EmptyMessage, Request, Response

public abstract class Message extends Object
The class Message models the base class of all CoAP messages. CoAP messages are of type Request, Response or EmptyMessage. Each message has a CoAP.Type, a message identifier (MID), a token (0-8 bytes), a collection of options (OptionSet) and a payload.

Furthermore, a message can be acknowledged, rejected, canceled, or time out; the meaning of which is defined more specifically in the subclasses. Clients can register MessageObservers with a message which will be notified when any of the events listed above occur.

Note: The messageObservers and options properties are initialized lazily. This saves a few bytes in case the properties are not in use. For instance an empty message should not have any options and most messages will not have any observers registered.

See Also:
  • Field Details

    • LOGGER

      @Deprecated protected static final org.slf4j.Logger LOGGER
      Deprecated.
      scope will change to private
      The logger.
    • NONE

      public static final int NONE
      The Constant NONE in case no MID has been set.
      See Also:
    • MAX_MID

      public static final int MAX_MID
      The largest message ID allowed by CoAP.

      The value of this constant is 2^16 - 1.

      See Also:
  • Constructor Details

    • Message

      protected Message()
      Creates a new message with no specified message type.
    • Message

      public Message(CoAP.Type type)
      Creates a new message of a given type.

      The type must be one of CON, NON, ACK or RST.

      Parameters:
      type - the type
  • Method Details

    • toTracingString

      protected String toTracingString(String code)
      Get tracing string for message.
      Parameters:
      code - code of message as text.
      Returns:
      tracing string for message
      Since:
      2.2
    • getType

      public CoAP.Type getType()
      Gets the message type (CoAP.Type.CON, CoAP.Type.NON, CoAP.Type.ACK or CoAP.Type.RST). If no type has been defined, the type is null.
      Returns:
      the type
    • setType

      public Message setType(CoAP.Type type)
      Sets the CoAP message type. Provides a fluent API to chain setters.
      Parameters:
      type - the new type
      Returns:
      this Message
    • isConfirmable

      public boolean isConfirmable()
      Checks if this message is confirmable.
      Returns:
      true, if is confirmable
    • setConfirmable

      public Message setConfirmable(boolean con)
      Chooses between confirmable and non-confirmable message. Pass true for CON, false for NON. Provides a fluent API to chain setters.
      Parameters:
      con - true for CON, false for NON
      Returns:
      this Message
    • getRawCode

      public abstract int getRawCode()
      Gets the raw integer value of this message's code.
      Returns:
      the code value.
    • isIntendedPayload

      public boolean isIntendedPayload()
      Checks, if this message is intended to have payload. To be overwritten by subclass to provide a specific check.
      Returns:
      true, if message is intended to have payload
    • setUnintendedPayload

      public void setUnintendedPayload()
      Set marker for unintended payload. Enables to use payload with messages, which are not intended to have payload.
      Throws:
      IllegalStateException - if message is intended to have payload
    • isUnintendedPayload

      public boolean isUnintendedPayload()
      Checks, if message is marked to have unintended payload.
      Returns:
      true if message is marked to have unintended payload
    • setReliabilityLayerParameters

      public void setReliabilityLayerParameters(ReliabilityLayerParameters parameter)
      Set message specific reliability layer parameters.
      Parameters:
      parameter - message specific reliability layer parameters. null to reset to default configuration.
    • getReliabilityLayerParameters

      public ReliabilityLayerParameters getReliabilityLayerParameters()
      Get message specific reliability layer parameters.
      Returns:
      parameter message specific reliability layer parameters, or null, if default configuration is to be used.
    • getMID

      public int getMID()
      Gets the 16-bit message identification.
      Returns:
      the mid
    • hasMID

      public boolean hasMID()
      Checks whether this message has a valid ID.
      Returns:
      true if this message's ID is a 16 bit unsigned integer.
    • setMID

      public Message setMID(int mid)
      Sets the 16-bit message identification. Provides a fluent API to chain setters.
      Parameters:
      mid - the new mid
      Returns:
      this Message
      Throws:
      IllegalArgumentException - if mid is out of range NONE to MAX_MID
      IllegalStateException - if message is already serialized (setBytes(byte[]) has been called before)
    • removeMID

      public void removeMID()
      Clears this message's MID.
      Throws:
      IllegalStateException - if message is already serialized (setBytes(byte[]) has been called before)
    • hasEmptyToken

      public boolean hasEmptyToken()
      Checks whether this message has a non-zero length token.
      Returns:
      true if this message's token is either null or of length 0.
    • getToken

      public Token getToken()
      Gets this message's token.
      Returns:
      the token
    • getTokenBytes

      public byte[] getTokenBytes()
      Gets this message's 0- -8 byte token.
      Returns:
      the token
    • getTokenString

      public String getTokenString()
      Gets the 0--8 byte token as string representation.
      Returns:
      the token as string
    • setToken

      public Message setToken(byte[] tokenBytes)
      Sets the token bytes, which can be 0--8 bytes. Note: The token are generated by default with a TokenGenerator. If application defined tokens are to be used, these tokens must also comply to the scope encoding of the effectively used generator. This narrows the definition of RFC 7252, 5.3.1, from "client-local" to "node-local", and "system-local" tokens. Provides a fluent API to chain setters.
      Parameters:
      tokenBytes - the new token bytes
      Returns:
      this Message
      Throws:
      IllegalStateException - if message is already serialized (setBytes(byte[]) has been called before)
      See Also:
    • setToken

      public Message setToken(Token token)
      Sets the token. Note: The token are generated by default with a TokenGenerator. If application defined tokens are to be used, these tokens must also comply to the scope encoding of the effectively used generator. This narrows the definition of RFC 7252, 5.3.1, from "client-local" to "node-local", and "system-local" tokens. Provides a fluent API to chain setters.
      Parameters:
      token - the new token
      Returns:
      this Message
      Throws:
      IllegalStateException - if message is already serialized (setBytes(byte[]) has been called before)
    • getOptions

      public OptionSet getOptions()
      Gets the set of options. If no set has been defined yet, it creates a new one. EmptyMessages should not have any options.
      Returns:
      the options
      Throws:
      IllegalStateException - if message was offloaded.
    • setOptions

      public Message setOptions(OptionSet options)
      Sets the set of options. This function makes a defensive copy of the specified set of options. Provides a fluent API to chain setters.
      Parameters:
      options - the new options
      Returns:
      this Message
    • getMaxResourceBodySize

      public int getMaxResourceBodySize()
      Get the maximum resource body size. For incoming messages the protocol stack may set individual sizes. For outgoing requests, this limits the size of the response.
      Returns:
      maximum resource body size. 0 to use the Configuration value of CoapConfig.MAX_RESOURCE_BODY_SIZE.
      Since:
      2.3
    • setMaxResourceBodySize

      public void setMaxResourceBodySize(int maxResourceBodySize)
      Set the maximum resource body size. For incoming messages the protocol stack may set individual sizes. For outgoing requests, this limits the size of the response.
      Parameters:
      maxResourceBodySize - maximum resource body size. 0 or default is defined by the Configuration value of CoapConfig.MAX_RESOURCE_BODY_SIZE.
      Since:
      2.3
    • getPayloadSize

      public int getPayloadSize()
      Gets the size (amount of bytes) of the payload. Be aware that this might differ from the payload string length due to the UTF-8 encoding.
      Returns:
      the payload size
    • getPayload

      public byte[] getPayload()
      Gets the raw payload.
      Returns:
      the payload.
      Throws:
      IllegalStateException - if message was offloaded.
    • getPayloadString

      public String getPayloadString()
      Gets the payload in the form of a string. Returns an empty string if no payload is defined.
      Returns:
      the payload as string
      Throws:
      IllegalStateException - if message was offloaded.
    • getPayloadTracingString

      protected String getPayloadTracingString()
    • setPayload

      public Message setPayload(String payload)
      Sets the UTF-8 bytes from the specified string as payload. Provides a fluent API to chain setters.
      Parameters:
      payload - the payload as string. null is replaced by an empty string. An empty string is not considered to be payload and therefore not cause a IllegalArgumentException, if this message must not have payload.
      Returns:
      this Message
      Throws:
      IllegalArgumentException - if this message must not have payload
      See Also:
    • setPayload

      public Message setPayload(byte[] payload)
      Sets the payload. Provides a fluent API to chain setters.
      Parameters:
      payload - the new payload. null is replaced by an empty array. An empty array is not considered to be payload and therefore not cause an IllegalArgumentException, if this message must not have payload.
      Returns:
      this Message
      Throws:
      IllegalArgumentException - if this message must not have payload
      See Also:
    • assertPayloadMatchsBlocksize

      public abstract void assertPayloadMatchsBlocksize()
      Check, if the payload size matches the BlockOption.getSize().
      Throws:
      IllegalStateException - if the BlockOption is provided but the payload exceeds that.
      Since:
      3.0
    • getDestinationContext

      public org.eclipse.californium.elements.EndpointContext getDestinationContext()
      Get destination endpoint context. May be null for Request during it's construction.
      Returns:
      the destination endpoint context.
    • getEffectiveDestinationContext

      public org.eclipse.californium.elements.EndpointContext getEffectiveDestinationContext()
      Get the effective destination context. May differ from getDestinationContext() on retransmissions.
      Returns:
      the effective destination context.
      Since:
      2.3
      See Also:
      • EndpointContextUtil.getFollowUpEndpointContext(EndpointContext, EndpointContext)
    • getSourceContext

      public org.eclipse.californium.elements.EndpointContext getSourceContext()
      Get source endpoint context.
      Returns:
      the source endpoint context.
    • setDestinationContext

      public Message setDestinationContext(org.eclipse.californium.elements.EndpointContext peerContext)
      Set destination endpoint context. Multicast addresses are only supported for Requests. Provides a fluent API to chain setters.
      Parameters:
      peerContext - destination endpoint context
      Returns:
      this Message
      Throws:
      IllegalArgumentException - if destination address is multicast address, but message is no Request
      See Also:
    • setEffectiveDestinationContext

      public void setEffectiveDestinationContext(org.eclipse.californium.elements.EndpointContext peerContext)
      Set the effective destination context. Used to set a different destination context for retransmissions.
      Parameters:
      peerContext - destination context for retransmissions
      Since:
      2.3
      See Also:
      • EndpointContextUtil.getFollowUpEndpointContext(EndpointContext, EndpointContext)
    • setRequestDestinationContext

      protected void setRequestDestinationContext(org.eclipse.californium.elements.EndpointContext peerContext)
      Set destination endpoint context for requests. Multicast addresses are supported.
      Parameters:
      peerContext - destination endpoint context
      See Also:
    • setSourceContext

      public Message setSourceContext(org.eclipse.californium.elements.EndpointContext peerContext)
      Set source endpoint context. Provides a fluent API to chain setters.
      Parameters:
      peerContext - source endpoint context
      Returns:
      this Message
    • setLocalAddress

      public void setLocalAddress(InetSocketAddress local)
      Set address of the receiving local endpoint.
      Parameters:
      local - local address of the receiving endpoint
      Since:
      3.0
    • getLocalAddress

      public InetSocketAddress getLocalAddress()
      Gets the local address of the receiving endpoint.
      Returns:
      local address of the receiving endpoint. null for outgoing messages.
      Since:
      3.0
    • isAcknowledged

      public boolean isAcknowledged()
      Checks if is this message has been acknowledged.
      Returns:
      true, if is acknowledged
    • setAcknowledged

      public void setAcknowledged(boolean acknowledged)
      Marks this message as acknowledged. Since 3.0 doesn't longer call MessageObserver.onAcknowledgement(). Use acknowledge() instead. Not part of the fluent API.
      Parameters:
      acknowledged - if acknowledged
    • acknowledge

      public boolean acknowledge()
      Acknowledge a unacknowledged confirmable message. Checks and set acknowledged atomically. Calls MessageObserver.onAcknowledgement(), if message was unacknowledged. Not part of the fluent API.
      Returns:
      true, if message was unacknowledged and confirmable, false, if message was already acknowledged or is not confirmable
      Since:
      3.0 (doesn't longer call setAcknowledged(boolean))
    • isRejected

      public boolean isRejected()
      Checks if this message has been rejected.
      Returns:
      true, if is rejected
    • setRejected

      public void setRejected(boolean rejected)
      Marks this message as rejected. Not part of the fluent API.
      Parameters:
      rejected - if rejected
    • isTimedOut

      public boolean isTimedOut()
      Checks if this message has timed out. Confirmable messages in particular might timeout.
      Returns:
      true, if timed out
    • setTimedOut

      public void setTimedOut(boolean timedOut)
      Marks this message as timed out. Confirmable messages in particular might timeout.
      Parameters:
      timedOut - true if timed out
    • isCanceled

      public boolean isCanceled()
      Checks if this message has been canceled.
      Returns:
      true, if is canceled
    • setCanceled

      public void setCanceled(boolean canceled)
      Marks this message as canceled. Not part of the fluent API.
      Parameters:
      canceled - if canceled
    • setReadyToSend

      public void setReadyToSend()
      Indicate, that this message is ready to be send. Not part of the fluent API.
    • onConnecting

      public void onConnecting()
      Indicate, that this message triggered the connector to establish a connection. Not part of the fluent API.
    • onDtlsRetransmission

      public void onDtlsRetransmission(int flight)
      Indicate, that this message triggered the connector to establish a connection and a dtls handshake flight was retransmitted.
      Parameters:
      flight - 1 ... 6, number of retransmitted flight.
    • isSent

      public boolean isSent()
      Checks if this message has been sent.
      Returns:
      true, if is sent
    • setSent

      public void setSent(boolean sent)
      Marks this message as sent. Not part of the fluent API.
      Parameters:
      sent - if sent
    • getSendError

      public Throwable getSendError()
      Checks if this message has been sent.
      Returns:
      true, if is sent
    • setSendError

      public void setSendError(Throwable sendError)
      Marks this message with send error. Not part of the fluent API.
      Parameters:
      sendError - if error occurred while sending
    • onContextEstablished

      public void onContextEstablished(org.eclipse.californium.elements.EndpointContext endpointContext)
      Report resulting endpoint context. The destinationContext may not contain all information, but the connector will fill these information and report it. This method doesn't change the destinationContext but calls MessageObserver.onContextEstablished(EndpointContext).
      Parameters:
      endpointContext - resulting endpoint context.
    • onTransferComplete

      public void onTransferComplete()
      Report completion of message-transfer.
      Since:
      3.0 (was onComplete())
    • waitForSent

      public boolean waitForSent(long timeout) throws InterruptedException
      Waits for the message to be sent.

      This function blocks until the message is sent, has been canceled, the specified timeout has expired, or an error occurred. A timeout of 0 is interpreted as infinity. If the message is already sent, this method returns it immediately.

      Parameters:
      timeout - the maximum time to wait in milliseconds.
      Returns:
      true, if the message was sent in time, false, otherwise
      Throws:
      InterruptedException - the interrupted exception
    • isDuplicate

      public boolean isDuplicate()
      Checks if this message is a duplicate. Since 2.1 this also reflects, if the message is resent.
      Returns:
      true, if is a duplicate
    • setDuplicate

      public void setDuplicate(boolean duplicate)
      Marks this message as a duplicate. Not part of the fluent API.
      Parameters:
      duplicate - if a duplicate
    • getStatusTracingString

      protected String getStatusTracingString()
    • getBytes

      public byte[] getBytes()
      Gets the serialized message as byte array or null, if not serialized yet.
      Returns:
      the bytes of the serialized message or null
      Throws:
      IllegalStateException - if message was offloaded.
    • setBytes

      public void setBytes(byte[] bytes)
      Sets the bytes of the serialized message. Not part of the fluent API.
      Parameters:
      bytes - the serialized bytes
    • addMessageSize

      public void addMessageSize(int bytes)
      Add bytes to message size. Not part of the fluent API.
      Parameters:
      bytes - bytes to add
      Since:
      3.7
    • getMessageSize

      public int getMessageSize()
      Get message size. For incoming blockwise transfer the accumulated message size is returned. Not part of the fluent API.
      Returns:
      message size
      Since:
      3.7
    • hasBlock

      public abstract boolean hasBlock(BlockOption block)
      Checks whether a given block offset falls into this message's payload. Note: since 3.0 the block option of the message is also used for the check. If this message exactly ends at the offset of the provided block, this is also reported as overlapping.
      Parameters:
      block - The offset of the block.
      Returns:
      true if this message has a payload and its size is greater then the offset.
    • hasBlock

      protected boolean hasBlock(BlockOption block, BlockOption messageOffset)
      Checks whether a given block offset falls into this message's payload.
      Parameters:
      block - The offset of the block.
      messageOffset - The offset of the payload within the resource-body.
      Returns:
      true if this message has a payload and its size is greater then the offset.
      Since:
      3.0
    • getNanoTimestamp

      public long getNanoTimestamp()
      Gets the nano timestamp, when this message has been received, sent, or 0, if neither has happened yet. The sent timestamp is granted to be not after sending, therefore it's very short before actual sending the message. And the receive timestamp is granted to be not before receiving the message, therefore it's very short after actual receiving the message. If a "transparent blockwise-transfers" is received, the time reflects the time of the first block.
      Returns:
      the nano timestamp
      See Also:
      • ClockUtil.nanoRealtime()
    • setNanoTimestamp

      public void setNanoTimestamp(long timestamp)
      Sets the nano timestamp when this message has been received, sent, or 0 if neither has happened yet. Not part of the fluent API.
      Parameters:
      timestamp - the nano timestamp.
      See Also:
      • ClockUtil.nanoRealtime()
    • cancel

      public void cancel()
      Cancels this message. This method calls setCanceled(boolean) with true. Subclasses should override setCanceled(boolean) to react to cancellation.
    • retransmitting

      public void retransmitting()
      Notifies all registered MessageObservers that this message is about to be re-transmitted.
    • offload

      public void offload(Message.OffloadMode mode)
      Offload message. Remove payload, options and serialized bytes to reduce heap usage, when message is kept for deduplication. The server-side offloads message when sending the first response when CoapConfig.USE_MESSAGE_OFFLOADING is enabled. Requests are Message.OffloadMode.FULL offloaded, responses are Message.OffloadMode.PAYLOAD offloaded. A client-side may also chose to offload requests and responses based on CoapConfig.USE_MESSAGE_OFFLOADING, when the request and responses are not longer used by the client. For messages with setProtectFromOffload(), offloading is ineffective.
      Parameters:
      mode - Message.OffloadMode.PAYLOAD to offload the payload, Message.OffloadMode.FULL to offload the payload, the options, and the serialized bytes.
      Since:
      2.2
    • getOffloadMode

      public Message.OffloadMode getOffloadMode()
      Gets the offload mode.
      Returns:
      null, if message is not offloaded, Message.OffloadMode.PAYLOAD if the payload is offloaded, Message.OffloadMode.FULL if the payload, the options, and the serialized bytes are offloaded.
      Since:
      2.2
    • setProtectFromOffload

      public void setProtectFromOffload()
      Protect message from being offloaded. Used to protect observe- and starting-blockwise-requests and empty messages from being offloaded.
      Since:
      2.2
    • getMessageObservers

      public List<MessageObserver> getMessageObservers()
      Returns the observers registered for this message.
      Returns:
      an immutable list of the registered observers.
      See Also:
    • getMessageObserver

      public <T extends MessageObserver> T getMessageObserver(Class<T> type)
      Returns the observer of the provided type registered for this message.
      Type Parameters:
      T - type of observer
      Parameters:
      type - type of observer
      Returns:
      the registered observer of that type, or null, if not available.
      Since:
      3.3
      See Also:
    • addMessageObserver

      public void addMessageObserver(MessageObserver observer)
      Adds the specified message observer.
      Parameters:
      observer - the observer
      Throws:
      NullPointerException - if the observer is null.
      See Also:
    • addMessageObserver

      public void addMessageObserver(int index, MessageObserver observer)
      Adds the specified message observer.
      Parameters:
      observer - the observer
      index - index at which the observer is to be inserted
      Throws:
      NullPointerException - if the observer is null.
      Since:
      2.1
      See Also:
    • addMessageObservers

      public void addMessageObservers(List<MessageObserver> observers)
      Appends a list of observers to this message's existing observers.
      Parameters:
      observers - the observers to add
      Throws:
      NullPointerException - if the list is null.
      See Also:
    • removeMessageObserver

      public void removeMessageObserver(MessageObserver observer)
      Removes the specified message observer.
      Parameters:
      observer - the observer
      Throws:
      NullPointerException - if the observer is null.
      See Also: