Atomically recovers the channel.

@throws Exception when recovery fails due to a connection closure
436475
synchronized void recoverChannel(boolean viaConnectionRecovery) throws Exception {
    recoveryPending.set(false);
    if (circuit.isClosed())
      return;

    if (recoveryStats == null) {
      recoveryConsumers = consumerDeclarations.isEmpty() ? null
        : new LinkedHashMap<String, ConsumerDeclaration>(consumerDeclarations);
      recoveryStats = new RecurringStats(config.getChannelRecoveryPolicy());
      recoveryStats.incrementTime();
    } else if (recoveryStats.isPolicyExceeded()) {
      recoveryFailed(lastShutdownSignal);
      if (!viaConnectionRecovery)
        return;
    }

    try {
      notifyRecoveryStarted();
      delegate = callWithRetries(new Callable<Channel>() {
        @Override
        public Channel call() throws Exception {
          log.info("Recovering {}", ChannelHandler.this);
          previousMaxDeliveryTag = maxDeliveryTag;
          Channel channel = connectionHandler.createChannel(delegate.getChannelNumber());
          migrateConfiguration(channel);
          log.info("Recovered {}", ChannelHandler.this);
          return channel;
        }
      }, config.getChannelRecoveryPolicy(), recoveryStats, config.getRecoverableExceptions(), true,
        false);
      notifyRecovery();
      recoverConsumers(!viaConnectionRecovery);
      recoverySucceeded();
    } catch (Exception e) {
      ShutdownSignalException sse = Exceptions.extractCause(e, ShutdownSignalException.class);
      if (sse != null) {
        if (Exceptions.isConnectionClosure(sse))
          throw e;
      } else if (recoveryStats.isPolicyExceeded())
        recoveryFailed(e);
    }
  }
