Glacier2 Helper Classes
Ice includes a number of helper classes to help you build robust Glacier2 clients.
Compatibility Note
As of Ice 3.6, the Glacier2 helper classes use ACM heartbeats to automatically keep sessions alive. This functionality requires a Glacier2 router that also uses Ice 3.6 or later. Using an earlier version of Glacier2 will require your application to manually keep sessions alive.
The Glacier2::Application
Class
You may already be familiar with the Ice::Application
class, which encapsulates some basic Ice functionality such as communicator initialization, communicator destruction, and proper handling of signals and exceptions. The Glacier2::Application
extends Ice::Application
to add functionality that is commonly needed by Glacier2 clients:
- Keeps a session alive by periodically sending "heartbeat" requests
- Automatically restarts a session if a failure occurs
- Optionally creates an object adapter for callbacks
- Destroys the session when the application completes
The C++ definition of Glacier2::Application
is shown below. (The Java and C# versions offer identical functionality so we do not show them here.)
namespace Glacier2 { class Application : public Ice::Application { public: Application(); Application(Ice::SignalPolicy policy); virtual int runWithSession(int argc, char* argv[]) = 0; virtual Glacier2::SessionPrx createSession() = 0; virtual void sessionDestroyed(); static Glacier2::RouterPrx router(); static Glacier2::SessionPrx session(); void restart(); std::string categoryForClient(); Ice::Identity createCallbackIdentity(const std::string& name); Ice::ObjectPrx addWithUUID(const Ice::ObjectPtr& servant); Ice::ObjectAdapterPtr objectAdapter(); }; }
The class supports the following methods:
Application()
Instantiating the class using its default constructor has the same semantics as callingApplication(Ice::HandleSignals)
.
Application(Ice::SignalPolicy policy)
This constructor allows you to indicate whether the class should handle signals. TheSignalPolicy
enumeration contains two enumerators:HandleSignals
andNoSignalHandling
. If you specifyHandleSignals
, the class automatically shuts down or destroys its communicator upon receipt of certain signals. Refer to theIce::Application
documentation in the relevant language mapping chapter for more information on signal handling.
int runWithSession(int argc, char* argv[])
This method must be overridden by a subclass and represents the "main loop" of the application. It is called after the communicator has been initialized and the Glacier2 session has been established. The argument vector passed to this method contains the arguments passed toApplication::main
with all Ice-related options removed. The implementation ofrunWithSession
must return zero to indicate success and non-zero to indicate failure; the value returned byrunWithSession
becomes the return value ofApplication::main
.runWithSession
can callrestart
to restart the session. This destroys the current session, creates a new session (by callingcreateSession
), and callsrunWithSession
again. TheApplication
base class also restarts the session ifrunWithSession
raises (or allows to be raised) any of the following exceptions:Ice::ConnectionLostException
Ice::ConnectionRefusedException
Ice::RequestFailedException
Ice::TimeoutException
Ice::UnknownLocalException
All other exceptions cause the current session to be destroyed without restarting.
Glacier2::SessionPrx createSession()
This method must be overridden by a subclass to create the application's Glacier2 session. A successful call tocreateSession
is followed by a call torunWithSession
. The application terminates ifcreateSession
raises (or allows to be raised) anIce::LocalException
.
void sessionDestroyed()
A subclass can optionally override this method to take action when connectivity with the Glacier2 router is lost.
Glacier2::RouterPrx router()
Returns the proxy for the Glacier2 router.
Glacier2::SessionPrx session()
Returns the proxy for the current session.
void restart()
CausesApplication
to destroy the current session, create a new session (by callingcreateSession
), and start a new main loop (inrunWithSession
). This method does not return but rather raises aRestartSessionException
that is trapped byApplication
.
std::string categoryForClient()
Returns the category to be used in the identities of all of the client's callback objects. Clients must use this category for the router to forward callback requests to the intended client. The method raisesSessionNotExistException
if no session is currently active.
Ice::Identity createCallbackIdentity(const std::string& name)
Creates a new Ice identity for a callback object with the given identity name.
Ice::ObjectPrx addWithUUID(const Ice::ObjectPtr& servant)
Adds a servant to the callback object adapter's Active Servant Map using a UUID for the identity name.
Ice::ObjectAdapterPtr objectAdapter()
Returns the object adapter used for callbacks, creating the object adapter if necessary.
Example
The Ice distribution includes an example in demo/Glacier2/callback
that shows how to use the Glacier2::Application
class.
GUI Helper Classes
The "main loop" design imposed by the Glacier2::Application
class is not suitable for graphical applications, therefore Ice also includes a collection of C++, Java and C# classes that better accommodate the needs of GUI programs:
SessionFactoryHelper
This class simplifies the task of creating a Glacier2 session. It provides overloadedconnect
methods that support the two authentication styles (user name/password and SSL credentials) accepted by the Glacier2 router, and returns an instance ofSessionHelper
for each new session.
SessionHelper
This class encapsulates a Glacier2 session and provides much of the same functionality asGlacier2::Application
. The application must supply an instance ofSessionCallback
when creating the session;SessionHelper
invokes this callback object when important events occur in the session's lifecycle.
SessionCallback
An application implements this interface to receive notification about session lifecycle events.
The classes reside in the Glacier2
namespace or package. We discuss them further in the subsections below.
Example
You can find sample applications that make use of these classes in the demo/Glacier2/chat
directory of your Ice distribution.
The SessionFactoryHelper
Class
The SessionFactoryHelper
class provides convenience methods for configuring the settings that are commonly used to create a Glacier2 session, such as the router's host and port number. Once the application has completed its configuration, it calls one of the connect
methods to initialize a communicator, establish a Glacier2 session, and receive a SessionHelper
object with which it can manage the new session. An application should create a new SessionFactoryHelper
object for each router instance that it uses.
SessionFactoryHelper
creates an Ice.InitializationData
object if the application does not pass one to the SessionFactoryHelper
constructor. SessionFactoryHelper
also creates a new property set if necessary, and then sets some configuration properties required by Glacier2 clients. The resulting InitializationData
object is eventually used in connect
to initialize a new communicator.
The Java definition of SessionFactoryHelper
is shown below (the C++ and C# versions are nearly identical and not shown here):
package Glacier2; public class SessionFactoryHelper { public SessionFactoryHelper(SessionCallback callback) throws Ice.InitializationException; public SessionFactoryHelper(Ice.InitializationData initData, SessionCallback callback) throws Ice.InitializationException; public SessionFactoryHelper(Ice.Properties properties, SessionCallback callback) throws Ice.InitializationException; public void setRouterIdentity(Ice.Identity identity); public Ice.Identity getRouterIdentity(); public void setRouterHost(String hostname); public String getRouterHost(); public void setProtocol(String protocol); public String getProtocol(); public void setTimeout(int timeoutMillisecs); public int getTimeout(); public void setPort(int port); public int getPort(); public Ice.InitializationData getInitializationData(); public void setConnectContext(java.util.Map<String, String> ctx); public void setUseCallbacks(boolean useCallbacks); public boolean getUseCallbacks(); public SessionHelper connect(); public SessionHelper connect(String username, String password); }
The class supports the following methods:
SessionFactoryHelper(SessionCallback callback)
This constructor is useful when your application has no other configuration requirements. The constructor allocates anInitializationData
object and a new property set. The callback argument must not be null.
SessionFactoryHelper(Ice.InitializationData initData, SessionCallback callback)
Use this constructor when you want to prepare your own instance ofInitializationData
. Thecallback
argument must not be null.
SessionFactoryHelper(Ice.Properties properties, SessionCallback callback)
This constructor is convenient when you wish to supply an initial set of properties. The callback argument must not be null.
void setRouterIdentity(Ice.Identity identity)
Ice.Identity getRouterIdentity()
Determines the object identity of the Glacier2 router. If you don't callsetRouterIdentity
to provide an identity, the factory discovers the router's proxy by contacting theRouterFinder
object using the endpoint information you've configured for the factory (host, port, and so on).The factory ignores this setting if you configure
Ice.Default.Router
.
void setRouterHost(String hostname)
String getRouterHost()
Determines the host name of the Glacier2 router. The default router host islocalhost
.The factory ignores this setting if you configure
Ice.Default.Router
.
void setProtocol(String protocol)
String getProtocol()
Determines the Ice protocol used for communications with the Glacier2 router.protocol
can betcp
,ssl
,ws
orwss;
the default protocol isssl
.The factory ignores this setting if you configure
Ice.Default.Router
.
void setTimeout(int timeoutMillisecs)
int getTimeout()
Determines the timeout setting (in milliseconds) for the connection to the Glacier2 router. No timeout is used if the argument is less than or equal to zero. The default timeout is 10,000 ms.The factory ignores this setting if you configure
Ice.Default.Router
.
void setPort(int port)
int getPort()
Determines the port on which the Glacier2 router is listening. The default is 4063 when the protocol is tcp or ws, and 4064 when the protocol is ssl or wss.The factory ignores this setting if you configure
Ice.Default.Router
.
Ice.InitializationData getInitializationData()
Returns a reference to theInitializationData
object that will be used during communicator initialization. If necessary, an application can make modifications to this object prior to callingconnect
.
void setConnectContext(java.util.Map<String, String> ctx)
Sets the request context to be used when creating a session. This method must be invoked prior toconnect
.
void setUseCallbacks(boolean useCallbacks)
boolean getUseCallbacks()
Determines whether the session helper automatically creates an object adapter for callback servants. The default behavior is to create the object adapter.
SessionHelper connect()
Initializes a communicator, creates a Glacier2 session using SSL credentials, and returns a newSessionHelper
object. Theconnected
method is invoked on the session callback if the session was created successfully, otherwise the callback'sconnectFailed
method is invoked.
SessionHelper connect(String username, String password)
Initializes a communicator, creates a Glacier2 session using the given user name and password, and returns a newSessionHelper
object. Theconnected
method is invoked on the session callback if the session was created successfully, otherwise the callback'sconnectFailed
method is invoked.
The SessionHelper
Class
The SessionHelper
class encapsulates a Glacier2 session and keeps the session alive by periodically "pinging" the router. SessionHelper
also provides several convenience methods for common session-related actions:
package Glacier2; public class SessionHelper { public void destroy(); public Ice.Communicator communicator(); public String categoryForClient() throws SessionNotExistException; public Ice.ObjectPrx addWithUUID(Ice.Object servant) throws SessionNotExistException; public Glacier2.SessionPrx session() throws SessionNotExistException; public boolean isConnected(); public Ice.ObjectAdapter objectAdapter() throws SessionNotExistException; }
The class supports the following methods:
void destroy()
Initiates the destruction of the Glacier2 session, including the communicator created by theSessionHelper
. This is a non-blocking method that spawns a background thread to perform potentially blocking activities.SessionHelper
invokes thedisconnected
method on the application's callback object to indicate the completion of thedestroy
request. If the session has already been destroyed whendestroy
is called, the method does nothing.
Ice.Communicator communicator()
Returns the communicator created by theSessionHelper
.
String categoryForClient()
Returns the category that must be used in the identities of all callback objects. RaisesSessionNotExistException
if no session is currently active.
Ice.ObjectPrx addWithUUID(Ice.Object servant)
Adds a servant to the callback object adapter using a UUID for the identity name. RaisesSessionNotExistException
if no session is currently active.
Glacier2.SessionPrx session()
Returns a proxy for the Glacier2 session. RaisesSessionNotExistException
if no session is currently active.
boolean isConnected()
Returns true if the session is currently active, false otherwise.
Ice.ObjectAdapter objectAdapter()
Returns the callback object adapter. This object adapter is only created if the session factory was configured to do so usingsetUseCallbacks
. RaisesSessionNotExistException
if no session is currently active.
The Java implementation of SessionHelper
installs a JVM shutdown hook that calls destroy
when the application is about to exit.
The SessionCallback
Interface
An application must supply an instance of SessionCallback
when instantiating a SessionFactoryHelper
object. The callback methods allow the application to receive notification about events in the lifecycle of the session:
package Glacier2; public interface SessionCallback { void createdCommunicator(SessionHelper session); void connected(SessionHelper session) throws SessionNotExistException; void disconnected(SessionHelper session); void connectFailed(SessionHelper session, Throwable ex); }
The following callback methods are supported:
void createdCommunicator(SessionHelper session)
Called after successfully initializing a communicator.
void connected(SessionHelper session)
Called after successfully establishing the Glacier2 session. The method can raiseSessionNotExistException
to force the new session to be destroyed.
void disconnected(SessionHelper session)
Called after the Glacier2 session is destroyed.
void connectFailed(SessionHelper session, Throwable ex)
Called if a failure occurred while attempting to establish a Glacier2 session.