Start line:  
End line:  

Snippet Preview

Snippet HTML Code

Stack Overflow Questions
The MIT License Copyright (c) 2010 Tad Glines Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
 
 package com.glines.socketio.server.transport;
 
 import java.util.List;
 
 
 
 
 public abstract class XHRTransport extends AbstractHttpTransport {
 	public static final String CONTINUATION_KEY =
 		"com.glines.socketio.server.transport.XHRTransport.Continuation";
 	private final int bufferSize;
 	private final int maxIdleTime;
 
 	protected abstract class XHRSessionHelper
 		protected final SocketIOSession session;
 		private final TransportBuffer buffer = new TransportBuffer();
 		private volatile boolean is_open = false;
 		private volatile Continuation continuation = null;
 		private final boolean isConnectionPersistant;
 		private boolean disconnectWhenEmpty = false;
 
 		XHRSessionHelper(SocketIOSession sessionboolean isConnectionPersistant) {
 			this. = session;
 			this. = isConnectionPersistant;
 			if (isConnectionPersistant) {
 			} else {
 			}
 		}
 
 		protected abstract void startSend(HttpServletResponse responsethrows IOException;
 
 		protected abstract void writeData(ServletResponse responseString datathrows IOException;
 
 		protected abstract void finishSend(ServletResponse responsethrows IOException;
 		
 		public void disconnect() {
 			synchronized (this) {
 				abort();
 			}
 		}
 
 		public void close() {
 			synchronized (this) {
 			}
 		}
 
		}
		public void sendMessage(SocketIOFrame frame)
			synchronized (this) {
				Log.debug("Session["+.getSessionId()+"]: " +
						"sendMessage(frame): [" + frame.getFrameType() + "]: " + frame.getData());
				if () {
					if ( != null) {
						List<Stringmessages = .drainMessages();
						messages.add(frame.encode());
						StringBuilder data = new StringBuilder();
						for (String msgmessages) {
							data.append(msg);
						}
						try {
catch (IOException e) {
							throw new SocketIOException(e);
						}
							 = null;
							cont.complete();
else {
						}
else {
						String data = frame.encode();
						if (.putMessage(data) == false) {
							throw new SocketIOException();
						}
					}
else {
				}
			}
		}
		public void sendMessage(String messagethrows SocketIOException {
			Log.debug("Session["+.getSessionId()+"]: " +
					"sendMessage(String): " + message);
		}
		public void sendMessage(int messageTypeString message)
			synchronized (this) {
				Log.debug("Session["+.getSessionId()+"]: " +
						"sendMessage(int, String): [" + messageType + "]: " + message);
					sendMessage(new SocketIOFrame(..messageTypemessage));
else {
				}
			}
		}
		public void handle(HttpServletRequest request,
				throws IOException {
			if ("GET".equals(request.getMethod())) {
				synchronized (this) {
					if (! && .isEmpty()) {
else {
						/*
						 */
						if ( != null || cont != null) {
							if ( == cont) {
								 = null;
								finishSend(response);
							}
							if (cont != null) {
							}
							return;
						}
							if (!.isEmpty()) {
								List<Stringmessages = .drainMessages();
								if (messages.size() > 0) {
									StringBuilder data = new StringBuilder();
									for (String msgmessages) {
										data.append(msg);
									}
									startSend(response);
									writeData(responsedata.toString());
									finishSend(response);
else {
									}
								}
else {
								request.setAttribute(session);
								 = ContinuationSupport.getContinuation(request);
								startSend(response);
							}
else {
						}
					}
				}
else if ("POST".equals(request.getMethod())) {
				if () {
					int size = request.getContentLength();
					BufferedReader reader = request.getReader();
					if (size == 0) {
else {
						String data = decodePostData(request.getContentType(), IO.toString(reader));
						if (data != null && data.length() > 0) {
							List<SocketIOFramelist = SocketIOFrame.parse(data);
							synchronized (session) {
								for (SocketIOFrame msglist) {
									session.onMessage(msg);
								}
							}
						}
                        // Ensure that the disconnectWhenEmpty flag is obeyed in the case where
                        // it is set during a POST.
                        synchronized (this) {
                            if ( && .isEmpty()) {
                                if (session.getConnectionState() == .) {
                                    session.onDisconnect(.);
                                }
                                abort();
                            }
                        }
					}
				}
else {
			}
		}
		protected String decodePostData(String contentTypeString data) {
			if (contentType.startsWith("application/x-www-form-urlencoded")) {
				if (data.substring(0, 5).equals("data=")) {
					return URIUtil.decodePath(data.substring(5));
else {
					return "";
				}
else if (contentType.startsWith("text/plain")) {
				return data;
else {
				// TODO: Treat as text for now, maybe error in the future.
				return data;
			}
		}
		public void onComplete(Continuation cont) {
			if ( != null && cont == ) {
				 = null;
					 = false;
					}
else {
else {
else {
						}
					}
				}
			}
		}
		public void onTimeout(Continuation cont) {
			if ( != null && cont == ) {
				 = null;
					 = false;
else {
					if (! && .isEmpty()) {
else {
						try {
catch (IOException e) {
						}
					}
				}
			}
		}
		protected abstract void customConnect(HttpServletRequest request,
				HttpServletResponse responsethrows IOException;
		public void connect(HttpServletRequest request,
				HttpServletResponse responsethrows IOException {
			 = ContinuationSupport.getContinuation(request);
			}
			customConnect(requestresponse);
			 = true;
			finishSend(response);
            if ( != null) {
                if () {
                    request.setAttribute();
                    .suspend(response);
                } else {
                     = null;
                }
            }
		}
		public void disconnectWhenEmpty() {
		}
		public void abort() {
			 = false;
			if ( != null) {
				 = null;
				if (cont.isSuspended()) {
					cont.complete();
				}
			}
				public boolean onMessages(List<Stringmessages) {
					return false;
				}
				public boolean onMessage(String message) {
					return false;
				}
			});
		}
	}
	public XHRTransport(int bufferSizeint maxIdleTime) {
		this. = bufferSize;
		this. = maxIdleTime;
	}

This method should only be called within the context of an active HTTP request.
	protected abstract XHRSessionHelper createHelper(SocketIOSession session);
			HttpServletResponse responseTransport.InboundFactory inboundFactory,
			throws IOException {
		SocketIOInbound inbound = inboundFactory.getInbound(request);
		if (inbound != null) {
 			SocketIOSession session = sessionFactory.createSession(inbound);
			XHRSessionHelper handler =  createHelper(session);
			handler.connect(requestresponse);
			return session;
		}
		return null;
	}
New to GrepCode? Check out our FAQ X