/*
@link https://pusher.com/docs/pusher_protocol#presence-channel-events
8033
public function subscribe(ConnectionInterface $connection, stdClass $payload)
    {
        $this->saveConnection($connection);

        $connection->send(json_encode([
            'event' => 'pusher_internal:subscription_succeeded',
            'channel' => $this->channelName,
        ]));
    }
1309283
public function presence($status = null, $show = 'available', $to = null, $type = 'available', $priority = 0)
    {
        if ($type === 'available') {
            $type = '';
        }
        $to = htmlspecialchars($to);
        $status = htmlspecialchars($status);
        $show = htmlspecialchars($show);
        $type = htmlspecialchars($type);
        $priority = htmlspecialchars($priority);
        if ($show === 'unavailable') {
            $type = 'unavailable';
        }

        $out = "<presence";
        $out .= ' from="' . $this->fulljid . '"';
        if ($to) {
            $out .= ' to="' . $to . '"';
        }
        if ($type) {
            $out .= ' type="' . $type . '"';
        }
        $inner = '';
        if ($show !== 'available') {
            $inner .= "<show>$show</show>";
        }
        if ($status) {
            $inner .= "<status>$status</status>";
        }
        if ($priority) {
            $inner .= "<priority>$priority</priority>";
        }
        if ($inner === '') {
            $out .= "/>";
        } else {
            $out .= '>' . $inner . '</presence>';
        }

        $this->sendXML($out);
    }
634765
def pusher_connected(self, data):
        
        # Inform user that pusher is done connecting
        self.logger.info("Pusherclient connected")

        # Bind the events we want to listen to
        self.callback_client.bind("payment_authorized",
                                  self.payment_authorized)
        self.callback_client.bind("shortlink_scanned",
                                  self.shortlink_scanned)
968332
function pushListener(event) {
    var jsonString = event.data && event.data.text() ? event.data.text() : null;

    if (!jsonString) {
      console.log('Leanplum: Push received without payload, skipping display.');
      return;
    }

    // noinspection JSCheckFunctionSignatures
    var options = JSON.parse(jsonString);

    /** @namespace options.title The title of the push notification. **/
    /** @namespace options.tag The id of the push notification **/
    if (!options || !options.title || !options.tag) {
      console.log('Leanplum: No options, title or tag/id received, skipping ' + 'display.');
      return;
    }

    // Extract open action url. We only support open url action for now.
    /** @namespace options.data.openAction The openAction of the push notification. **/
    if (options.data && options.data.openAction && options.data.openAction.hasOwnProperty(ACTION_NAME_KEY) && options.data.openAction[ACTION_NAME_KEY] === OPEN_URL_ACTION && options.data.openAction.hasOwnProperty(ARG_URL)) {
      openActions[options.tag] = options.data.openAction[ARG_URL];
    }

    // Extract title and delete from options.
    var title = options.title;
    Reflect.deleteProperty(options, 'title');
    /** @namespace self.registration **/
    /** @namespace self.registration.showNotification **/
    event.waitUntil(self.registration.showNotification(title, options));
  }
626352
public void setPresenceBasedDelivery(boolean presenceBased)  {
        addField(ConfigureNodeFields.presence_based_delivery, FormField.Type.bool);
        setAnswer(ConfigureNodeFields.presence_based_delivery.getFieldName(), presenceBased);
    }
1231316
@Override
  public void onPut(byte[] key, TypePut type)
  {
    //_watchKey.init(key);
    WatchKey watchKey = new WatchKey(key);
   
    switch (type) {
    case LOCAL:
      ArrayList<WatchEntry> listLocal = _entryMapLocal.get(watchKey);
      onPut(listLocal, key);
      break;
      
    case REMOTE:
    {
      int hash = _table.getPodHash(key);
      TablePodNodeAmp node = _table.getTablePod().getNode(hash);
      
      if (node.isSelfCopy()) {
        // copies are responsible for their own local watch events
        onPut(key, TypePut.LOCAL);
      }
      
      if (node.isSelfOwner()) {
        // only the owner sends remote watch events
        /*
        System.out.println("NSO: " +  BartenderSystem.getCurrentSelfServer().getDisplayName()
                           + " " + node.isSelfOwner() + " " + node + " " + Hex.toHex(key));
                           */
        ArrayList<WatchEntry> listRemote = _entryMapRemote.get(watchKey);
        onPut(listRemote, key);
      }
      break;
    }
      
    default:
      throw new IllegalArgumentException(String.valueOf(type));
    }
  }