850733
public void startRecovery() throws Exception {
        if (tc.isEntryEnabled())
            Tr.entry(tc, "startRecovery");

        // Note that _recoverDBLogStarted is always false if we are logging to a filesystem.
        // If we are logging to an RDBMS, then we will start the TM which will spin off a thread
        // to perform recovery processing. Unfortunately, this latter thread, as part of
        // DataSource processing, will also attempt to start the TM as a result of registering
        // ResourceInfo. This flag guards against that eventuality.
        if (!_recoverDBLogStarted) {
            synchronized (this) {
                TMHelper.setTMService(this);

                // Initalize trace
                Tr.reinitializeTracer();

                // Test whether we are logging to an RDBMS
                final ConfigurationProvider cp = ConfigurationProviderManager.getConfigurationProvider();
                if (cp != null && cp.isSQLRecoveryLog()) {
                    _recoverDBLogStarted = true;
                    if (tc.isDebugEnabled())
                        Tr.debug(tc, "Tran Logging to an RDBMS set recoverDBLogStarted flag");
                }

                if (getState() != TMService.TMStates.INACTIVE && getState() != TMService.TMStates.STOPPED) {
                    if (tc.isEntryEnabled())
                        Tr.exit(tc, "start", "Already started");
                    return;
                }

                setResyncException(null);
                _recLogService = new RecLogServiceImpl();

                // Create the Recovery Director
                _recoveryDirector = RecoveryDirectorFactory.createRecoveryDirector();

                // For cloud support, retrieve recovery identity from the configuration if it is defined.
                if (cp != null) {
                    _recoveryIdentity = cp.getRecoveryIdentity();
                    if (tc.isDebugEnabled())
                        Tr.debug(tc, "RecoveryIdentity is ", _recoveryIdentity);
                    _recoveryGroup = cp.getRecoveryGroup();
                    if (tc.isDebugEnabled())
                        Tr.debug(tc, "recoveryGroup is ", _recoveryGroup);
                }

                //Add this guard to ensure that we have sufficient config to drive recovery.
                boolean allowRecovery = true;
                if (cp == null) {
                    // A null ConfigurationProvider cannot be tolerated.
                    allowRecovery = false;
                    if (tc.isDebugEnabled())
                        Tr.debug(tc, "Configuration Provider is null");
                } else {
                    String sName = cp.getServerName();
                    if (tc.isDebugEnabled())
                        Tr.debug(tc, "Retrieved server name " + sName);
                    if (sName == null || sName.isEmpty()) {
                        // An empty string serverName suggests that the Location Service was unavailable
                        allowRecovery = false;
                    }
                }

                if (!allowRecovery) {
                    try {
                        shutdown();
                    } catch (RuntimeException e) {
                        FFDCFilter.processException(e, "com.ibm.tx.jta.util.TxTMHelper.start", "279", this);
                    }

                    final Throwable se = new SystemException();
                    if (tc.isEntryEnabled())
                        Tr.exit(tc, "start", se);
                    throw (SystemException) se;
                }

                if (_recoveryIdentity != null && !_recoveryIdentity.isEmpty()) {
                    _recLogService.initialize(_recoveryIdentity);
                } else {
                    String serverName = null;
                    if (cp != null) {
                        serverName = cp.getServerName();
                    }
                    _recLogService.initialize(serverName);
                }

                TxRecoveryAgentImpl txAgent = createRecoveryAgent(_recoveryDirector);

                // For now I'll code such that the presence of a RecoveryIdentity attribute says that we are operating in the Cloud
                if (_recoveryIdentity != null && !_recoveryIdentity.isEmpty()) {
                    _recLogService.setPeerRecoverySupported(true);
                    txAgent.setPeerRecoverySupported(true);
                    // Override the disable2PC property if it has been set
                    TransactionImpl.setDisable2PCDefault(false);
                    Tr.audit(tc, "WTRN0108I: Server with identity " + _recoveryIdentity + " is monitoring its peers for Transaction Peer Recovery");
                }

                //TODO: We don't currently use the recoveryGroup....but in due course we will, so retain this
                // code snippet
                if (_recoveryGroup != null && !_recoveryGroup.isEmpty()) {
                    txAgent.setRecoveryGroup(_recoveryGroup);

                    _recLogService.setRecoveryGroup(_recoveryGroup);
                }

                setRecoveryAgent(txAgent);

                // Fake recovery only mode if we're to wait
                RecoveryManager._waitForRecovery = _waitForRecovery;

                // Kick off recovery
                _recLogService.startRecovery(_recoveryLogFactory);

                // Defect RTC 99071. Don't make the STATE transition until recovery has been fully
                // initialised, after replay completion but before resync completion.
                setState(TMService.TMStates.RECOVERING);

                if (_waitForRecovery) {
                    if (tc.isDebugEnabled())
                        Tr.debug(tc, "Waiting for completion of asynchronous recovery");
                    _asyncRecoverySemaphore.waitEvent();
                    if (tc.isDebugEnabled())
                        Tr.debug(tc, "Asynchronous recovery is complete");

                    if (_resyncException != null) {
                        try {
                            shutdown();
                        } catch (RuntimeException e) {
                            FFDCFilter.processException(e, "com.ibm.tx.jta.util.TxTMHelper.start", "137", this);
                        }

                        final Throwable se = new SystemException().initCause(_resyncException);
                        if (tc.isEntryEnabled())
                            Tr.exit(tc, "start", se);
                        throw (SystemException) se;
                    }
                } // eof if waitForRecovery
            } // eof synchronized block
        } // eof if !_recoverDBLogStarted
        else if (tc.isDebugEnabled())
            Tr.debug(tc, "Tran Logging to an RDBMS and START processing is in progress");

        if (tc.isEntryEnabled())
            Tr.exit(tc, "startRecovery");
    }
1204821
def recover(self, requeue=False, cb=None):
        '''
        
        '''
        args = Writer()
        args.write_bit(requeue)

        # The XML spec is incorrect; this method is always synchronous
        #  http://lists.rabbitmq.com/pipermail/rabbitmq-discuss/2011-January/010738.html
        self._recover_cb.append(cb)
        self.send_frame(MethodFrame(self.channel_id, 60, 110, args))
        self.channel.add_synchronous_cb(self._recv_recover_ok)
277122
public void rebuild() throws Exception
    {
        Preconditions.checkState(!executorService.isShutdown(), "cache has been closed");

        ensurePath();

        clear();

        List<String> children = client.getChildren().forPath(path);
        for ( String child : children )
        {
            String fullPath = ZKPaths.makePath(path, child);
            internalRebuildNode(fullPath);

            if ( rebuildTestExchanger != null )
            {
                rebuildTestExchanger.exchange(new Object());
            }
        }

        // this is necessary so that any updates that occurred while rebuilding are taken
        offerOperation(new RefreshOperation(this, RefreshMode.FORCE_GET_DATA_AND_STAT));
    }
154790
@Override
    protected void recoverOperation(DataFrameRecord<Operation> dataFrameRecord, OperationMetadataUpdater metadataUpdater) throws DataCorruptionException {
        if (this.callbacks.beginRecoverOperation != null) {
            Callbacks.invokeSafely(this.callbacks.beginRecoverOperation, dataFrameRecord.getItem(), dataFrameRecord.getFrameEntries(), null);
        }

        try {
            super.recoverOperation(dataFrameRecord, metadataUpdater);
        } catch (Throwable ex) {
            if (this.callbacks.operationFailed != null) {
                Callbacks.invokeSafely(this.callbacks.operationFailed, dataFrameRecord.getItem(), ex, null);
            }

            throw ex;
        }

        if (this.callbacks.operationSuccess != null) {
            Callbacks.invokeSafely(this.callbacks.operationSuccess, dataFrameRecord.getItem(), null);
        }
    }
