Exchanges the initial fully-formed messages which establishes the transaction context for queries to
the dbserver.

@throws IOException if there is a problem during the exchange
977258
private void performSetupExchange() throws IOException {
        Message setupRequest = new Message(0xfffffffeL, Message.KnownType.SETUP_REQ, new NumberField(posingAsPlayer, 4));
        sendMessage(setupRequest);
        Message response = Message.read(is);
        if (response.knownType != Message.KnownType.MENU_AVAILABLE) {
            throw new IOException("Did not receive message type 0x4000 in response to setup message, got: " + response);
        }
        if (response.arguments.size() != 2) {
            throw new IOException("Did not receive two arguments in response to setup message, got: " + response);
        }
        final Field player = response.arguments.get(1);
        if (!(player instanceof NumberField)) {
            throw new IOException("Second argument in response to setup message was not a number: " + response);
        }
        if (((NumberField)player).getValue() != targetPlayer) {
            throw new IOException("Expected to connect to player " + targetPlayer +
                    ", but welcome response identified itself as player " + ((NumberField)player).getValue());
        }
    }
275879
public static synchronized void start() {
        if(status.equals("started"))
            return;
        init();

        long t = System.currentTimeMillis();

        Transactions.clear();
        queueWorker.clear();
        operationLog.initialize();
        messageListener.start();

        //find not
        operationLog.listUndone(new Closure<MessageBean, Object>() {
            @Override
            public Object call(MessageBean input) {
                try{
                    queueWorker.runRealWrite(input);
                    operationLog.markDone(input.getId());
                }catch (Throwable e){
                    queueWorker.onError(input, e);
                }
                return null;
            }
        });
        //update
        startupUpdator.update(queueWorker);
        queueWorker.start();
        startupUpdator.start();
        try{
            fileExchange.start();
        }catch (BindException e){
            LOG.error("Cannot start file exchange capability, BindException occurs: "+e.getMessage());
            System.exit(1);
        }

        status = "started";
        LOG.info("Cluster node "+nodeId+" started ("+(System.currentTimeMillis()-t)+" ms.)");
    }
