1
2
3
4
5
6
7
8
9
10 package org.apache.commons.messagelet.impl;
11
12 import java.io.IOException;
13 import java.io.PrintWriter;
14
15 import javax.jms.Destination;
16 import javax.jms.JMSException;
17 import javax.jms.Message;
18 import javax.servlet.ServletOutputStream;
19 import javax.servlet.http.HttpServletResponse;
20 import javax.servlet.http.HttpServletResponseWrapper;
21
22 import org.apache.commons.messagelet.MessageletResponse;
23 import org.apache.commons.messenger.Messenger;
24
25
26
27
28
29
30
31 public class HttpMessageletResponseImpl extends HttpServletResponseWrapper implements MessageletResponse {
32
33
34 private Messenger messenger;
35
36 private Destination replyToDestination;
37
38
39
40
41 private BufferedServletOutputStream stream = null;
42
43 protected PrintWriter writer;
44
45 public HttpMessageletResponseImpl(HttpServletResponse response) {
46 super(response);
47 }
48
49
50 public void reset() {
51 writer = null;
52 stream = null;
53 }
54
55
56 public void finish() throws IOException, JMSException {
57 try {
58 if ( writer != null ) {
59 writer.flush();
60 writer.close();
61 }
62 if ( stream != null ) {
63 byte[] data = stream.toByteArray();
64
65
66 String text = new String(data);
67 Message message = getReplyMessenger().createTextMessage( text );
68 sendReply( message );
69 }
70 }
71 finally {
72 writer = null;
73 stream = null;
74 }
75 }
76
77
78
79
80
81 public void sendReply(Message replyMessage) throws JMSException {
82 getReplyMessenger().send( getReplyToDestination(), replyMessage );
83 }
84
85 public Messenger getReplyMessenger() {
86 return messenger;
87 }
88
89 public Destination getReplyToDestination() {
90 return replyToDestination;
91 }
92
93 public void setReplyMessenger(Messenger messenger) {
94 this.messenger = messenger;
95 }
96
97 public void setReplyToDestination(Destination replyToDestination) {
98 this.replyToDestination = replyToDestination;
99 }
100
101
102
103
104
105 public void flushBuffer() throws IOException {
106 if ( stream != null ) {
107 stream.flush();
108 }
109 }
110
111 public ServletOutputStream getOutputStream() throws IOException {
112 if (writer != null) {
113 throw new IllegalStateException("getWriter() has already been called " +
114 "for this response");
115 }
116 if (stream == null) {
117 stream = createOutputStream();
118 }
119 return stream;
120 }
121
122 public PrintWriter getWriter() throws IOException {
123 if (writer != null) {
124 return writer;
125 }
126 if (stream != null) {
127 throw new IllegalStateException("getOutputStream() has already been called for this response");
128 }
129 stream = createOutputStream();
130 writer = new PrintWriter(stream);
131 return writer;
132 }
133
134 protected BufferedServletOutputStream createOutputStream() {
135 return new BufferedServletOutputStream();
136 }
137 }
138