Enable push notifications.

@param pushJid
@param node
@param publishOptions
@return true if it was successfully enabled, false if not
@throws NoResponseException
@throws XMPPErrorException
@throws NotConnectedException
@throws InterruptedException
192955
public boolean enable(Jid pushJid, String node, HashMap<String, String> publishOptions)
            throws NoResponseException, XMPPErrorException, NotConnectedException, InterruptedException {
        EnablePushNotificationsIQ enablePushNotificationsIQ = new EnablePushNotificationsIQ(pushJid, node,
                publishOptions);
        return changePushNotificationsStatus(enablePushNotificationsIQ);
    }
473159
public void sendComposingNotification(Jid to, String packetID) throws NotConnectedException, InterruptedException {
        // Create the message to send
        Message msg = new Message(to);
        // Create a MessageEvent Package and add it to the message
        MessageEvent messageEvent = new MessageEvent();
        messageEvent.setComposing(true);
        messageEvent.setStanzaId(packetID);
        msg.addExtension(messageEvent);
        // Send the packet
        connection().sendStanza(msg);
    }
659477
public Boolean pushEnabled() {
        Long value = get(SETTINGS_ENABLE_PUSH);
        if (value == null) {
            return null;
        }
        return TRUE.equals(value);
    }
225341
private void registerPushServices() {
        RespokeClient activeInstance = null;

        // If there are already client instances running, check if any of them have already connected
        for (RespokeClient eachInstance : instances) {
            if (eachInstance.isConnected()) {
                // The push service only supports one endpoint per device, so the token only needs to be registered for the first active client (if there is more than one)
                activeInstance = eachInstance;
            }
        }

        if (null != activeInstance) {
            // Notify the Respoke servers that this device is eligible to receive notifications directed at this endpointID
            activeInstance.registerPushServicesWithToken(pushToken);
        }
    }
347422
public void setPublishQueuePersistance(String publishQueuePersistance) {

        if (m_frozen) {
            throw new CmsRuntimeException(Messages.get().container(Messages.ERR_CONFIG_FROZEN_0));
        }
        m_publishQueuePersistance = Boolean.valueOf(publishQueuePersistance).booleanValue();
    }
358406
private void sendPublishStopNotify() {
        Status stopStatus = new Status(StatusCodes.NS_UNPUBLISHED_SUCCESS);
        stopStatus.setClientid(getStreamId());
        stopStatus.setDetails(getPublishedName());

        StatusMessage stopMsg = new StatusMessage();
        stopMsg.setBody(stopStatus);
        pushMessage(stopMsg);
        setState(StreamState.STOPPED);
    }
1058943
@ObjectiveCName("changeNotificationsSoundPeer:withValue:")
    public void changeNotificationsSound(Peer peer, String val) {
        modules.getSettingsModule().changeNotificationPeerSound(peer, val);
    }
525636
protected void pushMessage(StatusMessage msg) {
        if (connMsgOut != null) {
            try {
                connMsgOut.pushMessage(msg);
            } catch (IOException err) {
                log.error("Error while pushing message: {}", msg, err);
            }
        } else {
            log.warn("Consumer message output is null");
        }
    }
682020
public void sendCancelledNotification(Jid to, String packetID) throws NotConnectedException, InterruptedException {
        // Create the message to send
        Message msg = new Message(to);
        // Create a MessageEvent Package and add it to the message
        MessageEvent messageEvent = new MessageEvent();
        messageEvent.setCancelled(true);
        messageEvent.setStanzaId(packetID);
        msg.addExtension(messageEvent);
        // Send the packet
        connection().sendStanza(msg);
    }
775087
@Override
    public void publish() {
        try {
            String destination = String.format(DESTINATION, vip);
            executePost(destination, createJsonFromConfig(config));
        } catch (JSONException e) {
            /* forget it */
        }
    }
413971
private void createOrUpdatePushServiceToken(final String token, String httpURI, String httpMethod, JSONObject data, final SharedPreferences prefs) {
        signalingChannel.sendRESTMessage(httpMethod, httpURI, data, new RespokeSignalingChannel.RESTListener() {
            @Override
            public void onSuccess(Object response) {
                if (response instanceof JSONObject) {
                    try {
                        JSONObject responseJSON = (JSONObject) response;
                        pushServiceID = responseJSON.getString("id");

                        SharedPreferences.Editor editor = prefs.edit();
                        editor.putString(PROPERTY_LAST_VALID_PUSH_TOKEN, token);
                        editor.putString(PROPERTY_LAST_VALID_PUSH_TOKEN_ID, pushServiceID);
                        editor.apply();
                    } catch (JSONException e) {
                        Log.d(TAG, "Unexpected response from server while registering push service token");
                    }
                } else {
                    Log.d(TAG, "Unexpected response from server while registering push service token");
                }
            }

            @Override
            public void onError(String errorMessage) {
                Log.d(TAG, "Error registering push service token: " + errorMessage);
            }
        });
    }