104511
private void setOfflinePresences() {
        Presence packetUnavailable;
        outerloop: for (Jid user : presenceMap.keySet()) {
            Map<Resourcepart, Presence> resources = presenceMap.get(user);
            if (resources != null) {
                for (Resourcepart resource : resources.keySet()) {
                    packetUnavailable = new Presence(Presence.Type.unavailable);
                    EntityBareJid bareUserJid = user.asEntityBareJidIfPossible();
                    if (bareUserJid == null) {
                        LOGGER.warning("Can not transform user JID to bare JID: '" + user + "'");
                        continue;
                    }
                    packetUnavailable.setFrom(JidCreate.fullFrom(bareUserJid, resource));
                    try {
                        presencePacketListener.processStanza(packetUnavailable);
                    }
                    catch (NotConnectedException e) {
                        throw new IllegalStateException(
                                        "presencePacketListener should never throw a NotConnectedException when processStanza is called with a presence of type unavailable",
                                        e);
                    }
                    catch (InterruptedException e) {
                        break outerloop;
                    }
                }
            }
        }
    }
1340610
@Override
    public void pushNewRequest(Http2PushBuilder pushBuilder) {

        if (TraceComponent.isAnyTracingEnabled() && tc.isEntryEnabled()) {
            Tr.entry(tc, "HTTPRequestMessageImpl.pushNewRequest(): pushNewRequest() started " + this);
        }

        //Test to see if this is an HTTP/2 link, and that the client endpoint wants to accept push_promise frames
        if (!isPushSupported()) {
            if (TraceComponent.isAnyTracingEnabled() && tc.isEntryEnabled()) {
                Tr.exit(tc, "HTTPRequestMessageImpl.pushNewRequest(): Push_promise is not client supported, this is not an HTTP/2 connection, or the connection is closing.");
            }
            return;
        }

        // Find the existing H2 connection and stream so we can use them to send the
        // push_promise frame to the client.
        HttpInboundServiceContext isc = (HttpInboundServiceContext) getServiceContext();
        HttpInboundLink link = ((HttpInboundServiceContextImpl) isc).getLink();

        H2HeaderTable h2WriteTable = ((H2HttpInboundLinkWrap) link).muxLink.getWriteTable();

        // Get the request headers from the pushBuilder.
        // Create a headers block to be use for the push_promise and headers frames
        ByteArrayOutputStream ppStream = new ByteArrayOutputStream();

        // path is equal to uri + queryString
        String pbPath = null;
        if (pushBuilder.getPathQueryString() != null) {
            pbPath = pushBuilder.getURI() + pushBuilder.getPathQueryString();
        } else {
            pbPath = pushBuilder.getURI();
        }

        if (TraceComponent.isAnyTracingEnabled() && tc.isDebugEnabled()) {
            Tr.debug(tc, "HTTPRequestMessageImpl pbPath = " + pbPath);
        }

        try {
            // If all is well, start encoding, first the method
            ppStream.write(H2Headers.encodeHeader(h2WriteTable, HpackConstants.METHOD, pushBuilder.getMethod(), LiteralIndexType.NOINDEXING));

            // Encode the scheme
            String scheme = new String("https");
            if (!isc.isSecure()) {
                scheme = new String("http");
            }
            ppStream.write(H2Headers.encodeHeader(h2WriteTable, HpackConstants.SCHEME, scheme, LiteralIndexType.NOINDEXING));

            // Encode authority
            // If the :authority header was sent in the request, get the information from there
            // If it was not, use getTargetHost and and getTargetPort to create it
            // If it's still null, we have to bail, since it's a required header in a push_promise frame
            String auth = ((H2HttpInboundLinkWrap) link).muxLink.getAuthority();
            if (null == auth) {
                auth = getTargetHost();
                if (null != auth) {
                    if (0 <= getTargetPort()) {
                        auth = auth + ":" + Integer.toString(getTargetPort());
                    }
                } else {
                    if (TraceComponent.isAnyTracingEnabled() && tc.isDebugEnabled()) {
                        Tr.exit(tc, "HTTPRequestMessageImpl: Cannot find hostname for required :authority pseudo header");
                    }
                    return;
                }
            }

            ppStream.write(H2Headers.encodeHeader(h2WriteTable, HpackConstants.AUTHORITY, auth, LiteralIndexType.NOINDEXING));

            ppStream.write(H2Headers.encodeHeader(h2WriteTable, HpackConstants.PATH, pbPath, LiteralIndexType.NOINDEXING));

            if (TraceComponent.isAnyTracingEnabled() && tc.isDebugEnabled()) {
                Tr.debug(tc, "HTTPRequestMessageImpl: Method is GET,  scheme is " + scheme + ", auth is " + auth);
            }

            // Encode headers, if any are present
            Set<HeaderField> headerSet = pushBuilder.getHeaders();
            if (headerSet != null) {
                Iterator<HeaderField> hsit = headerSet.iterator();
                HeaderField hf = null;
                while (hsit.hasNext()) {
                    hf = hsit.next();
                    if (TraceComponent.isAnyTracingEnabled() && tc.isDebugEnabled()) {
                        Tr.debug(tc, "HTTPRequestMessageImpl.getHeaders() " + hf.getName() + " " + hf.asString());
                    }
                    ppStream.write(H2Headers.encodeHeader(h2WriteTable, hf.getName(), hf.asString(), LiteralIndexType.NOINDEXING));

                }
            } else {
                if (TraceComponent.isAnyTracingEnabled() && tc.isDebugEnabled()) {
                    Tr.debug(tc, "HTTPRequestMessageImpl.getHeaders() no headers");
                }
            }

        }
        // Either IOException from write, or CompressionException from encodeHeader
        catch (IOException ioe) {
            if (TraceComponent.isAnyTracingEnabled() && tc.isDebugEnabled()) {
                Tr.exit(tc, "HTTPRequestMessageImpl.pushNewRequest(): The attempt to write an HTTP/2 Push Promise frame resulted in an IOException. Exception {0}" + ioe);
            }
            return;
        } catch (CompressionException ce) {
            if (TraceComponent.isAnyTracingEnabled() && tc.isEntryEnabled()) {
                Tr.exit(tc, "HTTPRequestMessageImpl.pushNewRequest(): The attempt to encode an HTTP/2 Push Promise frame resulted in a CompressionException. Exception {0}" + ce);
            }
            return;
        }

        // Get the next available even numbered promised stream id
        int promisedStreamId = ((H2HttpInboundLinkWrap) link).muxLink.getNextPromisedStreamId();
        // createNewInboundLink creates new:
        // - H2VirtualConnectionImpl
        // - H2HttpInboundLinkWrap
        // - H2StreamProcessor in Idle state
        // It puts the new SP into the SPTable

        H2StreamProcessor promisedSP = ((H2HttpInboundLinkWrap) link).muxLink.createNewInboundLink(promisedStreamId);
        if (promisedSP == null) {
            if (TraceComponent.isAnyTracingEnabled() && tc.isEntryEnabled()) {
                Tr.exit(tc, "pushNewRequest exit; cannot create new push stream -"
                            + " the max number of concurrent streams has already been reached on link: " + link);
            }
            return;
        }
        ((H2HttpInboundLinkWrap) link).setPushPromise(true);
        // Update the promised stream state to Localreserved
        promisedSP.initializePromisedStream();

        if (TraceComponent.isAnyTracingEnabled() && tc.isDebugEnabled()) {
            Tr.debug(tc, "HTTPRequestMessageImpl.pushNewRequest(): push_promise stream-id is " + promisedStreamId);
        }

        // Get the existing stream id
        int streamId = ((H2HttpInboundLinkWrap) link).getStreamId();

        // Create the push_promise frame to send to the client
        FramePushPromise pushPromiseFrame = new FramePushPromise(streamId, ppStream.toByteArray(), promisedStreamId, 0, true, false, false);

        // Create a headers frame to send to wc, as if it had come in from the client
        FramePPHeaders headersFrame = new FramePPHeaders(streamId, ppStream.toByteArray());

        // Get the existing stream processor and send the push_promise frame to the client
        H2StreamProcessor existingSP = ((H2HttpInboundLinkWrap) link).muxLink.getStreamProcessor(streamId);
        if (existingSP != null) {
            try {
                existingSP.processNextFrame(pushPromiseFrame, Constants.Direction.WRITING_OUT);
            } catch (Http2Exception e) {
                if (TraceComponent.isAnyTracingEnabled() && tc.isEntryEnabled()) {
                    Tr.exit(tc, "HTTPRequestMessageImpl.pushNewRequest(): processNextFrame threw a ProtocolException " + e);
                }
                return;
            }
        } else {
            if (TraceComponent.isAnyTracingEnabled() && tc.isEntryEnabled()) {
                Tr.exit(tc, "HTTPRequestMessageImpl.pushNewRequest(): The client connection using stream-id " + streamId + " has been closed, push() was ignored..");
            }
            return;
        }

        if (TraceComponent.isAnyTracingEnabled() && tc.isDebugEnabled()) {
            Tr.debug(tc, "HTTPRequestMessageImpl.pushNewRequest(): Push promise frame sent on stream-id " + streamId);
        }

        // Send the headers frame to wc
        promisedSP.sendRequestToWc(headersFrame);

        if (TraceComponent.isAnyTracingEnabled() && tc.isEntryEnabled()) {
            Tr.exit(tc, "HTTPRequestMessageImpl.pushNewRequest(): pushNewRequest() exit " + this);
        }

    }
