View Javadoc
1   /*
2    * Copyright 2013 The Netty Project
3    *
4    * The Netty Project licenses this file to you under the Apache License,
5    * version 2.0 (the "License"); you may not use this file except in compliance
6    * with the License. You may obtain a copy of the License at:
7    *
8    *   https://www.apache.org/licenses/LICENSE-2.0
9    *
10   * Unless required by applicable law or agreed to in writing, software
11   * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
12   * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
13   * License for the specific language governing permissions and limitations
14   * under the License.
15   */
16  package io.netty5.channel;
17  
18  import io.netty5.util.internal.StringUtil;
19  
20  import java.net.SocketAddress;
21  
22  import static java.util.Objects.requireNonNull;
23  
24  /**
25   * The default {@link AddressedEnvelope} implementation.
26   *
27   * @param <M> the type of the wrapped message
28   * @param <A> the type of the recipient address
29   */
30  public class DefaultAddressedEnvelope<M, A extends SocketAddress> implements AddressedEnvelope<M, A> {
31  
32      private final M message;
33      private final A sender;
34      private final A recipient;
35  
36      /**
37       * Creates a new instance with the specified {@code message}, {@code recipient} address, and
38       * {@code sender} address.
39       */
40      public DefaultAddressedEnvelope(M message, A recipient, A sender) {
41          requireNonNull(message, "message");
42  
43          if (recipient == null && sender == null) {
44              throw new NullPointerException("recipient and sender");
45          }
46  
47          this.message = message;
48          this.sender = sender;
49          this.recipient = recipient;
50      }
51  
52      /**
53       * Creates a new instance with the specified {@code message} and {@code recipient} address.
54       * The sender address becomes {@code null}.
55       */
56      public DefaultAddressedEnvelope(M message, A recipient) {
57          this(message, recipient, null);
58      }
59  
60      @Override
61      public M content() {
62          return message;
63      }
64  
65      @Override
66      public A sender() {
67          return sender;
68      }
69  
70      @Override
71      public A recipient() {
72          return recipient;
73      }
74  
75      @Override
76      public String toString() {
77          if (sender != null) {
78              return StringUtil.simpleClassName(this) +
79                      '(' + sender + " => " + recipient + ", " + message + ')';
80          } else {
81              return StringUtil.simpleClassName(this) +
82                      "(=> " + recipient + ", " + message + ')';
83          }
84      }
85  }