1 19 20 package org.apache.cayenne.remote.service; 21 22 import java.lang.ref.WeakReference ; 23 import java.util.HashMap ; 24 import java.util.Map ; 25 26 import javax.servlet.http.HttpSession ; 27 28 import org.apache.cayenne.DataChannel; 29 import org.apache.cayenne.remote.RemoteSession; 30 import org.apache.commons.logging.Log; 31 import org.apache.commons.logging.LogFactory; 32 33 40 public abstract class HttpRemoteService extends BaseRemoteService { 41 42 static final String SESSION_ATTRIBUTE = "HttpRemoteService.ServerSession"; 43 44 private final Log logObj = LogFactory.getLog(HttpRemoteService.class); 46 47 private Map sharedChannels = new HashMap (); 48 49 52 protected abstract HttpSession getSession(boolean create); 53 54 59 protected ServerSession getServerSession() { 60 HttpSession httpSession = getSession(true); 61 return (ServerSession) httpSession.getAttribute(SESSION_ATTRIBUTE); 62 } 63 64 68 protected ServerSession createServerSession() { 69 70 HttpSession httpSession = getSession(true); 71 72 DataChannel channel = createChannel(); 73 RemoteSession remoteSession = createRemoteSession( 74 httpSession.getId(), 75 null, 76 false); 77 ServerSession serverSession = new ServerSession(remoteSession, channel); 78 79 httpSession.setAttribute(SESSION_ATTRIBUTE, serverSession); 80 return serverSession; 81 } 82 83 89 protected ServerSession createServerSession(String name) { 90 if (name == null) { 91 throw new IllegalArgumentException ("Name is null for shared session."); 92 } 93 94 HttpSession httpSession = getSession(true); 95 DataChannel channel; 96 97 synchronized (sharedChannels) { 98 channel = getSharedChannel(name); 99 if (channel == null) { 100 channel = createChannel(); 101 saveSharedChannel(name, channel); 102 logObj.debug("Starting a new shared channel: " + name); 103 } 104 else { 105 logObj.debug("Joining existing shared channel: " + name); 106 } 107 } 108 109 RemoteSession remoteSession = createRemoteSession(httpSession.getId(), name, true); 110 111 ServerSession serverSession = new ServerSession(remoteSession, channel); 112 httpSession.setAttribute(SESSION_ATTRIBUTE, serverSession); 113 return serverSession; 114 } 115 116 protected DataChannel getSharedChannel(String name) { 117 WeakReference ref = (WeakReference ) sharedChannels.get(name); 118 return (ref != null) ? (DataChannel) ref.get() : null; 119 } 120 121 protected void saveSharedChannel(String name, DataChannel channel) { 122 sharedChannels.put(name, new WeakReference (channel)); 125 } 126 } 127 | Popular Tags |