1134905
@Override
    protected void onMethodEntry() {
        if (enabledListeners.isEmpty())
            return;

        String probeKey = createKey();
        ProbeImpl probe = getProbe(probeKey);
        long probeId = probe.getIdentifier();

        setProbeInProgress(true);
        visitLdcInsn(Long.valueOf(probeId)); // long1 long2
        if (isStatic() || isConstructor()) {
            visitInsn(ACONST_NULL); // long1 long2 this
        } else {
            visitVarInsn(ALOAD, 0); // long1 long2 this
        }
        visitInsn(ACONST_NULL); // long1 long2 this that
        createParameterArray(); // long1 long2 this that args
        visitFireProbeInvocation();
        setProbeInProgress(false);

        setProbeListeners(probe, enabledListeners);
    }
1130244
void signalProtocolEstablished(String inboundProtocol) {
        assert !channel.isClientMode() : "Signal protocol should only be made on channel in serverMode";
        this.inboundProtocol = inboundProtocol;
        channel.outboundPipeline().wakeup();
    }
737856
static <W, R> TcpClientImpl<W, R> _create(ClientState<W, R> state,
                                                                      TcpClientEventPublisher eventPublisher) {
        DetachedChannelPipeline channelPipeline = state.unsafeDetachedPipeline();
        state = state.channelProviderFactory(new TcpChannelProviderFactory(channelPipeline,
                                                                           state.getChannelProviderFactory()));

        HostConnectorFactory<W, R> hostConnectorFactory = new HostConnectorFactory<>(state, eventPublisher);

        ConnectionProvider<W, R> cp = state.getFactory()
                                             .newProvider(state.getHostStream().map(hostConnectorFactory));

        InterceptingTcpClient<W, R> interceptingTcpClient = new InterceptingTcpClientImpl<>(cp, eventPublisher);
        TcpClientImpl<W, R> client = new TcpClientImpl<>(state, eventPublisher, interceptingTcpClient);
        client.requestSetLazily = new ConnectionRequestImpl<>(cp);
        return client;
    }
