/*
(non-Javadoc)

@see org.restcomm.protocols.ss7.tcap.api.tc.dialog.Dialog#send(org.mobicents
.protocols.ss7.tcap.api.tc.dialog.events.TCContinueRequest)
438804
public void send(TCConversationRequest 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();
                TCConversationMessageImpl tcbm = (TCConversationMessageImpl) TcapFactory.createTCConversationMessage();

                tcbm.setDialogTermitationPermission(event.getDialogTermitationPermission());
                tcbm.setOriginatingTransactionId(Utils.encodeTransactionId(this.localTransactionId, this.isSwapTcapIdBytes));
                tcbm.setDestinationTransactionId(this.remoteTransactionId);
                // local address may change, lets check it;
                if (event.getOriginatingAddress() != null && !event.getOriginatingAddress().equals(this.localAddress)) {
                    this.localAddress = event.getOriginatingAddress();
                }

                if (event.getApplicationContextName() != null || event.getConfidentiality() != null
                        || event.getSecurityContext() != null || event.getUserInformation() != null) {
                    // set dialog portion
                    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.scheduledComponentList.size() > 0) {
                    Component[] componentsToSend = new Component[this.scheduledComponentList.size()];
                    this.prepareComponents(componentsToSend);
                    tcbm.setComponent(componentsToSend);

                }

                AsnOutputStream aos = new AsnOutputStream();
                try {
                    tcbm.encode(aos);
                    if (this.provider.getStack().getStatisticsEnabled()) {
                        this.provider.getStack().getCounterProviderImpl().updateTcConversationSentCount(this);
                    }
                    this.provider.send(aos.toByteArray(), event.getReturnMessageOnError(), this.remoteAddress,
                            this.localAddress, this.seqControl, this.getNetworkId(), this.localSsn);
                    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)
                TCConversationMessageImpl tcbm = (TCConversationMessageImpl) TcapFactory.createTCConversationMessage();

                tcbm.setDialogTermitationPermission(event.getDialogTermitationPermission());
                tcbm.setOriginatingTransactionId(Utils.encodeTransactionId(this.localTransactionId, this.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);
                    if (this.provider.getStack().getStatisticsEnabled()) {
                        this.provider.getStack().getCounterProviderImpl().updateTcConversationSentCount(this);
                    }
                    this.provider.send(aos.toByteArray(), event.getReturnMessageOnError(), this.remoteAddress,
                            this.localAddress, this.seqControl, this.getNetworkId(), this.localSsn);
                    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();
        }
    }
633548
@Override
	public void send() throws IOException {
		if(logger.isDebugEnabled()) {
			logger.debug("send - method=" + this.getMethod());
		}
		checkReadOnly();
		// Cope with com.bea.sipservlet.tck.agents.api.javax_servlet_sip.SipServletMessageTest.testSend101
		// make sure a message received cannot be sent out
		checkMessageState();
		final Request request = (Request) super.message;
		final String requestMethod = getMethod();
		final SipApplicationDispatcher sipApplicationDispatcher = sipFactoryImpl.getSipApplicationDispatcher();
		final MobicentsSipSession session = getSipSession();
		final DNSServerLocator dnsServerLocator = sipApplicationDispatcher.getDNSServerLocator();
		Hop hop = null;
		// RFC 3263 support
		if(dnsServerLocator != null) {
			if(Request.CANCEL.equals(requestMethod)) {
				// RFC 3263 Section 4 : a CANCEL for a particular SIP request MUST be sent to the same SIP
				// server that the SIP request was delivered to.
				TransactionApplicationData inviteTxAppData = ((TransactionApplicationData)inviteTransactionToCancel.getApplicationData());
				if(inviteTxAppData != null && inviteTxAppData.getHops() != null) {
					hop = inviteTxAppData.getHops().peek();
				}
			} else {
				javax.sip.address.URI uriToResolve =  request.getRequestURI();
				RouteHeader routeHeader = (RouteHeader) request.getHeader(RouteHeader.NAME);
				if(routeHeader != null) {
					uriToResolve = routeHeader.getAddress().getURI();
				} else {
					// RFC5626 - see if we are to find a flow for this request.
					// Note: we should do this even if the "uriToResolve" is coming
					// from a route header but since we currently have not implemented
					// the correct things for a proxy scenario, only do it for UAS
					// scenarios. At least this will minimize the potential for messing
					// up right now...
					uriToResolve = resolveSipOutbound(uriToResolve);
				}
				String uriToResolveTransport = ((javax.sip.address.SipURI)uriToResolve).getTransportParam();
				boolean transportParamModified = false;
				if(session.getProxy() == null && session.getTransport() != null && uriToResolve.isSipURI() && uriToResolveTransport  == null &&
						// no need to modify the Request URI for UDP which is the default transport
						!session.getTransport().equalsIgnoreCase(ListeningPoint.UDP)) {
					try {
						((javax.sip.address.SipURI)uriToResolve).setTransportParam(session.getTransport());
						transportParamModified = true;
					} catch (ParseException e) {
						// nothing to do here, will never happen
					}
				}
				Queue<Hop> hops = dnsServerLocator.locateHops(uriToResolve);
				if(transportParamModified) {
					// Issue http://code.google.com/p/sipservlets/issues/detail?id=186
					// Resetting the transport to what is was before the modification to avoid modifying the route set
					if(uriToResolveTransport == null) {
						((javax.sip.address.SipURI)uriToResolve).removeParameter("transport");
					} else {
						try {
							((javax.sip.address.SipURI)uriToResolve).setTransportParam(uriToResolveTransport);
						} catch (ParseException e) {
							// nothing to do here, will never happen
						}
					}
				}
				if(hops != null && hops.size() > 0) {
					// RFC 3263 support don't remove the current hop, it will be the one to reuse for CANCEL and ACK to non 2xx transactions
					hop = hops.peek();
					transactionApplicationData.setHops(hops);
				}
			}
		}
		if(logger.isDebugEnabled()) {
			logger.debug("send - calling send(hop) - hop=" + hop);
		}
		send(hop);
	}
117756
public void onMessageEvent(javax.sip.RequestEvent event,
			ActivityContextInterface aci) {

		final Request request = event.getRequest();
		try {
			// message body should be *FIRST_TOKEN<timer value in
			// seconds>MIDDLE_TOKEN<msg to send back to UA>LAST_TOKEN*
			final String body = new String(request.getRawContent());
			final int firstTokenStart = body.indexOf(FIRST_TOKEN);
			final int timerDurationStart = firstTokenStart + FIRST_TOKEN_LENGTH;
			final int middleTokenStart = body.indexOf(MIDDLE_TOKEN,
					timerDurationStart);
			final int bodyMessageStart = middleTokenStart + MIDDLE_TOKEN_LENGTH;
			final int lastTokenStart = body.indexOf(LAST_TOKEN,
					bodyMessageStart);
			if (firstTokenStart > -1 && middleTokenStart > -1
					&& lastTokenStart > -1) {
				// extract the timer duration
				final int timerDuration = Integer.parseInt(body.substring(
						timerDurationStart, middleTokenStart));
				// create a null AC and attach the sbb local object
				final ActivityContextInterface timerACI = this.nullACIFactory
						.getActivityContextInterface(this.nullActivityFactory
								.createNullActivity());
				timerACI.attach(sbbContext.getSbbLocalObject());
				// set the timer on the null AC, because the one from this event
				// will end as soon as we send back the 200 ok
				this.timerFacility.setTimer(timerACI, null, System
						.currentTimeMillis()
						+ (timerDuration * 1000), new TimerOptions());
				// extract the body message
				final String bodyMessage = body.substring(bodyMessageStart,
						lastTokenStart);
				// store it in a cmp field
				setBody(bodyMessage);
				// do the same for the call id
				setCallId((CallIdHeader) request.getHeader(CallIdHeader.NAME));
				// also store the sender's address, so we can send the wake up
				// message
				final FromHeader fromHeader = (FromHeader) request
						.getHeader(FromHeader.NAME);
				if (tracer.isInfoEnabled()) {
					tracer.info("Received a valid message from "
							+ fromHeader.getAddress()
							+ " requesting a reply containing '" + bodyMessage
							+ "' after " + timerDuration + "s");
				}
				setSender(fromHeader.getAddress());
				// finally reply to the SIP message request
				sendResponse(event, Response.OK);
			} else {
				// parsing failed
				tracer.warning("Invalid msg '" + body + "' received");
				sendResponse(event, Response.BAD_REQUEST);
			}
		} catch (Throwable e) {
			// oh oh something wrong happened
			tracer.severe("Exception while processing MESSAGE", e);
			try {
				sendResponse(event, Response.SERVER_INTERNAL_ERROR);
			} catch (Exception f) {
				tracer.severe("Exception while sending SERVER INTERNAL ERROR",
						f);
			}
		}
	}
1057509
protected <T extends RaftRequest, U extends RaftResponse> void sendRequest(T request, BiFunction<MemberId, T, CompletableFuture<U>> sender, CompletableFuture<U> future) {
    sendRequest(request, sender, 0, future);
  }
537434
private void send(final Destination d, final Priority p, final byte[] apdu, final int response)
		throws KNXTimeoutException, KNXDisconnectException, KNXLinkClosedException
	{
		svcResponse = response;
		if (d.isConnectionOriented()) {
			tl.connect(d);
			tl.sendData(d, p, apdu);
		}
		else
			tl.sendData(d.getAddress(), p, apdu);
	}
1371477
public void send(ReqT request) throws IOException {
    if (mClosed || mCanceled || mClosedFromRemote) {
      throw new CancelledException(formatErrorMessage(
          "Failed to send request %s: stream is already closed or canceled.", request));
    }
    try (LockResource lr = new LockResource(mLock)) {
      checkError();
    }
    mRequestObserver.onNext(request);
  }
529952
@Override
    public SMTPClientFuture<FutureResult<Collection<SMTPResponse>>> send(SMTPPipeliningRequest request) {
        SMTPClientFutureImpl<FutureResult<Collection<SMTPResponse>>> future = new SMTPClientFutureImpl<FutureResult<Collection<SMTPResponse>>>(false);
        future.setSMTPClientSession(this);
        AggregationListener listener = new AggregationListener(future, request.getRequests().size());
        for(SMTPRequest req: request.getRequests()) {
            send(req).addListener(listener);
        }
        return future;
    }
364668
public void sendRequest() throws IOException
    {
        /* Create & Format URL */
        URL url = new URL(CleverBotQuery.formatRequest(CleverBotQuery.URL_STRING, this.key, this.phrase, this.conversationID));

        /* Open Connection */
        URLConnection urlConnection = url.openConnection();

        /* Read input */
        BufferedReader in = new BufferedReader(new InputStreamReader(urlConnection.getInputStream()));
        String inputLine = in.readLine();

        /* Create JSON Object */
        JsonObject jsonObject = new JsonParser().parse(inputLine).getAsJsonObject(); // convert to JSON

        /* Get params */
        this.setConversationID(jsonObject.get("cs").getAsString()); // update conversation ID
        this.setResponse(jsonObject.get("output").getAsString()); // get output
        this.setRandomNumber(Integer.parseInt(jsonObject.get("random_number").getAsString())); // get output
        in.close(); // close!
    }