1054913
def reconnect(self):
        '''
        '''
        if self._connection.closed():
            self._connection.reset()

            yield from self._connection.connect()
314242
void recoverExchange(String exchangeName, ResourceDeclaration exchangeDeclaration)
      throws Exception {
    try {
      log.info("Recovering exchange {} via {}", exchangeName, this);
      exchangeDeclaration.invoke(getRecoveryChannel());
    } catch (Exception e) {
      log.error("Failed to recover exchange {} via {}", exchangeName, this, e);
      if (throwOnRecoveryFailure() || Exceptions.isCausedByConnectionClosure(e))
        throw e;
    }
  }
622765
protected void reConnect(VirtualConnection inVC, IOException ioe) {

        if (getLink().isReconnectAllowed()) {
            // start the reconnect
            if (TraceComponent.isAnyTracingEnabled() && tc.isDebugEnabled()) {
                Tr.debug(tc, "Attempting reconnect: " + getLink().getVirtualConnection());
            }
            // 359362 - null out the JIT read buffers
            getTSC().getReadInterface().setBuffer(null);
            getLink().reConnectAsync(ioe);
        } else {
            callErrorCallback(inVC, ioe);
        }
    }
586072
def _try_reconnect(self):
        """"""

        try:
            if self.connection_interrupted:
                self.connect_direct(self.connection_string, force=True)
                self.connection_interrupted = False
                self.connected = True

                # Reenable streaming interface if that was open before as well
                if self._reports is not None:
                    self._loop.run_coroutine(self.adapter.open_interface(0, 'streaming'))

                # Reenable tracing interface if that was open before as well
                if self._traces is not None:
                    self._loop.run_coroutine(self.adapter.open_interface(0, 'tracing'))
        except HardwareError as exc:
            self._logger.exception("Error reconnecting to device after an unexpected disconnect")
            raise HardwareError("Device disconnected unexpectedly and we could not reconnect", reconnect_error=exc) from exc
138206
@Override
	public void connectionFreed(IManagedConnectionEvent<C> event) {
		// physical connection is already set free
		if (!event.getManagedConnection().hasCoreConnection()) {
			return;
		}
		C con = event.getManagedConnection().getCoreConnection();
		if (con == null || !(con instanceof IXADataRecorderAware)) {
			return;
		}

		IXADataRecorderAware messageAwareConnection = (IXADataRecorderAware) con;
		// Transaction is closed and the xaDataRecorder is destroyed ...
		IXADataRecorder xaDataRecorder = messageAwareConnection
				.getXADataRecorder();
		if (xaDataRecorder == null) {
			return;
		}

		// if commit/rollback was performed, nothing happend. If no the logged
		// data is closed but not destroy. So recovery can happen

		if (event.getManagedConnection().hasTransactionalData()) {
			xaRecorderRepository.close(); // close without removing the recover
											// data
		} else {
			xaDataRecorder.destroy();
		}
		messageAwareConnection.setXADataRecorder(null);

	}
1307940
Channel getChannel() throws ConnectionFailedException {
        Channel ch = channel.get();
        if (ch == null) {
            throw new ConnectionFailedException("Connection to " + connectionName + " is not established.");
        }
        return ch;
    }