1209536
protected void push_structured_event_heartbeat(String channelName) {
        //  ToDo
        try {
            //  If full name try to get structure from channel_map with different tango hosts
            if (channelName.startsWith("tango://")) {
                EventChannelStruct  eventChannelStruct = getEventChannelStruct(channelName);
                if (eventChannelStruct!=null) {
                    eventChannelStruct.last_heartbeat = System.currentTimeMillis();
                    return;
                }
            }

            //  Not Found !
            //	In case of (use_db==false)
            //	domain name is only device name
            //	but key is full name (//host:port/a/b/c....)
            Enumeration keys = channel_map.keys();
            boolean found = false;
            while (keys.hasMoreElements() && !found) {
                String name = (String) keys.nextElement();
                EventChannelStruct eventChannelStruct = channel_map.get(name);
                //  Check with device name for adm device
                String  admDeviceName = eventChannelStruct.adm_device_proxy.name();
                if (admDeviceName.equalsIgnoreCase(channelName)) {
                    eventChannelStruct.last_heartbeat = System.currentTimeMillis();
                    found = true;
                }
            }
            if (!found)
                System.err.println(channelName + " Not found");
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
758269
public void push(
    int         state,
    GBSNode     node,
    String      pusher)
  {
    _lastStacker = pusher;
    push(state, node);
  }
247942
public void addPushResponse(int streamId, HttpCarbonResponse pushResponse) {
        pushResponsesMap.put(streamId, pushResponse);
        responseFuture.notifyPushResponse(streamId, pushResponse);
    }
748733
void pushReceivedException(EventChannelStruct event_channel_struct, EventCallBackStruct callback_struct, DevError error) {
        try {
            if (event_channel_struct != null) {
                if (event_channel_struct.consumer instanceof NotifdEventConsumer) {
                    if (!callback_struct.filter_ok) {
                        callback_struct.filter_id = NotifdEventConsumer.getInstance().add_filter_for_channel(
                                event_channel_struct, callback_struct.filter_constraint);
                        callback_struct.filter_ok = true;
                    }
                }
            } else
                return;

            int eventSource = (event_channel_struct.consumer instanceof NotifdEventConsumer)?
                    EventData.NOTIFD_EVENT : EventData.ZMQ_EVENT;
            DevError[] errors = {error};
            String domain_name = callback_struct.device.name();
            if (callback_struct.attr_name!=null)
                domain_name += "/" + callback_struct.attr_name.toLowerCase();
            EventData event_data =
                    new EventData(event_channel_struct.adm_device_proxy,
                            domain_name, callback_struct.event_name, callback_struct.event_type,
                            eventSource, null, null, null, null, null, errors);

            CallBack callback = callback_struct.callback;
            event_data.device = callback_struct.device;
            event_data.name = callback_struct.device.name();
            event_data.event = callback_struct.event_name;

            if (callback_struct.use_ev_queue) {
                EventQueue ev_queue = callback_struct.device.getEventQueue();
                ev_queue.insert_event(event_data);
            } else
                callback.push_event(event_data);

        } catch (DevFailed e) { /* */ }
    }
998069
@Override
    public void channelConnected(ChannelHandlerContext ctx, ChannelStateEvent event) {
        // register the newly established channel
        Channel channel = event.getChannel();
        LOG.info("connection established to :{}, local port:{}", client.getRemoteAddr(), channel.getLocalAddress());

        client.connectChannel(ctx.getChannel());
        client.handleResponse(ctx.getChannel(), null);
    }
577489
@Handler(channels = EncryptedChannel.class)
    public void onPurge(Purge event, IOSubchannel encryptedChannel) {
        @SuppressWarnings("unchecked")
        final Optional<PlainChannel> plainChannel
            = (Optional<PlainChannel>) LinkedIOSubchannel
                .downstreamChannel(this, encryptedChannel);
        if (plainChannel.isPresent()) {
            plainChannel.get().purge();
        }
    }