/
ServerLocatorImpl.java
1929 lines (1585 loc) · 55.4 KB
/
ServerLocatorImpl.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
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
/*
* Copyright 2010 Red Hat, Inc.
* Red Hat licenses this file to you under the Apache License, version
* 2.0 (the "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
* http://www.apache.org/licenses/LICENSE-2.0
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
* implied. See the License for the specific language governing
* permissions and limitations under the License.
*/
package org.hornetq.core.client.impl;
import java.io.Serializable;
import java.lang.reflect.Array;
import java.security.AccessController;
import java.security.PrivilegedAction;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collection;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
import java.util.concurrent.CopyOnWriteArrayList;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.Executor;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.RejectedExecutionException;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.ThreadFactory;
import java.util.concurrent.TimeUnit;
import org.hornetq.api.core.DiscoveryGroupConfiguration;
import org.hornetq.api.core.HornetQException;
import org.hornetq.api.core.HornetQExceptionType;
import org.hornetq.api.core.HornetQIllegalStateException;
import org.hornetq.api.core.Interceptor;
import org.hornetq.api.core.TransportConfiguration;
import org.hornetq.api.core.client.ClientSessionFactory;
import org.hornetq.api.core.client.ClusterTopologyListener;
import org.hornetq.api.core.client.HornetQClient;
import org.hornetq.api.core.client.TopologyMember;
import org.hornetq.api.core.client.loadbalance.ConnectionLoadBalancingPolicy;
import org.hornetq.core.cluster.DiscoveryEntry;
import org.hornetq.core.cluster.DiscoveryGroup;
import org.hornetq.core.cluster.DiscoveryListener;
import org.hornetq.core.protocol.ClientPacketDecoder;
import org.hornetq.core.protocol.core.impl.PacketDecoder;
import org.hornetq.core.remoting.FailureListener;
import org.hornetq.core.client.HornetQClientLogger;
import org.hornetq.core.client.HornetQClientMessageBundle;
import org.hornetq.spi.core.remoting.Connector;
import org.hornetq.utils.ClassloadingUtil;
import org.hornetq.utils.HornetQThreadFactory;
import org.hornetq.utils.Pair;
import org.hornetq.utils.UUIDGenerator;
/**
* This is the implementation of {@link org.hornetq.api.core.client.ServerLocator} and all
* the proper javadoc is located on that interface.
*
* @author Tim Fox
*/
public final class ServerLocatorImpl implements ServerLocatorInternal, DiscoveryListener, Serializable
{
/*needed for backward compatibility*/
@SuppressWarnings("unused")
private final Set<ClusterTopologyListener> topologyListeners = new HashSet<ClusterTopologyListener>();
/*end of compatibility fixes*/
private enum STATE
{
INITIALIZED, CLOSED, CLOSING
};
private static final long serialVersionUID = -1615857864410205260L;
private final boolean ha;
private boolean finalizeCheck = true;
private boolean clusterConnection;
private transient String identity;
private final Set<ClientSessionFactoryInternal> factories = new HashSet<ClientSessionFactoryInternal>();
private final Set<ClientSessionFactoryInternal> connectingFactories = new HashSet<ClientSessionFactoryInternal>();
private volatile TransportConfiguration[] initialConnectors;
private final DiscoveryGroupConfiguration discoveryGroupConfiguration;
private final StaticConnector staticConnector = new StaticConnector();
private final Topology topology;
//needs to be serializable
private final String topologyArrayGuard = new String();
private volatile Pair<TransportConfiguration, TransportConfiguration>[] topologyArray;
private volatile boolean receivedTopology;
private boolean compressLargeMessage;
// if the system should shutdown the pool when shutting down
private transient boolean shutdownPool;
private transient ExecutorService threadPool;
private transient ScheduledExecutorService scheduledThreadPool;
private transient DiscoveryGroup discoveryGroup;
private transient ConnectionLoadBalancingPolicy loadBalancingPolicy;
// Settable attributes:
private boolean cacheLargeMessagesClient;
private long clientFailureCheckPeriod;
private long connectionTTL;
private long callTimeout;
private long callFailoverTimeout;
private int minLargeMessageSize;
private int consumerWindowSize;
private int consumerMaxRate;
private int confirmationWindowSize;
private int producerWindowSize;
private int producerMaxRate;
private boolean blockOnAcknowledge;
private boolean blockOnDurableSend;
private boolean blockOnNonDurableSend;
private boolean autoGroup;
private boolean preAcknowledge;
private String connectionLoadBalancingPolicyClassName;
private int ackBatchSize;
private boolean useGlobalPools;
private int scheduledThreadPoolMaxSize;
private int threadPoolMaxSize;
private long retryInterval;
private double retryIntervalMultiplier;
private long maxRetryInterval;
private int reconnectAttempts;
private int initialConnectAttempts;
private boolean failoverOnInitialConnection;
private int initialMessagePacketSize;
/**
* As the class is Serializable, the guard field must be of a serializable type in order to be
* final.
*/
private final String stateGuard = new String();
private transient STATE state;
private transient CountDownLatch latch;
private final List<Interceptor> incomingInterceptors = new CopyOnWriteArrayList<Interceptor>();
private final List<Interceptor> outgoingInterceptors = new CopyOnWriteArrayList<Interceptor>();
private static ExecutorService globalThreadPool;
private Executor startExecutor;
private static ScheduledExecutorService globalScheduledThreadPool;
private AfterConnectInternalListener afterConnectListener;
private String groupID;
private String nodeID;
private TransportConfiguration clusterTransportConfiguration;
/*
* we use the client decoder by default but there are times when we want to use the server packet decoder
*/
private PacketDecoder packetDecoder = ClientPacketDecoder.INSTANCE;
private final Exception e = new Exception();
// To be called when there are ServerLocator being finalized.
// To be used on test assertions
public static Runnable finalizeCallback = null;
public static synchronized void clearThreadPools()
{
if (globalThreadPool != null)
{
globalThreadPool.shutdown();
try
{
if (!globalThreadPool.awaitTermination(10, TimeUnit.SECONDS))
{
throw new IllegalStateException("Couldn't finish the globalThreadPool");
}
}
catch (InterruptedException e)
{
}
finally
{
globalThreadPool = null;
}
}
if (globalScheduledThreadPool != null)
{
globalScheduledThreadPool.shutdown();
try
{
if (!globalScheduledThreadPool.awaitTermination(10, TimeUnit.SECONDS))
{
throw new IllegalStateException("Couldn't finish the globalScheduledThreadPool");
}
}
catch (InterruptedException e)
{
}
finally
{
globalScheduledThreadPool = null;
}
}
}
private static synchronized ExecutorService getGlobalThreadPool()
{
if (globalThreadPool == null)
{
ThreadFactory factory = new HornetQThreadFactory("HornetQ-client-global-threads", true, getThisClassLoader());
globalThreadPool = Executors.newCachedThreadPool(factory);
}
return globalThreadPool;
}
private static synchronized ScheduledExecutorService getGlobalScheduledThreadPool()
{
if (globalScheduledThreadPool == null)
{
ThreadFactory factory = new HornetQThreadFactory("HornetQ-client-global-scheduled-threads",
true,
getThisClassLoader());
globalScheduledThreadPool = Executors.newScheduledThreadPool(HornetQClient.DEFAULT_SCHEDULED_THREAD_POOL_MAX_SIZE,
factory);
}
return globalScheduledThreadPool;
}
private synchronized void setThreadPools()
{
if (threadPool != null)
{
return;
}
else if (useGlobalPools)
{
threadPool = getGlobalThreadPool();
scheduledThreadPool = getGlobalScheduledThreadPool();
}
else
{
this.shutdownPool = true;
ThreadFactory factory = new HornetQThreadFactory("HornetQ-client-factory-threads-" + System.identityHashCode(this),
true,
getThisClassLoader());
if (threadPoolMaxSize == -1)
{
threadPool = Executors.newCachedThreadPool(factory);
}
else
{
threadPool = Executors.newFixedThreadPool(threadPoolMaxSize, factory);
}
factory = new HornetQThreadFactory("HornetQ-client-factory-pinger-threads-" + System.identityHashCode(this),
true,
getThisClassLoader());
scheduledThreadPool = Executors.newScheduledThreadPool(scheduledThreadPoolMaxSize, factory);
}
}
private static ClassLoader getThisClassLoader()
{
return AccessController.doPrivileged(new PrivilegedAction<ClassLoader>()
{
public ClassLoader run()
{
return ClientSessionFactoryImpl.class.getClassLoader();
}
});
}
private void instantiateLoadBalancingPolicy()
{
if (connectionLoadBalancingPolicyClassName == null)
{
throw new IllegalStateException("Please specify a load balancing policy class name on the session factory");
}
AccessController.doPrivileged(new PrivilegedAction<Object>()
{
public Object run()
{
loadBalancingPolicy = (ConnectionLoadBalancingPolicy)ClassloadingUtil.newInstanceFromClassLoader(connectionLoadBalancingPolicyClassName);
return null;
}
});
}
private synchronized void initialise() throws HornetQException
{
if (state == STATE.INITIALIZED)
return;
synchronized (stateGuard)
{
if (state == STATE.CLOSING)
throw new HornetQIllegalStateException();
try
{
state = STATE.INITIALIZED;
latch = new CountDownLatch(1);
setThreadPools();
instantiateLoadBalancingPolicy();
if (discoveryGroupConfiguration != null)
{
discoveryGroup = createDiscoveryGroup(nodeID, discoveryGroupConfiguration);
discoveryGroup.registerListener(this);
discoveryGroup.start();
}
}
catch (Exception e)
{
state = null;
throw HornetQClientMessageBundle.BUNDLE.failedToInitialiseSessionFactory(e);
}
}
}
private static DiscoveryGroup createDiscoveryGroup(String nodeID, DiscoveryGroupConfiguration config) throws Exception
{
DiscoveryGroup group = new DiscoveryGroup(nodeID, config.getName(),
config.getRefreshTimeout(), config.getBroadcastEndpointFactoryConfiguration().createBroadcastEndpointFactory(), null);
return group;
}
private ServerLocatorImpl(final Topology topology,
final boolean useHA,
final DiscoveryGroupConfiguration discoveryGroupConfiguration,
final TransportConfiguration[] transportConfigs)
{
e.fillInStackTrace();
this.topology = topology == null ? new Topology(this) : topology;
this.ha = useHA;
this.discoveryGroupConfiguration = discoveryGroupConfiguration;
this.initialConnectors = transportConfigs;
this.nodeID = UUIDGenerator.getInstance().generateStringUUID();
clientFailureCheckPeriod = HornetQClient.DEFAULT_CLIENT_FAILURE_CHECK_PERIOD;
connectionTTL = HornetQClient.DEFAULT_CONNECTION_TTL;
callTimeout = HornetQClient.DEFAULT_CALL_TIMEOUT;
callFailoverTimeout = HornetQClient.DEFAULT_CALL_FAILOVER_TIMEOUT;
minLargeMessageSize = HornetQClient.DEFAULT_MIN_LARGE_MESSAGE_SIZE;
consumerWindowSize = HornetQClient.DEFAULT_CONSUMER_WINDOW_SIZE;
consumerMaxRate = HornetQClient.DEFAULT_CONSUMER_MAX_RATE;
confirmationWindowSize = HornetQClient.DEFAULT_CONFIRMATION_WINDOW_SIZE;
producerWindowSize = HornetQClient.DEFAULT_PRODUCER_WINDOW_SIZE;
producerMaxRate = HornetQClient.DEFAULT_PRODUCER_MAX_RATE;
blockOnAcknowledge = HornetQClient.DEFAULT_BLOCK_ON_ACKNOWLEDGE;
blockOnDurableSend = HornetQClient.DEFAULT_BLOCK_ON_DURABLE_SEND;
blockOnNonDurableSend = HornetQClient.DEFAULT_BLOCK_ON_NON_DURABLE_SEND;
autoGroup = HornetQClient.DEFAULT_AUTO_GROUP;
preAcknowledge = HornetQClient.DEFAULT_PRE_ACKNOWLEDGE;
ackBatchSize = HornetQClient.DEFAULT_ACK_BATCH_SIZE;
connectionLoadBalancingPolicyClassName = HornetQClient.DEFAULT_CONNECTION_LOAD_BALANCING_POLICY_CLASS_NAME;
useGlobalPools = HornetQClient.DEFAULT_USE_GLOBAL_POOLS;
scheduledThreadPoolMaxSize = HornetQClient.DEFAULT_SCHEDULED_THREAD_POOL_MAX_SIZE;
threadPoolMaxSize = HornetQClient.DEFAULT_THREAD_POOL_MAX_SIZE;
retryInterval = HornetQClient.DEFAULT_RETRY_INTERVAL;
retryIntervalMultiplier = HornetQClient.DEFAULT_RETRY_INTERVAL_MULTIPLIER;
maxRetryInterval = HornetQClient.DEFAULT_MAX_RETRY_INTERVAL;
reconnectAttempts = HornetQClient.DEFAULT_RECONNECT_ATTEMPTS;
initialConnectAttempts = HornetQClient.INITIAL_CONNECT_ATTEMPTS;
failoverOnInitialConnection = HornetQClient.DEFAULT_FAILOVER_ON_INITIAL_CONNECTION;
cacheLargeMessagesClient = HornetQClient.DEFAULT_CACHE_LARGE_MESSAGE_CLIENT;
initialMessagePacketSize = HornetQClient.DEFAULT_INITIAL_MESSAGE_PACKET_SIZE;
cacheLargeMessagesClient = HornetQClient.DEFAULT_CACHE_LARGE_MESSAGE_CLIENT;
compressLargeMessage = HornetQClient.DEFAULT_COMPRESS_LARGE_MESSAGES;
clusterConnection = false;
}
/**
* Create a ServerLocatorImpl using UDP discovery to lookup cluster
*/
public ServerLocatorImpl(final boolean useHA, final DiscoveryGroupConfiguration groupConfiguration)
{
this(new Topology(null), useHA, groupConfiguration, null);
if (useHA)
{
// We only set the owner at where the Topology was created.
// For that reason we can't set it at the main constructor
topology.setOwner(this);
}
}
/**
* Create a ServerLocatorImpl using a static list of live servers
*
* @param transportConfigs
*/
public ServerLocatorImpl(final boolean useHA, final TransportConfiguration... transportConfigs)
{
this(new Topology(null), useHA, null, transportConfigs);
if (useHA)
{
// We only set the owner at where the Topology was created.
// For that reason we can't set it at the main constructor
topology.setOwner(this);
}
}
/**
* Create a ServerLocatorImpl using UDP discovery to lookup cluster
*/
public ServerLocatorImpl(final Topology topology,
final boolean useHA,
final DiscoveryGroupConfiguration groupConfiguration)
{
this(topology, useHA, groupConfiguration, null);
}
/**
* Create a ServerLocatorImpl using a static list of live servers
*
* @param transportConfigs
*/
public ServerLocatorImpl(final Topology topology,
final boolean useHA,
final TransportConfiguration... transportConfigs)
{
this(topology, useHA, null, transportConfigs);
}
private synchronized TransportConfiguration selectConnector()
{
// if the ServerLocator is !had, we will always use the initialConnectors
// on that case if the ServerLocator was configured to be in-vm, it will always be in-vm no matter
// what updates were sent from the server
if (receivedTopology && ha)
{
synchronized (topologyArrayGuard)
{
int pos = loadBalancingPolicy.select(topologyArray.length);
Pair<TransportConfiguration, TransportConfiguration> pair = topologyArray[pos];
return pair.getA();
}
}
else
{
// Get from initialconnectors
int pos = loadBalancingPolicy.select(initialConnectors.length);
return initialConnectors[pos];
}
}
public void start(Executor executor) throws Exception
{
initialise();
this.startExecutor = executor;
if (executor != null)
{
executor.execute(new Runnable()
{
public void run()
{
try
{
connect();
}
catch (Exception e)
{
if (!isClosed())
{
HornetQClientLogger.LOGGER.errorConnectingToNodes(e);
}
}
}
});
}
}
public void disableFinalizeCheck()
{
finalizeCheck = false;
}
@Override
public ClientSessionFactoryInternal connect() throws HornetQException
{
return connect(false);
}
private ClientSessionFactoryInternal connect(final boolean skipWarnings) throws HornetQException
{
synchronized (this)
{
// static list of initial connectors
if (initialConnectors != null && discoveryGroup == null)
{
ClientSessionFactoryInternal sf = (ClientSessionFactoryInternal)staticConnector.connect(skipWarnings);
addFactory(sf);
return sf;
}
}
// wait for discovery group to get the list of initial connectors
return (ClientSessionFactoryInternal)createSessionFactory();
}
@Override
public ClientSessionFactoryInternal connectNoWarnings() throws HornetQException
{
return connect(true);
}
public void setAfterConnectionInternalListener(AfterConnectInternalListener listener)
{
this.afterConnectListener = listener;
}
public AfterConnectInternalListener getAfterConnectInternalListener()
{
return afterConnectListener;
}
public ClientSessionFactory createSessionFactory(String nodeID) throws Exception
{
TopologyMember topologyMember = topology.getMember(nodeID);
if (HornetQClientLogger.LOGGER.isTraceEnabled())
{
HornetQClientLogger.LOGGER.trace("Creating connection factory towards " + nodeID + " = " + topologyMember + ", topology=" + topology.describe());
}
if (topologyMember == null)
{
return null;
}
if (topologyMember.getLive() != null)
{
ClientSessionFactoryInternal factory = (ClientSessionFactoryInternal)createSessionFactory(topologyMember.getLive());
if (topologyMember.getBackup() != null)
{
factory.setBackupConnector(topologyMember.getLive(), topologyMember.getBackup());
}
return factory;
}
if (topologyMember.getLive() == null && topologyMember.getBackup() != null)
{
// This shouldn't happen, however I wanted this to consider all possible cases
ClientSessionFactoryInternal factory = (ClientSessionFactoryInternal)createSessionFactory(topologyMember.getBackup());
return factory;
}
// it shouldn't happen
return null;
}
public ClientSessionFactory createSessionFactory(final TransportConfiguration transportConfiguration) throws Exception
{
assertOpen();
initialise();
ClientSessionFactoryInternal factory = new ClientSessionFactoryImpl(this,
transportConfiguration,
callTimeout,
callFailoverTimeout,
clientFailureCheckPeriod,
connectionTTL,
retryInterval,
retryIntervalMultiplier,
maxRetryInterval,
reconnectAttempts,
threadPool,
scheduledThreadPool,
incomingInterceptors,
outgoingInterceptors,
packetDecoder);
addToConnecting(factory);
try
{
try
{
factory.connect(reconnectAttempts, failoverOnInitialConnection);
}
catch (HornetQException e1)
{
//we need to make sure is closed just for garbage collection
factory.close();
throw e1;
}
addFactory(factory);
return factory;
}
finally
{
removeFromConnecting(factory);
}
}
public ClientSessionFactory createSessionFactory(final TransportConfiguration transportConfiguration, int reconnectAttempts, boolean failoverOnInitialConnection) throws Exception
{
assertOpen();
initialise();
ClientSessionFactoryInternal factory = new ClientSessionFactoryImpl(this,
transportConfiguration,
callTimeout,
callFailoverTimeout,
clientFailureCheckPeriod,
connectionTTL,
retryInterval,
retryIntervalMultiplier,
maxRetryInterval,
reconnectAttempts,
threadPool,
scheduledThreadPool,
incomingInterceptors,
outgoingInterceptors,
packetDecoder);
addToConnecting(factory);
try
{
try
{
factory.connect(reconnectAttempts, failoverOnInitialConnection);
}
catch (HornetQException e1)
{
//we need to make sure is closed just for garbage collection
factory.close();
throw e1;
}
addFactory(factory);
return factory;
}
finally
{
removeFromConnecting(factory);
}
}
private void removeFromConnecting(ClientSessionFactoryInternal factory)
{
synchronized (connectingFactories)
{
connectingFactories.remove(factory);
}
}
private void addToConnecting(ClientSessionFactoryInternal factory)
{
synchronized (connectingFactories)
{
assertOpen();
connectingFactories.add(factory);
}
}
public ClientSessionFactory createSessionFactory() throws HornetQException
{
assertOpen();
initialise();
if (initialConnectors == null && discoveryGroup != null)
{
// Wait for an initial broadcast to give us at least one node in the cluster
long timeout = clusterConnection ? 0 : discoveryGroupConfiguration.getDiscoveryInitialWaitTimeout();
boolean ok = discoveryGroup.waitForBroadcast(timeout);
if (!ok)
{
throw HornetQClientMessageBundle.BUNDLE.connectionTimedOutInInitialBroadcast();
}
}
ClientSessionFactoryInternal factory = null;
synchronized (this)
{
boolean retry;
int attempts = 0;
do
{
retry = false;
TransportConfiguration tc = selectConnector();
if (tc == null)
{
throw HornetQClientMessageBundle.BUNDLE.noTCForSessionFactory();
}
// try each factory in the list until we find one which works
try
{
factory = new ClientSessionFactoryImpl(this,
tc,
callTimeout,
callFailoverTimeout,
clientFailureCheckPeriod,
connectionTTL,
retryInterval,
retryIntervalMultiplier,
maxRetryInterval,
reconnectAttempts,
threadPool,
scheduledThreadPool,
incomingInterceptors,
outgoingInterceptors,
packetDecoder);
try
{
addToConnecting(factory);
factory.connect(initialConnectAttempts, failoverOnInitialConnection);
}
finally
{
removeFromConnecting(factory);
}
}
catch (HornetQException e)
{
factory.close();
factory = null;
if (e.getType() == HornetQExceptionType.NOT_CONNECTED)
{
attempts++;
synchronized (topologyArrayGuard)
{
if (topologyArray != null && attempts == topologyArray.length)
{
throw HornetQClientMessageBundle.BUNDLE.cannotConnectToServers();
}
if (topologyArray == null && initialConnectors != null && attempts == initialConnectors.length)
{
throw HornetQClientMessageBundle.BUNDLE.cannotConnectToServers();
}
}
retry = true;
}
else
{
throw e;
}
}
}
while (retry);
// We always wait for the topology, as the server
// will send a single element if not cluster
// so clients can know the id of the server they are connected to
final long timeout = System.currentTimeMillis() + callTimeout;
while (!isClosed() && !receivedTopology && timeout > System.currentTimeMillis())
{
// Now wait for the topology
try
{
wait(1000);
}
catch (InterruptedException ignore)
{
}
}
if (isClosed() || !receivedTopology)
{
if (factory != null)
factory.cleanup();
throw HornetQClientMessageBundle.BUNDLE.connectionTimedOutOnReceiveTopology(discoveryGroup);
}
addFactory(factory);
return factory;
}
}
public boolean isHA()
{
return ha;
}
public boolean isCacheLargeMessagesClient()
{
return cacheLargeMessagesClient;
}
public void setCacheLargeMessagesClient(final boolean cached)
{
cacheLargeMessagesClient = cached;
}
public long getClientFailureCheckPeriod()
{
return clientFailureCheckPeriod;
}
public void setClientFailureCheckPeriod(final long clientFailureCheckPeriod)
{
checkWrite();
this.clientFailureCheckPeriod = clientFailureCheckPeriod;
}
public long getConnectionTTL()
{
return connectionTTL;
}
public void setConnectionTTL(final long connectionTTL)
{
checkWrite();
this.connectionTTL = connectionTTL;
}
public long getCallTimeout()
{
return callTimeout;
}
public void setCallTimeout(final long callTimeout)
{
checkWrite();
this.callTimeout = callTimeout;
}
public long getCallFailoverTimeout()
{
return callFailoverTimeout;
}
public void setCallFailoverTimeout(long callFailoverTimeout)
{
checkWrite();
this.callFailoverTimeout = callFailoverTimeout;
}
public int getMinLargeMessageSize()
{
return minLargeMessageSize;
}
public void setMinLargeMessageSize(final int minLargeMessageSize)
{
checkWrite();
this.minLargeMessageSize = minLargeMessageSize;
}
public int getConsumerWindowSize()
{
return consumerWindowSize;
}
public void setConsumerWindowSize(final int consumerWindowSize)
{
checkWrite();
this.consumerWindowSize = consumerWindowSize;
}
public int getConsumerMaxRate()
{
return consumerMaxRate;
}
public void setConsumerMaxRate(final int consumerMaxRate)
{
checkWrite();
this.consumerMaxRate = consumerMaxRate;
}
public int getConfirmationWindowSize()
{
return confirmationWindowSize;
}
public void setConfirmationWindowSize(final int confirmationWindowSize)
{
checkWrite();
this.confirmationWindowSize = confirmationWindowSize;
}
public int getProducerWindowSize()
{
return producerWindowSize;
}
public void setProducerWindowSize(final int producerWindowSize)
{
checkWrite();
this.producerWindowSize = producerWindowSize;
}
public int getProducerMaxRate()
{
return producerMaxRate;
}