PageRenderTime 37ms CodeModel.GetById 12ms app.highlight 18ms RepoModel.GetById 2ms app.codeStats 0ms

/sub-projects/jquery-stream-play/trunk/app/controllers/Application.java

http://jquery-stream.googlecode.com/
Java | 98 lines | 65 code | 22 blank | 11 comment | 6 complexity | 4a9d55834113b190308f89a68c8c7426 MD5 | raw file
 1package controllers;
 2
 3import java.util.Arrays;
 4import java.util.LinkedHashMap;
 5import java.util.Map;
 6
 7import play.data.parsing.UrlEncodedParser;
 8import play.libs.Codec;
 9import play.libs.F.Either;
10import play.libs.F.EventStream;
11import play.libs.F.Matcher;
12import play.libs.F.Promise;
13import play.mvc.Controller;
14import play.mvc.Http.WebSocketClose;
15import play.mvc.Http.WebSocketEvent;
16import play.mvc.WebSocketController;
17
18import com.google.gson.Gson;
19
20public class Application extends Controller {
21
22	final static EventStream<String> eventStream = new EventStream<String>();
23
24	public static void index() {
25		render();
26	}
27
28	public static void open() {
29		// Content-Type header
30		response.contentType = "text/plain";
31
32		response.writeChunk(
33			// Id
34			Codec.UUID() + ";" +
35			// Padding
36			Arrays.toString(new float[200]).replaceAll(".", " ") + ";");
37
38		while (true) {
39			try {
40				// Waits until a message arrives
41				String message = await(eventStream.nextEvent());
42
43				// default message format is message-size ; message-data ;
44				response.writeChunk(message.length() + ";" + message + ";");
45			} catch (Exception e) {
46				break;
47			}
48		}
49	}
50	
51	public static void handle(Map<String, String> metadata, String username, String message) {
52		if ("close".equals(metadata.get("type"))) {
53			return;
54		}
55
56		// send-request
57		doHandle(username, message);
58	}
59
60	public static class WebSocket extends WebSocketController {
61
62		public static void open() {
63			while (inbound.isOpen()) {
64				Either<WebSocketEvent, String> either = await(Promise.waitEither(
65						inbound.nextEvent(), eventStream.nextEvent()));
66
67				// EventStream
68				for (String message : Matcher.ClassOf(String.class).match(either._2)) {
69					outbound.send(message);
70				}
71
72				// WebSocketEvent - message
73				for (String message : WebSocketEvent.TextFrame.match(either._1)) {
74					// Parses query string
75					Map<String, String[]> params = UrlEncodedParser.parse(message);
76
77					doHandle(params.get("username")[0], params.get("message")[0]);
78				}
79
80				// WebSocketEvent - close
81				for (WebSocketClose closed : WebSocketEvent.SocketClosed.match(either._1)) {
82					disconnect();
83				}
84			}
85		}
86
87	}
88
89	// Request handler
90	static void doHandle(String username, String message) {
91		Map<String, String> data = new LinkedHashMap<String, String>();
92		data.put("username", username);
93		data.put("message", message);
94
95		eventStream.publish(new Gson().toJson(data));
96	}
97
98}