238035
public boolean disable(Jid pushJid, String node)
            throws NoResponseException, XMPPErrorException, NotConnectedException, InterruptedException {
        DisablePushNotificationsIQ disablePushNotificationsIQ = new DisablePushNotificationsIQ(pushJid, node);
        return changePushNotificationsStatus(disablePushNotificationsIQ);
    }
989347
private JSONObject publishHostId(
            InetSocketAddress hostAddr,
            MessagingChannel messagingChannel,
            Set<String> activeVersions) throws Exception
    {
        JSONObject jsObj = new JSONObject();
        jsObj.put(TYPE, ConnectionType.PUBLISH_HOSTID.name());
        jsObj.put(HOST_ID, m_localHostId);
        jsObj.put(PORT, m_internalPort);
        jsObj.put(ADDRESS,
                m_internalInterface.isEmpty() ? m_reportedInternalInterface : m_internalInterface);
        jsObj.put(VERSION_STRING, m_acceptor.getVersionChecker().getVersionString());

        jsObj = m_acceptor.decorate(jsObj, Optional.empty());
        jsObj.put(MAY_EXCHANGE_TS, true);

        byte[] jsBytes = jsObj.toString(4).getBytes(StandardCharsets.UTF_8);
        ByteBuffer pushHostId = ByteBuffer.allocate(4 + jsBytes.length);
        pushHostId.putInt(jsBytes.length);
        pushHostId.put(jsBytes).flip();
        messagingChannel.writeMessage(pushHostId);

        // read the json response from socketjoiner with version info and validate it
        return processJSONResponse(messagingChannel, activeVersions, true);
    }
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);
        }

    }
776729
public void sendUpdateNotification(final String hub, final String topic) throws NotificationException {
        try {
            final StringBuilder sb = new StringBuilder("hub.mode=publish&hub.url=").append(URLEncoder.encode(topic, "UTF-8"));
            final URL hubUrl = new URL(hub);
            final HttpURLConnection connection = (HttpURLConnection) hubUrl.openConnection();
            // connection.setRequestProperty("Host", hubUrl.getHost());
            connection.setRequestProperty("User-Agent", "ROME-Certiorem");
            connection.setRequestProperty("ContentType", "application/x-www-form-urlencoded");
            connection.setDoOutput(true);
            connection.connect();

            final OutputStream os = connection.getOutputStream();
            os.write(sb.toString().getBytes("UTF-8"));
            os.close();

            final int rc = connection.getResponseCode();
            connection.disconnect();

            if (rc != 204) {
                throw new NotificationException("Server returned an unexcepted response code: " + rc + " " + connection.getResponseMessage());
            }

        } catch (final UnsupportedEncodingException ex) {
            LOG.error("Could not encode URL", ex);
            throw new NotificationException("Could not encode URL", ex);
        } catch (final IOException ex) {
            LOG.error("Communication error", ex);
            throw new NotificationException("Unable to communicate with " + hub, ex);
        }
    }
700936
synchronized boolean sendPayload(final PayloadData payload) {
		if (payload == null) {
			throw new IllegalArgumentException("Payload is null");
		}

		// we don't allow concurrent payload sending
		if (isSendingPayload()) {
			return false;
		}

		// we mark the sender as "busy" so no other payloads would be sent until we're done
		sendingFlag = true;

		try {
			sendPayloadRequest(payload);
		} catch (Exception e) {
			ApptentiveLog.e(e, "Exception while sending payload: %s", payload);
			logException(e);

			// for NullPointerException, the message object would be null, we should handle it separately
			// TODO: add a helper class for handling that
			String message = e.getMessage();
			if (message == null) {
				message = StringUtils.format("%s is thrown", e.getClass().getSimpleName());
			}

			// if an exception was thrown - mark payload as failed
			handleFinishSendingPayload(payload, false, message, -1, null); // TODO: a better approach
		}

		return true;
	}
247942
public void addPushResponse(int streamId, HttpCarbonResponse pushResponse) {
        pushResponsesMap.put(streamId, pushResponse);
        responseFuture.notifyPushResponse(streamId, pushResponse);
    }