This repository has been archived by the owner on Apr 8, 2019. It is now read-only.
/
AbstractConsumerRegistry.java
654 lines (553 loc) · 20.9 KB
/
AbstractConsumerRegistry.java
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
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
/*
* JBoss, a division of Red Hat
* Copyright 2012, Red Hat Middleware, LLC, and individual
* contributors as indicated by the @authors tag. See the
* copyright.txt in the distribution for a full listing of
* individual contributors.
*
* This is free software; you can redistribute it and/or modify it
* under the terms of the GNU Lesser General Public License as
* published by the Free Software Foundation; either version 2.1 of
* the License, or (at your option) any later version.
*
* This software is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this software; if not, write to the Free
* Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA
* 02110-1301 USA, or see the FSF site: http://www.fsf.org.
*/
package org.gatein.wsrp.consumer.registry;
import org.gatein.common.util.ParameterValidation;
import org.gatein.pc.api.PortletInvokerException;
import org.gatein.pc.federation.FederatingPortletInvoker;
import org.gatein.wsrp.WSRPConsumer;
import org.gatein.wsrp.api.session.SessionEventBroadcaster;
import org.gatein.wsrp.consumer.ConsumerException;
import org.gatein.wsrp.consumer.ProducerInfo;
import org.gatein.wsrp.consumer.WSRPConsumerImpl;
import org.gatein.wsrp.consumer.handlers.session.InMemorySessionRegistry;
import org.gatein.wsrp.consumer.handlers.session.SessionRegistry;
import org.gatein.wsrp.consumer.migration.InMemoryMigrationService;
import org.gatein.wsrp.consumer.migration.MigrationService;
import org.gatein.wsrp.consumer.spi.ConsumerRegistrySPI;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.util.ArrayList;
import java.util.Collection;
import java.util.HashSet;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.concurrent.ConcurrentHashMap;
/**
* Provides a base implementation for ConsumerRegistry behavior. It is <em>strongly</em> recommended that implementations inherit from this abstract superclass. The goal is to
* make sure that the consumer states are properly stored and consistent across cluster nodes.
*
* @author <a href="mailto:chris.laprun@jboss.com">Chris Laprun</a>
* @version $Revision: 12693 $
* @since 2.6
*/
public abstract class AbstractConsumerRegistry implements ConsumerRegistrySPI
{
/** Gives access to the Portal's portlet invokers to be able to register/unregisters consumers as PortletInvokers */
private FederatingPortletInvoker federatingPortletInvoker;
/** Broadcasts session events to consumers and their interested components. Provided default implementation should be replaced when services are wired at the portal level. */
private SessionEventBroadcaster sessionEventBroadcaster = SessionEventBroadcaster.NO_OP_BROADCASTER;
/** Deals with import/export functionality. Provided default implementation should be replaced when services are wired at the portal level. */
private MigrationService migrationService = new InMemoryMigrationService();
/** Records which portlet session is associated with which ProducerSessionInformation */
private SessionRegistry sessionRegistry = new InMemorySessionRegistry();
private static final String CONSUMER_WITH_ID = "Consumer with id '";
private static final String RELEASE_SESSIONS_LISTENER = "release_sessions_listener_";
protected static final Logger log = LoggerFactory.getLogger(AbstractConsumerRegistry.class);
/** Caches consumers to avoid having to recreate them if possible as the lifecycle transitions might be a little complex and not completely possible to restore from persistence */
protected ConsumerCache consumerCache;
protected AbstractConsumerRegistry()
{
initConsumerCache();
}
/** Initializes the ConsumerCache so that subclasses have the opportunity to do some specific processing. */
protected abstract void initConsumerCache();
public synchronized void setConsumerCache(ConsumerCache consumers)
{
if (consumers == null)
{
consumers = new InMemoryConsumerCache(this);
}
this.consumerCache = consumers;
}
public synchronized void setSessionRegistry(SessionRegistry sessionRegistry)
{
if (sessionRegistry == null)
{
sessionRegistry = new InMemorySessionRegistry();
}
this.sessionRegistry = sessionRegistry;
}
public SessionRegistry getSessionRegistry()
{
return sessionRegistry;
}
public FederatingPortletInvoker getFederatingPortletInvoker()
{
return federatingPortletInvoker;
}
public synchronized void setSessionEventBroadcaster(SessionEventBroadcaster sessionEventBroadcaster)
{
if (sessionEventBroadcaster == null)
{
sessionEventBroadcaster = SessionEventBroadcaster.NO_OP_BROADCASTER;
}
this.sessionEventBroadcaster = sessionEventBroadcaster;
}
public MigrationService getMigrationService()
{
return migrationService;
}
public synchronized void setMigrationService(MigrationService migrationService)
{
if (migrationService == null)
{
migrationService = new InMemoryMigrationService();
}
this.migrationService = migrationService;
}
public WSRPConsumer createConsumer(String id, Integer expirationCacheSeconds, String wsdlURL)
{
ParameterValidation.throwIllegalArgExceptionIfNullOrEmpty(id, "Consumer identifier", "Creating a Consumer");
if (getConsumer(id) != null)
{
throw new ConsumerException(CONSUMER_WITH_ID + id + "' already exists!");
}
ProducerInfo info = new ProducerInfo(this);
info.setId(id);
info.setExpirationCacheSeconds(expirationCacheSeconds);
info.getEndpointConfigurationInfo().setWsdlDefinitionURL(wsdlURL);
save(info, "Couldn't create Consumer '" + id + "'");
log.debug(CONSUMER_WITH_ID + id + "' created");
return createConsumerFrom(info, true);
}
public void destroyConsumer(String id)
{
ParameterValidation.throwIllegalArgExceptionIfNullOrEmpty(id, "Consumer identifier", "Destroying a Consumer");
WSRPConsumer consumer = getConsumer(id);
if (consumer != null)
{
ProducerInfo info = consumer.getProducerInfo();
try
{
consumer.releaseSessions();
}
catch (PortletInvokerException e)
{
log.debug("releaseSessions failed when attempting to destroy " + CONSUMER_WITH_ID + id + "'");
}
// if the consumer is registered, deregister it
if (info.isRegistered())
{
registerOrDeregisterConsumerWith(id, false);
}
deactivateConsumer(consumer);
delete(info);
// remove from cache
consumerCache.removeConsumer(id);
}
else
{
throw new ConsumerException(CONSUMER_WITH_ID + id + "' doesn't exist!");
}
log.debug(CONSUMER_WITH_ID + id + "' destroyed");
}
public synchronized void setFederatingPortletInvoker(FederatingPortletInvoker federatingPortletInvoker)
{
this.federatingPortletInvoker = federatingPortletInvoker;
}
public WSRPConsumer createConsumerFrom(ProducerInfo producerInfo, boolean putInCache)
{
// make sure we set the registry after loading from DB since registry is not persisted.
// producerInfo.setRegistry(this);
final WSRPConsumerImpl consumer = createAndActivateIfNeeded(producerInfo);
// cache consumer
if (putInCache)
{
consumerCache.putConsumer(producerInfo.getId(), consumer);
}
return consumer;
}
private WSRPConsumerImpl createAndActivateIfNeeded(ProducerInfo producerInfo)
{
final WSRPConsumerImpl consumer = new WSRPConsumerImpl(producerInfo);
// try to activate consumer if it's marked as active and isn't yet
if (producerInfo.isActive() && !consumer.isActive())
{
activateConsumer(consumer);
}
return consumer;
}
public void activateConsumerWith(String id) throws ConsumerException
{
ParameterValidation.throwIllegalArgExceptionIfNullOrEmpty(id, "Consumer identifier", "Activating a Consumer");
activateConsumer(getConsumer(id));
}
protected void activateConsumer(WSRPConsumer consumer)
{
startOrStopConsumer(consumer, true, false);
}
public void deactivateConsumerWith(String id) throws ConsumerException
{
ParameterValidation.throwIllegalArgExceptionIfNullOrEmpty(id, "Consumer identifier", "Deactivating a Consumer");
deactivateConsumer(getConsumer(id));
}
protected void deactivateConsumer(WSRPConsumer consumer)
{
startOrStopConsumer(consumer, false, false);
}
public void registerWithFederatingPortletInvoker(WSRPConsumer consumer)
{
startOrStopConsumer(consumer, true, true);
}
public void deregisterWithFederatingPortletInvoker(WSRPConsumer consumer)
{
startOrStopConsumer(consumer, false, true);
}
public long getPersistedLastModifiedForProducerInfoWith(String id)
{
ProducerInfo producerInfo = loadProducerInfo(id);
if (producerInfo == null)
{
return Long.MIN_VALUE;
}
else
{
return producerInfo.getLastModified();
}
}
public synchronized String updateProducerInfo(ProducerInfo producerInfo)
{
ParameterValidation.throwIllegalArgExceptionIfNull(producerInfo, "ProducerInfo");
// only save producer info if we have local modifications that postdate last persisted change
if (producerInfo.getLastModified() > getPersistedLastModifiedForProducerInfoWith(producerInfo.getId()))
{
String oldId = update(producerInfo);
// if we updated and oldId is not null, we need to update the local information
if (oldId != null)
{
WSRPConsumer consumer = createConsumerFrom(producerInfo, true);
// update the federating portlet invoker if needed
if (federatingPortletInvoker.isResolved(oldId))
{
federatingPortletInvoker.unregisterInvoker(oldId);
}
// update cache
consumerCache.removeConsumer(oldId);
consumerCache.putConsumer(producerInfo.getId(), consumer);
}
return oldId;
}
else
{
return null;
}
}
public void start() throws Exception
{
reloadConsumers();
}
public void reloadConsumers()
{
consumerCache.initFromStorage();
}
public void stop() throws Exception
{
for (WSRPConsumer consumer : getConsumers(false))
{
// if producer is not active, it shouldn't be registered with the federating portlet invoker, hence do not
// unregister it. We have changed how consumers are registered (active consumers are not automatically
// registered anymore), we also need to check if the consumer is known by the federating portlet invoker...
String producerId = consumer.getProducerId();
if (consumer.getProducerInfo().isActive() && federatingPortletInvoker.isResolved(producerId))
{
federatingPortletInvoker.unregisterInvoker(producerId);
}
try
{
consumer.stop();
}
catch (Exception e)
{
// ignore and continue
}
}
}
public List<WSRPConsumer> getConfiguredConsumers()
{
return getConsumers(true);
}
public WSRPConsumer getConsumer(String id)
{
ParameterValidation.throwIllegalArgExceptionIfNullOrEmpty(id, "consumer id", null);
return consumerCache.getConsumer(id);
}
public boolean containsConsumer(String id)
{
return getConsumer(id) != null;
}
public int getConfiguredConsumerNumber()
{
return getConfiguredConsumersIds().size();
}
public void registerOrDeregisterConsumerWith(String id, boolean register)
{
ParameterValidation.throwIllegalArgExceptionIfNullOrEmpty(id, "Consumer identifier", "Registering or deregistering a Consumer");
WSRPConsumer consumer = getConsumer(id);
if (consumer == null)
{
throw new ConsumerException(CONSUMER_WITH_ID + id + "' doesn't exist!");
}
try
{
if (register)
{
consumer.getProducerInfo().register();
}
else
{
consumer.getProducerInfo().deregister();
}
}
catch (Exception e)
{
// unexpected exception: deactivate the consumer
deactivateConsumer(consumer);
Throwable cause = e.getCause();
throw new ConsumerException("Couldn't " + (register ? "register" : "deregister") + CONSUMER_WITH_ID + id + "'",
cause != null ? cause : e);
}
}
private void startOrStopConsumer(WSRPConsumer consumer, boolean start, boolean registerOrDeregisterOnly)
{
ParameterValidation.throwIllegalArgExceptionIfNull(consumer, "WSRPConsumer");
try
{
String id = consumer.getProducerId();
if (start)
{
if (!registerOrDeregisterOnly)
{
consumer.refresh(false);
}
// only register with the FederatingPortletInvoker if we're not already
if (!federatingPortletInvoker.isResolved(id))
{
federatingPortletInvoker.registerInvoker(id, consumer);
}
sessionEventBroadcaster.registerListener(getListenerIdFrom(id), consumer);
}
else
{
if (!registerOrDeregisterOnly)
{
consumer.deactivate();
}
// only unregisters with the FederatingPortletInvoker if we are registered
if (federatingPortletInvoker.isResolved(id))
{
federatingPortletInvoker.unregisterInvoker(id);
}
sessionEventBroadcaster.unregisterListener(getListenerIdFrom(id));
}
}
catch (Exception e)
{
throw new ConsumerException("Couldn't " + (start ? "start" : "stop") + " Consumer service '" + consumer.getProducerId() + "'", e);
}
// update ProducerInfo
updateProducerInfo(consumer.getProducerInfo());
}
private String getListenerIdFrom(String id)
{
return RELEASE_SESSIONS_LISTENER + id;
}
protected List<WSRPConsumer> getConsumers(boolean startConsumers)
{
final Collection<WSRPConsumer> consumerz = consumerCache.getConsumers();
if (startConsumers)
{
for (WSRPConsumer consumer : consumerz)
{
final ProducerInfo info = consumer.getProducerInfo();
if (info.isActive() && !consumer.isActive())
{
try
{
consumer.refresh(false);
}
catch (Exception e)
{
log.info("Couldn't activate consumer " + consumer.getProducerId());
info.setActiveAndSave(false);
}
}
}
}
return new ArrayList<WSRPConsumer>(consumerz);
}
protected class ProducerInfoIterator implements Iterator<ProducerInfo>
{
private Iterator<WSRPConsumer> consumers;
public ProducerInfoIterator(Iterator<WSRPConsumer> consumers)
{
this.consumers = consumers;
}
public boolean hasNext()
{
return consumers.hasNext();
}
public ProducerInfo next()
{
return consumers.next().getProducerInfo();
}
public void remove()
{
throw new UnsupportedOperationException("remove not supported on this iterator implementation");
}
}
/** Implements a local cache for consumers. */
protected static class InMemoryConsumerCache implements ConsumerCache
{
private Map<String, WSRPConsumer> consumers = new ConcurrentHashMap<String, WSRPConsumer>(11);
private boolean invalidated;
private ConsumerRegistrySPI registry;
public InMemoryConsumerCache(ConsumerRegistrySPI registry)
{
this.registry = registry;
}
public void initFromStorage()
{
// first, remove all existing state
clear();
// then load ProducerInfos from persistence and create consumers from them
Iterator<ProducerInfo> infosFromStorage = registry.getProducerInfosFromStorage();
while (infosFromStorage.hasNext())
{
ProducerInfo info = infosFromStorage.next();
consumers.put(info.getId(), createConsumer(info));
}
// since our state is fresh from persistence, we can't possibly be invalidated! :)
setInvalidated(false);
}
private WSRPConsumer createConsumer(ProducerInfo info)
{
return registry.createConsumerFrom(info, false);
}
public Collection<WSRPConsumer> getConsumers()
{
refreshIfNeeded();
return consumers.values();
}
public WSRPConsumer getConsumer(String id)
{
// try cache first
WSRPConsumer consumer = consumers.get(id);
return getUpdatedConsumer(id, consumer);
}
/**
* Updates the specified consumer if its local state doesn't match the persisted state anymore.
*
* @param id the identifier of the consumer to update in case the specified consumer is <code>null</code>, which might happen if, for example, the consumer is not
* present locally
* @param consumer the consumer to update if required
* @return an updated version (if so needed) of the consumer identified with the specified identifier
*/
private WSRPConsumer getUpdatedConsumer(String id, WSRPConsumer consumer)
{
if (consumer == null || consumer.getProducerInfo().getLastModified() < registry.getPersistedLastModifiedForProducerInfoWith(id))
{
// if consumer is not in cache (null) or was modified in persistence, (re-)load it from persistence
ProducerInfo info = registry.loadProducerInfo(id);
if (info != null)
{
consumer = createConsumer(info);
consumers.put(id, consumer);
return consumer;
}
else
{
// we didn't find any consumer with that id in persistence either, return null
return null;
}
}
else
{
// our consumer is already up-to-date, return it
return consumer;
}
}
public WSRPConsumer removeConsumer(String id)
{
return consumers.remove(id);
}
public void putConsumer(String id, WSRPConsumer consumer)
{
consumers.put(id, consumer);
}
public void clear()
{
consumers.clear();
invalidated = true;
}
public boolean isInvalidated()
{
return invalidated;
}
public void setInvalidated(boolean invalidated)
{
this.invalidated = invalidated;
}
/**
* Refreshes the cache information if needed. In particular, this means that after calling this method, the set of cached consumers should be consistent with the persisted
* state, all consumers being up-to-date with their persisted state, obsolete consumers are removed, new ones are added.
*/
protected void refreshIfNeeded()
{
// if we've been invalidated, remove all cached consumers
if (isInvalidated())
{
consumers.clear();
}
// get the identifiers of known consumers from the persistence layer
Collection<String> consumersIds = registry.getConfiguredConsumersIds();
// first remove all obsolete Consumers in cache
Set<String> obsoleteConsumers = new HashSet<String>(consumers.keySet());
obsoleteConsumers.removeAll(consumersIds);
for (String obsolete : obsoleteConsumers)
{
consumers.remove(obsolete);
}
// then check, for each consumer, if it has been modified since we last checked
for (String id : consumersIds)
{
// get the cached consumer
WSRPConsumer consumerInfo = consumers.get(id);
if (consumerInfo != null)
{
// if we have a consumer for that id, check that it's up-to-date and update it if needed
getUpdatedConsumer(id, consumerInfo);
}
else
{
// if we don't have a consumer for that id, load it from persistence and cache it
ProducerInfo producerInfo = registry.loadProducerInfo(id);
consumers.put(id, createConsumer(producerInfo));
}
}
// state that we're not invalid anymore if we previously were
setInvalidated(false);
}
}
}