PageRenderTime 45ms CodeModel.GetById 21ms app.highlight 17ms RepoModel.GetById 1ms app.codeStats 0ms

/tags/1.2/src/main/java/flowersinthesand/test/StreamServlet.java

http://jquery-stream.googlecode.com/
Java | 203 lines | 166 code | 37 blank | 0 comment | 25 complexity | a26ea4eb27b6b5abd5204e8c57b23c7f MD5 | raw file
  1package flowersinthesand.test;
  2
  3import java.io.IOException;
  4import java.io.PrintWriter;
  5import java.util.Map;
  6import java.util.Timer;
  7import java.util.TimerTask;
  8import java.util.UUID;
  9import java.util.concurrent.ConcurrentHashMap;
 10
 11import javax.servlet.AsyncContext;
 12import javax.servlet.AsyncEvent;
 13import javax.servlet.AsyncListener;
 14import javax.servlet.ServletException;
 15import javax.servlet.http.HttpServletRequest;
 16import javax.servlet.http.HttpServletResponse;
 17
 18import org.eclipse.jetty.util.UrlEncoded;
 19import org.eclipse.jetty.websocket.WebSocket;
 20import org.eclipse.jetty.websocket.WebSocketServlet;
 21
 22public class StreamServlet extends WebSocketServlet {
 23
 24	private static final long serialVersionUID = -7525476704378017593L;
 25
 26	@Override
 27	protected void service(HttpServletRequest request, HttpServletResponse response)
 28			throws ServletException, IOException {
 29		if (Boolean.valueOf(request.getParameter("error"))) {
 30			response.sendError(HttpServletResponse.SC_BAD_REQUEST);
 31		} else {
 32			super.service(request, response);
 33		}
 34	}
 35
 36	private Map<String, AsyncContext> asyncContexts = new ConcurrentHashMap<String, AsyncContext>();
 37
 38	@Override
 39	protected void doGet(final HttpServletRequest request, HttpServletResponse response)
 40			throws ServletException, IOException {
 41
 42		response.setCharacterEncoding("utf-8");
 43		final boolean htmlContent = Boolean.valueOf(request.getParameter("htmlContent"));
 44		response.setContentType(htmlContent ? "text/html" : "text/plain");
 45		response.setHeader("Access-Control-Allow-Origin", "*");
 46
 47		final boolean differentFormat = Boolean.valueOf(request.getParameter("differentFormat"));
 48		final String id = UUID.randomUUID().toString();
 49		final PrintWriter writer = response.getWriter();
 50		writer.print(id);
 51		writer.print(differentFormat ? "\r\n" : ";");
 52
 53		for (int i = 0; i < 1024; i++) {
 54			writer.print(' ');
 55		}
 56		writer.print(differentFormat ? "\r\n" : ";");
 57		writer.flush();
 58
 59		final AsyncContext ac = request.startAsync();
 60		ac.addListener(new AsyncListener() {
 61			public void onComplete(AsyncEvent event) throws IOException {
 62				asyncContexts.remove(id);
 63			}
 64
 65			public void onTimeout(AsyncEvent event) throws IOException {
 66				asyncContexts.remove(id);
 67			}
 68
 69			public void onError(AsyncEvent event) throws IOException {
 70				asyncContexts.remove(id);
 71			}
 72
 73			public void onStartAsync(AsyncEvent event) throws IOException {
 74
 75			}
 76		});
 77		asyncContexts.put(id, ac);
 78
 79		if (Boolean.valueOf(request.getParameter("delayOpen"))) {
 80			new Timer().schedule(new TimerTask() {
 81
 82				@Override
 83				public void run() {
 84					writer.print("OPEN");
 85					writer.flush();
 86				}
 87
 88			}, 100);
 89		}
 90		if (Boolean.valueOf(request.getParameter("message"))) {
 91			new Timer().schedule(new TimerTask() {
 92
 93				@Override
 94				public void run() {
 95					if (htmlContent) {
 96						writer.print("<script>app.handle('Hello World')</script>");
 97						writer.flush();
 98					} else {
 99						sendMessage(writer, createMessage(request.getParameter("dataType")),
100								differentFormat);
101					}
102				}
103
104			}, 100);
105		}
106		if (Boolean.valueOf(request.getParameter("close"))) {
107			ac.setTimeout(150);
108		}
109	}
110
111	@Override
112	protected void doPost(HttpServletRequest request, HttpServletResponse response)
113			throws ServletException, IOException {
114		request.setCharacterEncoding("utf-8");
115
116		AsyncContext ac = asyncContexts.get(request.getParameter("metadata.id"));
117		if (ac == null) {
118			return;
119		}
120
121		if ("close".equals(request.getParameter("metadata.type"))) {
122			ac.complete();
123			return;
124		}
125
126		sendMessage(ac.getResponse().getWriter(), request.getParameter("message"));
127	}
128
129	private void sendMessage(PrintWriter writer, String message) {
130		sendMessage(writer, message, false);
131	}
132
133	private void sendMessage(PrintWriter writer, String message, boolean differentFormat) {
134		if (!differentFormat) {
135			writer.print(message.length() + ";" + message + ";");
136		} else {
137			writer.print(message + "\r\n");
138		}
139
140		writer.flush();
141	}
142
143	@Override
144	public WebSocket doWebSocketConnect(final HttpServletRequest request, String protocol) {
145		return new WebSocket.OnTextMessage() {
146
147			Connection connection;
148
149			@Override
150			public void onOpen(Connection connection) {
151				this.connection = connection;
152				if (Boolean.valueOf(request.getParameter("message"))) {
153					try {
154						connection.sendMessage(createMessage(request.getParameter("dataType")));
155					} catch (IOException e) {
156						throw new RuntimeException(e);
157					}
158				}
159				if (connection.getProtocol() != null) {
160					try {
161						connection.sendMessage(connection.getProtocol());
162					} catch (IOException e) {
163						throw new RuntimeException(e);
164					}
165				}
166				if (Boolean.valueOf(request.getParameter("close"))) {
167					connection.disconnect();
168				}
169			}
170
171			@Override
172			public void onClose(int closeCode, String message) {
173
174			}
175
176			@Override
177			public void onMessage(String data) {
178				UrlEncoded parameters = new UrlEncoded(data);
179				try {
180					connection.sendMessage(parameters.getString("message"));
181				} catch (IOException e) {
182					throw new RuntimeException(e);
183				}
184			}
185
186		};
187	}
188
189	private String createMessage(String dataType) {
190		if ("text".equals(dataType)) {
191			return "data";
192		} else if ("json".equals(dataType)) {
193			return "{\"data\":\"data\"}";
194		} else if ("xml".equals(dataType)) {
195			return "<data>data</data>";
196		} else if ("csv".equals(dataType)) {
197			return "data1,data2,data3";
198		} else {
199			return "data";
200		}
201	}
202
203}