Sends binary data to a client asynchronously.

@param session the client session where the message will be sent
@param inputStream the binary data to send
@param threadPool where the job will be submitted so it can execute asynchronously
438952
public void sendBinaryAsync(Session session, InputStream inputStream, ExecutorService threadPool) {
        if (session == null) {
            return;
        }

        if (inputStream == null) {
            throw new IllegalArgumentException("inputStream must not be null");
        }

        log.debugf("Attempting to send async binary data to client [%s]", session.getId());

        if (session.isOpen()) {
            if (this.asyncTimeout != null) {
                // TODO: what to do with timeout?
            }

            CopyStreamRunnable runnable = new CopyStreamRunnable(session, inputStream);
            threadPool.execute(runnable);
        }

        return;
    }
332954
@Override
  void write(ByteCodeWriter out)
    throws IOException
  {
    out.write(ConstantPool.CP_INVOKEDYNAMIC);
    out.writeShort(_bootstrapMethodAttrIndex);
    out.writeShort(_nameAndTypeIndex);
  }
1355264
void sessionError(final SibRaMessagingEngineConnection connection,
            final ConsumerSession session, final Throwable throwable) {

        final String methodName = "sessionError";
        if (TraceComponent.isAnyTracingEnabled() && TRACE.isEntryEnabled()) {
            SibTr.entry(this, TRACE, methodName, new Object[] { connection,
                    session });
        }

        final SIDestinationAddress destination = session
                .getDestinationAddress();

        if (_remoteDestination) {

            /*
             * Output a message to the admin console and attempt to create a new
             * listener
             */

            SibTr.warning(TRACE, "CONSUMER_FAILED_CWSIV0770", new Object[] {
                    destination.getDestinationName(),
                    _endpointConfiguration.getBusName(), this, throwable });

            try {

                createListener(connection);

            } catch (final ResourceException exception) {

                // No FFDC code needed

            }

        } else {

            if (SibRaEngineComponent.isMessagingEngineReloading(connection
                    .getConnection().getMeUuid())) {

                /*
                 * Output a warning to the admin console and close the
                 * connection - will be recreated during engineReloaded if
                 * required
                 */

                SibTr.warning(TRACE, "FAILURE_DURING_RELOAD_CWSIV0774",
                        new Object[] { throwable,
                                destination.getDestinationName(),
                                connection.getConnection().getMeName(),
                                destination.getBusName(), this });

                closeConnection(connection.getConnection().getMeUuid());

            } else {

                /*
                 * Output a message to the admin console and deactivate the
                 * endpoint
                 */

                SibTr.error(TRACE, "SESSION_ERROR_CWSIV0766", new Object[] {
                        throwable, destination.getDestinationName(),
                        connection.getConnection().getMeName(),
                        destination.getBusName(), this });

                deactivate();

            }

        }

        if (TraceComponent.isAnyTracingEnabled() && TRACE.isEntryEnabled()) {
            SibTr.exit(this, TRACE, methodName);
        }

    }
470889
private void write(IoSession session, IoBuffer data) {
        IoBuffer dest = buffersMap.putIfAbsent(session,
                new IoBufferLazyInitializer(bufferSize));

        write(session, data, dest);
    }
801937
void sessionError(final SibRaMessagingEngineConnection connection,
            final ConsumerSession session, final Throwable throwable) {

        /*
         * Do nothing - sessions are only used synchronously so the caller will
         * be notified
         */

        final String methodName = "sessionError";
        if (TraceComponent.isAnyTracingEnabled() && TRACE.isEntryEnabled()) {
            SibTr.entry(this, TRACE, methodName, new Object[] { connection,
                    session, throwable });
            SibTr.exit(this, TRACE, methodName);
        }

    }
1236510
@Override
    public void flush(int requestNumber) {
        if (TraceComponent.isAnyTracingEnabled() && tc.isEntryEnabled())
            SibTr.entry(this, tc, "flush", "" + requestNumber);

        // Locate the browser session to use.
        BrowserSession browserSession = mainConsumer.getBrowserSession();
        SIBusMessage msg = null;

        // Browse the next message and send it to the client.
        try {
            msg = getNextMessage(browserSession, getConversation(), (short) requestNumber);
            if (msg != null)
                sendMessage(msg);

            // Send a response to the browse request.
            try {
                getConversation().send(poolManager.allocate(),
                                       JFapChannelConstants.SEG_FLUSH_SESS_R,
                                       requestNumber,
                                       Conversation.PRIORITY_LOWEST,
                                       true,
                                       ThrottlingPolicy.BLOCK_THREAD,
                                       null);
            } catch (SIException e) {
                FFDCFilter.processException(e, CLASS_NAME + ".flush",
                                            CommsConstants.CATBROWSECONSUMER_FLUSH_01,
                                            this);

                SibTr.error(tc, "COMMUNICATION_ERROR_SICO2012", e);

                // Nothing else we can do at this point as the comms exception suggests that the
                // conversation is dead, anyway.
            }

        } catch (OperationFailedException e) {
            // No FFDC code needed
            if (TraceComponent.isAnyTracingEnabled() && tc.isEventEnabled())
                SibTr.exception(this, tc, e);
        }

        if (TraceComponent.isAnyTracingEnabled() && tc.isEntryEnabled())
            SibTr.exit(this, tc, "flush");
    }