25808
private void sendRequest() {

        final String queryString = !eventSpinner.isEnabled() ? String.valueOf(queryEditText.getText()) : null;
        final String eventString = eventSpinner.isEnabled() ? String.valueOf(String.valueOf(eventSpinner.getSelectedItem())) : null;
        final String contextString = String.valueOf(contextEditText.getText());

        if (TextUtils.isEmpty(queryString) && TextUtils.isEmpty(eventString)) {
            onError(new AIError(getString(R.string.non_empty_query)));
            return;
        }

        final AsyncTask<String, Void, AIResponse> task = new AsyncTask<String, Void, AIResponse>() {

            private AIError aiError;

            @Override
            protected AIResponse doInBackground(final String... params) {
                final AIRequest request = new AIRequest();
                String query = params[0];
                String event = params[1];

                if (!TextUtils.isEmpty(query))
                    request.setQuery(query);
                if (!TextUtils.isEmpty(event))
                    request.setEvent(new AIEvent(event));
                final String contextString = params[2];
                RequestExtras requestExtras = null;
                if (!TextUtils.isEmpty(contextString)) {
                    final List<AIContext> contexts = Collections.singletonList(new AIContext(contextString));
                    requestExtras = new RequestExtras(contexts, null);
                }

                try {
                    return aiDataService.request(request, requestExtras);
                } catch (final AIServiceException e) {
                    aiError = new AIError(e);
                    return null;
                }
            }

            @Override
            protected void onPostExecute(final AIResponse response) {
                if (response != null) {
                    onResult(response);
                } else {
                    onError(aiError);
                }
            }
        };

        task.execute(queryString, eventString, contextString);
    }
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);
	}
