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.codec;
21  
22  import org.apache.mina.common.ByteBuffer;
23  import org.apache.mina.common.ByteBufferProxy;
24  import org.apache.mina.common.IoFilter;
25  import org.apache.mina.common.IoFilterAdapter;
26  import org.apache.mina.common.IoFilterChain;
27  import org.apache.mina.common.IoSession;
28  import org.apache.mina.common.WriteFuture;
29  import org.apache.mina.common.support.DefaultWriteFuture;
30  import org.apache.mina.filter.codec.support.SimpleProtocolDecoderOutput;
31  import org.apache.mina.filter.codec.support.SimpleProtocolEncoderOutput;
32  import org.apache.mina.util.SessionLog;
33  
34  /**
35   * An {@link IoFilter} which translates binary or protocol specific data into
36   * message object and vice versa using {@link ProtocolCodecFactory},
37   * {@link ProtocolEncoder}, or {@link ProtocolDecoder}.
38   * 
39   * @author The Apache Directory Project (mina-dev@directory.apache.org)
40   * @version $Rev: 585074 $, $Date: 2007-10-16 17:13:01 +0900 (화, 16 10월 2007) $
41   */
42  public class ProtocolCodecFilter extends IoFilterAdapter {
43      public static final String ENCODER = ProtocolCodecFilter.class.getName()
44              + ".encoder";
45  
46      public static final String DECODER = ProtocolCodecFilter.class.getName()
47              + ".decoder";
48      
49      private static final String DECODER_OUT = ProtocolCodecFilter.class.getName()
50              + ".decoderOut";
51  
52      private static final Class[] EMPTY_PARAMS = new Class[0];
53  
54      private static final ByteBuffer EMPTY_BUFFER = ByteBuffer.wrap(new byte[0]);
55  
56      private final ProtocolCodecFactory factory;
57  
58      public ProtocolCodecFilter(ProtocolCodecFactory factory) {
59          if (factory == null) {
60              throw new NullPointerException("factory");
61          }
62          this.factory = factory;
63      }
64  
65      public ProtocolCodecFilter(final ProtocolEncoder encoder,
66              final ProtocolDecoder decoder) {
67          if (encoder == null) {
68              throw new NullPointerException("encoder");
69          }
70          if (decoder == null) {
71              throw new NullPointerException("decoder");
72          }
73  
74          this.factory = new ProtocolCodecFactory() {
75              public ProtocolEncoder getEncoder() {
76                  return encoder;
77              }
78  
79              public ProtocolDecoder getDecoder() {
80                  return decoder;
81              }
82          };
83      }
84  
85      public ProtocolCodecFilter(final Class encoderClass,
86              final Class decoderClass) {
87          if (encoderClass == null) {
88              throw new NullPointerException("encoderClass");
89          }
90          if (decoderClass == null) {
91              throw new NullPointerException("decoderClass");
92          }
93          if (!ProtocolEncoder.class.isAssignableFrom(encoderClass)) {
94              throw new IllegalArgumentException("encoderClass: "
95                      + encoderClass.getName());
96          }
97          if (!ProtocolDecoder.class.isAssignableFrom(decoderClass)) {
98              throw new IllegalArgumentException("decoderClass: "
99                      + decoderClass.getName());
100         }
101         try {
102             encoderClass.getConstructor(EMPTY_PARAMS);
103         } catch (NoSuchMethodException e) {
104             throw new IllegalArgumentException(
105                     "encoderClass doesn't have a public default constructor.");
106         }
107         try {
108             decoderClass.getConstructor(EMPTY_PARAMS);
109         } catch (NoSuchMethodException e) {
110             throw new IllegalArgumentException(
111                     "decoderClass doesn't have a public default constructor.");
112         }
113 
114         this.factory = new ProtocolCodecFactory() {
115             public ProtocolEncoder getEncoder() throws Exception {
116                 return (ProtocolEncoder) encoderClass.newInstance();
117             }
118 
119             public ProtocolDecoder getDecoder() throws Exception {
120                 return (ProtocolDecoder) decoderClass.newInstance();
121             }
122         };
123     }
124 
125     public void onPreAdd(IoFilterChain parent, String name,
126             NextFilter nextFilter) throws Exception {
127         if (parent.contains(ProtocolCodecFilter.class)) {
128             throw new IllegalStateException(
129                     "A filter chain cannot contain more than one ProtocolCodecFilter.");
130         }
131     }
132 
133     public void onPostRemove(IoFilterChain parent, String name,
134             NextFilter nextFilter) throws Exception {
135         disposeEncoder(parent.getSession());
136         disposeDecoder(parent.getSession());
137         disposeDecoderOut(parent.getSession());
138     }
139 
140     public void messageReceived(NextFilter nextFilter, IoSession session,
141             Object message) throws Exception {
142         if (!(message instanceof ByteBuffer)) {
143             nextFilter.messageReceived(session, message);
144             return;
145         }
146 
147         ByteBuffer in = (ByteBuffer) message;
148         ProtocolDecoder decoder = getDecoder(session);
149         ProtocolDecoderOutput decoderOut = getDecoderOut(session, nextFilter);
150 
151         try {
152             while (in.hasRemaining()) {
153                 int oldPos = in.position();
154                 try {
155                     synchronized (decoderOut) {
156                         decoder.decode(session, in, decoderOut);
157                     }
158                     // Finish decoding if no exception was thrown.
159                     decoderOut.flush();
160                     break;
161                 } catch (Throwable t) {
162                     ProtocolDecoderException pde;
163                     if (t instanceof ProtocolDecoderException) {
164                         pde = (ProtocolDecoderException) t;
165                     } else {
166                         pde = new ProtocolDecoderException(t);
167                     }
168                     pde.setHexdump(in.getHexDump());
169                     
170                     // Fire the exceptionCaught event.
171                     decoderOut.flush();
172                     nextFilter.exceptionCaught(session, pde);
173                     
174                     // Stop retrying if the buffer position didn't change
175                     // because retrying can cause an infinite loop.
176                     if (in.position() == oldPos) {
177                         break;
178                     }
179                 }
180             }
181         } finally {
182             // Release the read buffer.
183             in.release();
184         }
185     }
186 
187     public void messageSent(NextFilter nextFilter, IoSession session,
188             Object message) throws Exception {
189         if (message instanceof HiddenByteBuffer) {
190             return;
191         }
192 
193         if (!(message instanceof MessageByteBuffer)) {
194             nextFilter.messageSent(session, message);
195             return;
196         }
197 
198         nextFilter.messageSent(session, ((MessageByteBuffer) message).message);
199     }
200 
201     public void filterWrite(NextFilter nextFilter, IoSession session,
202             WriteRequest writeRequest) throws Exception {
203         Object message = writeRequest.getMessage();
204         if (message instanceof ByteBuffer) {
205             nextFilter.filterWrite(session, writeRequest);
206             return;
207         }
208 
209         ProtocolEncoder encoder = getEncoder(session);
210         ProtocolEncoderOutputImpl encoderOut = getEncoderOut(session,
211                 nextFilter, writeRequest);
212 
213         try {
214             encoder.encode(session, message, encoderOut);
215             encoderOut.flush();
216             nextFilter.filterWrite(session, new WriteRequest(
217                     new MessageByteBuffer(writeRequest.getMessage()),
218                     writeRequest.getFuture(), writeRequest.getDestination()));
219         } catch (Throwable t) {
220             ProtocolEncoderException pee;
221             if (t instanceof ProtocolEncoderException) {
222                 pee = (ProtocolEncoderException) t;
223             } else {
224                 pee = new ProtocolEncoderException(t);
225             }
226             throw pee;
227         }
228     }
229 
230     public void sessionClosed(NextFilter nextFilter, IoSession session)
231             throws Exception {
232         // Call finishDecode() first when a connection is closed.
233         ProtocolDecoder decoder = getDecoder(session);
234         ProtocolDecoderOutput decoderOut = getDecoderOut(session, nextFilter);
235         try {
236             decoder.finishDecode(session, decoderOut);
237         } catch (Throwable t) {
238             ProtocolDecoderException pde;
239             if (t instanceof ProtocolDecoderException) {
240                 pde = (ProtocolDecoderException) t;
241             } else {
242                 pde = new ProtocolDecoderException(t);
243             }
244             throw pde;
245         } finally {
246             // Dispose all.
247             disposeEncoder(session);
248             disposeDecoder(session);
249             disposeDecoderOut(session);
250             decoderOut.flush();
251         }
252 
253         nextFilter.sessionClosed(session);
254     }
255 
256     private ProtocolEncoder getEncoder(IoSession session) throws Exception {
257         ProtocolEncoder encoder = (ProtocolEncoder) session
258                 .getAttribute(ENCODER);
259         if (encoder == null) {
260             encoder = factory.getEncoder();
261             session.setAttribute(ENCODER, encoder);
262         }
263         return encoder;
264     }
265 
266     private ProtocolEncoderOutputImpl getEncoderOut(IoSession session,
267             NextFilter nextFilter, WriteRequest writeRequest) {
268         return new ProtocolEncoderOutputImpl(session, nextFilter, writeRequest);
269     }
270 
271     private ProtocolDecoder getDecoder(IoSession session) throws Exception {
272         ProtocolDecoder decoder = (ProtocolDecoder) session
273                 .getAttribute(DECODER);
274         if (decoder == null) {
275             decoder = factory.getDecoder();
276             session.setAttribute(DECODER, decoder);
277         }
278         return decoder;
279     }
280 
281     private ProtocolDecoderOutput getDecoderOut(IoSession session,
282             NextFilter nextFilter) {
283         ProtocolDecoderOutput out = (ProtocolDecoderOutput) session.getAttribute(DECODER_OUT);
284         if (out == null) {
285             out = new SimpleProtocolDecoderOutput(session, nextFilter);
286             session.setAttribute(DECODER_OUT, out);
287         }
288 
289         return out;
290     }
291 
292     private void disposeEncoder(IoSession session) {
293         ProtocolEncoder encoder = (ProtocolEncoder) session
294                 .removeAttribute(ENCODER);
295         if (encoder == null) {
296             return;
297         }
298 
299         try {
300             encoder.dispose(session);
301         } catch (Throwable t) {
302             SessionLog.warn(session, "Failed to dispose: "
303                     + encoder.getClass().getName() + " (" + encoder + ')');
304         }
305     }
306 
307     private void disposeDecoder(IoSession session) {
308         ProtocolDecoder decoder = (ProtocolDecoder) session
309                 .removeAttribute(DECODER);
310         if (decoder == null) {
311             return;
312         }
313 
314         try {
315             decoder.dispose(session);
316         } catch (Throwable t) {
317             SessionLog.warn(session, "Falied to dispose: "
318                     + decoder.getClass().getName() + " (" + decoder + ')');
319         }
320     }
321     
322     private void disposeDecoderOut(IoSession session) {
323         session.removeAttribute(DECODER_OUT);
324     }
325     
326     private static class HiddenByteBuffer extends ByteBufferProxy {
327         private HiddenByteBuffer(ByteBuffer buf) {
328             super(buf);
329         }
330     }
331 
332     private static class MessageByteBuffer extends ByteBufferProxy {
333         private final Object message;
334 
335         private MessageByteBuffer(Object message) {
336             super(EMPTY_BUFFER);
337             this.message = message;
338         }
339 
340         public void acquire() {
341             // no-op since we are wraping a zero-byte buffer, this instance is to just curry the message
342         }
343 
344         public void release() {
345             // no-op since we are wraping a zero-byte buffer, this instance is to just curry the message
346         }
347     }
348 
349     private static class ProtocolEncoderOutputImpl extends
350             SimpleProtocolEncoderOutput {
351         private final IoSession session;
352 
353         private final NextFilter nextFilter;
354 
355         private final WriteRequest writeRequest;
356 
357         public ProtocolEncoderOutputImpl(IoSession session,
358                 NextFilter nextFilter, WriteRequest writeRequest) {
359             this.session = session;
360             this.nextFilter = nextFilter;
361             this.writeRequest = writeRequest;
362         }
363 
364         protected WriteFuture doFlush(ByteBuffer buf) {
365             WriteFuture future = new DefaultWriteFuture(session);
366             nextFilter.filterWrite(session, new WriteRequest(
367                     new HiddenByteBuffer(buf), future, writeRequest
368                             .getDestination()));
369             return future;
370         }
371     }
372 }