Build the messaging configuration for the Reporting Client
178745
function getMessagingConfig() {
  return {
    host:         process.env.FH_MESSAGING_HOST || '',
    cluster:      process.env.FH_MESSAGING_CLUSTER || '',
    realTimeLoggingEnabled: isRealtimeLoggingEnabled(),
    mbaasType: mbaasType(),
    decoupled: process.env.FH_MBAAS_DECOUPLED ||  false,
    msgServer:    {
      logMessageURL: getLogMessageURL()
    },
    backupFiles:  {
      fileName: process.env.FH_MESSAGING_BACKUP_FILE || ''
    },
    recoveryFiles:{
      fileName: process.env.FH_MESSAGING_RECOVERY_FILE || ''
    }
  };
}
656297
def _connect_sentry(message, result):
    '''
    
    '''
    pillar_data = __salt__['pillar.raw']()
    grains = __salt__['grains.items']()
    raven_config = pillar_data['raven']
    hide_pillar = raven_config.get('hide_pillar')
    sentry_data = {
        'result': result,
        'pillar': 'HIDDEN' if hide_pillar else pillar_data,
        'grains': grains
    }
    data = {
        'platform': 'python',
        'culprit': message,
        'level': 'error'
    }
    tags = {}
    if 'tags' in raven_config:
        for tag in raven_config['tags']:
            tags[tag] = grains[tag]

    if _ret_is_not_error(result):
        data['level'] = 'info'

    if raven_config.get('report_errors_only') and data['level'] != 'error':
        return

    if raven_config.get('dsn'):
        client = Client(raven_config.get('dsn'), transport=HTTPTransport)
    else:
        try:
            servers = []
            for server in raven_config['servers']:
                servers.append(server + '/api/store/')
            client = Client(
                servers=servers,
                public_key=raven_config['public_key'],
                secret_key=raven_config['secret_key'],
                project=raven_config['project'],
                transport=HTTPTransport
            )
        except KeyError as missing_key:
            log.error(
                'Sentry returner needs key \'%s\' in pillar',
                missing_key
            )
            return

    try:
        msgid = client.capture(
            'raven.events.Message',
            message=message,
            data=data,
            extra=sentry_data,
            tags=tags
        )
        log.info('Message id %s written to sentry', msgid)
    except Exception as exc:
        log.error('Can\'t send message to sentry: %s', exc, exc_info=True)
