Publish 'numMessages' arbitrary events from live users with the provided delay, to a
PubSub topic.
546666
public static void publishData(int numMessages, int delayInMillis)
      throws IOException {
    List<PubsubMessage> pubsubMessages = new ArrayList<>();

    for (int i = 0; i < Math.max(1, numMessages); i++) {
      Long currTime = System.currentTimeMillis();
      String message = generateEvent(currTime, delayInMillis);
      PubsubMessage pubsubMessage = new PubsubMessage()
              .encodeData(message.getBytes("UTF-8"));
      pubsubMessage.setAttributes(
          ImmutableMap.of(GameConstants.TIMESTAMP_ATTRIBUTE,
              Long.toString((currTime - delayInMillis) / 1000 * 1000)));
      if (delayInMillis != 0) {
        System.out.println(pubsubMessage.getAttributes());
        System.out.println("late data for: " + message);
      }
      pubsubMessages.add(pubsubMessage);
    }

    PublishRequest publishRequest = new PublishRequest();
    publishRequest.setMessages(pubsubMessages);
    pubsub.projects().topics().publish(topic, publishRequest).execute();
  }
44162
def publish(topic, args=nil, kwargs=nil, options={}, &callback)
      command = WampRails::Command::Publish.new(topic, args, kwargs, options, self)
      self._queue_command(command, callback)
    end
691428
public PubsubFuture<List<String>> publish(final String project, final String topic,
                                            final Message... messages) {
    return publish(project, topic, asList(messages));
  }
932997
public void broadcastTextMessage(String topicName, String textMessage, int delaySeconds)
            throws NamingException, JMSException, ServiceLocatorException {
        if (mdwMessageProducer != null) {
            mdwMessageProducer.broadcastMessageToTopic(topicName, textMessage);
        }
        else {
            TopicConnectionFactory tFactory = null;
            TopicConnection tConnection = null;
            TopicSession tSession = null;
            TopicPublisher tPublisher = null;
            try {
                // if (logger.isDebugEnabled()) logger.debug("broadcast JMS
                // message: " +
                // textMessage);
                // cannot log above - causing recursive broadcasting
                tFactory = getTopicConnectionFactory(null);
                tConnection = tFactory.createTopicConnection();
                tSession = tConnection.createTopicSession(false, Session.AUTO_ACKNOWLEDGE);
                Topic topic = getTopic(topicName);
                tPublisher = tSession.createPublisher(topic);

                // TODO: platform-independent delay
                // WLMessageProducer wlMessageProducer =
                // (WLMessageProducer)tPublisher;
                // long delayInMilliSec = 0;
                // if(pMinDelay > 0){
                // delayInMilliSec = delaySeconds*1000;
                // }
                // wlMessageProducer.setTimeToDeliver(delayInMilliSec);
                TextMessage message = tSession.createTextMessage();
                tConnection.start();

                message.setText(textMessage);
                tPublisher.publish(message, DeliveryMode.PERSISTENT,
                        TextMessage.DEFAULT_DELIVERY_MODE, TextMessage.DEFAULT_TIME_TO_LIVE);
                // }catch(ServiceLocatorException ex){
                // ex.printStackTrace();
                // never log exception here!!! infinite loop when publishing log
                // messages
                // throw new JMSException(ex.getMessage());
            }
            finally {
                closeResources(tConnection, tSession, tPublisher);

            }
        }
    }
704152
def publish(self, topic, obj, reference_message=None):
        
        logging.debug("Publishing topic (%s): \n%s" % (topic, obj))
        e = Event(
            data=obj,
            type=topic,
        )
        if hasattr(obj, "sender"):
            e.sender = obj.sender

        if reference_message:
            original_incoming_event_hash = None
            if hasattr(reference_message, "original_incoming_event_hash"):
                original_incoming_event_hash = reference_message.original_incoming_event_hash
            elif hasattr(reference_message, "source") and hasattr(reference_message.source, "hash"):
                original_incoming_event_hash = reference_message.source.hash
            elif hasattr(reference_message, "source") and hasattr(reference_message.source, "original_incoming_event_hash"):
                original_incoming_event_hash = reference_message.source.original_incoming_event_hash
            elif hasattr(reference_message, "hash"):
                original_incoming_event_hash = reference_message.hash
            if original_incoming_event_hash:
                e.original_incoming_event_hash = original_incoming_event_hash

        return self.publish_to_backend(
            self._localize_topic(topic),
            self.encrypt(e)
        )