554062
private void recover(Connection conn) throws SQLException, RecoverableUnitSectionExistsException, InternalLogException {
        if (tc.isEntryEnabled())
            Tr.entry(tc, "recover", conn);

        Statement recoveryStmt = null;
        ResultSet recoveryRS = null;

        try {
            recoveryStmt = conn.createStatement();
            String queryString = "SELECT RU_ID, RUSECTION_ID, RUSECTION_DATA_INDEX, DATA" +
                                 " FROM " + _recoveryTableName + _logIdentifierString + _recoveryTableNameSuffix +
                                 " WHERE SERVER_NAME='" + _serverName +
                                 "' AND SERVICE_ID=" + _recoveryAgent.clientIdentifier();
            if (tc.isDebugEnabled())
                Tr.debug(tc, "Retrieve all rows from table using - " + queryString);

            recoveryRS = recoveryStmt.executeQuery(queryString);

            while (recoveryRS.next()) {
                final long ruId = recoveryRS.getLong(1);
                if (ruId != -1) {
                    SQLRecoverableUnitImpl ru = (SQLRecoverableUnitImpl) _recoverableUnits.get(ruId);
                    if (ru == null) {
                        if (tc.isDebugEnabled())
                            Tr.debug(tc, "Creating ru with id: " + ruId);
                        ru = new SQLRecoverableUnitImpl(this, ruId, _failureScope, true);
                    }

                    final long sectId = recoveryRS.getLong(2);
                    final int index = recoveryRS.getInt(3);
                    final byte[] data = recoveryRS.getBytes(4);

                    if (tc.isEventEnabled()) {
                        Tr.event(tc, "sql tranlog: read ruId: " + ruId);
                        Tr.event(tc, "sql tranlog: read sectionId: " + sectId);
                        Tr.event(tc, "sql tranlog: read item: " + index);
                        Tr.event(tc, "sql tranlog: read data: " + RLSUtils.toHexString(data, RLSUtils.MAX_DISPLAY_BYTES));
                    }

                    SQLRecoverableUnitSectionImpl sect = (SQLRecoverableUnitSectionImpl) ru.lookupSection((int) sectId);
                    if (sect == null) {
                        sect = (SQLRecoverableUnitSectionImpl) ru.createSection((int) sectId, index == 0);
                    }

                    sect.addData(index, data);
                } else if (tc.isDebugEnabled())
                    Tr.debug(tc, "Bypass locking row with id: " + ruId);
            }
        } finally {
            if (recoveryRS != null && !recoveryRS.isClosed())
                recoveryRS.close();
            if (recoveryStmt != null && !recoveryStmt.isClosed())
                recoveryStmt.close();
        }

        if (tc.isEntryEnabled())
            Tr.exit(tc, "recover");
    }
553804
private synchronized Channel channel() throws IOException {
        if (autoReconnect) {
            try {
                connect();
            } catch (GeneralSecurityException e) {
                throw new IOException(e);
            }
        }

        return channel;
    }
1279233
public void lock() throws IOException, InterruptedException {
        if (channel == null) {
            initializeChannel();
        }
        lockSem.acquire();
        lock = channel.lock();
    }
842666
String recoverQueue(String queueName, QueueDeclaration queueDeclaration) throws Exception {
    try {
      String newQueueName =
          ((Queue.DeclareOk) queueDeclaration.invoke(getRecoveryChannel())).getQueue();
      if (queueName.equals(newQueueName))
        log.info("Recovered queue {} via {}", queueName, this);
      else {
        log.info("Recovered queue {} as {} via {}", queueName, newQueueName, this);
        queueDeclaration.name = newQueueName;
      }

      return newQueueName;
    } catch (Exception e) {
      log.error("Failed to recover queue {} via {}", queueName, this, e);
      if (throwOnRecoveryFailure() || Exceptions.isCausedByConnectionClosure(e))
        throw e;
      return queueName;
    }
  }
1162834
protected void handleConnectionException(int errorCode, Throwable originalCause)
    throws ActivityException {
        InternalEvent message = InternalEvent.createActivityStartMessage(getActivityId(),
                getProcessInstanceId(), getWorkTransitionInstanceId(), getMasterRequestId(),
                COMPCODE_AUTO_RETRY);
        ScheduledEventQueue eventQueue = ScheduledEventQueue.getSingleton();
        int retry_interval = this.getRetryInterval();
        Date scheduledTime = new Date(DatabaseAccess.getCurrentTime()+retry_interval*1000);
        super.loginfo("The activity failed, set to retry at " + StringHelper.dateToString(scheduledTime));
        eventQueue.scheduleInternalEvent(ScheduledEvent.INTERNAL_EVENT_PREFIX+this.getActivityInstanceId(),
                scheduledTime, message.toString(), "procinst:"+this.getProcessInstanceId().toString());
        this.setReturnCode(COMPCODE_AUTO_RETRY);
        // the above is to prevent engine from making transitions (typically to exception handler)
        throw new ActivityException(errorCode, originalCause.getMessage(), originalCause);
    }
1248639
@Override
    public void handleDownstream(ChannelHandlerContext ctx, ChannelEvent evt) throws Exception {
        if (!(evt instanceof MessageEvent)) {
            ctx.sendDownstream(evt);
            return;
        }

        final MessageEvent e = (MessageEvent) evt;
        final Object originalMessage = e.getMessage();
        final Object encodedMessage = encode(ctx, e.getChannel(), originalMessage);
        if (originalMessage == encodedMessage)
            ctx.sendDownstream(evt);
        else if (encodedMessage != null)
            ctx.sendDownstream(new DownstreamMessageEvent(ctx.getChannel(), e.getFuture(), encodedMessage, e.getRemoteAddress())); // Channels.write(ctx, e.getFuture(), encodedMessage, e.getRemoteAddress());
    }