/*
(non-Javadoc)

@see org.restcomm.protocols.ss7.tcap.api.tc.dialog.Dialog#send(org.mobicents
.protocols.ss7.tcap.api.tc.dialog.events.TCBeginRequest)
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();
        }
    }
745568
@Override
	public void send(AbstractPacket packet) throws PacketTransportException
	{
		if (closed)
			throw new PacketTransportException("Transport is closed");
	
		if (packet.isResponseExpected())
			lastSendActivity = System.currentTimeMillis();
		
		boolean wakeUpRequired;
		synchronized (sendQueue)
		{
			wakeUpRequired = sendQueue.isEmpty();
			sendQueue.add(packet);
		}
		
		if (wakeUpRequired)
			multiplexer.wakeUp();
	}
595854
protected void sendEvent(T event, Object receiver, CreationalContext<?> creationalContext) {
        try {
            preNotify(event, receiver);
            // As we are working with the contextual instance, we may not have the
            // actual object, but a container proxy (e.g. EJB)
            notificationStrategy.invoke(receiver, observerMethod, event, beanManager, creationalContext);
        } finally {
            postNotify(event, receiver);
        }
    }
1022847
public void send(String destination, Object body) {
        AsyncMessage message = this.defaultMessageCreator.createMessage();
        message.setDestination(destination);
        message.setBody(body);
        getMessageBroker().routeMessageToService(message, null);
    }
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);
  }
318721
public void send(TCResponseRequest event) throws TCAPSendException {

        if (this.previewMode)
            return;

        if (!this.isStructured()) {
            throw new TCAPSendException("Unstructured dialogs do not use Response");
        }

        try {
            dialogLock.lock();
            TCResponseMessageImpl tcbm = null;

            if (state == TRPseudoState.InitialReceived) {
                // TC-END request primitive issued in response to a TC-BEGIN
                // indication primitive
                this.idleTimerActionTaken = true;
                stopIdleTimer();
                tcbm = (TCResponseMessageImpl) TcapFactory.createTCResponseMessage();
                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);
                }

            } else if (state == TRPseudoState.Active) {
                restartIdleTimer();
                tcbm = (TCResponseMessageImpl) TcapFactory.createTCResponseMessage();

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

            } else {
                throw new TCAPSendException(String.format("State is not %s or %s: it is %s", TRPseudoState.Active,
                        TRPseudoState.InitialReceived, this.state));
            }

            AsnOutputStream aos = new AsnOutputStream();
            try {
                tcbm.encode(aos);
                if (this.provider.getStack().getStatisticsEnabled()) {
                    this.provider.getStack().getCounterProviderImpl().updateTcResponseSentCount(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-Response message: " + e.getMessage(), e);
            } finally {
                // FIXME: is this proper place - should we not release in case
                // of error ?
                release();
            }
        } finally {
            dialogLock.unlock();
        }
    }
109865
public BaseMessage sendMessageRequest(BaseMessage messageOut)
    {
        TrxMessageHeader trxMessageHeader = (TrxMessageHeader)messageOut.getMessageHeader();
        String strTrxID = (String)trxMessageHeader.get(TrxMessageHeader.LOG_TRX_ID);
        try {
            // Create a fake Incoming message with this message's external data
            String strMessageCode = (String)trxMessageHeader.get(LocalMessageTransport.LOCAL_PROCESSOR);
            TrxMessageHeader trxMessageHeaderIn = new TrxMessageHeader(null, null);
            trxMessageHeaderIn.put(TrxMessageHeader.MESSAGE_CODE, strMessageCode);

            BaseMessage messageIn = new TreeMessage(trxMessageHeaderIn, null);
            new ExternalMapTrxMessageIn(messageIn, messageOut.getExternalMessage().getRawData());
            // And fake send it by calling this:
            BaseMessage messageReply = this.processIncomingMessage(messageIn, null);
            this.logMessage(strTrxID, messageOut, MessageInfoTypeModel.REQUEST, MessageTypeModel.MESSAGE_OUT, MessageStatusModel.SENT, null, null);

            this.setupReplyMessage(messageReply, null, MessageInfoTypeModel.REPLY, MessageTypeModel.MESSAGE_OUT);
            int iErrorCode = this.convertToExternal(messageReply, null);
            if (iErrorCode != DBConstants.NORMAL_RETURN)
            {
                String strMessageDescription = this.getTask().getLastError(iErrorCode);
                if ((strMessageDescription == null) || (strMessageDescription.length() == 0))
                    strMessageDescription = "Error converting to external format";
                messageReply = BaseMessageProcessor.processErrorMessage(this, messageOut, strMessageDescription);
            }

            return messageReply;
        } catch (Throwable ex)  {
            ex.printStackTrace();
            String strError = "Error in processing or replying to a message";
            Utility.getLogger().warning(strError);
            this.logMessage(strTrxID, null, MessageInfoTypeModel.REQUEST, MessageTypeModel.MESSAGE_OUT, MessageStatusModel.ERROR, strError, null);
            return BaseMessageProcessor.processErrorMessage(this, messageOut, strError);
        }
    }
771090
protected void sendRequest(HttpURLConnection connection, Request request) throws IOException {
        // Set up the request.
        connection.setRequestMethod(request.method);
        connection.setRequestProperty("Accept", "application/json");
        connection.setRequestProperty("Authorization", request.authorization);

        // If a different HttpHandler is used, we won't get this header. We would need to refactor
        // to a delegation pattern to give the client code's HttpHandler a chance to process the
        // Request first, then attach our custom headers, which would likely be a breaking change.
        connection.setRequestProperty("Keen-Sdk", "java-" + KeenVersion.getSdkVersion());

        // If the request has a body, send it. Otherwise just connect.
        if (request.body != null) {
            if (HttpMethods.GET.equals(request.method) ||
                HttpMethods.DELETE.equals(request.method)) {
                throw new IllegalStateException("Trying to send a GET request with a request " +
                                                "body, which would result in sending a POST.");
            }

            connection.setDoOutput(true);
            connection.setRequestProperty("Content-Type", "application/json");
            request.body.writeTo(connection.getOutputStream());
        } else {
            connection.connect();
        }
    }
1350587
@Override
	public boolean sendMessageToClient(MessageFromClient message, Session client) {
		MessageToClient mtc = messageToClientService.createMessageToClient(message, client);
		if (mtc != null) {
			client.getAsyncRemote().sendObject(mtc);
			return true;
		}
		return false;
	}
602991
public SoapClientRequestActionBuilder send() {
        SoapClientRequestActionBuilder soapClientRequestActionBuilder;
        if (soapClient != null) {
            soapClientRequestActionBuilder = new SoapClientRequestActionBuilder(action, soapClient);
        } else {
            soapClientRequestActionBuilder = new SoapClientRequestActionBuilder(action, soapClientUri);
        }

        soapClientRequestActionBuilder.withApplicationContext(applicationContext);

        return soapClientRequestActionBuilder;
    }
793089
public void sendAndReceive(HttpMessage msg, boolean isFollowRedirect) throws IOException {

		log.debug("sendAndReceive " + msg.getRequestHeader().getMethod() + " "
				+ msg.getRequestHeader().getURI() + " start");
		msg.setTimeSentMillis(System.currentTimeMillis());

		try {
			notifyRequestListeners(msg);
			if (!isFollowRedirect
					|| !(msg.getRequestHeader().getMethod().equalsIgnoreCase(HttpRequestHeader.POST) || msg
							.getRequestHeader().getMethod().equalsIgnoreCase(HttpRequestHeader.PUT))) {
				// ZAP: Reauthentication when sending a message from the perspective of a User
				sendAuthenticated(msg, isFollowRedirect);
				return;
			}

			// ZAP: Reauthentication when sending a message from the perspective of a User
			sendAuthenticated(msg, false);

			HttpMessage temp = msg.cloneAll();
			temp.setRequestingUser(getUser(msg));
			// POST/PUT method cannot be redirected by library. Need to follow by code

			// loop 1 time only because httpclient can handle redirect itself after first GET.
			for (int i = 0; i < 1
					&& (HttpStatusCode.isRedirection(temp.getResponseHeader().getStatusCode()) && temp
							.getResponseHeader().getStatusCode() != HttpStatusCode.NOT_MODIFIED); i++) {
				String location = temp.getResponseHeader().getHeader(HttpHeader.LOCATION);
				URI baseUri = temp.getRequestHeader().getURI();
				URI newLocation = new URI(baseUri, location, false);
				temp.getRequestHeader().setURI(newLocation);

				temp.getRequestHeader().setMethod(HttpRequestHeader.GET);
				temp.getRequestHeader().setHeader(HttpHeader.CONTENT_LENGTH, null);
				// ZAP: Reauthentication when sending a message from the perspective of a User
				sendAuthenticated(temp, true);
			}

			msg.setResponseHeader(temp.getResponseHeader());
			msg.setResponseBody(temp.getResponseBody());

		} finally {
			msg.setTimeElapsedMillis((int) (System.currentTimeMillis() - msg.getTimeSentMillis()));
			log.debug("sendAndReceive " + msg.getRequestHeader().getMethod() + " "
					+ msg.getRequestHeader().getURI() + " took " + msg.getTimeElapsedMillis());

			notifyResponseListeners(msg);
		}
	}
517574
public void sendAsync(BasicMessageWithExtraData<? extends BasicMessage> messageWithData) {
        if (!isConnected()) {
            throw new IllegalStateException("WebSocket connection was closed. Cannot send any messages");
        }

        BasicMessage message = messageWithData.getBasicMessage();
        configurationAuthentication(message);

        sendExecutor.execute(new Runnable() {
            @Override
            public void run() {
                try {
                    if (messageWithData.getBinaryData() == null) {
                        String messageString = ApiDeserializer.toHawkularFormat(message);
                        @SuppressWarnings("resource")
                        Buffer buffer = new Buffer().writeUtf8(messageString);
                        RequestBody requestBody = RequestBody.create(WebSocket.TEXT, buffer.readByteArray());
                        FeedCommProcessor.this.webSocket.sendMessage(requestBody);
                    } else {
                        BinaryData messageData = ApiDeserializer.toHawkularFormat(message,
                                messageWithData.getBinaryData());

                        RequestBody requestBody = new RequestBody() {
                            @Override
                            public MediaType contentType() {
                                return WebSocket.BINARY;
                            }

                            @Override
                            public void writeTo(BufferedSink bufferedSink) throws IOException {
                                emitToSink(messageData, bufferedSink);
                            }
                        };

                        FeedCommProcessor.this.webSocket.sendMessage(requestBody);
                    }
                } catch (Throwable t) {
                    log.errorFailedToSendOverFeedComm(message.getClass().getName(), t);
                }
            }
        });
    }
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);
	}
959643
private void sendRequest(String methodName, Object... params) {
        sendRequest(new InvocationRequest(methodName, params), true);
        
    }
1269050
@Override
  public FcmSendMessageResult sendMessageTo(final String to, final FcmSendMessageRequest request) {
    return proxy.sendMessageTo(to, request);
  }
1138360
private void sendRegisterRequest() {
    StreamManager.RegisterInstanceRequest request =
        StreamManager.RegisterInstanceRequest.newBuilder().
            setInstance(instance).setTopologyName(topologyName).setTopologyId(topologyId).
            build();

    // The timeout would be the reconnect-interval-seconds
    sendRequest(request, null,
        StreamManager.RegisterInstanceResponse.newBuilder(),
        systemConfig.getInstanceReconnectStreammgrInterval());
  }
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)");
        }
    }