View Javadoc
1   /*
2    * Copyright 2022 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.buffer.api.Buffer;
19  import io.netty5.util.Resource;
20  import io.netty5.util.Send;
21  
22  import java.net.SocketAddress;
23  import java.util.function.Supplier;
24  
25  /**
26   * Base class for addressed envelopes that have {@link Buffer} instances as messages.
27   *
28   * @param <A> The type of socket address used for recipient and sender.
29   * @param <T> The concrete sub-type of this class, used for implementing {@link #send()}.
30   */
31  public abstract class BufferAddressedEnvelope<A extends SocketAddress, T extends BufferAddressedEnvelope<A, T>>
32          extends DefaultAddressedEnvelope<Buffer, A>
33          implements Resource<T> {
34      protected BufferAddressedEnvelope(Buffer message, A recipient, A sender) {
35          super(message, recipient, sender);
36      }
37  
38      protected BufferAddressedEnvelope(Buffer message, A recipient) {
39          super(message, recipient);
40      }
41  
42      @Override
43      public Send<T> send() {
44          Send<Buffer> contentSend = content().send();
45          @SuppressWarnings("unchecked")
46          Class<T> type = (Class<T>) getClass();
47          Supplier<T> supplier = () -> replace(contentSend.receive());
48          return Send.sending(type, supplier);
49      }
50  
51      /**
52       * Create a new addressed envelope instance, that has the same recipient and sender as this one, but the given
53       * content.
54       *
55       * @param content The contents of the returned addressed envelope instance.
56       * @return An addressed envelope instance that has the same recipient and sender as this one, but the given content.
57       */
58      public abstract T replace(Buffer content);
59  
60      @Override
61      public void close() {
62          content().close();
63      }
64  
65      @Override
66      public boolean isAccessible() {
67          return content().isAccessible();
68      }
69  }