1286723
def send_report(self, report_parts):
        
        logger.info('Creating an email message')
        report_parts = sorted(
            filter(lambda x: x.fmt in self.formats, report_parts),
            key=lambda x: self.formats.index(x.fmt)
        )
        fmtname = '{0}-{1}.{2}' if len(report_parts) > 1 else '{0}.{2}'
        root_part = MIMEMultipart('mixed')
        root_part.preamble = 'This is a multi-part message in MIME format.'

        logger.debug('Creating the text/"text_type" parts')
        for i, text_part in enumerate(report_parts):
            attachment_name = fmtname.format(socket.gethostname(), i, text_part.ext)
            attach_part = MIMEText(text_part.text, text_part.ext, 'utf-8')
            attach_part.add_header('Content-Disposition', 'attachment', filename=attachment_name)
            root_part.attach(attach_part)

        if self.rawlogs:
            out = BytesIO()
            do_chunked_gzip(self.rawfh, out, filename=u'raw.log.gz')
            out.seek(0, os.SEEK_END)
            size = out.tell()

            if size > self.rawlogs_limit:
                logger.warning('%d is over the defined max of %r', size, self.rawlogs_limit)
                logger.warning('Not attaching the raw logs')
            else:
                logger.debug('Creating the application/x-gzip part')
                attach_part = MIMEBase('application', 'x-gzip')
                attach_part.set_payload(out.getvalue())

                from email.encoders import encode_base64

                logger.debug('Encoding the gzipped raw logs with base64')
                encode_base64(attach_part)
                attach_part.add_header('Content-Disposition', 'attachment', filename='raw.log.gz')
                root_part.attach(attach_part)

        if self.gpg_encrypt:
            import gpgme
            try:
                if self.gpg_keyringdir and os.path.exists(self.gpg_keyringdir):
                    logger.debug('Setting keyring dir to %r', self.gpg_keyringdir)
                    os.environ['GNUPGHOME'] = self.gpg_keyringdir

                cleartext = BytesIO(root_part.as_string().encode())
                ciphertext = BytesIO()

                ctx = gpgme.Context()
                ctx.armor = True

                if self.gpg_recipients:
                    recipients = [ctx.get_key(recipient) for recipient in self.gpg_recipients]
                else:
                    recipients = []
                    for key in ctx.keylist():
                        for subkey in key.subkeys:
                            if subkey.can_encrypt:
                                logger.debug('Found can_encrypt key = %d', subkey.keyid)
                                recipients.append(key)
                                break

                signers = [ctx.get_key(signer) for signer in self.gpg_signers]
                if signers:
                    logger.info('Encrypting and signing the report')
                    ctx.signers = signers
                    ctx.encrypt_sign(recipients, gpgme.ENCRYPT_ALWAYS_TRUST, cleartext, ciphertext)
                else:
                    logger.info('Encrypting the report')
                    ctx.encrypt(recipients, gpgme.ENCRYPT_ALWAYS_TRUST, cleartext, ciphertext)

                logger.debug('Creating the MIME envelope for PGP')

                gpg_envelope_part = MIMEMultipart('encrypted')
                gpg_envelope_part.set_param('protocol', 'application/pgp-encrypted', header='Content-Type')
                gpg_envelope_part.preamble = 'This is an OpenPGP/MIME encrypted message (RFC 2440 and 3156)'

                gpg_mime_version_part = MIMEBase('application', 'pgp-encrypted')
                gpg_mime_version_part.add_header('Content-Disposition', 'PGP/MIME version identification')
                gpg_mime_version_part.set_payload('Version: 1')

                gpg_payload_part = MIMEBase('application', 'octet-stream', name='encrypted.asc')
                gpg_payload_part.add_header('Content-Disposition', 'OpenPGP encrypted message')
                gpg_payload_part.add_header('Content-Disposition', 'inline', filename='encrypted.asc')
                gpg_payload_part.set_payload(ciphertext.getvalue())

                gpg_envelope_part.attach(gpg_mime_version_part)
                gpg_envelope_part.attach(gpg_payload_part)

                # envelope becomes the new root part
                root_part = gpg_envelope_part

            except ImportError:
                logger.error('Need crypto libraries for gpg_encrypt.')
                logger.error('Install pygpgme for GPG encryption support.')
                logger.error('Not mailing the report out of caution.')
                return

        # Define headers
        root_part['Date'] = formatdate()
        root_part['From'] = self.email_address
        root_part['To'] = ', '.join(self.mailto)
        root_part['Subject'] = '{0} system events: {1}'.format(
                socket.gethostname(), time.strftime('%c', time.localtime())
        )
        root_part['Message-Id'] = make_msgid()
        root_part['X-Mailer'] = u'{0}-{1}'.format(package_name, __version__)
        
        mail_message(self.smtp_server, root_part.as_string(), self.email_address, self.mailto)
        print('Mailed the report to: {0}'.format(','.join(self.mailto)))
650279
def configure(self, listener):
        
        listener.capture([
            lambda msg: flavor(msg) == 'callback_query',
            {'message': self._chat_origin_included}
        ])

        listener.capture([
            lambda msg: flavor(msg) == 'callback_query',
            {'inline_message_id': self._inline_origin_included}
        ])
592931
public function buildAdminScreen()
    {

        $p = new DesignPanel($this, "ADMIN");
        $this->initializePanels("ADMIN");
        $this->setAttribute("ReportTitle", ReporticoApp::get('menu_title'));
        ReporticoLang::loadModeLanguagePack("languages", $this->output_charset);
        ReporticoLang::loadModeLanguagePack("admin", $this->output_charset);
        ReporticoLang::localiseTemplateStrings($this->panels["MAIN"]->template);

        if (ReporticoApp::getConfig("project") != "admin") {
            return;
        }

        if (ReporticoApp::get("static_menu") && is_array(ReporticoApp::get("static_menu"))) {
            $ct = 0;
            foreach (ReporticoApp::get("static_menu") as $menuitem) {
                if ($menuitem["title"] == "<AUTO>") {
                    // Generate Menu from XML files
                    if (is_dir(ReporticoApp::get("projpath"))) {
                        if ($dh = opendir(ReporticoApp::get("projpath"))) {
                            while (($file = readdir($dh)) !== false) {
                                $mtch = "/" . $menuitem["report"] . "/";
                                if (preg_match($mtch, $file)) {
                                    $repxml = new XmlReader($this, $file, false, "ReportTitle");
                                    $this->panels["MENU"]->setMenuItem($file, $repxml->search_response);
                                }
                            }
                            closedir($dh);
                        }
                    }
                } else {
                    $this->panels["MENU"]->setMenuItem($menuitem["report"], ReporticoLang::templateXlate($menuitem["title"]));
                }
                $ct++;
            }

            if ($ct == 0) {
                ReporticoApp::handleError("No Menu Items Available - Check Language - " . ReporticoApp::get("language"));
            }

            // Generate list of projects to choose from by finding all folders above the
            // current project area (i.e. the projects folder) and looking for any folder
            // that contains a config.php file (which means it proably is a project)
            $projpath = $this->projects_folder;
            if (!is_dir($projpath)) {
                ReporticoUtility::findFileToInclude($projpath, $projpath);
            }

            if (is_dir($projpath)) {
                $ct = 0;
                if ($dh = opendir($projpath)) {
                    while (($file = readdir($dh)) !== false) {
                        if ($file == ".") {
                            continue;
                        }

                        if (is_dir($projpath . "/" . $file)) {
                            if (is_file($projpath . "/" . $file . "/config.php")) {
                                //$repxml = new XmlReader($this, $file, false, "ReportTitle");
                                $this->panels["ADMIN"]->setProjectItem($file, $file);
                            }
                        }

                    }
                    closedir($dh);
                }
            }

        }
    }
