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
40 public class ImageResponseDecoder extends CumulativeProtocolDecoder {
41
42 private static final String DECODER_STATE_KEY = ImageResponseDecoder.class.getName() + ".STATE";
43
44 public static final int MAX_IMAGE_SIZE = 5 * 1024 * 1024;
45
46 private static class DecoderState {
47 BufferedImage image1;
48 }
49
50 protected boolean doDecode(IoSession session, IoBuffer in, ProtocolDecoderOutput out) throws Exception {
51 DecoderState decoderState = (DecoderState) session.getAttribute(DECODER_STATE_KEY);
52 if (decoderState == null) {
53 decoderState = new DecoderState();
54 session.setAttribute(DECODER_STATE_KEY, decoderState);
55 }
56 if (decoderState.image1 == null) {
57
58 if (in.prefixedDataAvailable(4, MAX_IMAGE_SIZE)) {
59 decoderState.image1 = readImage(in);
60 } else {
61
62 return false;
63 }
64 }
65 if (decoderState.image1 != null) {
66
67 if (in.prefixedDataAvailable(4, MAX_IMAGE_SIZE)) {
68 BufferedImage image2 = readImage(in);
69 ImageResponse imageResponse = new ImageResponse(decoderState.image1, image2);
70 out.write(imageResponse);
71 decoderState.image1 = null;
72 return true;
73 } else {
74
75 return false;
76 }
77 }
78 return false;
79 }
80
81 private BufferedImage readImage(IoBuffer in) throws IOException {
82 int length = in.getInt();
83 byte[] bytes = new byte[length];
84 in.get(bytes);
85 ByteArrayInputStream bais = new ByteArrayInputStream(bytes);
86 return ImageIO.read(bais);
87 }
88
89 }