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: 612026 $, $Date: 2008-01-15 07:16:14 +0100 (Tue, 15 Jan 2008) $
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         int oldPos = in.position();
152         try {
153             synchronized (decoderOut) {
154                 decoder.decode(session, in, decoderOut);
155             }
156         } catch (Throwable t) {
157             ProtocolDecoderException pde;
158             if (t instanceof ProtocolDecoderException) {
159                 pde = (ProtocolDecoderException) t;
160             } else {
161                 pde = new ProtocolDecoderException(t);
162             }
163             
164             if (pde.getHexdump() == null) {
165                 int curPos = in.position();
166                 in.position(oldPos);
167                 pde.setHexdump(in.getHexDump());
168                 in.position(curPos);
169             }
170             throw pde;
171         } finally {
172             try {
173                 // Release the read buffer.
174                 in.release();
175             } finally {
176                 decoderOut.flush();
177             }
178         }
179     }
180 
181     public void messageSent(NextFilter nextFilter, IoSession session,
182             Object message) throws Exception {
183         if (message instanceof HiddenByteBuffer) {
184             return;
185         }
186 
187         if (!(message instanceof MessageByteBuffer)) {
188             nextFilter.messageSent(session, message);
189             return;
190         }
191 
192         nextFilter.messageSent(session, ((MessageByteBuffer) message).message);
193     }
194 
195     public void filterWrite(NextFilter nextFilter, IoSession session,
196             WriteRequest writeRequest) throws Exception {
197         Object message = writeRequest.getMessage();
198         if (message instanceof ByteBuffer) {
199             nextFilter.filterWrite(session, writeRequest);
200             return;
201         }
202 
203         ProtocolEncoder encoder = getEncoder(session);
204         ProtocolEncoderOutputImpl encoderOut = getEncoderOut(session,
205                 nextFilter, writeRequest);
206 
207         try {
208             encoder.encode(session, message, encoderOut);
209             encoderOut.flush();
210             nextFilter.filterWrite(session, new WriteRequest(
211                     new MessageByteBuffer(writeRequest.getMessage()),
212                     writeRequest.getFuture(), writeRequest.getDestination()));
213         } catch (Throwable t) {
214             ProtocolEncoderException pee;
215             if (t instanceof ProtocolEncoderException) {
216                 pee = (ProtocolEncoderException) t;
217             } else {
218                 pee = new ProtocolEncoderException(t);
219             }
220             throw pee;
221         }
222     }
223 
224     public void sessionClosed(NextFilter nextFilter, IoSession session)
225             throws Exception {
226         // Call finishDecode() first when a connection is closed.
227         ProtocolDecoder decoder = getDecoder(session);
228         ProtocolDecoderOutput decoderOut = getDecoderOut(session, nextFilter);
229         try {
230             decoder.finishDecode(session, decoderOut);
231         } catch (Throwable t) {
232             ProtocolDecoderException pde;
233             if (t instanceof ProtocolDecoderException) {
234                 pde = (ProtocolDecoderException) t;
235             } else {
236                 pde = new ProtocolDecoderException(t);
237             }
238             throw pde;
239         } finally {
240             // Dispose all.
241             disposeEncoder(session);
242             disposeDecoder(session);
243             disposeDecoderOut(session);
244             decoderOut.flush();
245         }
246 
247         nextFilter.sessionClosed(session);
248     }
249 
250     private ProtocolEncoder getEncoder(IoSession session) throws Exception {
251         ProtocolEncoder encoder = (ProtocolEncoder) session
252                 .getAttribute(ENCODER);
253         if (encoder == null) {
254             encoder = factory.getEncoder();
255             session.setAttribute(ENCODER, encoder);
256         }
257         return encoder;
258     }
259 
260     private ProtocolEncoderOutputImpl getEncoderOut(IoSession session,
261             NextFilter nextFilter, WriteRequest writeRequest) {
262         return new ProtocolEncoderOutputImpl(session, nextFilter, writeRequest);
263     }
264 
265     private ProtocolDecoder getDecoder(IoSession session) throws Exception {
266         ProtocolDecoder decoder = (ProtocolDecoder) session
267                 .getAttribute(DECODER);
268         if (decoder == null) {
269             decoder = factory.getDecoder();
270             session.setAttribute(DECODER, decoder);
271         }
272         return decoder;
273     }
274 
275     private ProtocolDecoderOutput getDecoderOut(IoSession session,
276             NextFilter nextFilter) {
277         ProtocolDecoderOutput out = (ProtocolDecoderOutput) session.getAttribute(DECODER_OUT);
278         if (out == null) {
279             out = new SimpleProtocolDecoderOutput(session, nextFilter);
280             session.setAttribute(DECODER_OUT, out);
281         }
282 
283         return out;
284     }
285 
286     private void disposeEncoder(IoSession session) {
287         ProtocolEncoder encoder = (ProtocolEncoder) session
288                 .removeAttribute(ENCODER);
289         if (encoder == null) {
290             return;
291         }
292 
293         try {
294             encoder.dispose(session);
295         } catch (Throwable t) {
296             SessionLog.warn(session, "Failed to dispose: "
297                     + encoder.getClass().getName() + " (" + encoder + ')');
298         }
299     }
300 
301     private void disposeDecoder(IoSession session) {
302         ProtocolDecoder decoder = (ProtocolDecoder) session
303                 .removeAttribute(DECODER);
304         if (decoder == null) {
305             return;
306         }
307 
308         try {
309             decoder.dispose(session);
310         } catch (Throwable t) {
311             SessionLog.warn(session, "Falied to dispose: "
312                     + decoder.getClass().getName() + " (" + decoder + ')');
313         }
314     }
315     
316     private void disposeDecoderOut(IoSession session) {
317         session.removeAttribute(DECODER_OUT);
318     }
319     
320     private static class HiddenByteBuffer extends ByteBufferProxy {
321         private HiddenByteBuffer(ByteBuffer buf) {
322             super(buf);
323         }
324     }
325 
326     private static class MessageByteBuffer extends ByteBufferProxy {
327         private final Object message;
328 
329         private MessageByteBuffer(Object message) {
330             super(EMPTY_BUFFER);
331             this.message = message;
332         }
333 
334         public void acquire() {
335             // no-op since we are wraping a zero-byte buffer, this instance is to just curry the message
336         }
337 
338         public void release() {
339             // no-op since we are wraping a zero-byte buffer, this instance is to just curry the message
340         }
341     }
342 
343     private static class ProtocolEncoderOutputImpl extends
344             SimpleProtocolEncoderOutput {
345         private final IoSession session;
346 
347         private final NextFilter nextFilter;
348 
349         private final WriteRequest writeRequest;
350 
351         public ProtocolEncoderOutputImpl(IoSession session,
352                 NextFilter nextFilter, WriteRequest writeRequest) {
353             this.session = session;
354             this.nextFilter = nextFilter;
355             this.writeRequest = writeRequest;
356         }
357 
358         protected WriteFuture doFlush(ByteBuffer buf) {
359             WriteFuture future = new DefaultWriteFuture(session);
360             nextFilter.filterWrite(session, new WriteRequest(
361                     new HiddenByteBuffer(buf), future, writeRequest
362                             .getDestination()));
363             return future;
364         }
365     }
366 }