756806
function () {
		if (connectionRequestID) {
			var data = {
				actions: []
			};
			if (status.actions.eChipSet) {
				data.actions.push(MESSENGER_CONST.ACTION.ECHIP_SET);
			}
			if (status.actions.eChipGet) {
				data.actions.push(MESSENGER_CONST.ACTION.ECHIP_GET);
			}
			composeMessage(connectionRequestID, MESSENGER_CONST.TYPE.RESPONSE, MESSENGER_CONST.ACTION.CONNECT, data);
		}
	}
989246
def build_message(self):
        '''
        '''
        if self._text is None:
            raise InvalidPayloadError('text is required')

        message = {
            'text': self._text,
            'markdown': self._markdown
        }

        if self._channel != Incoming.DEFAULT_CHANNEL:
            message['channel'] = self._channel

        if self._attachments:
            message['attachments'] = []
            for attachment in self._attachments:
                if 'title' not in attachment and 'text' not in attachment:
                    raise InvalidPayloadError('title or text is required')
                message['attachments'].append(attachment)

        return message
1058744
function buildMessageBuilder(section) {

	const logOptions = process.env.X2_LOG || '';

	const msgBuilder = new Array();

	if (!/(^|,)nots(,|$)/i.test(logOptions))
		msgBuilder.push(() => (new Date()).toISOString());

	if (!/(^|,)nopid(,|$)/i.test(logOptions))
		msgBuilder.push(() => String(process.pid));

	let m;
	const envRE = new RegExp('(?:^|,)env:([^,]+)', 'gi');
	while ((m = envRE.exec(logOptions)) !== null) {
		const envName = m[1];
		msgBuilder.push(() => process.env[envName]);
	}

	if (section && !/(^|,)nosec(,|$)/i.test(logOptions))
		msgBuilder.push(() => section);

	return msgBuilder;
}
182435
def build_message(self, metric, value, timestamp, tags={}):
        """"""
        if not metric or metric.split(None, 1)[0] != metric:
            raise ValueError('"metric" must not have whitespace in it')
        if not isinstance(value, (int, float)):
            raise TypeError('"value" must be an int or a float, not a {}'.format(
                type(value).__name__))

        tags_suffix = ''.join(';{}={}'.format(x[0], x[1]) for x in sorted(tags.items()))

        message = u'{}{}{} {} {}\n'.format(
            self.prefix + '.' if self.prefix else '',
            metric,
            tags_suffix,
            value,
            int(round(timestamp))
        )
        message = message.encode('utf-8')
        return message
815135
def build_report
      # build cases
      builder = Nokogiri::XML::Builder.new do |xml|
        xml.testsuites {
          testsuite           = xml.testsuite {
            @cases.each do |tc|
              testcase             = xml.testcase {
                if tc.result_has_message?
                  result_type           = xml.send(tc.result)
                  result_type[:message] = tc.message if tc.message.present?
                end

                if tc.system_out.size > 0
                  xml.send('system-out') { xml.text tc.system_out.to_s }
                end

                if tc.system_err.size > 0
                  xml.send('system-err') { xml.text tc.system_err.to_s }
                end
              }

              testcase[:name]      = tc.name if tc.name.present?
              testcase[:time]      = tc.time if tc.time.present?

              testcase[:classname] = package if package.present?
              if tc.classname.present?
                if testcase[:classname].present?
                  testcase[:classname] = "#{testcase[:classname]}.#{tc.classname}"
                else
                  testcase[:classname] = tc.classname
                end
              end

            end
          }

          testsuite[:name]    = name if name.present?
          testsuite[:package] = package if package.present?
        }
      end

      builder.parent.root.to_xml
    end