353147
public static Function<IHTTPSession, Response> asyncHandler(@javax.annotation.Nonnull final ExecutorService pool, final String mimeType, @javax.annotation.Nonnull final Consumer<OutputStream> logic, final boolean async) {
    return session -> {
      @javax.annotation.Nonnull final PipedInputStream snk = new PipedInputStream();
      @javax.annotation.Nonnull final Semaphore onComplete = new Semaphore(0);
      pool.submit(() -> {
        try (@javax.annotation.Nonnull OutputStream out = new BufferedOutputStream(new AsyncOutputStream(new PipedOutputStream(snk)))) {
          try {
            logic.accept(out);
          } finally {
            onComplete.release();
          }
        } catch (@javax.annotation.Nonnull final IOException e) {
          e.printStackTrace();
          throw new RuntimeException(e);
        }
      });
      if (!async) {
        try {
          onComplete.acquire();
        } catch (@javax.annotation.Nonnull final InterruptedException e) {
          throw new RuntimeException(e);
        }
      }
      return NanoHTTPD.newChunkedResponse(Response.Status.OK, mimeType, new BufferedInputStream(snk));
    };
  }
965967
protected void sendInput()
    {
        Thread thread = new Thread()
        {
            public void run()
            {
                try
                {
                    stdin.write(input.getBytes("UTF-8"));
                    stdin.flush();
                    stdin.close();
                }
                catch (Exception e)
                {
                    exceptionCaught(e);
                }
            }
        };

        try
        {
            thread.start();
            thread.join();
        }
        catch (Exception e)
        {
            exceptionCaught(e);
        }
    }
435826
@Override
    public long processSyncWriteRequest(long numBytes, int timeout) throws IOException {
        if (TraceComponent.isAnyTracingEnabled() && tc.isEntryEnabled()) {
            Tr.entry(tc, "processSyncRequest(" + numBytes + "," + timeout + ")");
        }

        long numUserBytesWritten = 0; // no. of user bytes written

        if (numBytes != 0) {
            if (this.blockWait == null) {
                this.blockWait = new SimpleSync();
            }
            this.blockingIOError = null;

            // before we write, signal that we want to do the write ourselves
            // and not the worker threads.
            this.blockedThread = true;

            VirtualConnection vc = writeInternal(numBytes, null, false, timeout);

            while (vc == null) {
                // block until we are told to write
                this.blockWait.simpleWait();

                if (this.blockingIOError == null) {
                    vc = ((NioTCPChannel) getTCPConnLink().getTCPChannel()).getWorkQueueManager().processWork(this, 1);
                } else {
                    break;
                }
            }

            this.blockedThread = false;
            if (this.blockingIOError != null) {
                throw this.blockingIOError;
            }
            if (TraceComponent.isAnyTracingEnabled() && tc.isDebugEnabled()) {
                Tr.debug(tc, "getIOCompleteAmount() -->" + String.valueOf(getIOCompleteAmount()));
            }
            numUserBytesWritten = getIOCompleteAmount();
        } else {
            WsByteBuffer buffers[] = getBuffers();
            NioSocketIOChannel channel = (NioSocketIOChannel) getTCPConnLink().getSocketIOChannel();
            if (buffers.length == 1) {
                numUserBytesWritten = channel.write(buffers[0].getWrappedByteBufferNonSafe());
            } else {
                numUserBytesWritten = channel.write(getByteBufferArray());
            }
        }

        // return the number of bytes written
        if (TraceComponent.isAnyTracingEnabled() && tc.isEntryEnabled()) {
            Tr.exit(tc, "processSyncRequest", Long.valueOf(numUserBytesWritten));
        }
        return (numUserBytesWritten);
    }
249366
@Override
    public java.util.concurrent.Future<SendMessageResult> sendMessageAsync(String queueUrl, String messageBody) {

        return sendMessageAsync(new SendMessageRequest().withQueueUrl(queueUrl).withMessageBody(messageBody));
    }
746920
@Override
  public void sendAbortSessionAnswer(AbortSessionAnswer answer) throws InternalException, IllegalDiameterStateException, RouteException, OverloadException {
    send(Event.Type.SEND_SESSION_ABORT_ANSWER, answer);
  }
