ActiveMQ5.6.0中ActiveMQConnection类源码介绍

来源:互联网 发布:农村淘宝地址怎么填写 编辑:程序博客网 时间:2024/05/14 05:50

ActiveMQConnection类源码,删掉了部分属性的get、set方法

public class ActiveMQConnection implements Connection, TopicConnection, QueueConnection, StatsCapable, Closeable, StreamConnection, TransportListener, EnhancedConnection {    public static final String DEFAULT_USER;    public static final String DEFAULT_PASSWORD;    public static final String DEFAULT_BROKER_URL = "failover://tcp://localhost:61616";    private static final Logger LOG;    public final ConcurrentHashMap<ActiveMQTempDestination, ActiveMQTempDestination> activeTempDestinations = new ConcurrentHashMap();    protected boolean dispatchAsync = true;    protected boolean alwaysSessionAsync = true;    private TaskRunnerFactory sessionTaskRunner;    private final ThreadPoolExecutor executor;    private final ConnectionInfo info;    private ExceptionListener exceptionListener;    private ClientInternalExceptionListener clientInternalExceptionListener;    private boolean clientIDSet;    private boolean isConnectionInfoSentToBroker;    private boolean userSpecifiedClientID;    private ActiveMQPrefetchPolicy prefetchPolicy = new ActiveMQPrefetchPolicy();    private BlobTransferPolicy blobTransferPolicy;    private RedeliveryPolicy redeliveryPolicy;    private MessageTransformer transformer;    private boolean disableTimeStampsByDefault;    private boolean optimizedMessageDispatch = true;    private boolean copyMessageOnSend = true;    private boolean useCompression;    private boolean objectMessageSerializationDefered;    private boolean useAsyncSend;    private boolean optimizeAcknowledge;    private long optimizeAcknowledgeTimeOut = 0L;    private boolean nestedMapAndListEnabled = true;    private boolean useRetroactiveConsumer;    private boolean exclusiveConsumer;    private boolean alwaysSyncSend;    private int closeTimeout = 15000;    private boolean watchTopicAdvisories = true;    private long warnAboutUnstartedConnectionTimeout = 500L;    private int sendTimeout = 0;    private boolean sendAcksAsync = true;    private boolean checkForDuplicates = true;    private final Transport transport;    private final IdGenerator clientIdGenerator;    private final JMSStatsImpl factoryStats;    private final JMSConnectionStatsImpl stats;    private final AtomicBoolean started = new AtomicBoolean(false);    private final AtomicBoolean closing = new AtomicBoolean(false);    private final AtomicBoolean closed = new AtomicBoolean(false);    private final AtomicBoolean transportFailed = new AtomicBoolean(false);    private final CopyOnWriteArrayList<ActiveMQSession> sessions = new CopyOnWriteArrayList();    private final CopyOnWriteArrayList<ActiveMQConnectionConsumer> connectionConsumers = new CopyOnWriteArrayList();    private final CopyOnWriteArrayList<ActiveMQInputStream> inputStreams = new CopyOnWriteArrayList();    private final CopyOnWriteArrayList<ActiveMQOutputStream> outputStreams = new CopyOnWriteArrayList();    private final CopyOnWriteArrayList<TransportListener> transportListeners = new CopyOnWriteArrayList();    private final ConcurrentHashMap<ConsumerId, ActiveMQDispatcher> dispatchers = new ConcurrentHashMap();    private final ConcurrentHashMap<ProducerId, ActiveMQMessageProducer> producers = new ConcurrentHashMap();    private final LongSequenceGenerator sessionIdGenerator = new LongSequenceGenerator();    private final SessionId connectionSessionId;    private final LongSequenceGenerator consumerIdGenerator = new LongSequenceGenerator();    private final LongSequenceGenerator producerIdGenerator = new LongSequenceGenerator();    private final LongSequenceGenerator tempDestinationIdGenerator = new LongSequenceGenerator();    private final LongSequenceGenerator localTransactionIdGenerator = new LongSequenceGenerator();    private AdvisoryConsumer advisoryConsumer;    private final CountDownLatch brokerInfoReceived = new CountDownLatch(1);    private BrokerInfo brokerInfo;    private IOException firstFailureError;    private int producerWindowSize = 0;    private final AtomicInteger protocolVersion = new AtomicInteger(9);    private final long timeCreated;    private final ConnectionAudit connectionAudit = new ConnectionAudit();    private DestinationSource destinationSource;    private final Object ensureConnectionInfoSentMutex = new Object();    private boolean useDedicatedTaskRunner;    protected volatile CountDownLatch transportInterruptionProcessingComplete;    private long consumerFailoverRedeliveryWaitPeriod;    private Scheduler scheduler;    private boolean messagePrioritySupported = true;    private boolean transactedIndividualAck = false;    private boolean nonBlockingRedelivery = false;    protected ActiveMQConnection(final Transport transport, IdGenerator clientIdGenerator, IdGenerator connectionIdGenerator, JMSStatsImpl factoryStats) throws Exception {        this.transport = transport;        this.clientIdGenerator = clientIdGenerator;        this.factoryStats = factoryStats;        this.executor = new ThreadPoolExecutor(1, 1, 5L, TimeUnit.SECONDS, new LinkedBlockingQueue(), new ThreadFactory() {            public Thread newThread(Runnable r) {                Thread thread = new Thread(r, "ActiveMQ Connection Executor: " + transport);                return thread;            }        });        String uniqueId = connectionIdGenerator.generateId();        this.info = new ConnectionInfo(new ConnectionId(uniqueId));        this.info.setManageable(true);        this.info.setFaultTolerant(transport.isFaultTolerant());        this.connectionSessionId = new SessionId(this.info.getConnectionId(), -1L);        this.transport.setTransportListener(this);        this.stats = new JMSConnectionStatsImpl(this.sessions, this instanceof XAConnection);        this.factoryStats.addConnection(this);        this.timeCreated = System.currentTimeMillis();        this.connectionAudit.setCheckForDuplicates(transport.isFaultTolerant());    }    public static ActiveMQConnection makeConnection() throws JMSException {        ActiveMQConnectionFactory factory = new ActiveMQConnectionFactory();        return (ActiveMQConnection)factory.createConnection();    }    public static ActiveMQConnection makeConnection(String uri) throws JMSException, URISyntaxException {        ActiveMQConnectionFactory factory = new ActiveMQConnectionFactory(uri);        return (ActiveMQConnection)factory.createConnection();    }    public static ActiveMQConnection makeConnection(String user, String password, String uri) throws JMSException, URISyntaxException {        ActiveMQConnectionFactory factory = new ActiveMQConnectionFactory(user, password, new URI(uri));        return (ActiveMQConnection)factory.createConnection();    }    public JMSConnectionStatsImpl getConnectionStats() {        return this.stats;    }    public Session createSession(boolean transacted, int acknowledgeMode) throws JMSException {        this.checkClosedOrFailed();        this.ensureConnectionInfoSent();        if(!transacted) {            if(acknowledgeMode == 0) {                throw new JMSException("acknowledgeMode SESSION_TRANSACTED cannot be used for an non-transacted Session");            }            if(acknowledgeMode < 0 || acknowledgeMode > 4) {                throw new JMSException("invalid acknowledgeMode: " + acknowledgeMode + ". Valid values are Session.AUTO_ACKNOWLEDGE (1), " + "Session.CLIENT_ACKNOWLEDGE (2), Session.DUPS_OK_ACKNOWLEDGE (3), ActiveMQSession.INDIVIDUAL_ACKNOWLEDGE (4) or for transacted sessions Session.SESSION_TRANSACTED (0)");            }        }        return new ActiveMQSession(this, this.getNextSessionId(), transacted?0:(acknowledgeMode == 0?1:acknowledgeMode), this.isDispatchAsync(), this.isAlwaysSessionAsync());    }    protected SessionId getNextSessionId() {        return new SessionId(this.info.getConnectionId(), this.sessionIdGenerator.getNextSequenceId());    }    public String getClientID() throws JMSException {        this.checkClosedOrFailed();        return this.info.getClientId();    }    public void setClientID(String newClientID) throws JMSException {        this.checkClosedOrFailed();        if(this.clientIDSet) {            throw new IllegalStateException("The clientID has already been set");        } else if(this.isConnectionInfoSentToBroker) {            throw new IllegalStateException("Setting clientID on a used Connection is not allowed");        } else {            this.info.setClientId(newClientID);            this.userSpecifiedClientID = true;            this.ensureConnectionInfoSent();        }    }    public void setDefaultClientID(String clientID) throws JMSException {        this.info.setClientId(clientID);        this.userSpecifiedClientID = true;    }    public ConnectionMetaData getMetaData() throws JMSException {        this.checkClosedOrFailed();        return ActiveMQConnectionMetaData.INSTANCE;    }    public ExceptionListener getExceptionListener() throws JMSException {        this.checkClosedOrFailed();        return this.exceptionListener;    }    public void setExceptionListener(ExceptionListener listener) throws JMSException {        this.checkClosedOrFailed();        this.exceptionListener = listener;    }    public ClientInternalExceptionListener getClientInternalExceptionListener() {        return this.clientInternalExceptionListener;    }    public void setClientInternalExceptionListener(ClientInternalExceptionListener listener) {        this.clientInternalExceptionListener = listener;    }    public void start() throws JMSException {        this.checkClosedOrFailed();        this.ensureConnectionInfoSent();        if(this.started.compareAndSet(false, true)) {            Iterator i = this.sessions.iterator();            while(i.hasNext()) {                ActiveMQSession session = (ActiveMQSession)i.next();                session.start();            }        }    }    public void stop() throws JMSException {        this.checkClosedOrFailed();        if(this.started.compareAndSet(true, false)) {            CopyOnWriteArrayList var1 = this.sessions;            synchronized(this.sessions) {                Iterator i = this.sessions.iterator();                while(i.hasNext()) {                    ActiveMQSession s = (ActiveMQSession)i.next();                    s.stop();                }            }        }    }    public void close() throws JMSException {        boolean interrupted = Thread.interrupted();        try {            if(!this.closed.get() && !this.transportFailed.get()) {                this.stop();            }            synchronized(this) {                if(!this.closed.get()) {                    this.closing.set(true);                    if(this.destinationSource != null) {                        this.destinationSource.stop();                        this.destinationSource = null;                    }                    if(this.advisoryConsumer != null) {                        this.advisoryConsumer.dispose();                        this.advisoryConsumer = null;                    }                    Scheduler scheduler = this.scheduler;                    if(scheduler != null) {                        try {                            scheduler.stop();                        } catch (Exception var17) {                            JMSException ex = JMSExceptionSupport.create(var17);                            throw ex;                        }                    }                    long lastDeliveredSequenceId = 0L;                    Iterator removeCommand;                    ActiveMQSession c;                    for(removeCommand = this.sessions.iterator(); removeCommand.hasNext(); lastDeliveredSequenceId = Math.max(lastDeliveredSequenceId, c.getLastDeliveredSequenceId())) {                        c = (ActiveMQSession)removeCommand.next();                        c.dispose();                    }                    removeCommand = this.connectionConsumers.iterator();                    while(removeCommand.hasNext()) {                        ActiveMQConnectionConsumer c1 = (ActiveMQConnectionConsumer)removeCommand.next();                        c1.dispose();                    }                    removeCommand = this.inputStreams.iterator();                    while(removeCommand.hasNext()) {                        ActiveMQInputStream c2 = (ActiveMQInputStream)removeCommand.next();                        c2.dispose();                    }                    removeCommand = this.outputStreams.iterator();                    while(removeCommand.hasNext()) {                        ActiveMQOutputStream c3 = (ActiveMQOutputStream)removeCommand.next();                        c3.dispose();                    }                    removeCommand = this.activeTempDestinations.values().iterator();                    while(removeCommand.hasNext()) {                        ActiveMQTempDestination c4 = (ActiveMQTempDestination)removeCommand.next();                        c4.delete();                    }                    if(this.isConnectionInfoSentToBroker) {                        RemoveInfo removeCommand1 = this.info.createRemoveCommand();                        removeCommand1.setLastDeliveredSequenceId(lastDeliveredSequenceId);                        this.doSyncSendPacket(this.info.createRemoveCommand(), this.closeTimeout);                        this.doAsyncSendPacket(new ShutdownInfo());                    }                    this.started.set(false);                    if(this.sessionTaskRunner != null) {                        this.sessionTaskRunner.shutdown();                    }                    this.closed.set(true);                    this.closing.set(false);                }            }        } finally {            try {                if(this.executor != null) {                    this.executor.shutdown();                }            } catch (Throwable var16) {                LOG.error("Error shutting down thread pool " + var16, var16);            }            ServiceSupport.dispose(this.transport);            this.factoryStats.removeConnection(this);            if(interrupted) {                Thread.currentThread().interrupt();            }        }    }    public ConnectionConsumer createDurableConnectionConsumer(Topic topic, String subscriptionName, String messageSelector, ServerSessionPool sessionPool, int maxMessages) throws JMSException {        return this.createDurableConnectionConsumer(topic, subscriptionName, messageSelector, sessionPool, maxMessages, false);    }    public ConnectionConsumer createDurableConnectionConsumer(Topic topic, String subscriptionName, String messageSelector, ServerSessionPool sessionPool, int maxMessages, boolean noLocal) throws JMSException {        this.checkClosedOrFailed();        this.ensureConnectionInfoSent();        SessionId sessionId = new SessionId(this.info.getConnectionId(), -1L);        ConsumerInfo info = new ConsumerInfo(new ConsumerId(sessionId, this.consumerIdGenerator.getNextSequenceId()));        info.setDestination(ActiveMQMessageTransformation.transformDestination(topic));        info.setSubscriptionName(subscriptionName);        info.setSelector(messageSelector);        info.setPrefetchSize(maxMessages);        info.setDispatchAsync(this.isDispatchAsync());        if(info.getDestination().getOptions() != null) {            HashMap options = new HashMap(info.getDestination().getOptions());            IntrospectionSupport.setProperties(this.info, options, "consumer.");        }        return new ActiveMQConnectionConsumer(this, sessionPool, info);    }    public boolean isStarted() {        return this.started.get();    }    public boolean isClosed() {        return this.closed.get();    }    public boolean isClosing() {        return this.closing.get();    }    public boolean isTransportFailed() {        return this.transportFailed.get();    }    public ActiveMQPrefetchPolicy getPrefetchPolicy() {        return this.prefetchPolicy;    }    public void setPrefetchPolicy(ActiveMQPrefetchPolicy prefetchPolicy) {        this.prefetchPolicy = prefetchPolicy;    }    public Transport getTransportChannel() {        return this.transport;    }    public String getInitializedClientID() throws JMSException {        this.ensureConnectionInfoSent();        return this.info.getClientId();    }    public boolean isDisableTimeStampsByDefault() {        return this.disableTimeStampsByDefault;    }    public void setDisableTimeStampsByDefault(boolean timeStampsDisableByDefault) {        this.disableTimeStampsByDefault = timeStampsDisableByDefault;    }    public boolean isOptimizedMessageDispatch() {        return this.optimizedMessageDispatch;    }    public void setOptimizedMessageDispatch(boolean dispatchOptimizedMessage) {        this.optimizedMessageDispatch = dispatchOptimizedMessage;    }    public int getCloseTimeout() {        return this.closeTimeout;    }    public void setCloseTimeout(int closeTimeout) {        this.closeTimeout = closeTimeout;    }    public ConnectionInfo getConnectionInfo() {        return this.info;    }    public boolean isUseRetroactiveConsumer() {        return this.useRetroactiveConsumer;    }    public void setUseRetroactiveConsumer(boolean useRetroactiveConsumer) {        this.useRetroactiveConsumer = useRetroactiveConsumer;    }    public boolean isNestedMapAndListEnabled() {        return this.nestedMapAndListEnabled;    }    public void setNestedMapAndListEnabled(boolean structuredMapsEnabled) {        this.nestedMapAndListEnabled = structuredMapsEnabled;    }    public boolean isExclusiveConsumer() {        return this.exclusiveConsumer;    }    public void setExclusiveConsumer(boolean exclusiveConsumer) {        this.exclusiveConsumer = exclusiveConsumer;    }    public void addTransportListener(TransportListener transportListener) {        this.transportListeners.add(transportListener);    }    public void removeTransportListener(TransportListener transportListener) {        this.transportListeners.remove(transportListener);    }    public TaskRunnerFactory getSessionTaskRunner() {        synchronized(this) {            if(this.sessionTaskRunner == null) {                this.sessionTaskRunner = new TaskRunnerFactory("ActiveMQ Session Task", 7, false, 1000, this.isUseDedicatedTaskRunner());            }        }        return this.sessionTaskRunner;    }    public void setSessionTaskRunner(TaskRunnerFactory sessionTaskRunner) {        this.sessionTaskRunner = sessionTaskRunner;    }    public DestinationSource getDestinationSource() throws JMSException {        if(this.destinationSource == null) {            this.destinationSource = new DestinationSource(this);            this.destinationSource.start();        }        return this.destinationSource;    }    protected void addSession(ActiveMQSession session) throws JMSException {        this.sessions.add(session);        if(this.sessions.size() > 1 || session.isTransacted()) {            this.optimizedMessageDispatch = false;        }    }    protected void removeSession(ActiveMQSession session) {        this.sessions.remove(session);        this.removeDispatcher((ActiveMQDispatcher)session);    }    protected void addConnectionConsumer(ActiveMQConnectionConsumer connectionConsumer) throws JMSException {        this.connectionConsumers.add(connectionConsumer);    }    protected void removeConnectionConsumer(ActiveMQConnectionConsumer connectionConsumer) {        this.connectionConsumers.remove(connectionConsumer);        this.removeDispatcher((ActiveMQDispatcher)connectionConsumer);    }    public TopicSession createTopicSession(boolean transacted, int acknowledgeMode) throws JMSException {        return new ActiveMQTopicSession((ActiveMQSession)this.createSession(transacted, acknowledgeMode));    }    public ConnectionConsumer createConnectionConsumer(Destination destination, String messageSelector, ServerSessionPool sessionPool, int maxMessages, boolean noLocal) throws JMSException {        this.checkClosedOrFailed();        this.ensureConnectionInfoSent();        ConsumerId consumerId = this.createConsumerId();        ConsumerInfo consumerInfo = new ConsumerInfo(consumerId);        consumerInfo.setDestination(ActiveMQMessageTransformation.transformDestination(destination));        consumerInfo.setSelector(messageSelector);        consumerInfo.setPrefetchSize(maxMessages);        consumerInfo.setNoLocal(noLocal);        consumerInfo.setDispatchAsync(this.isDispatchAsync());        if(consumerInfo.getDestination().getOptions() != null) {            HashMap options = new HashMap(consumerInfo.getDestination().getOptions());            IntrospectionSupport.setProperties(consumerInfo, options, "consumer.");        }        return new ActiveMQConnectionConsumer(this, sessionPool, consumerInfo);    }    private ConsumerId createConsumerId() {        return new ConsumerId(this.connectionSessionId, this.consumerIdGenerator.getNextSequenceId());    }    private ProducerId createProducerId() {        return new ProducerId(this.connectionSessionId, this.producerIdGenerator.getNextSequenceId());    }    public QueueSession createQueueSession(boolean transacted, int acknowledgeMode) throws JMSException {        return new ActiveMQQueueSession((ActiveMQSession)this.createSession(transacted, acknowledgeMode));    }    public void checkClientIDWasManuallySpecified() throws JMSException {        if(!this.userSpecifiedClientID) {            throw new JMSException("You cannot create a durable subscriber without specifying a unique clientID on a Connection");        }    }    public void asyncSendPacket(Command command) throws JMSException {        if(this.isClosed()) {            throw new ConnectionClosedException();        } else {            this.doAsyncSendPacket(command);        }    }    private void doAsyncSendPacket(Command command) throws JMSException {        try {            this.transport.oneway(command);        } catch (IOException var3) {            throw JMSExceptionSupport.create(var3);        }    }    public void syncSendPacket(Command command, final AsyncCallback onComplete) throws JMSException {        if(onComplete == null) {            this.syncSendPacket(command);        } else {            if(this.isClosed()) {                throw new ConnectionClosedException();            }            try {                this.transport.asyncRequest(command, new ResponseCallback() {                    public void onCompletion(FutureResponse resp) {                        Object exception = null;                        try {                            Response response = resp.getResult();                            if(response.isException()) {                                ExceptionResponse jmsEx = (ExceptionResponse)response;                                exception = jmsEx.getException();                            }                        } catch (Exception var7) {                            exception = var7;                        }                        if(exception != null) {                            if(exception instanceof JMSException) {                                onComplete.onException((JMSException)exception);                            } else {                                if(ActiveMQConnection.this.isClosed() || ActiveMQConnection.this.closing.get()) {                                    ActiveMQConnection.LOG.debug("Received an exception but connection is closing");                                }                                JMSException jmsEx1 = null;                                try {                                    jmsEx1 = JMSExceptionSupport.create((Throwable)exception);                                } catch (Throwable var6) {                                    ActiveMQConnection.LOG.error("Caught an exception trying to create a JMSException for " + exception, var6);                                }                                if(exception instanceof SecurityException) {                                    Transport t = ActiveMQConnection.this.transport;                                    if(null != t) {                                        ServiceSupport.dispose(t);                                    }                                }                                if(jmsEx1 != null) {                                    onComplete.onException(jmsEx1);                                }                            }                        } else {                            onComplete.onSuccess();                        }                    }                });            } catch (IOException var4) {                throw JMSExceptionSupport.create(var4);            }        }    }    public Response syncSendPacket(Command command) throws JMSException {        if(this.isClosed()) {            throw new ConnectionClosedException();        } else {            try {                Response e = (Response)this.transport.request(command);                if(e.isException()) {                    ExceptionResponse er = (ExceptionResponse)e;                    if(er.getException() instanceof JMSException) {                        throw (JMSException)er.getException();                    }                    if(this.isClosed() || this.closing.get()) {                        LOG.debug("Received an exception but connection is closing");                    }                    JMSException jmsEx = null;                    try {                        jmsEx = JMSExceptionSupport.create(er.getException());                    } catch (Throwable var6) {                        LOG.error("Caught an exception trying to create a JMSException for " + er.getException(), var6);                    }                    if(er.getException() instanceof SecurityException) {                        Transport t = this.transport;                        if(null != t) {                            ServiceSupport.dispose(t);                        }                    }                    if(jmsEx != null) {                        throw jmsEx;                    }                }                return e;            } catch (IOException var7) {                throw JMSExceptionSupport.create(var7);            }        }    }    public Response syncSendPacket(Command command, int timeout) throws JMSException {        if(!this.isClosed() && !this.closing.get()) {            return this.doSyncSendPacket(command, timeout);        } else {            throw new ConnectionClosedException();        }    }    private Response doSyncSendPacket(Command command, int timeout) throws JMSException {        try {            Response e = (Response)(timeout > 0?this.transport.request(command, timeout):this.transport.request(command));            if(e != null && e.isException()) {                ExceptionResponse er = (ExceptionResponse)e;                if(er.getException() instanceof JMSException) {                    throw (JMSException)er.getException();                } else {                    throw JMSExceptionSupport.create(er.getException());                }            } else {                return e;            }        } catch (IOException var5) {            throw JMSExceptionSupport.create(var5);        }    }    public StatsImpl getStats() {        return this.stats;    }    protected synchronized void checkClosedOrFailed() throws JMSException {        this.checkClosed();        if(this.transportFailed.get()) {            throw new ConnectionFailedException(this.firstFailureError);        }    }    protected synchronized void checkClosed() throws JMSException {        if(this.closed.get()) {            throw new ConnectionClosedException();        }    }    protected void ensureConnectionInfoSent() throws JMSException {        Object var1 = this.ensureConnectionInfoSentMutex;        synchronized(this.ensureConnectionInfoSentMutex) {            if(!this.isConnectionInfoSentToBroker && !this.closed.get()) {                if(this.info.getClientId() == null || this.info.getClientId().trim().length() == 0) {                    this.info.setClientId(this.clientIdGenerator.generateId());                }                this.syncSendPacket(this.info.copy());                this.isConnectionInfoSentToBroker = true;                ConsumerId consumerId = new ConsumerId(new SessionId(this.info.getConnectionId(), -1L), this.consumerIdGenerator.getNextSequenceId());                if(this.watchTopicAdvisories) {                    this.advisoryConsumer = new AdvisoryConsumer(this, consumerId);                }            }        }    }    public synchronized boolean isWatchTopicAdvisories() {        return this.watchTopicAdvisories;    }    public synchronized void setWatchTopicAdvisories(boolean watchTopicAdvisories) {        this.watchTopicAdvisories = watchTopicAdvisories;    }    public void cleanup() throws JMSException {        if(this.advisoryConsumer != null && !this.isTransportFailed()) {            this.advisoryConsumer.dispose();            this.advisoryConsumer = null;        }        Iterator i = this.sessions.iterator();        while(i.hasNext()) {            ActiveMQSession c = (ActiveMQSession)i.next();            c.dispose();        }        i = this.connectionConsumers.iterator();        while(i.hasNext()) {            ActiveMQConnectionConsumer c1 = (ActiveMQConnectionConsumer)i.next();            c1.dispose();        }        i = this.inputStreams.iterator();        while(i.hasNext()) {            ActiveMQInputStream c2 = (ActiveMQInputStream)i.next();            c2.dispose();        }        i = this.outputStreams.iterator();        while(i.hasNext()) {            ActiveMQOutputStream c3 = (ActiveMQOutputStream)i.next();            c3.dispose();        }        if(this.isConnectionInfoSentToBroker) {            if(!this.transportFailed.get() && !this.closing.get()) {                this.syncSendPacket(this.info.createRemoveCommand());            }            this.isConnectionInfoSentToBroker = false;        }        if(this.userSpecifiedClientID) {            this.info.setClientId((String)null);            this.userSpecifiedClientID = false;        }        this.clientIDSet = false;        this.started.set(false);    }    public void finalize() throws Throwable {        Scheduler s = this.scheduler;        if(s != null) {            s.stop();        }    }    public void changeUserInfo(String userName, String password) throws JMSException {        if(this.isConnectionInfoSentToBroker) {            throw new IllegalStateException("changeUserInfo used Connection is not allowed");        } else {            this.info.setUserName(userName);            this.info.setPassword(password);        }    }    public String getResourceManagerId() throws JMSException {        this.waitForBrokerInfo();        if(this.brokerInfo == null) {            throw new JMSException("Connection failed before Broker info was received.");        } else {            return this.brokerInfo.getBrokerId().getValue();        }    }    public String getBrokerName() {        try {            this.brokerInfoReceived.await(5L, TimeUnit.SECONDS);            return this.brokerInfo == null?null:this.brokerInfo.getBrokerName();        } catch (InterruptedException var2) {            Thread.currentThread().interrupt();            return null;        }    }    public BrokerInfo getBrokerInfo() {        return this.brokerInfo;    }    public BlobTransferPolicy getBlobTransferPolicy() {        if(this.blobTransferPolicy == null) {            this.blobTransferPolicy = this.createBlobTransferPolicy();        }        return this.blobTransferPolicy;    }    public void setBlobTransferPolicy(BlobTransferPolicy blobTransferPolicy) {        this.blobTransferPolicy = blobTransferPolicy;    }    public long getTimeCreated() {        return this.timeCreated;    }    private void waitForBrokerInfo() throws JMSException {        try {            this.brokerInfoReceived.await();        } catch (InterruptedException var2) {            Thread.currentThread().interrupt();            throw JMSExceptionSupport.create(var2);        }    }    public Transport getTransport() {        return this.transport;    }    public void addProducer(ProducerId producerId, ActiveMQMessageProducer producer) {        this.producers.put(producerId, producer);    }    public void removeProducer(ProducerId producerId) {        this.producers.remove(producerId);    }    public void addDispatcher(ConsumerId consumerId, ActiveMQDispatcher dispatcher) {        this.dispatchers.put(consumerId, dispatcher);    }    public void removeDispatcher(ConsumerId consumerId) {        this.dispatchers.remove(consumerId);    }    public void onCommand(Object o) {        final Command command = (Command)o;        if(!this.closed.get() && command != null) {            try {                command.visit(new CommandVisitorAdapter() {                    public Response processMessageDispatch(MessageDispatch md) throws Exception {                        ActiveMQConnection.this.waitForTransportInterruptionProcessingToComplete();                        ActiveMQDispatcher dispatcher = (ActiveMQDispatcher)ActiveMQConnection.this.dispatchers.get(md.getConsumerId());                        if(dispatcher != null) {                            Message msg = md.getMessage();                            if(msg != null) {                                msg = msg.copy();                                msg.setReadOnlyBody(true);                                msg.setReadOnlyProperties(true);                                msg.setRedeliveryCounter(md.getRedeliveryCounter());                                msg.setConnection(ActiveMQConnection.this);                                md.setMessage(msg);                            }                            dispatcher.dispatch(md);                        }                        return null;                    }                    public Response processProducerAck(ProducerAck pa) throws Exception {                        if(pa != null && pa.getProducerId() != null) {                            ActiveMQMessageProducer producer = (ActiveMQMessageProducer)ActiveMQConnection.this.producers.get(pa.getProducerId());                            if(producer != null) {                                producer.onProducerAck(pa);                            }                        }                        return null;                    }                    public Response processBrokerInfo(BrokerInfo info) throws Exception {                        ActiveMQConnection.this.brokerInfo = info;                        ActiveMQConnection.this.brokerInfoReceived.countDown();                        ActiveMQConnection.access$772(ActiveMQConnection.this, !ActiveMQConnection.this.brokerInfo.isFaultTolerantConfiguration()?1:0);                        ActiveMQConnection.this.getBlobTransferPolicy().setBrokerUploadUrl(info.getBrokerUploadUrl());                        return null;                    }                    public Response processConnectionError(final ConnectionError error) throws Exception {                        ActiveMQConnection.this.executor.execute(new Runnable() {                            public void run() {                                ActiveMQConnection.this.onAsyncException(error.getException());                            }                        });                        return null;                    }                    public Response processControlCommand(ControlCommand commandx) throws Exception {                        ActiveMQConnection.this.onControlCommand(commandx);                        return null;                    }                    public Response processConnectionControl(ConnectionControl control) throws Exception {                        ActiveMQConnection.this.onConnectionControl((ConnectionControl)command);                        return null;                    }                    public Response processConsumerControl(ConsumerControl control) throws Exception {                        ActiveMQConnection.this.onConsumerControl((ConsumerControl)command);                        return null;                    }                    public Response processWireFormat(WireFormatInfo info) throws Exception {                        ActiveMQConnection.this.onWireFormatInfo((WireFormatInfo)command);                        return null;                    }                });            } catch (Exception var5) {                this.onClientInternalException(var5);            }        }        Iterator iter = this.transportListeners.iterator();        while(iter.hasNext()) {            TransportListener listener = (TransportListener)iter.next();            listener.onCommand(command);        }    }    protected void onWireFormatInfo(WireFormatInfo info) {        this.protocolVersion.set(info.getVersion());    }    public void onClientInternalException(final Throwable error) {        if(!this.closed.get() && !this.closing.get()) {            if(this.clientInternalExceptionListener != null) {                this.executor.execute(new Runnable() {                    public void run() {                        ActiveMQConnection.this.clientInternalExceptionListener.onException(error);                    }                });            } else {                LOG.debug("Async client internal exception occurred with no exception listener registered: " + error, error);            }        }    }    public void onAsyncException(Throwable error) {        if(!this.closed.get() && !this.closing.get()) {            if(this.exceptionListener != null) {                if(!(error instanceof JMSException)) {                    error = JMSExceptionSupport.create((Throwable)error);                }                final JMSException e = (JMSException)error;                this.executor.execute(new Runnable() {                    public void run() {                        ActiveMQConnection.this.exceptionListener.onException(e);                    }                });            } else {                LOG.debug("Async exception with no exception listener: " + error, (Throwable)error);            }        }    }    public void onException(final IOException error) {        this.onAsyncException(error);        if(!this.closing.get() && !this.closed.get()) {            this.executor.execute(new Runnable() {                public void run() {                    ActiveMQConnection.this.transportFailed(error);                    ServiceSupport.dispose(ActiveMQConnection.this.transport);                    ActiveMQConnection.this.brokerInfoReceived.countDown();                    try {                        ActiveMQConnection.this.cleanup();                    } catch (JMSException var3) {                        ActiveMQConnection.LOG.warn("Exception during connection cleanup, " + var3, var3);                    }                    Iterator iter = ActiveMQConnection.this.transportListeners.iterator();                    while(iter.hasNext()) {                        TransportListener listener = (TransportListener)iter.next();                        listener.onException(error);                    }                }            });        }    }    public void transportInterupted() {        this.transportInterruptionProcessingComplete = new CountDownLatch(this.dispatchers.size() - (this.advisoryConsumer != null?1:0));        if(LOG.isDebugEnabled()) {            LOG.debug("transport interrupted, dispatchers: " + this.transportInterruptionProcessingComplete.getCount());        }        this.signalInterruptionProcessingNeeded();        Iterator iter = this.sessions.iterator();        while(iter.hasNext()) {            ActiveMQSession listener = (ActiveMQSession)iter.next();            listener.clearMessagesInProgress();        }        iter = this.connectionConsumers.iterator();        while(iter.hasNext()) {            ActiveMQConnectionConsumer listener1 = (ActiveMQConnectionConsumer)iter.next();            listener1.clearMessagesInProgress();        }        iter = this.transportListeners.iterator();        while(iter.hasNext()) {            TransportListener listener2 = (TransportListener)iter.next();            listener2.transportInterupted();        }    }    public void transportResumed() {        Iterator iter = this.transportListeners.iterator();        while(iter.hasNext()) {            TransportListener listener = (TransportListener)iter.next();            listener.transportResumed();        }    }    protected ActiveMQTempDestination createTempDestination(boolean topic) throws JMSException {        Object dest;        if(topic) {            dest = new ActiveMQTempTopic(this.info.getConnectionId(), this.tempDestinationIdGenerator.getNextSequenceId());        } else {            dest = new ActiveMQTempQueue(this.info.getConnectionId(), this.tempDestinationIdGenerator.getNextSequenceId());        }        DestinationInfo info = new DestinationInfo();        info.setConnectionId(this.info.getConnectionId());        info.setOperationType(0);        info.setDestination((ActiveMQDestination)dest);        this.syncSendPacket(info);        ((ActiveMQTempDestination)dest).setConnection(this);        this.activeTempDestinations.put(dest, dest);        return (ActiveMQTempDestination)dest;    }    public void deleteTempDestination(ActiveMQTempDestination destination) throws JMSException {        this.checkClosedOrFailed();        Iterator destInfo = this.sessions.iterator();        ActiveMQSession s;        do {            if(!destInfo.hasNext()) {                this.activeTempDestinations.remove(destination);                DestinationInfo destInfo1 = new DestinationInfo();                destInfo1.setConnectionId(this.info.getConnectionId());                destInfo1.setOperationType(1);                destInfo1.setDestination(destination);                destInfo1.setTimeout(0L);                this.syncSendPacket(destInfo1);                return;            }            s = (ActiveMQSession)destInfo.next();        } while(!s.isInUse(destination));        throw new JMSException("A consumer is consuming from the temporary destination");    }    public boolean isDeleted(ActiveMQDestination dest) {        return this.advisoryConsumer == null?false:!this.activeTempDestinations.contains(dest);    }    public boolean isCopyMessageOnSend() {        return this.copyMessageOnSend;    }    public LongSequenceGenerator getLocalTransactionIdGenerator() {        return this.localTransactionIdGenerator;    }    public boolean isUseCompression() {        return this.useCompression;    }    public void setUseCompression(boolean useCompression) {        this.useCompression = useCompression;    }    public void destroyDestination(ActiveMQDestination destination) throws JMSException {        this.checkClosedOrFailed();        this.ensureConnectionInfoSent();        DestinationInfo info = new DestinationInfo();        info.setConnectionId(this.info.getConnectionId());        info.setOperationType(1);        info.setDestination(destination);        info.setTimeout(0L);        this.syncSendPacket(info);    }    public InputStream createInputStream(Destination dest) throws JMSException {        return this.createInputStream(dest, (String)null);    }    public InputStream createInputStream(Destination dest, String messageSelector) throws JMSException {        return this.createInputStream(dest, messageSelector, false);    }    public InputStream createInputStream(Destination dest, String messageSelector, boolean noLocal) throws JMSException {        return this.createInputStream(dest, messageSelector, noLocal, -1L);    }    public InputStream createInputStream(Destination dest, String messageSelector, boolean noLocal, long timeout) throws JMSException {        return this.doCreateInputStream(dest, messageSelector, noLocal, (String)null, timeout);    }    public InputStream createDurableInputStream(Topic dest, String name) throws JMSException {        return this.createInputStream(dest, (String)null, false);    }    public InputStream createDurableInputStream(Topic dest, String name, String messageSelector) throws JMSException {        return this.createDurableInputStream(dest, name, messageSelector, false);    }    public InputStream createDurableInputStream(Topic dest, String name, String messageSelector, boolean noLocal) throws JMSException {        return this.createDurableInputStream(dest, name, messageSelector, noLocal, -1L);    }    public InputStream createDurableInputStream(Topic dest, String name, String messageSelector, boolean noLocal, long timeout) throws JMSException {        return this.doCreateInputStream(dest, messageSelector, noLocal, name, timeout);    }    private InputStream doCreateInputStream(Destination dest, String messageSelector, boolean noLocal, String subName, long timeout) throws JMSException {        this.checkClosedOrFailed();        this.ensureConnectionInfoSent();        return new ActiveMQInputStream(this, this.createConsumerId(), ActiveMQDestination.transform(dest), messageSelector, noLocal, subName, this.prefetchPolicy.getInputStreamPrefetch(), timeout);    }    public OutputStream createOutputStream(Destination dest) throws JMSException {        return this.createOutputStream(dest, (Map)null, 2, 4, 0L);    }    public OutputStream createNonPersistentOutputStream(Destination dest) throws JMSException {        return this.createOutputStream(dest, (Map)null, 1, 4, 0L);    }    public OutputStream createOutputStream(Destination dest, Map<String, Object> streamProperties, int deliveryMode, int priority, long timeToLive) throws JMSException {        this.checkClosedOrFailed();        this.ensureConnectionInfoSent();        return new ActiveMQOutputStream(this, this.createProducerId(), ActiveMQDestination.transform(dest), streamProperties, deliveryMode, priority, timeToLive);    }    public void unsubscribe(String name) throws InvalidDestinationException, JMSException {        this.checkClosedOrFailed();        RemoveSubscriptionInfo rsi = new RemoveSubscriptionInfo();        rsi.setConnectionId(this.getConnectionInfo().getConnectionId());        rsi.setSubscriptionName(name);        rsi.setClientId(this.getConnectionInfo().getClientId());        this.syncSendPacket(rsi);    }    void send(ActiveMQDestination destination, ActiveMQMessage msg, MessageId messageId, int deliveryMode, int priority, long timeToLive, boolean async) throws JMSException {        this.checkClosedOrFailed();        if(destination.isTemporary() && this.isDeleted(destination)) {            throw new JMSException("Cannot publish to a deleted Destination: " + destination);        } else {            msg.setJMSDestination(destination);            msg.setJMSDeliveryMode(deliveryMode);            long expiration = 0L;            if(!this.isDisableTimeStampsByDefault()) {                long timeStamp = System.currentTimeMillis();                msg.setJMSTimestamp(timeStamp);                if(timeToLive > 0L) {                    expiration = timeToLive + timeStamp;                }            }            msg.setJMSExpiration(expiration);            msg.setJMSPriority(priority);            msg.setJMSRedelivered(false);            msg.setMessageId(messageId);            msg.onSend();            msg.setProducerId(msg.getMessageId().getProducerId());            if(LOG.isDebugEnabled()) {                LOG.debug("Sending message: " + msg);            }            if(async) {                this.asyncSendPacket(msg);            } else {                this.syncSendPacket(msg);            }        }    }    public void addOutputStream(ActiveMQOutputStream stream) {        this.outputStreams.add(stream);    }    public void removeOutputStream(ActiveMQOutputStream stream) {        this.outputStreams.remove(stream);    }    public void addInputStream(ActiveMQInputStream stream) {        this.inputStreams.add(stream);    }    public void removeInputStream(ActiveMQInputStream stream) {        this.inputStreams.remove(stream);    }    protected void onControlCommand(ControlCommand command) {        String text = command.getCommand();        if(text != null && "shutdown".equals(text)) {            LOG.info("JVM told to shutdown");            System.exit(0);        }    }    protected void onConnectionControl(ConnectionControl command) {        if(command.isFaultTolerant()) {            this.optimizeAcknowledge = false;            Iterator i = this.sessions.iterator();            while(i.hasNext()) {                ActiveMQSession s = (ActiveMQSession)i.next();                s.setOptimizeAcknowledge(false);            }        }    }    protected void onConsumerControl(ConsumerControl command) {        Iterator i;        ActiveMQSession s;        if(command.isClose()) {            i = this.sessions.iterator();            while(i.hasNext()) {                s = (ActiveMQSession)i.next();                s.close(command.getConsumerId());            }        } else {            i = this.sessions.iterator();            while(i.hasNext()) {                s = (ActiveMQSession)i.next();                s.setPrefetchSize(command.getConsumerId(), command.getPrefetch());            }        }    }    protected void transportFailed(IOException error) {        this.transportFailed.set(true);        if(this.firstFailureError == null) {            this.firstFailureError = error;        }    }    public void setCopyMessageOnSend(boolean copyMessageOnSend) {        this.copyMessageOnSend = copyMessageOnSend;    }    protected BlobTransferPolicy createBlobTransferPolicy() {        return new BlobTransferPolicy();    }    public int getProtocolVersion() {        return this.protocolVersion.get();    }    public int getProducerWindowSize() {        return this.producerWindowSize;    }    public void setProducerWindowSize(int producerWindowSize) {        this.producerWindowSize = producerWindowSize;    }    public void setAuditDepth(int auditDepth) {        this.connectionAudit.setAuditDepth(auditDepth);    }    public void setAuditMaximumProducerNumber(int auditMaximumProducerNumber) {        this.connectionAudit.setAuditMaximumProducerNumber(auditMaximumProducerNumber);    }    protected void removeDispatcher(ActiveMQDispatcher dispatcher) {        this.connectionAudit.removeDispatcher(dispatcher);    }    protected boolean isDuplicate(ActiveMQDispatcher dispatcher, Message message) {        return this.checkForDuplicates && this.connectionAudit.isDuplicate(dispatcher, message);    }    protected void rollbackDuplicate(ActiveMQDispatcher dispatcher, Message message) {        this.connectionAudit.rollbackDuplicate(dispatcher, message);    }    public IOException getFirstFailureError() {        return this.firstFailureError;    }    protected void waitForTransportInterruptionProcessingToComplete() throws InterruptedException {        CountDownLatch cdl = this.transportInterruptionProcessingComplete;        if(cdl != null) {            if(!this.closed.get() && !this.transportFailed.get() && cdl.getCount() > 0L) {                LOG.warn("dispatch paused, waiting for outstanding dispatch interruption processing (" + cdl.getCount() + ") to complete..");                cdl.await(10L, TimeUnit.SECONDS);            }            this.signalInterruptionProcessingComplete();        }    }    protected void transportInterruptionProcessingComplete() {        CountDownLatch cdl = this.transportInterruptionProcessingComplete;        if(cdl != null) {            cdl.countDown();            try {                this.signalInterruptionProcessingComplete();            } catch (InterruptedException var3) {                ;            }        }    }    private void signalInterruptionProcessingComplete() throws InterruptedException {        CountDownLatch cdl = this.transportInterruptionProcessingComplete;        if(cdl.getCount() == 0L) {            if(LOG.isDebugEnabled()) {                LOG.debug("transportInterruptionProcessingComplete for: " + this.getConnectionInfo().getConnectionId());            }            this.transportInterruptionProcessingComplete = null;            FailoverTransport failoverTransport = (FailoverTransport)this.transport.narrow(FailoverTransport.class);            if(failoverTransport != null) {                failoverTransport.connectionInterruptProcessingComplete(this.getConnectionInfo().getConnectionId());                if(LOG.isDebugEnabled()) {                    LOG.debug("notified failover transport (" + failoverTransport + ") of interruption completion for: " + this.getConnectionInfo().getConnectionId());                }            }        }    }    private void signalInterruptionProcessingNeeded() {        FailoverTransport failoverTransport = (FailoverTransport)this.transport.narrow(FailoverTransport.class);        if(failoverTransport != null) {            failoverTransport.getStateTracker().transportInterrupted(this.getConnectionInfo().getConnectionId());            if(LOG.isDebugEnabled()) {                LOG.debug("notified failover transport (" + failoverTransport + ") of pending interruption processing for: " + this.getConnectionInfo().getConnectionId());            }        }    }    public void setConsumerFailoverRedeliveryWaitPeriod(long consumerFailoverRedeliveryWaitPeriod) {        this.consumerFailoverRedeliveryWaitPeriod = consumerFailoverRedeliveryWaitPeriod;    }    public long getConsumerFailoverRedeliveryWaitPeriod() {        return this.consumerFailoverRedeliveryWaitPeriod;    }    protected Scheduler getScheduler() throws JMSException {        Scheduler result = this.scheduler;        if(result == null) {            synchronized(this) {                result = this.scheduler;                if(result == null) {                    this.checkClosed();                    try {                        result = this.scheduler = new Scheduler("ActiveMQConnection[" + this.info.getConnectionId().getValue() + "] Scheduler");                        this.scheduler.start();                    } catch (Exception var5) {                        throw JMSExceptionSupport.create(var5);                    }                }            }        }        return result;    }    protected ThreadPoolExecutor getExecutor() {        return this.executor;    }    public boolean isCheckForDuplicates() {        return this.checkForDuplicates;    }    public void setCheckForDuplicates(boolean checkForDuplicates) {        this.checkForDuplicates = checkForDuplicates;    }    public boolean isTransactedIndividualAck() {        return this.transactedIndividualAck;    }    public void setTransactedIndividualAck(boolean transactedIndividualAck) {        this.transactedIndividualAck = transactedIndividualAck;    }    public boolean isNonBlockingRedelivery() {        return this.nonBlockingRedelivery;    }    public void setNonBlockingRedelivery(boolean nonBlockingRedelivery) {        this.nonBlockingRedelivery = nonBlockingRedelivery;    }    public void cleanUpTempDestinations() {        if(this.activeTempDestinations != null && !this.activeTempDestinations.isEmpty()) {            Iterator entries = this.activeTempDestinations.entrySet().iterator();            while(entries.hasNext()) {                Entry entry = (Entry)entries.next();                try {                    ActiveMQTempDestination ex = (ActiveMQTempDestination)entry.getValue();                    String thisConnectionId = this.info.getConnectionId() == null?"":this.info.getConnectionId().toString();                    if(ex.getConnectionId() != null && ex.getConnectionId().equals(thisConnectionId)) {                        this.deleteTempDestination((ActiveMQTempDestination)entry.getValue());                    }                } catch (Exception var5) {                    ;                }            }        }    }    static {        DEFAULT_USER = ActiveMQConnectionFactory.DEFAULT_USER;        DEFAULT_PASSWORD = ActiveMQConnectionFactory.DEFAULT_PASSWORD;        LOG = LoggerFactory.getLogger(ActiveMQConnection.class);    }}



0 0