summaryrefslogtreecommitdiff
path: root/java/src/Glacier2/Application.java
blob: d005e32c8b3d505858ce173183f1858b3ed8ef4a (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
// **********************************************************************
//
// Copyright (c) 2003-2009 ZeroC, Inc. All rights reserved.
//
// This copy of Ice is licensed to you under the terms described in the
// ICE_LICENSE file included in this distribution.
//
// **********************************************************************

package Glacier2;

/**
 * An extension of Ice.Application that makes it easy to write
 * Glacier2 applications.
 *
 * <p> Applications must create a derived class that implements the
 * {@link #createSession} and {@link #runWithSession} methods.<p>
 *
 * The base class invokes {@link #createSession} to create a new
 * Glacier2 session and then invokes {@link #runWithSession} in
 * which the subclass performs its application logic. The base class
 * automatically destroys the session when {@link #runWithSession}
 * returns.
 *
 * If {@link #runWithSession} calls {@link #restart} or raises any of
 * the exceptions Ice.ConnectionRefusedException,
 * Ice.ConnectionLostException, Ice.UnknownLocalException,
 * Ice.RequestFailedException, or Ice.TimeoutException, the base
 * class destroys the current session and restarts the application
 * with another call to {@link #createSession} followed by
 * {@link #runWithSession}.
 * 
 * The application can optionally override the {@link #sessionDestroyed}
 * callback method if it needs to take action when connectivity with
 * the Glacier2 router is lost.
 *
 * A program can contain only one instance of this class.
 *
 * @see Ice.Application
 * @see Glacier2.Router
 * @see Glacier2.Session
 * @see Ice.Communicator
 * @see Ice.Logger
 * @see #runWithSession
 **/
public abstract class Application extends Ice.Application
{
    /**
     * This exception is raised if the session should be restarted.
     */
    public class RestartSessionException extends Exception
    {
    }

    /**
     * Initializes an instance that calls {@link Communicator#shutdown} if
     * a signal is received.
     **/
    public
    Application()
    {
    }

    /**
     * Initializes an instance that handles signals according to the signal
     * policy.
     *
     * @param signalPolicy Determines how to respond to signals.
     *
     * @see SignalPolicy
     **/
    public
    Application(Ice.SignalPolicy signalPolicy)
    {
        super(signalPolicy);
    }


    /**
     * Called once the communicator has been initialized and the Glacier2 session
     * has been established. A derived class must implement <code>runWithSession</code>,
     * which is the application's starting method.
     *
     * @param args The argument vector for the application. <code>Application</code>
     * scans the argument vector passed to <code>main</code> for options that are
     * specific to the Ice run time and removes them; therefore, the vector passed
     * to <code>run</code> is free from Ice-related options and contains only options
     * and arguments that are application-specific.
     *
     * @return The <code>runWithSession</code> method should return zero for successful
     * termination, and non-zero otherwise. <code>Application.main</code> returns the
     * value returned by <code>runWithSession</code>.
     **/
    public abstract int
    runWithSession(String[] args)
        throws RestartSessionException;

    /**
     * Run should not be overridden for Glacier2.Application. Instead
     * <code>runWithSession</code> should be used.
     */
    final public int
    run(String[] args)
    {
        // This shouldn't be called.
        assert false;
        return 0;
    }

    /**
     * Called to restart the application's Glacier2 session. This
     * method never returns.
     *
     * @throws RestartSessionException This exception is always thrown.
     **/
    public void
    restart()
        throws RestartSessionException
    {
        throw new RestartSessionException();
    }

    /**
     * Creates a new Glacier2 session. A call to
     * <code>createSession</code> always precedes a call to
     * <code>runWithSession</code>. If <code>Ice.LocalException</code>
     * is thrown from this method, the application is terminated.

     * @return The Glacier2 session.
     **/
    abstract public Glacier2.SessionPrx
    createSession();

    /**
     * Called when the base class detects that the session has been destroyed.
     * A subclass can override this method to take action after the loss of
     * connectivity with the Glacier2 router.
     **/
    public void
    sessionDestroyed()
    {
    }

    /**
     * Returns the Glacier2 router proxy
     * @return The router proxy.
     **/
    public static Glacier2.RouterPrx
    router()
    {
        return _router;
    }

    /**
     * Returns the Glacier2 session proxy
     * @return The session proxy.
     **/
    public static Glacier2.SessionPrx
    session()
    {
        return _session;
    }

    /**
     * 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.
     * @return The category.
     * @throws SessionNotExistException No session exists.
     **/
    public String
    categoryForClient() throws SessionNotExistException
    {
        if(_router == null)
        {
            throw new SessionNotExistException();
        }
        return _router.getCategoryForClient();
    }

    /**
     * Create a new Ice identity for callback objects with the given
     * identity name field.
     * @return The identity.
     * @throws SessionNotExistException No session exists.
     **/
    public Ice.Identity
    createCallbackIdentity(String name) throws SessionNotExistException
    {
        return new Ice.Identity(name, categoryForClient());
    }

    /**
     * Adds a servant to the callback object adapter's Active Servant Map with a UUID.
     * @param servant The servant to add.
     * @return The proxy for the servant.
     * @throws SessionNotExistException No session exists.
     **/
    public Ice.ObjectPrx
    addWithUUID(Ice.Object servant) throws SessionNotExistException 
    {
        return objectAdapter().add(servant, createCallbackIdentity(java.util.UUID.randomUUID().toString()));
    }

    /**
     * Creates an object adapter for callback objects.
     * @return The object adapter.
     * @throws SessionNotExistException No session exists.
     */
    public synchronized Ice.ObjectAdapter
    objectAdapter() throws SessionNotExistException
    {
        if(_adapter == null)
        {
            if(_router == null)
            {
                throw new SessionNotExistException();
            }
            _adapter = communicator().createObjectAdapterWithRouter("", _router);
            _adapter.activate();
        }
        return _adapter;
    }

    private class SessionPingThread extends Thread
    {
        SessionPingThread(Glacier2.RouterPrx router, long period)
        {
            _router = router;
            _period = period;
            _done = false;
        }

        synchronized public void
        run()
        {
            while(true)
            {
                _router.refreshSession_async(new Glacier2.AMI_Router_refreshSession()
                    {
                        public void
                        ice_response()
                        {
                        }

                        public void
                        ice_exception(Ice.LocalException ex)
                        {
                            // Here the session has gone. The thread
                            // terminates, and we notify the
                            // application that the session has been
                            // destroyed.
                            done();
                            sessionDestroyed();
                        }

                        public void
                        ice_exception(Ice.UserException ex)
                        {
                            // Here the session has gone. The thread
                            // terminates, and we notify the
                            // application that the session has been
                            // destroyed.
                            done();
                            sessionDestroyed();
                        }
                    });

                if(!_done)
                {
                    try
                    {
                        wait(_period);
                    }
                    catch(InterruptedException ex)
                    {
                    }
                }

                if(_done)
                {
                    break;
                }
            }
        }

        public synchronized void
        done()
        {
            if(!_done)
            {
                _done = true;
                notify();
            }
        }

        private final Glacier2.RouterPrx _router;
        private final long _period;
        private boolean _done = false;
    }

    protected int
    doMain(Ice.StringSeqHolder argHolder, Ice.InitializationData initData)
    {
        // Set the default properties for all Glacier2 applications.
        initData.properties.setProperty("Ice.ACM.Client", "0");
        initData.properties.setProperty("Ice.RetryIntervals", "-1");

        boolean restart;
        Ice.IntHolder ret = new Ice.IntHolder();
        do
        {
            // A copy of the initialization data and the string seq
            // needs to be passed to doMainInternal, as these can be
            // changed by the application.
            Ice.InitializationData id = (Ice.InitializationData)initData.clone();
            id.properties = id.properties._clone();
            Ice.StringSeqHolder h = new Ice.StringSeqHolder();
            h.value = argHolder.value.clone();

            restart = doMain(h, id, ret);
        }
        while(restart);
        return ret.value;
    }

    private boolean
    doMain(Ice.StringSeqHolder argHolder, Ice.InitializationData initData, Ice.IntHolder status)
    {
        // Reset internal state variables from Ice.Application. The
        // remainder are reset at the end of this method.
        _callbackInProgress = false;
        _destroyed = false;
        _interrupted = false;

        boolean restart = false;
        status.value = 0;

        SessionPingThread ping = null;
        try
        {
            _communicator = Ice.Util.initialize(argHolder, initData);

            _router = Glacier2.RouterPrxHelper.uncheckedCast(communicator().getDefaultRouter());
            if(_router == null)
            {
                Ice.Util.getProcessLogger().error("no glacier2 router configured");
                status.value = 1;
            }
            else
            {
                //
                // The default is to destroy when a signal is received.
                //
                if(_signalPolicy == Ice.SignalPolicy.HandleSignals)
                {
                    destroyOnInterrupt();
                }

                // If createSession throws, we're done.
                try
                {
                    _session = createSession();
                    _createdSession = true;
                }
                catch(Ice.LocalException ex)
                {
                    Ice.Util.getProcessLogger().error(IceInternal.Ex.toString(ex));
                    status.value = 1;
                }

                if(_createdSession)
                {
                    ping = new SessionPingThread(_router, (_router.getSessionTimeout() * 1000) / 2);
                    ping.start();
                    status.value = runWithSession(argHolder.value);
                }
            }
        }
        // We want to restart on those exceptions which indicate a
        // break down in communications, but not those exceptions that
        // indicate a programming logic error (ie: marshal, protocol
        // failure, etc).
        catch(RestartSessionException ex)
        {
            restart = true;
        }
        catch(Ice.ConnectionRefusedException ex)
        {
            Ice.Util.getProcessLogger().error(IceInternal.Ex.toString(ex));
            restart = true;
        }
        catch(Ice.ConnectionLostException ex)
        {
            Ice.Util.getProcessLogger().error(IceInternal.Ex.toString(ex));
            restart = true;
        }
        catch(Ice.UnknownLocalException ex)
        {
            Ice.Util.getProcessLogger().error(IceInternal.Ex.toString(ex));
            restart = true;
        }
        catch(Ice.RequestFailedException ex)
        {
            Ice.Util.getProcessLogger().error(IceInternal.Ex.toString(ex));
            restart = true;
        }
        catch(Ice.TimeoutException ex)
        {
            Ice.Util.getProcessLogger().error(IceInternal.Ex.toString(ex));
            restart = true;
        }
        catch(Ice.LocalException ex)
        {
            Ice.Util.getProcessLogger().error(IceInternal.Ex.toString(ex));
            status.value = 1;
        }
        catch(java.lang.Exception ex)
        {
            Ice.Util.getProcessLogger().error("unknown exception" + IceInternal.Ex.toString(ex));
            status.value = 1;
        }
        catch(java.lang.Error err)
        {
            //
            // We catch Error to avoid hangs in some non-fatal situations
            //
            Ice.Util.getProcessLogger().error("Java error " + IceInternal.Ex.toString(err));
            status.value = 1;
        }

        // This clears any set interrupt.
        if(_signalPolicy == Ice.SignalPolicy.HandleSignals)
        {
            defaultInterrupt();
        }

        synchronized(_mutex)
        {
            while(_callbackInProgress)
            {
                try
                {
                    _mutex.wait();
                }
                catch(java.lang.InterruptedException ex)
                {
                }
            }

            if(_destroyed)
            {
                _communicator = null;
            }
            else
            {
                _destroyed = true;
                //
                // And _communicator != null, meaning will be
                // destroyed next, _destroyed = true also ensures that
                // any remaining callback won't do anything
                //
            }
        }

        if(ping != null)
        {
            ping.done();
            while(true)
            {
                try
                {
                    ping.join();
                    break;
                }
                catch(InterruptedException ex)
                {
                }
            }
            ping = null;
        }

        if(_createdSession && _router != null)
        {
            try
            {
                _router.destroySession();
            }
            catch(Ice.ConnectionLostException ex)
            {
                // Expected if another thread invoked on an object from the session concurrently.
            }
            catch(Glacier2.SessionNotExistException ex)
            {
                // This can also occur.
            }
            catch(Throwable ex)
            {
                // Not expected.
                Ice.Util.getProcessLogger().error("unexpected exception when destroying the session:\n" + 
                                                  IceInternal.Ex.toString(ex));
            }
            _router = null;
        }

        if(_communicator != null)
        {
            try
            {
                _communicator.destroy();
            }
            catch(Ice.LocalException ex)
            {
                Ice.Util.getProcessLogger().error(IceInternal.Ex.toString(ex));
                status.value = 1;
            }
            catch(java.lang.Exception ex)
            {
                Ice.Util.getProcessLogger().error("unknown exception" + IceInternal.Ex.toString(ex));
                status.value = 1;
            }
            _communicator = null;
        }

        synchronized(_mutex)
        {
            if(_appHook != null)
            {
                _appHook.done();
            }
        }

        // Reset internal state. We cannot reset the Application state
        // here, since _destroyed must remain true until we re-run
        // this method.
        _adapter = null;
        _router = null;
        _session = null;
        _createdSession = false;

        return restart;
    }

    private static Ice.ObjectAdapter _adapter;
    private static Glacier2.RouterPrx _router;
    private static Glacier2.SessionPrx _session;
    private static boolean _createdSession = false;
}