904699
void send(AbstractMessage aMessage, int priority)
  {
    if (TraceComponent.isAnyTracingEnabled() && tc.isEntryEnabled())
      SibTr.entry(tc, "send", new Object[] {this,
                                            aMessage,
                                            new Integer(priority),
                                            "verboseMsg OUT : " + aMessage.toVerboseString()});
    if(TraceComponent.isAnyTracingEnabled() && tc.isDebugEnabled())
      MPIOMsgDebug.debug(tc, aMessage, priority);
    
    // comms accepting messages, write the message
    // immediately.
    try
    {
      //send the encoded message
      connection.send(aMessage, priority);          

      if (TraceComponent.isAnyTracingEnabled() && tc.isDebugEnabled())
        SibTr.debug(tc, "send", "Message accepted by Comms");
    } 
    catch (SIConnectionDroppedException e)
    {
      // No FFDC code needed
      
      if (TraceComponent.isAnyTracingEnabled() && tc.isDebugEnabled())
        SibTr.debug(tc, "send", "Message refused by Comms: Connection Dropped");
      
      // Pass this exception up to our parent.  Note that we'll assume
      // we're still alive, and let our parent (in coordination with TRM
      // decide whether or not to nuke us).
      mpio.error(connection, e);
    }       
    catch (SIConnectionUnavailableException e)
    {
      // No FFDC code needed
      if (TraceComponent.isAnyTracingEnabled() && tc.isDebugEnabled())
        SibTr.debug(tc, "send", "Message refused by Comms: Connection Unavailable");
      
      // Pass this exception up to our parent.  Note that we'll assume
      // we're still alive, and let our parent (in coordination with TRM
      // decide whether or not to nuke us).
      mpio.error(connection, e);
    } 
    catch (SIConnectionLostException e)
    {
      // No FFDC code needed
      if (TraceComponent.isAnyTracingEnabled() && tc.isDebugEnabled())
        SibTr.debug(tc, "send", "Message refused by Comms: Connection Lost");
      
      // Pass this exception up to our parent.  Note that we'll assume
      // we're still alive, and let our parent (in coordination with TRM
      // decide whether or not to nuke us).
      mpio.error(connection, e);
    }
    catch(MessageEncodeFailedException e)
    {
      // No FFDC code needed
      //this should never happen, but comms declare the exception, so
      //we have to deal with it
      if (TraceComponent.isAnyTracingEnabled() && tc.isDebugEnabled())
        SibTr.debug(tc, "send", "Message refused by Comms: Msg Encode Failed");
      
      // Pass this exception up to our parent.  Note that we'll assume
      // we're still alive, and let our parent (in coordination with TRM
      // decide whether or not to nuke us).
      mpio.error(connection, e);
    }
    catch(MessageCopyFailedException e)
    {
      // No FFDC code needed
      //this should never happen, but comms declare the exception, so
      //we have to deal with it
      if (TraceComponent.isAnyTracingEnabled() && tc.isDebugEnabled())
        SibTr.debug(tc, "send", "Message refused by Comms: Msg Copy Failed");
      
      // Pass this exception up to our parent.  Note that we'll assume
      // we're still alive, and let our parent (in coordination with TRM
      // decide whether or not to nuke us).
      mpio.error(connection, e);
    }
    catch(UnsupportedEncodingException e)
    {
      // No FFDC code needed
      //this should never happen, but comms declare the exception, so
      //we have to deal with it
      if (TraceComponent.isAnyTracingEnabled() && tc.isDebugEnabled())
        SibTr.debug(tc, "send", "Message refused by Comms: Msg Encoding Failed");
      
      // Pass this exception up to our parent.  Note that we'll assume
      // we're still alive, and let our parent (in coordination with TRM
      // decide whether or not to nuke us).
      mpio.error(connection, e);
    }
    catch(IncorrectMessageTypeException e)
    {
      // No FFDC code needed
      //this should never happen, but comms declare the exception, so
      //we have to deal with it
      if (TraceComponent.isAnyTracingEnabled() && tc.isDebugEnabled())
        SibTr.debug(tc, "send", "Message refused by Comms: Incorrect Message Type");
      
      // Pass this exception up to our parent.  Note that we'll assume
      // we're still alive, and let our parent (in coordination with TRM
      // decide whether or not to nuke us).
      mpio.error(connection, e);
    }
      
    if (TraceComponent.isAnyTracingEnabled() && tc.isEntryEnabled())
      SibTr.exit(tc, "send");
  }