1011117
void processPing(final HttpServerExchange exchange, final RequestData requestData) throws IOException {

        final String jvmRoute = requestData.getFirst(JVMROUTE);
        final String scheme = requestData.getFirst(SCHEME);
        final String host = requestData.getFirst(HOST);
        final String port = requestData.getFirst(PORT);

        final String OK = "Type=PING-RSP&State=OK&id=" + creationTime;
        final String NOTOK = "Type=PING-RSP&State=NOTOK&id=" + creationTime;

        if (jvmRoute != null) {
            // ping the corresponding node.
            final Node nodeConfig = container.getNode(jvmRoute);
            if (nodeConfig == null) {
                sendResponse(exchange, NOTOK);
                return;
            }
            final NodePingUtil.PingCallback callback = new NodePingUtil.PingCallback() {
                @Override
                public void completed() {
                    try {
                        sendResponse(exchange, OK);
                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                }

                @Override
                public void failed() {
                    try {
                        nodeConfig.markInError();
                        sendResponse(exchange, NOTOK);
                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                }
            };
            nodeConfig.ping(exchange, callback);
        } else {
            if (scheme == null && host == null && port == null) {
                sendResponse(exchange, OK);
                return;
            } else {
                if (host == null || port == null) {
                    processError(TYPESYNTAX, SMISFLD, exchange);
                    return;
                }
                // Check whether we can reach the host
                checkHostUp(scheme, host, Integer.parseInt(port), exchange, new NodePingUtil.PingCallback() {
                    @Override
                    public void completed() {
                        sendResponse(exchange, OK);
                    }

                    @Override
                    public void failed() {
                        sendResponse(exchange, NOTOK);
                    }
                });
                return;
            }
        }
    }
222034
public void initialize() throws IOException, NotInitializedException {
    logger.debug("Initialising TCPTransportClient. Origin address is [{}] and destination address is [{}]", origAddress, destAddress);
    if (destAddress == null) {
      throw new NotInitializedException("Destination address is not set");
    }
    socketChannel = SelectorProvider.provider().openSocketChannel();

    try {
      if (origAddress != null) {
        socketChannel.socket().bind(origAddress);
      }

      socketChannel.connect(destAddress);
      //PCB added logging
      socketChannel.configureBlocking(BLOCKING_IO);
      getParent().onConnected();
    }
    catch (IOException e) {
      if (origAddress != null) {
        socketChannel.socket().close();
      }
      socketChannel.close();
      throw e;
    }
  }
1099694
protected ProxyMessage exchange(ProxyMessage request)
                           throws SocksException{
      ProxyMessage reply;
      try{
         request.write(out);
         reply = formMessage(in);
      }catch(SocksException s_ex){
         throw s_ex;
      }catch(IOException ioe){
         throw(new SocksException(SOCKS_PROXY_IO_ERROR,""+ioe));
      }
      return reply;
   }
11980
public void processTransactionTerminated(
            TransactionTerminatedEvent transactionTerminatedEvent) {
        Transaction transaction = null;
        if(transactionTerminatedEvent.isServerTransaction()) {
            transaction = transactionTerminatedEvent.getServerTransaction();
            if(logger.isDebugEnabled()) {
                logger.debug("timeout => " + transaction.getRequest().toString());
            }
        } else {
            transaction = transactionTerminatedEvent.getClientTransaction();
            if(logger.isDebugEnabled()) {
                logger.debug("timeout => " + transaction.getRequest().toString());
            }
        }
        if(Request.BYE.equals(transaction.getRequest().getMethod())) {
            String callId = ((CallIdHeader)transaction.getRequest().getHeader(CallIdHeader.NAME)).getCallId();
            register.unStickSessionFromNode(callId);
        }
    }
15436
public <R> EtcdResponsePromise<R> send(final EtcdRequest<R> etcdRequest) throws IOException {
    ConnectionState connectionState = new ConnectionState(uris, lastWorkingUriIndex);

    if (etcdRequest.getPromise() == null) {
      etcdRequest.setPromise(new EtcdResponsePromise<R>(
        etcdRequest.getRetryPolicy(),
        connectionState,
        new RetryHandler() {
          @Override
          public void doRetry(ConnectionState connectionState) throws IOException {
            connect(etcdRequest, connectionState);
          }
      }));
    }

    connect(etcdRequest, connectionState);

    return etcdRequest.getPromise();
  }
195976
public void setTransactionIsolation(final int level) throws SQLException {
    cmdPrologue();
    lock.lock();
    try {
      String query = "SET SESSION TRANSACTION ISOLATION LEVEL";
      switch (level) {
        case Connection.TRANSACTION_READ_UNCOMMITTED:
          query += " READ UNCOMMITTED";
          break;
        case Connection.TRANSACTION_READ_COMMITTED:
          query += " READ COMMITTED";
          break;
        case Connection.TRANSACTION_REPEATABLE_READ:
          query += " REPEATABLE READ";
          break;
        case Connection.TRANSACTION_SERIALIZABLE:
          query += " SERIALIZABLE";
          break;
        default:
          throw new SQLException("Unsupported transaction isolation level");
      }
      executeQuery(query);
      transactionIsolationLevel = level;
    } finally {
      lock.unlock();
    }
  }
966975
public void process(final Exchange exchange) throws Exception {
        final Message in = exchange.getIn();

        final String contentType = in.getHeader(CONTENT_TYPE, "", String.class);
        final String body = in.getBody(String.class);
        final Set<String> endpoints = new HashSet<>();

        for (final String s : in.getHeader(REINDEXING_RECIPIENTS, "", String.class).split(",")) {
            endpoints.add(s.trim());
        }

        if (contentType.equals("application/json") && body != null && !body.trim().isEmpty()) {
            try {
                final JsonNode root = MAPPER.readTree(body);
                final Iterator<JsonNode> ite = root.elements();
                while (ite.hasNext()) {
                    final JsonNode n = ite.next();
                    endpoints.add(n.asText());
                }
            } catch (JsonProcessingException e) {
                LOGGER.debug("Invalid JSON", e);
                in.setHeader(HTTP_RESPONSE_CODE, BAD_REQUEST);
                in.setBody("Invalid JSON");
            }
        }
        in.setHeader(REINDEXING_RECIPIENTS, join(",", endpoints));
    }
368279
@Override
    public void handleRequest(final HttpServerExchange exchange) throws Exception
    {
        if (this.defaultResponseListener != null) {
            exchange.addDefaultResponseListener(defaultResponseListener);
        }

        long fiGlobal = this.headers.fastIterateNonEmpty();

        while (fiGlobal != -1) {
            final HeaderValues headerValues = headers.fiCurrent(fiGlobal);

            exchange.getResponseHeaders().addAll(headerValues.getHeaderName(), headerValues);

            fiGlobal = headers.fiNextNonEmpty(fiGlobal);
        }

        next.handleRequest(exchange);
    }
409903
private void completeExtensionInitiations(TransactionBroadcaster transactionBroadcaster) {
        StoredPaymentChannelClientStates clientStoredChannels = (StoredPaymentChannelClientStates)
                vWallet.getExtensions().get(StoredPaymentChannelClientStates.class.getName());
        if(clientStoredChannels != null) {
            clientStoredChannels.setTransactionBroadcaster(transactionBroadcaster);
        }
        StoredPaymentChannelServerStates serverStoredChannels = (StoredPaymentChannelServerStates)
                vWallet.getExtensions().get(StoredPaymentChannelServerStates.class.getName());
        if(serverStoredChannels != null) {
            serverStoredChannels.setTransactionBroadcaster(transactionBroadcaster);
        }
    }
292418
public void handleInit(ChaincodeMessage message) throws InvalidTransactionException  {
		Runnable task = () -> {
			ChaincodeMessage nextStatemessage = null;
			boolean send = true;
			try {
				// Get the function and args from Payload
				ChaincodeInput input;
				try {
					input = ChaincodeInput.parseFrom(message.getPayload());
				} catch (InvalidProtocolBufferException e) {
                    nextStatemessage = ChaincodeMessage.newBuilder()
                            .setType(ERROR)
                            .setPayload(ByteString.copyFromUtf8("Unmarshall error -"
                                    + e.getMessage()))
                            .setTxid(message.getTxid())
                            .build();
                    return;
				}

				//			// Mark as a transaction (allow put/del state)
				markIsTransaction(message.getTxid(), true);

				// Create the ChaincodeStub which the chaincode can use to callback
				ChaincodeStub stub = new ChaincodeStub(message.getTxid(), this, message.getSecurityContext());
				// Call chaincode's Run
				ByteString result;
				try {
					result = chaincode.runHelper(stub, getFunction(input.getArgsList()), getParameters(input.getArgsList()));
				} catch (Exception e) {
					// Send ERROR message to chaincode support and change state
					logger.debug(String.format("[%s]Init failed. Sending %s", shortID(message), ERROR));
					nextStatemessage = ChaincodeMessage.newBuilder()
							.setType(ERROR)
							.setPayload(ByteString.copyFromUtf8(e.getMessage()))
							.setTxid(message.getTxid())
							.build();
					return;
				} finally {
					// delete isTransaction entry
					deleteIsTransaction(message.getTxid());
				}

				// Send COMPLETED message to chaincode support and change state
				nextStatemessage = ChaincodeMessage.newBuilder()
						.setType(COMPLETED)
						.setPayload(result)
						.setTxid(message.getTxid())
						.build();

				logger.debug(String.format(String.format("[%s]Init succeeded. Sending %s",
						shortID(message), COMPLETED)));

				//TODO put in all exception states
			}
		 finally {
				triggerNextState(nextStatemessage, send);
			}
		};

		//Run above task
		new Thread(task).start();
	}
1299533
final void beginGlobalTx(EJBKey key, EJBMethodInfoImpl methodInfo)
                    throws CSIException
    {
        //d135218 - removed check which assures that EJB 2.0 beans with
        //          sticky local transactions do not try to become involved
        //          in multiple transactions simultaneously.  This is checked
        //          during activation now.

        try {
            // d201891 global tx set time out value is now done by the tx service
            //    during begin processing.
            txCtrl.txService.begin();
            svUOWSynchReg.putResource("com.ibm.websphere.profile", // d458031
                                      methodInfo.getJPATaskName()); // d515803
            if (TraceComponent.isAnyTracingEnabled()) // d527372
            {
                if (tc.isEventEnabled())
                {
                    Tr.event(tc, "Began TX cntxt: " + txCtrl.txService.getTransaction()); //LIDB1673.2.1.5
                    Tr.event(tc, "Set JPA task name: " + methodInfo.getJPATaskName());
                }

                // d165585 Begins
                if (TETxLifeCycleInfo.isTraceEnabled()) // PQ74774
                { // PQ74774
                    String idStr = txCtrl.txService.getTransaction().toString();
                    int idx;
                    idStr = (idStr != null)
                                    ? (((idx = idStr.indexOf("(")) != -1)
                                                    ? idStr.substring(idx + 1, idStr.indexOf(")"))
                                                    : ((idx = idStr.indexOf("tid=")) != -1)
                                                                    ? idStr.substring(idx + 4)
                                                                    : idStr)
                                    : "NoTx";
                    TETxLifeCycleInfo.traceGlobalTxBegin(idStr, "Begin Global Tx");
                } // PQ74774
                // d165585 Ends
            }
        } catch (Exception ex) {
            FFDCFilter.processException(ex, CLASS_NAME + ".beginGlobalTx", "243", this);
            if (TraceComponent.isAnyTracingEnabled() && tc.isEventEnabled()) {
                Tr.event(tc, "Begin global tx failed", ex);
            }
            throw new CSIException("Begin global tx failed", ex);
        }
    }
1038355
private void resolveIncompleteTransactions() throws SQLException {

      switch(transactionState) {
         case COMPLETED:
            //All we know for certain is that at least one commit/rollback was called. Do nothing.
            break;
         case STARTED:
            //At least one statement was created with auto-commit false & no commit/rollback.
            //Follow the default policy.
            if(conn != null && openStatements.size() > 0) {
               switch(incompleteTransactionPolicy) {
                  case REPORT:
                     throw new SQLException("Statement closed with incomplete transaction", JDBConnection.SQLSTATE_INVALID_TRANSACTION_STATE);
                  case COMMIT:
                     if(!conn.isClosed()) {
                        conn.commit();
                     }
                     break;
                  case ROLLBACK:
                     if(!conn.isClosed()) {
                        conn.rollback();
                     }
               }
            }
            break;
      }
   }
622605
public void process(final Exchange exchange) throws Exception {
        final Message in = exchange.getIn();
        final String eventURIBase = in.getHeader(AuditHeaders.EVENT_BASE_URI, String.class);
        final String eventID = in.getHeader(FCREPO_EVENT_ID, String.class);
        final Resource eventURI = createResource(eventURIBase + "/" + eventID);

        // generate SPARQL Update
        final StringBuilder query = new StringBuilder("update=");
        query.append(ProcessorUtils.insertData(serializedGraphForMessage(in, eventURI), ""));

        // update exchange
        in.setBody(query.toString());
        in.setHeader(AuditHeaders.EVENT_URI, eventURI.toString());
        in.setHeader(Exchange.CONTENT_TYPE, "application/x-www-form-urlencoded");
        in.setHeader(Exchange.HTTP_METHOD, "POST");
    }
1240011
public void doBegin(Object transaction, TransactionDefinition definition) throws TransactionException {
		try {
			CompensatingTransactionObject txObject = (CompensatingTransactionObject) transaction;
			if (txObject.getHolder() == null) {
				CompensatingTransactionHolderSupport contextHolder = getNewHolder();
				txObject.setHolder(contextHolder);

				TransactionSynchronizationManager.bindResource(getTransactionSynchronizationKey(), contextHolder);
			}
		}
		catch (Exception e) {
			throw new CannotCreateTransactionException("Could not create DirContext instance for transaction", e);
		}
	}
857720
public function beginTransaction()
    {
        try {
            $this->connection->beginTransaction();
        } catch (DBALException $e) {
            throw new QueryException($e->getMessage(), $e->getCode(), $e);
        }
    }