1083918
def _send_event(self, title, text, tags, event_type, aggregation_key, severity='info'):
        """"""
        event_dict = {
            'timestamp': int(time()),
            'source_type_name': self.SOURCE_TYPE_NAME,
            'msg_title': title,
            'event_type': event_type,
            'alert_type': severity,
            'msg_text': text,
            'tags': tags,
            'aggregation_key': aggregation_key,
        }
        self.event(event_dict)
630195
def publish_events(self, events):
        
        content = self._serialize.body(events, '[CustomerIntelligenceEvent]')
        self._send(http_method='POST',
                   location_id='b5cc35c2-ff2b-491d-a085-24b6e9f396fd',
                   version='5.0-preview.1',
                   content=content)
1328403
def pub(topic_name, json_msg, repeat_rate=None, host=jps.env.get_master_host(), pub_port=jps.DEFAULT_PUB_PORT):
    '''
    '''
    pub = jps.Publisher(topic_name, host=host, pub_port=pub_port)
    time.sleep(0.1)
    if repeat_rate is None:
        pub.publish(json_msg)
    else:
        try:
            while True:
                pub.publish(json_msg)
                time.sleep(1.0 / repeat_rate)
        except KeyboardInterrupt:
            pass
237650
def _publish_deferred_messages(self):
        
        global message_stack
        if not self._rabbitmq_is_closed and message_stack:
            LOGGER.info('Publishing %i deferred message(s)', len(message_stack))
            while message_stack:
                self._publish_message(*message_stack.pop())
989859
def publish(self, message_type=ON_SEND, client_id=None, client_storage=None,
                *args, **kwargs):
        
        self.publisher.publish(
            message_type, client_id, client_storage, *args, **kwargs)
618981
def publish(self, topic, message):
        
        if not self.connections:
            raise NSQNoConnections()
        conn = random.choice(list(self.connections))
        conn.publish(topic, message)
531911
def insertAnnouncement(self, announcement):
        
        url = announcement.get('url', None)
        try:
            peers.Peer(url)
        except:
            raise exceptions.BadUrlException(url)
        try:
            # TODO get more details about the user agent
            models.Announcement.create(
                url=announcement.get('url'),
                attributes=json.dumps(announcement.get('attributes', {})),
                remote_addr=announcement.get('remote_addr', None),
                user_agent=announcement.get('user_agent', None))
        except Exception as e:
            raise exceptions.RepoManagerException(e)
84100
function announce (server, service) {
  var delay = 1000
  var packet = service._records()

  server.register(packet)

  ;(function broadcast () {
    // abort if the service have or is being stopped in the meantime
    if (!service._activated || service._destroyed) return

    server.mdns.respond(packet, function () {
      // This function will optionally be called with an error object. We'll
      // just silently ignore it and retry as we normally would
      if (!service.published) {
        service._activated = true
        service.published = true
        service.emit('up')
      }
      delay = delay * REANNOUNCE_FACTOR
      if (delay < REANNOUNCE_MAX_MS && !service._destroyed) {
        setTimeout(broadcast, delay).unref()
      }
    })
  })()
}
47783
public PubsubFuture<List<String>> publish(final String project, final String topic,
                                            final List<Message> messages) {
    return publish0(messages, Topic.canonicalTopic(project, topic));
  }
699081
def publish_if_new(cls):
    """"""
    message = cls.make_message()
    if message != cls.last_message:
      super(DashboardPubSub, cls).publish(message)
      cls.last_message = message
1175484
function publisher(port) {
  var socket = zeromq.socket('pub');
  socket.identity = 'pub' + process.pid;

  socket.connect(port);
  console.log('publisher connected to ' + port);

  // lets count messages / sec
  var totalMessages=0;
  setInterval(function() {
    console.log('total messages sent = '+totalMessages);
    totalMessages=0;
    // now fire messages
    for(var i=0;i<5000;i++) {
      var value = Math.random()*1000;
      socket.send('log ' + value);
      totalMessages++;
    }
  }, 1000);

}
838259
def pub(self, topic, message):
        ''''''
        return self.send(' '.join((constants.PUB, topic)), message)