View Javadoc
1   /*
2    *  Licensed to the Apache Software Foundation (ASF) under one
3    *  or more contributor license agreements.  See the NOTICE file
4    *  distributed with this work for additional information
5    *  regarding copyright ownership.  The ASF licenses this file
6    *  to you under the Apache License, Version 2.0 (the
7    *  "License"); you may not use this file except in compliance
8    *  with the License.  You may obtain a copy of the License at
9    *
10   *    http://www.apache.org/licenses/LICENSE-2.0
11   *
12   *  Unless required by applicable law or agreed to in writing,
13   *  software distributed under the License is distributed on an
14   *  "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
15   *  KIND, either express or implied.  See the License for the
16   *  specific language governing permissions and limitations
17   *  under the License.
18   *
19   */
20  package org.apache.mina.filter.stream;
21  
22  import java.io.IOException;
23  import java.util.Queue;
24  import java.util.concurrent.ConcurrentLinkedQueue;
25  
26  import org.apache.mina.core.buffer.IoBuffer;
27  import org.apache.mina.core.filterchain.IoFilterAdapter;
28  import org.apache.mina.core.filterchain.IoFilterChain;
29  import org.apache.mina.core.session.AttributeKey;
30  import org.apache.mina.core.session.IoSession;
31  import org.apache.mina.core.write.DefaultWriteRequest;
32  import org.apache.mina.core.write.WriteRequest;
33  
34  /**
35   * Filter implementation which makes it possible to write Stream
36   * objects directly using {@link IoSession#write(Object)}.
37   * 
38   * @param <T> The type of Stream
39   * 
40   * @author <a href="http://mina.apache.org">Apache MINA Project</a>
41   */
42  public abstract class AbstractStreamWriteFilter<T> extends IoFilterAdapter {
43      /**
44       * The default buffer size this filter uses for writing.
45       */
46      public static final int DEFAULT_STREAM_BUFFER_SIZE = 4096;
47  
48      /**
49       * The attribute name used when binding the streaming object to the session.
50       */
51      protected static final AttributeKey CURRENT_STREAM = new AttributeKey(AbstractStreamWriteFilter.class, "stream");
52  
53      protected static final AttributeKey WRITE_REQUEST_QUEUE = new AttributeKey(AbstractStreamWriteFilter.class, "queue");
54  
55      protected static final AttributeKey CURRENT_WRITE_REQUEST = new AttributeKey(AbstractStreamWriteFilter.class, "writeRequest");
56  
57      private int writeBufferSize = DEFAULT_STREAM_BUFFER_SIZE;
58  
59      /**
60       * {@inheritDoc}
61       */
62      @Override
63      public void onPreAdd(IoFilterChain parent, String name, NextFilter nextFilter) throws Exception {
64          Class<? extends IoFilterAdapter> clazz = getClass();
65          
66          if (parent.contains(clazz)) {
67              throw new IllegalStateException("Only one " + clazz.getName() + " is permitted.");
68          }
69      }
70  
71      /**
72       * {@inheritDoc}
73       */
74      @Override
75      public void filterWrite(NextFilter nextFilter, IoSession session, WriteRequest writeRequest) throws Exception {
76          // If we're already processing a stream we need to queue the WriteRequest.
77          if (session.getAttribute(CURRENT_STREAM) != null) {
78              Queue<WriteRequest> queue = getWriteRequestQueue(session);
79              
80              if (queue == null) {
81                  queue = new ConcurrentLinkedQueue<>();
82                  session.setAttribute(WRITE_REQUEST_QUEUE, queue);
83              }
84              
85              queue.add(writeRequest);
86              
87              return;
88          }
89  
90          Object message = writeRequest.getMessage();
91  
92          if (getMessageClass().isInstance(message)) {
93  
94              T stream = getMessageClass().cast(message);
95  
96              IoBuffer buffer = getNextBuffer(stream);
97              
98              if (buffer == null) {
99                  // End of stream reached.
100                 writeRequest.getFuture().setWritten();
101                 nextFilter.messageSent(session, writeRequest);
102             } else {
103                 session.setAttribute(CURRENT_STREAM, message);
104                 session.setAttribute(CURRENT_WRITE_REQUEST, writeRequest);
105 
106                 nextFilter.filterWrite(session, new DefaultWriteRequest(buffer));
107             }
108 
109         } else {
110             nextFilter.filterWrite(session, writeRequest);
111         }
112     }
113 
114     protected abstract Class<T> getMessageClass();
115 
116     @SuppressWarnings("unchecked")
117     private Queue<WriteRequest> getWriteRequestQueue(IoSession session) {
118         return (Queue<WriteRequest>) session.getAttribute(WRITE_REQUEST_QUEUE);
119     }
120 
121     @SuppressWarnings("unchecked")
122     private Queue<WriteRequest> removeWriteRequestQueue(IoSession session) {
123         return (Queue<WriteRequest>) session.removeAttribute(WRITE_REQUEST_QUEUE);
124     }
125 
126     /**
127      * {@inheritDoc}
128      */
129     @Override
130     public void messageSent(NextFilter nextFilter, IoSession session, WriteRequest writeRequest) throws Exception {
131         T stream = getMessageClass().cast(session.getAttribute(CURRENT_STREAM));
132 
133         if (stream == null) {
134             nextFilter.messageSent(session, writeRequest);
135         } else {
136             IoBuffer buffer = getNextBuffer(stream);
137 
138             if (buffer == null) {
139                 // End of stream reached.
140                 session.removeAttribute(CURRENT_STREAM);
141                 WriteRequest currentWriteRequest = (WriteRequest) session.removeAttribute(CURRENT_WRITE_REQUEST);
142 
143                 // Write queued WriteRequests.
144                 Queue<WriteRequest> queue = removeWriteRequestQueue(session);
145                 
146                 if (queue != null) {
147                     WriteRequest wr = queue.poll();
148                     
149                     while (wr != null) {
150                         filterWrite(nextFilter, session, wr);
151                         wr = queue.poll();
152                     }
153                 }
154 
155                 currentWriteRequest.getFuture().setWritten();
156                 nextFilter.messageSent(session, currentWriteRequest);
157             } else {
158                 nextFilter.filterWrite(session, new DefaultWriteRequest(buffer));
159             }
160         }
161     }
162 
163     /**
164      * @return the size of the write buffer in bytes. Data will be read from the
165      * stream in chunks of this size and then written to the next filter.
166      */
167     public int getWriteBufferSize() {
168         return writeBufferSize;
169     }
170 
171     /**
172      * Sets the size of the write buffer in bytes. Data will be read from the
173      * stream in chunks of this size and then written to the next filter.
174      *
175      * @param writeBufferSize The size of the write buffer
176      * @throws IllegalArgumentException if the specified size is &lt; 1.
177      */
178     public void setWriteBufferSize(int writeBufferSize) {
179         if (writeBufferSize < 1) {
180             throw new IllegalArgumentException("writeBufferSize must be at least 1");
181         }
182         
183         this.writeBufferSize = writeBufferSize;
184     }
185 
186     protected abstract IoBuffer getNextBuffer(T message) throws IOException;
187 }