1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20 package org.apache.mina.example.imagine.step1.codec;
21
22 import org.apache.mina.filter.codec.ProtocolDecoderOutput;
23 import org.apache.mina.filter.codec.CumulativeProtocolDecoder;
24 import org.apache.mina.core.buffer.IoBuffer;
25 import org.apache.mina.core.session.IoSession;
26 import org.apache.mina.example.imagine.step1.ImageResponse;
27
28 import javax.imageio.ImageIO;
29 import java.awt.image.BufferedImage;
30 import java.io.ByteArrayInputStream;
31 import java.io.IOException;
32
33
34
35
36
37
38
39 public class ImageResponseDecoder extends CumulativeProtocolDecoder {
40
41 private static final String DECODER_STATE_KEY = ImageResponseDecoder.class.getName() + ".STATE";
42
43 public static final int MAX_IMAGE_SIZE = 5 * 1024 * 1024;
44
45 private static class DecoderState {
46 BufferedImage image1;
47 }
48
49 protected boolean doDecode(IoSession session, IoBuffer in, ProtocolDecoderOutput out) throws Exception {
50 DecoderState decoderState = (DecoderState) session.getAttribute(DECODER_STATE_KEY);
51 if (decoderState == null) {
52 decoderState = new DecoderState();
53 session.setAttribute(DECODER_STATE_KEY, decoderState);
54 }
55 if (decoderState.image1 == null) {
56
57 if (in.prefixedDataAvailable(4, MAX_IMAGE_SIZE)) {
58 decoderState.image1 = readImage(in);
59 } else {
60
61 return false;
62 }
63 }
64 if (decoderState.image1 != null) {
65
66 if (in.prefixedDataAvailable(4, MAX_IMAGE_SIZE)) {
67 BufferedImage image2 = readImage(in);
68 ImageResponse imageResponse = new ImageResponse(decoderState.image1, image2);
69 out.write(imageResponse);
70 decoderState.image1 = null;
71 return true;
72 } else {
73
74 return false;
75 }
76 }
77 return false;
78 }
79
80 private BufferedImage readImage(IoBuffer in) throws IOException {
81 int length = in.getInt();
82 byte[] bytes = new byte[length];
83 in.get(bytes);
84 ByteArrayInputStream bais = new ByteArrayInputStream(bytes);
85 return ImageIO.read(bais);
86 }
87
88 }