129157
@Override
    public void sendRequest(final String fromParticipantId,
                            final DiscoveryEntryWithMetaInfo toDiscoveryEntry,
                            Request request,
                            MessagingQos messagingQos) {

        logger.trace("SEND USING RequestReplySenderImpl with Id: " + System.identityHashCode(this));

        MutableMessage message = messageFactory.createRequest(fromParticipantId,
                                                              toDiscoveryEntry.getParticipantId(),
                                                              request,
                                                              messagingQos);
        message.setLocalMessage(toDiscoveryEntry.getIsLocal());
        message.setStatelessAsync(request.getStatelessAsyncCallbackMethodId() != null);

        logger.debug("REQUEST call proxy: method: {}, requestReplyId: {}, messageId: {}, proxy participantId: {}, "
                + "provider participantId: {}, params: {}",
                     request.getMethodName(),
                     request.getRequestReplyId(),
                     message.getId(),
                     fromParticipantId,
                     toDiscoveryEntry.getParticipantId(),
                     request.getParams());
        messageSender.sendMessage(message);
    }
777928
public static void sendContinueResponseBlocking(final HttpServerExchange exchange) throws IOException {
        if (!exchange.isResponseChannelAvailable()) {
            throw UndertowMessages.MESSAGES.cannotSendContinueResponse();
        }
        if(exchange.getAttachment(ALREADY_SENT) != null) {
            return;
        }
        HttpServerExchange newExchange = exchange.getConnection().sendOutOfBandResponse(exchange);
        exchange.putAttachment(ALREADY_SENT, true);
        newExchange.setStatusCode(StatusCodes.CONTINUE);
        newExchange.getResponseHeaders().put(Headers.CONTENT_LENGTH, 0);
        newExchange.startBlocking();
        newExchange.getOutputStream().close();
        newExchange.getInputStream().close();
    }
