/*
(non-Javadoc)

@see org.restcomm.protocols.ss7.tcap.api.tc.dialog.Dialog#send(org.mobicents
.protocols.ss7.tcap.api.tc.dialog.events.TCContinueRequest)
351420
public void send(TCContinueRequest event) throws TCAPSendException {

        if (this.previewMode)
            return;

        if (!this.isStructured()) {
            throw new TCAPSendException("Unstructured dialogs do not use Continue");
        }
        try {
            this.dialogLock.lock();
            if (this.state == TRPseudoState.InitialReceived) {
                this.idleTimerActionTaken = true;
                restartIdleTimer();
                TCContinueMessageImpl tcbm = (TCContinueMessageImpl) TcapFactory.createTCContinueMessage();

                if (event.getApplicationContextName() != null) {

                    // set dialog portion
                    DialogPortion dp = TcapFactory.createDialogPortion();
                    dp.setUnidirectional(false);
                    DialogResponseAPDU apdu = TcapFactory.createDialogAPDUResponse();
                    apdu.setDoNotSendProtocolVersion(doNotSendProtocolVersion());
                    dp.setDialogAPDU(apdu);
                    apdu.setApplicationContextName(event.getApplicationContextName());
                    if (event.getUserInformation() != null) {
                        apdu.setUserInformation(event.getUserInformation());
                    }
                    // WHERE THE HELL THIS COMES FROM!!!!
                    // WHEN REJECTED IS USED !!!!!
                    Result res = TcapFactory.createResult();
                    res.setResultType(ResultType.Accepted);
                    ResultSourceDiagnostic rsd = TcapFactory.createResultSourceDiagnostic();
                    rsd.setDialogServiceUserType(DialogServiceUserType.Null);
                    apdu.setResultSourceDiagnostic(rsd);
                    apdu.setResult(res);
                    tcbm.setDialogPortion(dp);

                }

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

                }
                // local address may change, lets check it;
                if (event.getOriginatingAddress() != null && !event.getOriginatingAddress().equals(this.localAddress)) {
                    this.localAddress = event.getOriginatingAddress();
                }
                AsnOutputStream aos = new AsnOutputStream();
                try {
                    tcbm.encode(aos);
                    if (this.provider.getStack().getStatisticsEnabled()) {
                        this.provider.getStack().getCounterProviderImpl().updateTcContinueSentCount(this);
                    }
                    this.provider.send(aos.toByteArray(), event.getReturnMessageOnError(), this.remoteAddress,
                            this.localAddress, this.seqControl, this.networkId, this.localSsn, this.remotePc);
                    this.setState(TRPseudoState.Active);
                    this.scheduledComponentList.clear();
                } catch (Exception e) {
                    // FIXME: remove freshly added invokes to free invoke ID??
                    if (logger.isEnabledFor(Level.ERROR)) {
                        logger.error("Failed to send message: ", e);
                    }
                    throw new TCAPSendException("Failed to send TC-Continue message: " + e.getMessage(), e);
                }

            } else if (state == TRPseudoState.Active) {
                this.idleTimerActionTaken = true;
                restartIdleTimer();
                // in this we ignore acn and passed args(except qos)
                TCContinueMessageImpl tcbm = (TCContinueMessageImpl) TcapFactory.createTCContinueMessage();

                tcbm.setOriginatingTransactionId(Utils.encodeTransactionId(this.localTransactionId, isSwapTcapIdBytes));
                tcbm.setDestinationTransactionId(this.remoteTransactionId);
                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.provider.getStack().getCounterProviderImpl().updateTcContinueSentCount(this);
                    this.provider.send(aos.toByteArray(), event.getReturnMessageOnError(), this.remoteAddress,
                            this.localAddress, this.seqControl, this.networkId, this.localSsn, this.remotePc);
                    this.scheduledComponentList.clear();
                } catch (Exception e) {
                    // FIXME: remove freshly added invokes to free invoke ID??
                    if (logger.isEnabledFor(Level.ERROR)) {
                        logger.error("Failed to send message: ", e);
                    }
                    throw new TCAPSendException("Failed to send TC-Continue message: " + e.getMessage(), e);
                }
            } else {
                throw new TCAPSendException("Wrong state: " + this.state);
            }

        } finally {
            this.dialogLock.unlock();
        }
    }
288519
public void sendRequest(Message request, Object context, Message.Builder responseBuilder,
                          Duration timeout) {
    // Pack it as a no-timeout request and send it!
    final REQID rid = REQID.generate();
    contextMap.put(rid, context);
    responseMessageMap.put(rid, responseBuilder);

    // Add timeout for this request if necessary
    if (timeout.getSeconds() > 0) {
      registerTimerEvent(timeout, new Runnable() {
        @Override
        public void run() {
          handleTimeout(rid);
        }
      });
    }

    OutgoingPacket opk = new OutgoingPacket(rid, request);
    socketChannelHelper.sendPacket(opk);
  }
883496
@Override
    public void sendRequestHeaders() throws IOException, MessageSentException {

        if (TraceComponent.isAnyTracingEnabled() && tc.isEntryEnabled()) {
            Tr.entry(tc, "sendRequestHeaders(sync)");
        }
        if (headersSent()) {
            throw new MessageSentException("Headers already sent");
        }

        setPartialBody(true);
        getLink().setAllowReconnect(true);
        try {
            sendHeaders(getRequestImpl());
        } catch (IOException e) {
            // no FFDC required
            reConnect(e);
        }
        // check to see if we need to read the response now
        if (shouldReadResponseImmediately()) {
            startResponseReadSync();
        }
        if (TraceComponent.isAnyTracingEnabled() && tc.isEntryEnabled()) {
            Tr.exit(tc, "sendRequestHeaders(sync)");
        }
    }
1300461
public TCContinueRequest createContinue(Dialog d) {
        if (d == null) {
            throw new NullPointerException("Dialog is null");
        }
        TCContinueRequestImpl tccr = new TCContinueRequestImpl();
        tccr.setDialog(d);
        tccr.setOriginatingAddress(d.getLocalAddress());

        return tccr;
    }
33319
public void send(CEMILData msg, boolean waitForCon) throws KNXTimeoutException,
		KNXLinkClosedException
	{
		doSend(adjustMsgType(msg), waitForCon);
	}
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);
    }
1330643
private <T> HttpResponse sendRequest(final URI uri, final HttpRequest<T> request) throws IOException, ProtocolException
	{
		final HttpURLConnection connection;
		try
		{
			connection = mConnectionFactory.httpUrlConnection(uri);
		}
		catch (IllegalArgumentException e)
		{
			throw new ProtocolException("The given URI is not applicable to HTTP requests.", e);
		}
		// ensure the expected redirect behavior
		connection.setInstanceFollowRedirects(false);
		// set the request method
		connection.setDoOutput(request.method().supportsRequestPayload());
		connection.setRequestMethod(request.method().verb());
		// add all headers
		for (Header<?> header : request.headers())
		{
			connection.setRequestProperty(header.type().name(), header.toString());
		}
		// also set the content-type header if we have any content-type
		if (request.requestEntity().contentType() != null)
		{
			connection.setRequestProperty(HttpHeaders.CONTENT_TYPE.name(), HttpHeaders.CONTENT_TYPE.valueString(request.requestEntity().contentType()));
		}
		// send the request entity if applicable
		if (request.method().supportsRequestPayload())
		{
			OutputStream out = connection.getOutputStream();
			try
			{
				request.requestEntity().writeContent(out);
			}
			finally
			{
				out.close();
			}
		}
		// return the response
		return new HttpUrlConnectionResponse(uri, connection);
	}
1369434
public void onInviteEvent(javax.sip.RequestEvent requestEvent,
			ActivityContextInterface aci) {

		final ServerTransaction serverTransaction = requestEvent
				.getServerTransaction();

		try {
			// send "trying" response
			Response response = messageFactory.createResponse(Response.TRYING,
					requestEvent.getRequest());
			serverTransaction.sendResponse(response);
			// get local object
			final SbbLocalObject sbbLocalObject = this.sbbContext
					.getSbbLocalObject();
			
			// send 180
			response = messageFactory.createResponse(Response.RINGING,
					requestEvent.getRequest());
			serverTransaction.sendResponse(response);

			setFinalReplySent(false);
			// set timer of 1 secs on the dialog aci to send 200 OK after that
			timerFacility.setTimer(aci, null,
					System.currentTimeMillis() + 1000L, getTimerOptions());			
						
		} catch (Exception e) {
			getTracer().severe("failure while processing initial invite", e);
		}
	}
1228552
@Override
	public void send( AbstractPacket packet ) throws PacketTransportException
    {
        if (closed)
   			throw new PacketTransportException("Transport is closed");
        
        sender.send(packet);
    }
78235
public void send(TCUniRequest event) throws TCAPSendException {

        if (this.previewMode)
            return;

        if (this.isStructured()) {
            throw new TCAPSendException("Structured dialogs do not use Uni");
        }

        try {
            this.dialogLock.lock();
            TCUniMessageImpl msg = (TCUniMessageImpl) TcapFactory.createTCUniMessage();

            if (event.getApplicationContextName() != null) {
                DialogPortion dp = TcapFactory.createDialogPortion();
                DialogUniAPDU apdu = TcapFactory.createDialogAPDUUni();
                apdu.setDoNotSendProtocolVersion(doNotSendProtocolVersion());
                apdu.setApplicationContextName(event.getApplicationContextName());
                if (event.getUserInformation() != null) {
                    apdu.setUserInformation(event.getUserInformation());
                }
                dp.setUnidirectional(true);
                dp.setDialogAPDU(apdu);
                msg.setDialogPortion(dp);

            }

            if (this.scheduledComponentList.size() > 0) {
                Component[] componentsToSend = new Component[this.scheduledComponentList.size()];
                this.prepareComponents(componentsToSend);
                msg.setComponent(componentsToSend);

            }

            AsnOutputStream aos = new AsnOutputStream();
            try {
                msg.encode(aos);
                if (this.provider.getStack().getStatisticsEnabled()) {
                    this.provider.getStack().getCounterProviderImpl().updateTcUniSentCount(this);
                }
                this.provider.send(aos.toByteArray(), event.getReturnMessageOnError(), this.remoteAddress, this.localAddress,
                        this.seqControl, this.networkId, this.localSsn, this.remotePc);
                this.scheduledComponentList.clear();
            } catch (Exception e) {
                if (logger.isEnabledFor(Level.ERROR)) {
                    logger.error("Failed to send message: ", e);
                }
                throw new TCAPSendException("Failed to send TC-Uni message: " + e.getMessage(), e);
            } finally {
                release();
            }
        } finally {
            this.dialogLock.unlock();
        }
    }
419795
@Override
    public synchronized boolean send(final Object message,
                                     final boolean shouldClose,
                                     final OnComplete onComplete) throws IOException {
        if (!isOpen()) {
            return false;
        }

        this.sendQueued = true;

        byte[] data;
        if (message == null) {
            data = null;
        } else if (message instanceof String) {
            data = ((String)message).getBytes(getResponseCharset());
        } else if (message instanceof byte[]) {
            data = (byte[])message;
        } else {
            throw WebsocketUtil.wrongMessageType(message.getClass());
        }

        enqueue(new PendingSend(data, shouldClose, onComplete));

        return true;
    }
721568
private void sendCloseSession() throws IOException{
        ProtocolHeader h = new ProtocolHeader();
        h.setType(ProtocolType.CloseSession);

        sendAdminPacket(h, null);
    }
804976
private void sendSomeRequests() {
		ResponseListener responseListener = new MyResponseListener();

		sendCustomUrlRequest(responseListener);
		sendAutoRetryRequest(responseListener);
		downloadImage(responseListener);
		uploadData(responseListener);
		uploadFile(responseListener);
		uploadText(responseListener);
	}
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();
        }
    }
373302
private void sendRequest(String header, byte[] body) throws IOException {
        // Send entire message in one write, else suffer the fate of weird TCP/IP stacks.
        byte[] headerBytes = Utils.toBytes(header);
        byte[] requestBytes = headerBytes;
        if (body != null && body.length > 0) {
            requestBytes = new byte[headerBytes.length + body.length];
            System.arraycopy(headerBytes, 0, requestBytes, 0, headerBytes.length);
            System.arraycopy(body, 0, requestBytes, headerBytes.length, body.length);
        }
        
        // Send the header and body (if any) and flush the result.
        m_outStream.write(requestBytes);
        m_outStream.flush();
    }
791516
public void send(CEMILData msg, boolean waitForCon) throws KNXTimeoutException,
		KNXLinkClosedException
	{
		doSend(createEMI(msg), waitForCon, msg.getDestination());
	}