001/* 002 * Copyright 2002-2016 the original author or authors. 003 * 004 * Licensed under the Apache License, Version 2.0 (the "License"); 005 * you may not use this file except in compliance with the License. 006 * You may obtain a copy of the License at 007 * 008 * https://www.apache.org/licenses/LICENSE-2.0 009 * 010 * Unless required by applicable law or agreed to in writing, software 011 * distributed under the License is distributed on an "AS IS" BASIS, 012 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 013 * See the License for the specific language governing permissions and 014 * limitations under the License. 015 */ 016 017package org.springframework.web.socket.sockjs.transport.session; 018 019import java.io.IOException; 020import java.util.Map; 021 022import org.springframework.http.server.ServerHttpRequest; 023import org.springframework.http.server.ServerHttpResponse; 024import org.springframework.web.socket.WebSocketHandler; 025import org.springframework.web.socket.sockjs.SockJsTransportFailureException; 026import org.springframework.web.socket.sockjs.frame.SockJsFrame; 027import org.springframework.web.socket.sockjs.frame.SockJsMessageCodec; 028import org.springframework.web.socket.sockjs.transport.SockJsServiceConfig; 029 030/** 031 * A SockJS session for use with polling HTTP transports. 032 * 033 * @author Rossen Stoyanchev 034 * @since 4.0 035 */ 036public class PollingSockJsSession extends AbstractHttpSockJsSession { 037 038 public PollingSockJsSession(String sessionId, SockJsServiceConfig config, 039 WebSocketHandler wsHandler, Map<String, Object> attributes) { 040 041 super(sessionId, config, wsHandler, attributes); 042 } 043 044 045 /** 046 * @deprecated as of 4.2 this method is no longer used. 047 */ 048 @Override 049 @Deprecated 050 protected boolean isStreaming() { 051 return false; 052 } 053 054 @Override 055 protected void handleRequestInternal(ServerHttpRequest request, ServerHttpResponse response, 056 boolean initialRequest) throws IOException { 057 058 if (initialRequest) { 059 writeFrame(SockJsFrame.openFrame()); 060 } 061 else if (!getMessageCache().isEmpty()) { 062 flushCache(); 063 } 064 else { 065 scheduleHeartbeat(); 066 } 067 } 068 069 @Override 070 protected void flushCache() throws SockJsTransportFailureException { 071 String[] messages = new String[getMessageCache().size()]; 072 for (int i = 0; i < messages.length; i++) { 073 messages[i] = getMessageCache().poll(); 074 } 075 SockJsMessageCodec messageCodec = getSockJsServiceConfig().getMessageCodec(); 076 SockJsFrame frame = SockJsFrame.messageFrame(messageCodec, messages); 077 writeFrame(frame); 078 } 079 080 @Override 081 protected void writeFrame(SockJsFrame frame) throws SockJsTransportFailureException { 082 super.writeFrame(frame); 083 resetRequest(); 084 } 085 086} 087