/*
(non-Javadoc)

@see org.restcomm.protocols.ss7.tcap.api.tc.dialog.Dialog#sendUni()
434860
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 || 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());

                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.getNetworkId(), this.localSsn);
                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();
        }
    }
284517
public SendResult send(MessageBuilder builder, long timeout, TimeUnit unit) throws InterruptedException {
        Message msg = builder.build(this.messageBodyConverter);
        final String topic = msg.getTopic();
        MessageProducer producer = this.getOrCreateProducer(topic);
        try {
            return producer.sendMessage(msg, timeout, unit);
        }
        catch (MetaClientException e) {
            return new SendResult(false, null, -1, ExceptionUtils.getFullStackTrace(e));
        }
    }
680310
public static void send(UnitRequest unitRequest, NotifyHandler handler) {
        unitRequest.getContext().setRouted(true);
        singleton.send(unitRequest, handler);
    }
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();
        }
    }
939402
public HttpMessage uri(final String requestUri) {
        setHeader(DynamicEndpointUriResolver.ENDPOINT_URI_HEADER_NAME, requestUri);
        setHeader(HttpMessageHeaders.HTTP_REQUEST_URI, requestUri);
        return this;
    }
791516
public void send(CEMILData msg, boolean waitForCon) throws KNXTimeoutException,
		KNXLinkClosedException
	{
		doSend(createEMI(msg), waitForCon, msg.getDestination());
	}
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();
        }
    }
785108
private RESTResponse sendAndReceive(HttpMethod          method,
                                        String              uri,
                                        Map<String, String> headers,
                                        byte[]              body) throws IOException {
        // Add standard headers
        assert headers != null;
        headers.put(HttpDefs.HOST, m_host);
        headers.put(HttpDefs.ACCEPT, m_acceptFormat.toString());
        headers.put(HttpDefs.CONTENT_LENGTH, Integer.toString(body == null ? 0 : body.length));
        if (m_bCompress) {
            headers.put(HttpDefs.ACCEPT_ENCODING, "gzip");
        }
        if (m_credentials != null) {
            String authString =
                "Basic " + Utils.base64FromString(m_credentials.getUserid() + ":" + m_credentials.getPassword());
            headers.put("Authorization", authString);
        }
        
        // Form the message header.
        StringBuilder buffer = new StringBuilder();
        buffer.append(method.toString());
        buffer.append(" ");
        buffer.append(addTenantParam(uri));
        buffer.append(" HTTP/1.1\r\n");
        for (String name : headers.keySet()) {
            buffer.append(name);
            buffer.append(": ");
            buffer.append(headers.get(name));
            buffer.append("\r\n");
        }
        buffer.append("\r\n");

        m_logger.debug("Sending request to uri '{}'; message length={}",
                       uri, headers.get(HttpDefs.CONTENT_LENGTH));
        return sendAndReceive(buffer.toString(), body);
    }
1105239
@Override
	public void send(final CEMI frame, final BlockingMode mode)
		throws KNXTimeoutException, KNXConnectionClosedException, InterruptedException
	{
		if (layer == BusMonitorLayer)
			throw new IllegalStateException("send not permitted in busmonitor mode");
		if (!(frame instanceof CEMILData))
			throw new KNXIllegalArgumentException("unsupported cEMI type " + frame.getClass());
		super.send(frame, mode);
	}
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();
        }
    }
786536
private void sendStatusAndClose(final Channel chan, final HttpResponseStatus status) {
    if (chan.isConnected()) {
      final DefaultHttpResponse response = new DefaultHttpResponse(HttpVersion.HTTP_1_1, status);
      final ChannelFuture future = chan.write(response);
      future.addListener(ChannelFutureListener.CLOSE);
    }
  }
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();
        }
    }
226852
@JsonIgnore
  @Override
  public void setUri(URI uri) throws URISyntaxException, NoSuchAlgorithmException, KeyManagementException
  {
    super.setUri(uri);
  }
616321
@Override
    public void setURI(URI uri) throws URIException {
        // only set the host if specified by the URI
        if (uri.isAbsoluteURI()) {
            this.httphost = new HttpHost(uri);
        }
        // set the path, defaulting to root
        setPath(
            uri.getPath() == null
            ? "/"
            : uri.getEscapedPath()
        );
        setQueryString(uri.getEscapedQuery());
    }
344597
public static void addTransfer(String uri, Node n, boolean taguri) {
        if(!taguri) {
            n.type_id = uri;
            return;
        }
        n.type_id = ImplicitScanner.typeIdToUri(uri);
    }
1033037
@Override
	public void sendRequest(final KNXAddress dst, final Priority p, final byte[] nsdu)
		throws KNXLinkClosedException, KNXTimeoutException
	{
		final int mc = mode == TUNNELING ? CEMILData.MC_LDATA_REQ : CEMILData.MC_LDATA_IND;
		send(mc, dst, p, nsdu, false);
	}
1002359
@Override
  public void send(final CharSequence text) {
    final KeyCharacterMap characterMap = KeyCharacterMap.load(KeyCharacterMap.VIRTUAL_KEYBOARD);

    long timeout =
        System.currentTimeMillis()
            + serverInstrumentation.getAndroidWait().getTimeoutInMillis();
    SelendroidLogger.info("Using timeout of " + timeout + " milli seconds.");

    done = false;

    instrumentation.runOnMainSync(new Runnable() {
      public void run() {
        for (int i = 0; i < text.length(); i++) {
          char c = text.charAt(i);
          int code = WebViewKeys.getKeyEventFromUnicodeKey(c);
          if (code != -1) {
            webview.dispatchKeyEvent(new KeyEvent(KeyEvent.ACTION_DOWN, code));
            webview.dispatchKeyEvent(new KeyEvent(KeyEvent.ACTION_UP, code));
          } else {
            KeyEvent[] arr = characterMap.getEvents(new char[] {c});
            if (arr != null) {
              for (int j = 0; j < arr.length; j++) {
                webview.dispatchKeyEvent(arr[j]);
              }
            }
          }
        }
        done = true;
      }
    });
  }