941025
@Override
  public ListenableFuture<CloseableHttpResponse> sendRequest(final HttpUriRequest request) throws IOException {
    return singleThreadPool.submit(new Callable<CloseableHttpResponse>() {
      @Override
      public CloseableHttpResponse call() throws Exception {
        return client.execute(request);
      }
    });
  }
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();
        }
    }
1306832
public MessageId send(ProducerConnectionContext context, BasicMessage basicMessage) throws JMSException {
        return send(context, basicMessage, null);
    }
15478
public void sendComponent(Component componentRequest) throws TCAPSendException {

        if (this.previewMode)
            return;

        if (this.provider.getStack().getStatisticsEnabled()) {
            switch (componentRequest.getType()) {
                case InvokeNotLast:
                    this.provider.getStack().getCounterProviderImpl().updateInvokeNotLastSentCount(this,
                            (Invoke) componentRequest);

                    Invoke inv = (Invoke) componentRequest;
                    OperationCodeImpl oc = (OperationCodeImpl) inv.getOperationCode();
                    if (oc != null) {
                        this.provider.getStack().getCounterProviderImpl()
                                .updateOutgoingInvokesPerOperationCode(oc.getStringValue());
                    }
                    break;
                case InvokeLast:
                    this.provider.getStack().getCounterProviderImpl().updateInvokeLastSentCount(this,
                            (Invoke) componentRequest);

                    inv = (Invoke) componentRequest;
                    oc = (OperationCodeImpl) inv.getOperationCode();
                    if (oc != null) {
                        this.provider.getStack().getCounterProviderImpl()
                                .updateOutgoingInvokesPerOperationCode(oc.getStringValue());
                    }
                    break;
                case ReturnResultNotLast:
                    this.provider.getStack().getCounterProviderImpl().updateReturnResultNotLastSentCount(this);
                    break;
                case ReturnResultLast:
                    this.provider.getStack().getCounterProviderImpl().updateReturnResultLastSentCount(this);
                    break;
                case ReturnError:
                    this.provider.getStack().getCounterProviderImpl().updateReturnErrorSentCount(this);

                    ReturnError re = (ReturnError) componentRequest;
                    ErrorCodeImpl ec = (ErrorCodeImpl) re.getErrorCode();
                    if (ec != null) {
                        this.provider.getStack().getCounterProviderImpl().updateOutgoingErrorsPerErrorCode(ec.getStringValue());
                    }
                    break;
                case Reject:
                    this.provider.getStack().getCounterProviderImpl().updateRejectSentCount(this);

                    Reject rej = (Reject) componentRequest;
                    RejectProblem prob = (RejectProblem) rej.getProblem();
                    if (prob != null) {
                        this.provider.getStack().getCounterProviderImpl().updateOutgoingRejectPerProblem(prob.toString());
                    }
                    break;
            }
        }

        try {
            this.dialogLock.lock();
            if (componentRequest.getType() == ComponentType.InvokeNotLast
                    || componentRequest.getType() == ComponentType.InvokeLast) {
                InvokeImpl invoke = (InvokeImpl) componentRequest;

                // check if its taken!
                int invokeIndex = getIndexFromInvokeId(invoke.getInvokeId());
                if (this.operationsSent[invokeIndex] != null) {
                    throw new TCAPSendException("There is already operation with such invoke id!");
                }

                invoke.setState(OperationState.Pending);
                invoke.setDialog(this);

                // if the Invoke timeout value has not be reset by TCAP-User
                // for this invocation we are setting it to the the TCAP stack
                // default value
                if (invoke.getTimeout() == TCAPStackImpl._EMPTY_INVOKE_TIMEOUT)
                    invoke.setTimeout(this.provider.getStack().getInvokeTimeout());
            } else {
                if (componentRequest.getType() != ComponentType.ReturnResultNotLast) {
                    // we are sending a response and removing invokeId from
                    // incomingInvokeList
                    this.removeIncomingInvokeId(componentRequest.getCorrelationId());
                }
            }
            this.scheduledComponentList.add(componentRequest);
        } finally {
            this.dialogLock.unlock();
        }
    }