953289
public static Function<IHTTPSession, Response> syncHandler(final ExecutorService pool, final String mimeType, @javax.annotation.Nonnull final Consumer<OutputStream> logic, final boolean async) {
    return session -> {
      try (@javax.annotation.Nonnull ByteArrayOutputStream out = new ByteArrayOutputStream()) {
        logic.accept(out);
        out.flush();
        final byte[] bytes = out.toByteArray();
        return NanoHTTPD.newFixedLengthResponse(Response.Status.OK, mimeType, new ByteArrayInputStream(bytes), bytes.length);
      } catch (@javax.annotation.Nonnull final IOException e) {
        e.printStackTrace();
        throw new RuntimeException(e);
      }
    };
  }
1175261
private void sendRequest(byte[] reqBytes, URLConnection connection) {
        HttpURLConnection httpconnection = (HttpURLConnection) connection;
        OutputStream out = null;
        try {
            if (connectTimeout > 0) {
                httpconnection.setConnectTimeout(connectTimeout);
            }
            if (readTimeout > 0) {
                httpconnection.setReadTimeout(readTimeout);
            }
            httpconnection.setRequestMethod("POST");
            httpconnection.setUseCaches(false);
            httpconnection.setDoInput(true);
            httpconnection.setDoOutput(true);
            httpconnection.setRequestProperty("Content-Type", serializeHandler.getProtocol()
                    .getName() + ";charset=" + NaviRpcClientConstant.ENDODING);
            httpconnection.setRequestProperty("Content-Length", StringUtil.EMPTY + reqBytes.length);
            httpconnection.connect();
            out = httpconnection.getOutputStream();
            out.write(reqBytes);
            if (LOG.isDebugEnabled()) {
                LOG.debug("Send " + reqBytes.length + " bytes done");
            }
        } catch (Exception e) {
            throw new RpcException("Rpc send request failed - " + e.getMessage() + " on "
                    + connection.getURL(), e);
        } finally {
            if (out != null) {
                try {
                    out.close();
                } catch (IOException e) {
                    LOG.error("Close send request connection error");
                }
            }
        }
    }
1330255
public static void sendBinary(final ByteBuffer[] data, final WebSocketChannel wsChannel, final WebSocketCallback<Void> callback, long timeoutmillis) {
        sendInternal(mergeBuffers(data), WebSocketFrameType.BINARY, wsChannel, callback, null, timeoutmillis);
    }
1255924
public void sendEndEvaluationInstance(Stream inputStream) {
		InstanceContentEvent instanceContentEvent = new InstanceContentEvent(-1, firstInstance,false, true);
		inputStream.put(instanceContentEvent);
	}
955927
private void sendInputStream(InputStream inputStream) {
    byte[] buffer = new byte[ONE_KB];
    int read;
    try {
      // This method uses a blocking while loop to receive all contents of the underlying input stream.
      // AudioInputStreams, typically used for streaming microphone inputs return 0 only when the stream has been
      // closed. Elsewise AudioInputStream.read() blocks until enough audio frames are read.
      while (((read = inputStream.read(buffer)) > 0) && socketOpen) {

        // If OkHttp's WebSocket queue gets overwhelmed, it'll abruptly close the connection
        // (see: https://github.com/square/okhttp/issues/3317). This will ensure we wait until the coast is clear.
        while (socket.queueSize() > QUEUE_SIZE_LIMIT) {
          Thread.sleep(QUEUE_WAIT_MILLIS);
        }

        if (read == ONE_KB) {
          socket.send(ByteString.of(buffer));
        } else {
          socket.send(ByteString.of(Arrays.copyOfRange(buffer, 0, read)));
        }
      }
    } catch (IOException | InterruptedException e) {
      LOG.log(Level.SEVERE, e.getMessage(), e);
    } finally {
      try {
        inputStream.close();
      } catch (IOException e) {
        // do nothing - the InputStream may have already been closed externally.
      }
    }
  }
655651
@Override
  public final void onSessionClosed(Session session) {
    this.client.getConnector().removeSession(session);
    // Clear write queue to release noreply operations.
    ((AbstractSession) session).clearWriteQueue();
    MemcachedTCPSession memcachedSession = (MemcachedTCPSession) session;
    // destroy memached session
    memcachedSession.destroy();
    if (this.client.getConnector().isStarted() && memcachedSession.isAllowReconnect()) {
      this.reconnect(memcachedSession);
    }
    for (MemcachedClientStateListener listener : this.client.getStateListeners()) {
      listener.onDisconnected(this.client, session.getRemoteSocketAddress());
    }

  }