01: package com.icesoft.faces.webapp.http.core;
02:
03: import com.icesoft.faces.webapp.http.common.Request;
04: import com.icesoft.faces.webapp.http.common.Response;
05: import com.icesoft.faces.webapp.http.common.ResponseHandler;
06: import com.icesoft.faces.webapp.http.common.Server;
07: import com.icesoft.faces.webapp.http.common.standard.FixedXMLContentHandler;
08: import edu.emory.mathcs.backport.java.util.concurrent.BlockingQueue;
09: import edu.emory.mathcs.backport.java.util.concurrent.LinkedBlockingQueue;
10:
11: import java.io.IOException;
12: import java.io.Writer;
13: import java.util.Collection;
14: import java.util.HashSet;
15: import java.util.Set;
16:
17: public class SendUpdatedViews implements Server {
18: private static final Runnable Noop = new Runnable() {
19: public void run() {
20: }
21: };
22: private static final ResponseHandler EmptyResponseHandler = new ResponseHandler() {
23: public void respond(Response response) throws Exception {
24: response.setHeader("Content-Length", 0);
25: }
26: };
27: private BlockingQueue pendingRequest = new LinkedBlockingQueue(1);
28: private ViewQueue allUpdatedViews;
29:
30: public SendUpdatedViews(final Collection synchronouslyUpdatedViews,
31: final ViewQueue allUpdatedViews) {
32: this .allUpdatedViews = allUpdatedViews;
33: this .allUpdatedViews.onPut(new Runnable() {
34: public void run() {
35: try {
36: allUpdatedViews
37: .removeAll(synchronouslyUpdatedViews);
38: synchronouslyUpdatedViews.clear();
39: Set viewIdentifiers = new HashSet(allUpdatedViews);
40: if (!viewIdentifiers.isEmpty()) {
41: Request request = (Request) pendingRequest
42: .poll();
43: if (request != null) {
44: request
45: .respondWith(new UpdatedViewsHandler(
46: (String[]) viewIdentifiers
47: .toArray(new String[viewIdentifiers
48: .size()])));
49: }
50: }
51: } catch (Throwable e) {
52: e.printStackTrace();
53: }
54: }
55: });
56: }
57:
58: public void service(final Request request) throws Exception {
59: respondToPreviousRequest();
60: pendingRequest.put(request);
61: }
62:
63: private void respondToPreviousRequest() {
64: Request previousRequest = (Request) pendingRequest.poll();
65: if (previousRequest != null) {
66: try {
67: previousRequest.respondWith(EmptyResponseHandler);
68: } catch (Exception e) {
69: e.printStackTrace();
70: }
71: }
72: }
73:
74: public void shutdown() {
75: allUpdatedViews.onPut(Noop);
76: respondToPreviousRequest();
77: }
78:
79: private class UpdatedViewsHandler extends FixedXMLContentHandler {
80: private String[] viewIdentifiers;
81:
82: public UpdatedViewsHandler(String[] viewIdentifiers) {
83: this .viewIdentifiers = viewIdentifiers;
84: }
85:
86: public void writeTo(Writer writer) throws IOException {
87: writer.write("<updated-views>");
88: for (int i = 0; i < viewIdentifiers.length; i++) {
89: writer.write(viewIdentifiers[i]);
90: writer.write(' ');
91: }
92: writer.write("</updated-views>");
93: }
94: }
95: }
|