/* (non-Javadoc)
@see javax.ws.rs.sse.SseEventSink#send(javax.ws.rs.sse.OutboundSseEvent)
181918
@FFDCIgnore({WebApplicationException.class, IOException.class, NoSuitableMessageBodyWriterException.class})
    @Override
    public CompletionStage<?> send(OutboundSseEvent event) {
        final CompletableFuture<?> future = new CompletableFuture<>();

        if (!closed) {
            if (writer != null) {
                ByteArrayOutputStream os = null;
                try {
                    os = new ByteArrayOutputStream();
                    writer.writeTo(event, event.getClass(), null, new Annotation [] {}, event.getMediaType(), null, os);

                    String eventContents = os.toString();
                    if (TraceComponent.isAnyTracingEnabled() && tc.isDebugEnabled()) {
                        Tr.debug(tc, "send - sending " + eventContents);
                    }

                    if (!response.isCommitted()) {
                        response.setHeader("Content-Type", MediaType.SERVER_SENT_EVENTS);
                        response.flushBuffer();
                    }

                    //TODO: this seems like a bug, but most SSE clients seem to expect a named event
                    //      so for now, we will provide one if one is not provided by the user
                    if (event.getName() == null) {
                        response.getOutputStream().print("    UnnamedEvent\n");
                    }
                    response.getOutputStream().println(eventContents);
                    response.getOutputStream().flush();

                    return CompletableFuture.completedFuture(eventContents);
                } catch (NoSuitableMessageBodyWriterException ex) {
                    handleException(ex, future, event);
                    throw new IllegalArgumentException("No suitable message body writer for OutboundSseEvent created with data " + event.getData() + " and mediaType " + event.getMediaType() + ". The data contained within the OutboundSseEvent must match the mediaType."); 
                } catch (WebApplicationException ex) {
                    handleException(ex, future, event);
                } catch (IOException ex) {
                    handleException(ex, future, event);
                } finally {
                    if (os != null) {
                        try {
                            os.close();
                        } catch (IOException ex) {
                            //ignore
                        }
                    }
                }
            } else {  //no writer
                if (TraceComponent.isAnyTracingEnabled() && tc.isDebugEnabled()) {
                    Tr.debug(tc, "No MessageBodyWriter - returning null for event:  " + event);
                }
                future.complete(null);
            }  
        } else {
            if (TraceComponent.isAnyTracingEnabled() && tc.isDebugEnabled()) {
                Tr.debug(tc, "SseEventSink is closed - failed sending event:  " + event);
            }
            throw new IllegalStateException("SseEventSink is closed.");  
        }

        return future;
    }
165639
public void send(TCBeginRequest event) throws TCAPSendException {

        if (this.previewMode)
            return;

        if (this.state != TRPseudoState.Idle) {
            throw new TCAPSendException("Can not send Begin in this state: " + this.state);
        }

        if (!this.isStructured()) {
            throw new TCAPSendException("Unstructured dialogs do not use Begin");
        }
        try {
            this.dialogLock.lock();
            this.idleTimerActionTaken = true;
            restartIdleTimer();
            TCBeginMessageImpl tcbm = (TCBeginMessageImpl) TcapFactory.createTCBeginMessage();

            // build DP

            if (event.getApplicationContextName() != null) {
                this.dpSentInBegin = true;
                DialogPortion dp = TcapFactory.createDialogPortion();
                dp.setUnidirectional(false);
                DialogRequestAPDU apdu = TcapFactory.createDialogAPDURequest();
                apdu.setDoNotSendProtocolVersion(doNotSendProtocolVersion());
                dp.setDialogAPDU(apdu);
                apdu.setApplicationContextName(event.getApplicationContextName());
                this.lastACN = event.getApplicationContextName();
                if (event.getUserInformation() != null) {
                    apdu.setUserInformation(event.getUserInformation());
                    this.lastUI = event.getUserInformation();
                }
                tcbm.setDialogPortion(dp);

                if (this.provider.getStack().getStatisticsEnabled()) {
                    String acn = ((ApplicationContextNameImpl) event.getApplicationContextName()).getStringValue();
                    this.provider.getStack().getCounterProviderImpl().updateOutgoingDialogsPerApplicatioContextName(acn);
                }
            } else {
                if (this.provider.getStack().getStatisticsEnabled()) {
                    this.provider.getStack().getCounterProviderImpl().updateOutgoingDialogsPerApplicatioContextName("");
                }
            }

            // now comps
            tcbm.setOriginatingTransactionId(Utils.encodeTransactionId(this.localTransactionId, isSwapTcapIdBytes));
            if (this.scheduledComponentList.size() > 0) {
                Component[] componentsToSend = new Component[this.scheduledComponentList.size()];
                this.prepareComponents(componentsToSend);
                tcbm.setComponent(componentsToSend);
            }

            AsnOutputStream aos = new AsnOutputStream();
            try {
                tcbm.encode(aos);
                this.setState(TRPseudoState.InitialSent);
                if (this.provider.getStack().getStatisticsEnabled()) {
                    this.provider.getStack().getCounterProviderImpl().updateTcBeginSentCount(this);
                }
                this.provider.send(aos.toByteArray(), event.getReturnMessageOnError(), this.remoteAddress, this.localAddress,
                        this.seqControl, this.networkId, this.localSsn, this.remotePc);
                this.scheduledComponentList.clear();
            } catch (Throwable e) {
                // FIXME: remove freshly added invokes to free invoke ID??
                // TODO: should we release this dialog because TC-BEGIN sending has been failed
                if (logger.isEnabledFor(Level.ERROR)) {
                    logger.error("Failed to send message: ", e);
                }
                throw new TCAPSendException("Failed to send TC-Begin message: " + e.getMessage(), e);
            }

        } finally {
            this.dialogLock.unlock();
        }
    }
275415
@Override
    public void send(final Object message) throws MessageTransportException {
        if (shutdown.get())
            throw new MessageTransportException("send called on shutdown queue.");

        if (blocking) {
            while (true) {
                try {
                    queue.put(message);
                    if (statsCollector != null)
                        statsCollector.messageSent(message);
                    break;
                } catch (final InterruptedException ie) {
                    if (shutdown.get())
                        throw new MessageTransportException("Shutting down durring send.");
                }
            }
        } else {
            if (!queue.offer(message)) {
                if (statsCollector != null)
                    statsCollector.messageNotSent();
                throw new MessageTransportException("Failed to queue message due to capacity.");
            } else if (statsCollector != null)
                statsCollector.messageSent(message);
        }
    }
1049861
public void send(CEMI frame, BlockingMode mode) throws KNXConnectionClosedException
	{
		try {
			super.send(frame, NONBLOCKING);
			// we always succeed...
			setState(OK);
		}
		catch (final KNXTimeoutException e) {}
	}
821843
void sendMigrationEvent(final MigrationInfo migrationInfo, final MigrationEvent.MigrationStatus status) {
        if (migrationInfo.getSourceCurrentReplicaIndex() != 0
                && migrationInfo.getDestinationNewReplicaIndex() != 0) {
            // only fire events for 0th replica migrations
            return;
        }

        ClusterServiceImpl clusterService = node.getClusterService();
        MemberImpl current = clusterService.getMember(migrationInfo.getSourceAddress());
        MemberImpl newOwner = clusterService.getMember(migrationInfo.getDestinationAddress());
        MigrationEvent event = new MigrationEvent(migrationInfo.getPartitionId(), current, newOwner, status);
        EventService eventService = nodeEngine.getEventService();
        Collection<EventRegistration> registrations = eventService.getRegistrations(SERVICE_NAME, MIGRATION_EVENT_TOPIC);
        eventService.publishEvent(SERVICE_NAME, registrations, event, event.getPartitionId());
    }
33319
public void send(CEMILData msg, boolean waitForCon) throws KNXTimeoutException,
		KNXLinkClosedException
	{
		doSend(adjustMsgType(msg), waitForCon);
	}
683574
public void send(TCQueryRequest event) throws TCAPSendException {

        if (this.previewMode)
            return;

        if (this.state != TRPseudoState.Idle) {
            throw new TCAPSendException("Can not send Begin in this state: " + this.state);
        }

        if (!this.isStructured()) {
            throw new TCAPSendException("Unstructured dialogs do not use Begin");
        }
        try {
            this.dialogLock.lock();
            this.idleTimerActionTaken = true;
            restartIdleTimer();
            TCQueryMessageImpl tcbm = (TCQueryMessageImpl) TcapFactory.createTCQueryMessage();

            // build DP
            tcbm.setDialogTermitationPermission(event.getDialogTermitationPermission());
            tcbm.setOriginatingTransactionId(Utils.encodeTransactionId(this.localTransactionId, this.isSwapTcapIdBytes));

            if (event.getApplicationContextName() != null || event.getConfidentiality() != null
                    || event.getSecurityContext() != null || event.getUserInformation() != null) {
                this.dpSentInBegin = true;
                this.lastACN = event.getApplicationContextName();
                if (event.getUserInformation() != null) {
                    this.lastUI = event.getUserInformation();
                }

                DialogPortion dp = TcapFactory.createDialogPortion();
                dp.setProtocolVersion(TcapFactory.createProtocolVersionFull());
                dp.setApplicationContext(event.getApplicationContextName());
                dp.setUserInformation(event.getUserInformation());
                dp.setSecurityContext(event.getSecurityContext());
                dp.setConfidentiality(event.getConfidentiality());

                tcbm.setDialogPortion(dp);

                if (this.provider.getStack().getStatisticsEnabled()) {
                    if (event.getApplicationContextName() != null) {
                        String acn = ((ApplicationContextImpl) event.getApplicationContextName()).getStringValue();
                        this.provider.getStack().getCounterProviderImpl().updateOutgoingDialogsPerApplicatioContextName(acn);
                    } else {
                        this.provider.getStack().getCounterProviderImpl().updateOutgoingDialogsPerApplicatioContextName("");
                    }
                }
            }

            // now comps
            if (this.scheduledComponentList.size() > 0) {
                Component[] componentsToSend = new Component[this.scheduledComponentList.size()];
                this.prepareComponents(componentsToSend);
                tcbm.setComponent(componentsToSend);
            }

            AsnOutputStream aos = new AsnOutputStream();
            try {
                tcbm.encode(aos);
                this.setState(TRPseudoState.InitialSent);
                if (this.provider.getStack().getStatisticsEnabled()) {
                    this.provider.getStack().getCounterProviderImpl().updateTcQuerySentCount(this);
                }
                this.provider.send(aos.toByteArray(), event.getReturnMessageOnError(), this.remoteAddress, this.localAddress,
                        this.seqControl, this.getNetworkId(), this.localSsn);
                this.scheduledComponentList.clear();
            } catch (Throwable e) {
                if (logger.isEnabledFor(Level.ERROR)) {
                    logger.error("Failed to send message: ", e);
                }
                throw new TCAPSendException("Failed to send TC-Query message: " + e.getMessage(), e);
            }

        } finally {
            this.dialogLock.unlock();
        }
    }
611397
protected void sendEvent(final T event) {
        if (isStatic) {
            sendEvent(event, null, null);
        } else {
            CreationalContext<X> creationalContext = null;
            try {
                Object receiver = getReceiverIfExists(null);
                if (receiver == null && reception != Reception.IF_EXISTS) {
                    // creational context is created only if we need it for obtaining receiver
                    // ObserverInvocationStrategy takes care of creating CC for parameters, if needed
                    creationalContext = beanManager.createCreationalContext(declaringBean);
                    receiver = getReceiverIfExists(creationalContext);
                }
                if (receiver != null) {
                    sendEvent(event, receiver, creationalContext);
                }
            } finally {
                if (creationalContext != null) {
                    creationalContext.release();
                }
            }
        }
    }
1311804
protected void sendMessage(String xml) {
    byte[] bytes = null;
    try {
      bytes = xml.getBytes("UTF-8");
      writeBytes(bytes);
    } catch (SocketException se) {
      // when we get a socket exception, let's try to re-establish
      stop();
      start();
      try {
        writeBytes(bytes);
      } catch (IOException e) {
        throw new WebDriverException(e);
      }
    } catch (IOException e) {
      throw new WebDriverException(e);
    }
  }
1348012
private void sendAnnouncement(InetAddress broadcastAddress) {
        try {
            DatagramPacket announcement = new DatagramPacket(announcementBytes, announcementBytes.length,
                    broadcastAddress, DeviceFinder.ANNOUNCEMENT_PORT);
            socket.get().send(announcement);
            Thread.sleep(getAnnounceInterval());
        } catch (Throwable t) {
            logger.warn("Unable to send announcement packet, shutting down", t);
            stop();
        }
    }
1163812
public static void sendNotification (
        ClientObject target, String receiverCode, int methodId, Object[] args)
    {
        sendNotification(target, receiverCode, methodId, args, Transport.DEFAULT);
    }
502158
@Override
	public final void send(Message message, int deliveryMode, int priority, long timeToLive) throws JMSException
    {
    	if (this.destination == null)
    		throw new UnsupportedOperationException("Destination was not set at creation time");

        // Setup message fields
    	setupMessage(destination,message,deliveryMode,priority,timeToLive);
    	
    	// Handle foreign message implementations
        message = MessageTools.normalize(message);
        
    	sendToDestination(destination,false,message,deliveryMode,priority,timeToLive);
    }
639399
public void send(final Command msg) throws HandlerSocketException {
		Session session = this.selectSession();
		session.write(msg);
	}
342469
public void sendEvent(Event event) {
        for (ShouldSendEventCallback shouldSendEventCallback : shouldSendEventCallbacks) {
            if (!shouldSendEventCallback.shouldSend(event)) {
                logger.trace("Not sending Event because of ShouldSendEventCallback: {}", shouldSendEventCallback);
                return;
            }
        }

        try {
            connection.send(event);
        } catch (LockedDownException | TooManyRequestsException e) {
            logger.debug("Dropping an Event due to lockdown: " + event);
        } catch (Exception e) {
            logger.error("An exception occurred while sending the event to Sentry.", e);
        } finally {
            getContext().setLastEventId(event.getId());
        }
    }
1306832
public MessageId send(ProducerConnectionContext context, BasicMessage basicMessage) throws JMSException {
        return send(context, basicMessage, null);
    }
666534
@Override
	public final void send(Message message) throws JMSException
    {
    	if (this.destination == null)
    		throw new UnsupportedOperationException("Destination was not set at creation time");
    	
    	// Setup message fields
    	setupMessage(destination,message,defaultDeliveryMode,defaultPriority,defaultTimeToLive);
    	
    	// Handle foreign message implementations
        message = MessageTools.normalize(message);

        sendToDestination(destination,false,message,defaultDeliveryMode,defaultPriority,defaultTimeToLive);
    }
351488
@Override
    protected void sendToNode(Message message, short node, InetSocketAddress address) {
        try {
            if (LOG.isDebugEnabled())
                LOG.debug("Sending to node {} ({}): {}", new Object[]{node, address, message});
            message.cloneDataBuffers(); // important, as we're going to be doing actual sending on another thread

            final NodePeer peer = peers.get(node);
            if (peer == null)
                throw new NodeNotFoundException(node);

            peer.sendMessage(message);
            executor.submit(peer);
        } catch (InterruptedException ex) {
            LOG.error("InterruptedException", ex);
            throw new RuntimeException(ex);
        } catch (Exception ex) {
            LOG.error("Error while sending message " + message + " to node " + node, ex);
        }
    }