32900
public function export()
    {
        foreach ($this->messages as $message) {
            list($msg, $level, $category, $timestamp, $traces) = $message;

            $levelName = Logger::getLevelName($level);
            if (!in_array($levelName, ['error', 'warning', 'info'])) {
                $levelName = 'error';
            }
            $data = [
                'timestamp' => gmdate('Y-m-d\TH:i:s\Z', $timestamp),
                'level' => $levelName,
                'tags' => ['category' => $category],
                'message' => $msg,
            ];
            if (!empty($traces)) {
                $data['sentry.interfaces.Stacktrace'] = [
                    'frames' => Raven_Stacktrace::get_stack_info($traces),
                ];
            }

            $this->client->capture($data, false);
        }
    }
182528
@Override
    protected void configure() {
        bind(MessagingService.class).to(MessagingServiceImpl.class);

        bind(BounceProxyLifecycleMonitor.class).to(MonitoringServiceClient.class);
        bind(BounceProxyInformation.class).toProvider(BounceProxyInformationProvider.class);
    }
230664
def _publish_message(host, amqp_settings, routing_key, data):
    
    if host == "stdout":
        print("Published to %s: %s" % (routing_key, data))
        return True

    try:
        conn = Connection(**remove_nones(
            host=host,
            userid=amqp_settings.get("userid"),
            password=amqp_settings.get("password"),
            connect_timeout=amqp_settings.get("connect_timeout")
        ))
    except socket.error as e:
        print_error("Cannot connect to the message broker: %s" % (e))
        return False

    channel = conn.channel()

    # build the message
    msg = basic_message.Message(**remove_nones(
        body=json.dumps(data),
        delivery_mode=amqp_settings.get("message_delivery_mode"),
        content_type="application/json",
        content_encoding="utf-8"
    ))

    # publish the message
    try:
        channel.basic_publish(
            msg,
            amqp_settings["exchange_name"],
            routing_key
        )
    except Exception as e:
        print_error("Failed to publish message: %s" % (e))
        return False

    return True
1123053
def prepare_message(self, message_data, delivery_mode,
                        content_type, content_encoding, **kwargs):
        """"""
        return (message_data, content_type, content_encoding)
1279431
function(msg, config, node) {
    checkConfiguration(msg, node)
      .then(function(settings) {
        var options = toneutils.parseOptions(msg, config);
        options = toneutils.parseLanguage(msg, config, options);
        node.status({fill:'blue', shape:'dot', text:'requesting'});
        return invokeService(config, options, settings);
      })
      .then(function(data){
        node.status({})
        msg.response = data;
        node.send(msg);
        node.status({});
      })
      .catch(function(err){
        payloadutils.reportError(node,msg,err);
        node.send(msg);
      });
  }
1285803
function setupMsgStream() {
	if (!mmrpNode.isClient) {
		return;
	}

	logger.verbose('Setting up HTTP message stream communication');

	stream = new MsgStream(cfgMsgStream);

	stream.bindToHttpServer(mage.core.httpServer);

	stream.on('connect', function (address, clusterId, disconnects) {
		exports.connect(address, clusterId, disconnects);
	});

	stream.on('disconnect', function (address, clusterId) {
		exports.disconnect(address, clusterId);
	});

	stream.on('confirm', function (address, clusterId, msgIds) {
		exports.confirm(address, clusterId, msgIds);
	});

	mmrpNode.on('delivery.msgServer.messagepack', function (envelope) {
		var address = String(envelope.messages[0]);

		if (address && stream) {
			logger.verbose('Delivering message pack to address', address);

			stream.deliver(address, envelope.messages.slice(1));
			envelope.consumeRoute();
		}
	});

	mmrpNode.on('delivery.msgServer.hostGone', function (envelope) {
		var address = String(envelope.messages[0]);

		if (address && stream) {
			logger.verbose('Announcing host disappeared for address', address);

			stream.hostGone(address);
			envelope.consumeRoute();
		}
	});

	mmrpNode.on('delivery.mmrp.sendError', function (envelope) {
		var originalType = String(envelope.messages[1]);
		if (['msgServer.connect', 'msgServer.send'].indexOf(originalType) < 0) {
			return;
		}

		var address = String(envelope.messages[2]);

		if (address && stream) {
			logger.verbose('Announcing host disappeared for address', address);

			stream.hostGone(address);
			envelope.consumeRoute();
		}
	});
}
1268268
def make_data(self, message):

        

        if not isinstance(message, Message):
            return message
        return message.export(self.transport_content_type)