Node for AMQP sender
196407
function amqpSenderNode(config) {

        RED.nodes.createNode(this, config);

        // get endpoint configuration
        this.endpoint = RED.nodes.getNode(config.endpoint);
        // get all other configuration
        this.address = config.address;
        this.autosettle = config.autosettle;
        this.dynamic = config.dynamic;
        this.sndsettlemode = config.sndsettlemode;
        this.rcvsettlemode = config.rcvsettlemode;
        this.durable = config.durable;
        this.expirypolicy = config.expirypolicy;

        var node = this;
        // node not yet connected
        this.status({ fill: 'red', shape: 'dot', text: 'disconnected' });

        if (node.endpoint) {

            node.endpoint.connect(function(connection) {
                setup(connection);
            });

            /**
             * Node setup for creating sender link
             *
             * @param connection    Connection instance
             */
            function setup(connection) {

                node.connection = connection;

                // node connected
                node.status({ fill: 'green', shape: 'dot', text: 'connected' });

                // build sender options based on node configuration
                var options = {
                    target: {
                        address: node.address,
                        dynamic: node.dynamic,
                        durable: node.durable,
                        expiry_policy: node.expirypolicy
                    },
                    autosettle: node.autosettle,
                    snd_settle_mode: node.sndsettlemode,
                    rcv_settle_mode: node.rcvsettlemode
                };
                node.sender = node.connection.open_sender(options);

                node.sender.on('accepted', function(context) {
                    var msg = outDelivery(node, context.delivery);
                    node.send(msg);
                });

                node.sender.on('released', function(context) {
                    var msg = outDelivery(node, context.delivery);
                    node.send(msg);
                });

                node.sender.on('rejected', function(context) {
                    var msg = outDelivery(node, context.delivery);
                    node.send(msg);
                });

                node.connection.on('disconnected', function(context) {
                    // node disconnected
                    node.status({fill: 'red', shape: 'dot', text: 'disconnected' });
                });

                node.on('input', function(msg) {
                    // enough credits to send
                    if (node.sender.sendable()) {
                        node.sender.send(msg.payload);
                    }
                });

                node.on('close', function() {
                    if (node.sender != null)
                        node.sender.detach();
                    node.connection.close();
                });
            }

        }
    }
1138983
function MasterBroker (node) {
  let broker = {}

  //  Debug
  const _debug = D('dnsmq-messagebus:masterbroker')
  const _debugHeartbeat = D('dnsmq-messagebus:masterbroker:heartbeats')
  const debug = (...args) => _debug(node.name, ...args)

  /**
   * sends an heartbeat to the subscribing sockets
   * @private
   */
  function _sendHeartbeat () {
    if (!_bound) return
    _debugHeartbeat('')
    _pub.send(['heartbeats', node.name])
  }

  // Private API
  let _ip
  let _sub
  let _pub
  let _bound
  let _subPort
  let _pubPort
  let _hearbeatInterval
  let _isMaster = false

  /**
   * binds a new pair of pub/sub sockets to all the
   * interfaces, on random ports
   * @return {[type]} [description]
   */
  function bind () {
    if (_bound) return
    let {sub, pub} = getSockets()
    sub.bindSync(`tcp://0.0.0.0:*`)
    pub.bindSync(`tcp://0.0.0.0:*`)
    _sub = sub
    _pub = pub
    _subPort = getSocketPort(_sub)
    _pubPort = getSocketPort(_pub)
    _bound = true
  }
  /**
   * unbinds the pub/sub sockets
   * @return {[type]} [description]
   */
  function unbind () {
    if (!_bound) return
    _sub.close()
    _pub.close()
    _subPort = null
    _pubPort = null
    _bound = false
    stoptHeartbeats()
  }
  /**
   * setter for the private var `_ip` (IP address)
   * sets `_ip` just once
   * @param {string} ip
   */
  function setIP (ip) {
    if (!_ip) {
      debug(`discovered own IP: ${ip}`)
      _ip = ip
    }
  }
  /**
   * sends a message to subscribing sockets
   * containing infos about a just elected master
   * @param  {object} newMasterInfos
   */
  function signalNewMaster (newMasterInfos) {
    if (_bound) {
      debug(`signaling new master to connected nodes`)
      _pub.send(['newmaster', JSON.stringify(newMasterInfos)])
    }
  }
  /**
   * starts the emission of heartbeats at regular intervals
   */
  function startHeartbeats () {
    _isMaster = true
    if (_hearbeatInterval) return
    debug('starting heartbeats')
    _sendHeartbeat()
    _hearbeatInterval = setInterval(_sendHeartbeat, HEARTBEAT_INTERVAL)
  }
  /**
   * stops the emission of heartbeats
   */
  function stoptHeartbeats () {
    _isMaster = false
    if (!_hearbeatInterval) return
    debug('stopping heartbeats')
    clearInterval(_hearbeatInterval)
    _hearbeatInterval = null
  }

  return Object.defineProperties(broker, {
    isMaster: {get: () => _isMaster},
    endpoints: {
      get: () => ({
        sub: _ip ? `tcp://${_ip}:${_subPort}` : undefined,
        pub: _ip ? `tcp://${_ip}:${_pubPort}` : undefined
      })
    },
    ports: {
      get: () => ({
        sub: _subPort,
        pub: _pubPort
      })
    },
    bind: {value: bind},
    unbind: {value: unbind},
    setIP: {value: setIP},
    signalNewMaster: {value: signalNewMaster},
    startHeartbeats: {value: startHeartbeats},
    stoptHeartbeats: {value: stoptHeartbeats}
  })
}
504236
def _send_query(self):
        
        timeout = 60
        ofproto = self._datapath.ofproto
        parser = self._datapath.ofproto_parser
        if ofproto_v1_0.OFP_VERSION == ofproto.OFP_VERSION:
            send_port = ofproto.OFPP_NONE
        else:
            send_port = ofproto.OFPP_ANY

        # create a general query.
        res_igmp = igmp.igmp(
            msgtype=igmp.IGMP_TYPE_QUERY,
            maxresp=igmp.QUERY_RESPONSE_INTERVAL * 10,
            csum=0,
            address='0.0.0.0')
        res_ipv4 = ipv4.ipv4(
            total_length=len(ipv4.ipv4()) + len(res_igmp),
            proto=inet.IPPROTO_IGMP, ttl=1,
            src='0.0.0.0',
            dst=igmp.MULTICAST_IP_ALL_HOST)
        res_ether = ethernet.ethernet(
            dst=igmp.MULTICAST_MAC_ALL_HOST,
            src=self._datapath.ports[ofproto.OFPP_LOCAL].hw_addr,
            ethertype=ether.ETH_TYPE_IP)
        res_pkt = packet.Packet()
        res_pkt.add_protocol(res_ether)
        res_pkt.add_protocol(res_ipv4)
        res_pkt.add_protocol(res_igmp)
        res_pkt.serialize()

        flood = [parser.OFPActionOutput(ofproto.OFPP_FLOOD)]

        while True:
            # reset reply status.
            for status in self._mcast.values():
                for port in status.keys():
                    status[port] = False

            # send a general query to the host that sent this message.
            self._do_packet_out(
                self._datapath, res_pkt.data, send_port, flood)
            hub.sleep(igmp.QUERY_RESPONSE_INTERVAL)

            # QUERY timeout expired.
            del_groups = []
            for group, status in self._mcast.items():
                del_ports = []
                actions = []
                for port in status.keys():
                    if not status[port]:
                        del_ports.append(port)
                    else:
                        actions.append(parser.OFPActionOutput(port))
                if len(actions) and len(del_ports):
                    self._set_flow_entry(
                        self._datapath, actions, self.server_port, group)
                if not len(actions):
                    self._del_flow_entry(
                        self._datapath, self.server_port, group)
                    del_groups.append(group)
                if len(del_ports):
                    for port in del_ports:
                        self._del_flow_entry(self._datapath, port, group)
                for port in del_ports:
                    del status[port]
            for group in del_groups:
                del self._mcast[group]

            rest_time = timeout - igmp.QUERY_RESPONSE_INTERVAL
            hub.sleep(rest_time)
186440
function EmailNode(n) {
        RED.nodes.createNode(this, n);
        this.topic = n.topic;
        this.name = n.name;
        this.outserver = n.server;
        this.outport = n.port;
        this.secure = n.secure;
        let flag = false;
        if (this.credentials && this.credentials.hasOwnProperty('userid')) {
            this.userid = this.credentials.userid;
        } else {
            if (globalkeys) {
                this.userid = globalkeys.user;
                flag = true;
            }
        }
        if (this.credentials && this.credentials.hasOwnProperty('password')) {
            this.password = this.credentials.password;
        } else {
            if (globalkeys) {
                this.password = globalkeys.pass;
                flag = true;
            }
        }
        if (flag) {
            RED.nodes.addCredentials(n.id, {userid: this.userid, password: this.password, global: true});
        }
        let node = this;

        let smtpOptions = {
            host: node.outserver,
            port: node.outport,
            secure: node.secure,
        };

        if (this.userid && this.password) {
            smtpOptions.auth = {
                user: node.userid,
                pass: node.password,
            };
        }
        let smtpTransport = nodemailer.createTransport(smtpOptions);

        this.on('input', function(msg) {
            let params = processValuesFromContext(node, msg, [
                {name: 'port', type: 'portType'},
                {name: 'server', type: 'serverType'},
                {name: 'userid', type: 'useridType'},
                {name: 'password', type: 'passwordType'},
            ]);
            console.log('params are ....');
            console.log(JSON.stringify(params));

            if (params.userid && params.password) {
                smtpOptions.auth = {
                    user: params.userid,
                    pass: params.password,
                };
            }

            if (params.port && params.server) {
                smtpOptions.host = params.server;
                smtpOptions.port = params.port;
            }


            if (msg.hasOwnProperty('payload')) {
                if (smtpTransport) {
                    node.status({fill: 'blue', shape: 'dot', text: 'email.status.sending'});
                    if (msg.to && node.name && (msg.to !== node.name)) {
                        node.warn(RED._('node-red:common.errors.nooverride'));
                    }
                    let sendopts = {from: ((msg.from) ? msg.from : node.userid)}; // sender address
                    sendopts.to = node.name || msg.to; // comma separated list of addressees
                    if (node.name === '') {
                        sendopts.cc = msg.cc;
                        sendopts.bcc = msg.bcc;
                    }
                    sendopts.subject = msg.topic || msg.title || 'Message from Node-RED'; // subject line
                    if (msg.hasOwnProperty('envelope')) {
                        sendopts.envelope = msg.envelope;
                    }
                    if (Buffer.isBuffer(msg.payload)) { // if it's a buffer in the payload then auto create an attachment instead
                        if (!msg.filename) {
                            let fe = 'bin';
                            if ((msg.payload[0] === 0xFF) && (msg.payload[1] === 0xD8)) {
                                fe = 'jpg';
                            }
                            if ((msg.payload[0] === 0x47) && (msg.payload[1] === 0x49)) {
                                fe = 'gif';
                            } // 46
                            if ((msg.payload[0] === 0x42) && (msg.payload[1] === 0x4D)) {
                                fe = 'bmp';
                            }
                            if ((msg.payload[0] === 0x89) && (msg.payload[1] === 0x50)) {
                                fe = 'png';
                            } // 4E
                            msg.filename = 'attachment.' + fe;
                        }
                        let fname = msg.filename.replace(/^.*[\\\/]/, '') || 'file.bin';
                        sendopts.attachments = [{content: msg.payload, filename: fname}];
                        if (msg.hasOwnProperty('headers') && msg.headers.hasOwnProperty('content-type')) {
                            sendopts.attachments[0].contentType = msg.headers['content-type'];
                        }
                        // Create some body text..
                        sendopts.text = RED._('email.default-message', {filename: fname, description: (msg.description || '')});
                    } else {
                        let payload = RED.util.ensureString(msg.payload);
                        sendopts.text = payload; // plaintext body
                        if (/<[a-z][\s\S]*>/i.test(payload)) {
                            sendopts.html = payload;
                        } // html body
                        if (msg.attachments) {
                            sendopts.attachments = msg.attachments;
                        } // add attachments
                    }
                    smtpTransport.sendMail(sendopts, function(error, info) {
                        if (error) {
                            node.error(error, msg);
                            node.status({fill: 'red', shape: 'ring', text: 'email.status.sendfail'});
                        } else {
                            node.log(RED._('email.status.messagesent', {response: info.response}));
                            node.status({});
                        }
                    });
                } else {
                    node.warn(RED._('email.errors.nosmtptransport'));
                }
            } else {
                node.warn(RED._('email.errors.nopayload'));
            }
        });
    }
1018229
function(params, callback) {
        if (!client) {
          fireEvent("error", {
            errorCode: 999,
            errorMessage: "ActiveMQ Client is not ready or has not been initialized!"
          });
        }

        var subscribeHeaders = {
          "destination": params.destination,
          "ack": params.ack
        };

        client.subscribe(subscribeHeaders, function(error, message) {
          if (error) {
            fireEvent("error", {
              errorCode: 999,
              errorMessage: "ActiveMQ Subscription Error!"
            });
            return;
          }

          message.readString("utf-8", function(error, body) {
            if (error) {
              fireEvent("error", {
                errorCode: 999,
                errorMessage: "ActiveMQ Read Message Error!"
              });
              return;
            }

            callback && callback(body);

            client.ack(message);
          });
        });
      }
481619
function(msg) {
        if (onSendLogging)
          asyncLogger("Send", msg);

        switch (protocol) {
          case 'websocket':
            if (socketState === socketStateType.OPEN) {
              socket.emit(msg);
            } else {
              pushSendDataQueue.push(msg);
            }
            break;

          case 'queue':
            if (socketState === socketStateType.OPEN) {
              activemq.sendMessage({
                destination: params.queueSend,
                message: msg
              });
            } else {
              pushSendDataQueue.push(msg);
            }
            break;
        }
      }
234984
function (callback) { // # 1

          var address;
          if (self.conf.zookeeper) {
            if (typeof self.conf.zookeeper === 'string' || self.conf.zookeeper instanceof String) {
              address = self.conf.zookeeper;
            } else {
              if (self.conf.zookeeper.address)  address = self.conf.zookeeper.address;
            }
          }

          self.nodeManager = new NodeManager(
            address,
            true,
            function (err, message) {
              if (!err) {
                console.info(' (init) ZOOKEEPER is connected');
                self.nodeManager.createEphemeralPath(
                  NodeConstants.META_PATH + NodeConstants.GW_SERVER_PATH + '/' + self.conf.host + ':' + self.conf.port,
                  function (err, message) {
                    console.info('        ZOOKEEPER /' + self.conf.host + ':' + self.conf.port);

                    // init balacing config
                    self.nodeManager.getConfigInfo('balancing', function (data) {
                      if (data) {
                        self.conf.balancing = data;
                      }
                    });

                    callback(err, message);
                  }
                );
              } else {
                callback(err, message);
              }
            }
          );

        }
536865
function setup(connection) {

                node.connection = connection;

                // node connected
                node.status({ fill: 'green', shape: 'dot', text: 'connected' });

                // build sender options based on node configuration
                var options = {
                    target: {
                        address: node.address,
                        dynamic: node.dynamic,
                        durable: node.durable,
                        expiry_policy: node.expirypolicy
                    },
                    autosettle: node.autosettle,
                    snd_settle_mode: node.sndsettlemode,
                    rcv_settle_mode: node.rcvsettlemode
                };
                node.sender = node.connection.open_sender(options);

                node.sender.on('accepted', function(context) {
                    var msg = outDelivery(node, context.delivery);
                    node.send(msg);
                });

                node.sender.on('released', function(context) {
                    var msg = outDelivery(node, context.delivery);
                    node.send(msg);
                });

                node.sender.on('rejected', function(context) {
                    var msg = outDelivery(node, context.delivery);
                    node.send(msg);
                });

                node.connection.on('disconnected', function(context) {
                    // node disconnected
                    node.status({fill: 'red', shape: 'dot', text: 'disconnected' });
                });

                node.on('input', function(msg) {
                    // enough credits to send
                    if (node.sender.sendable()) {
                        node.sender.send(msg.payload);
                    }
                });

                node.on('close', function() {
                    if (node.sender != null)
                        node.sender.detach();
                    node.connection.close();
                });
            }
904758
def _send(self, msg):
        
        uuid = self.m2req.sender
        conn_id = self.m2req.conn_id

        header = "%s %d:%s," % (uuid, len(str(conn_id)), str(conn_id))
        zmq_message = header + ' ' + msg
        self.stream.send(zmq_message)
642535
def main(args, stop=False):
    
    daemon = AMQPDaemon(
        con_param=getConParams(
            settings.RABBITMQ_MX2MODS_VIRTUALHOST
        ),
        queue=settings.RABBITMQ_MX2MODS_INPUT_QUEUE,
        out_exch=settings.RABBITMQ_MX2MODS_EXCHANGE,
        out_key=settings.RABBITMQ_MX2MODS_OUTPUT_KEY,
        react_fn=reactToAMQPMessage,
        glob=globals()                # used in deserializer
    )

    if not stop and args and args.foreground:  # run at foreground
        daemon.run()
    else:
        daemon.run_daemon()
1325170
function createChannel(addr) {
  return amqp.connect(genAddr(addr)).then(conn => {
    return conn.createChannel().then(ch => {
      connections.push(conn);

      return [conn, ch];
    });
  }, debugError);
}
1184664
function Node (config) {
    RED.nodes.createNode(this, config);
    var node = this;

    this.on('input', function (msg) {
      var method = config['cwm-custom-mode'],
        message = '',
        params = {};

      username = sUsername || this.credentials.username;
      password = sPassword || this.credentials.password || config.password;
      apikey = sApikey || this.credentials.apikey || config.apikey;

      // All method to be overridden
      if (msg.params) {
        if (msg.params.method) {
          method = msg.params.method;
        }
        if (msg.params.username) {
          username = msg.params.username;
        }
        if (msg.params.password) {
          password = msg.params.password;
        }
        if (msg.params.apikey) {
          apikey = msg.params.apikey;
        }
        if (msg.params.version) {
          version = msg.params.version;
        }
      }
      endpoint = sEndpoint;
      if ((!config['cwm-default-endpoint']) && config['cwm-service-endpoint']) {
        endpoint = config['cwm-service-endpoint'];
      }

      node.status({});
      initialCheck(apikey, username, password, method)
        .then(function(){
          return buildParams(msg, method, config, params);
        })
        .then(function(){
          return checkForFile(method);
        })
        .then(function(fileNeeded){
          if (fileNeeded) {
            if (msg.payload instanceof Buffer) {
              return loadFile(node, method, params, msg);
            }
            // If the data is a json object then it will not
            // have been detected as a buffer.
            return setWorkspaceParams(method, params, msg.payload);
          }
          return Promise.resolve(params);
        })
        .then(function(p){
          params = p;
          node.status({fill:'blue', shape:'dot', text:'executing'});
          return executeMethod(node, method, params, msg);
        })
        .then(function(){
          temp.cleanup();
          node.status({});
          node.send(msg);
        })
        .catch(function(err){
          temp.cleanup();
          payloadutils.reportError(node,msg,err);
        });

    });
  }
1348678
def node(n, options = {})
      custom_params = []
      custom_params << use_named_parameter('dc', options[:dc]) if options[:dc]

      ret = send_get_request(@conn, ["/v1/health/node/#{n}"], options, custom_params)
      JSON.parse(ret.body).map { |node| OpenStruct.new node }
    end
881666
function setup(connection) {

                var request = undefined;
                var reply_to = undefined;
                var response = undefined;

                node.connection = connection;

                // node connected
                node.status({ fill: 'green', shape: 'dot', text: 'connected' });

                node.sender = node.connection.open_sender({ target: {} });

                // build receiver options
                var receiver_options = {
                    source: {
                        address: node.address
                    }
                };
                node.receiver = node.connection.open_receiver(receiver_options);

                node.receiver.on('message', function(context) {

                    // save request and reply_to address on AMQP message received
                    request = context.message;
                    reply_to = request.reply_to;

                    // provides the request and delivery as node output
                    var msg = {
                        payload: context.message,
                        delivery: context.delivery
                    };
                    node.send(msg);
                });

                node.connection.on('disconnected', function(context) {
                    // node disconnected
                    node.status({fill: 'red', shape: 'dot', text: 'disconnected' });
                });

                node.on('input', function(msg) {
                    // enough credits to send
                    if (node.sender.sendable()) {

                        if (reply_to) {

                            // fill the response with the provided one as input
                            response = msg.payload;
                            response.to = reply_to;

                            node.sender.send(response);
                        }
                    }
                });

                node.on('close', function() {
                    if (node.sender != null)
                        node.sender.detach();
                    if (node.receiver != null)
                        node.receiver.detach();
                    node.connection.close();
                })

            }
913122
function Node (config) {
    RED.nodes.createNode(this, config);
    var node = this;

    // Invoked when the node has received an input as part of a flow.
    this.on('input', function (msg) {
      processOnInput(msg, config, node);
    });
  }
467095
def receive(host, timeout):
    
    parameters = settings.get_amqp_settings()[host]

    queues = parameters["queues"]
    queues = dict(map(lambda (x, y): (y, x), queues.items()))  # reverse items
    queue = queues[parameters["out_key"]]

    channel = _get_channel(host, timeout)
    for method_frame, properties, body in channel.consume(queue):
        print json.dumps({
            "method_frame": str(method_frame),
            "properties": str(properties),
            "body": body
        })
        print "-" * 79
        print

        channel.basic_ack(method_frame.delivery_tag)
266566
function AmqpTasksSource(amqpOptions) {
  TasksSource.apply(this, arguments);
  assert.ok(amqpOptions, "amqpOptions are required in order to create a AmqpTasksSource");
  Object.defineProperty(this, 'amqpOptions', {
    value: amqpOptions,
    enumerable: false,
    configurable: false
  });
  this.connection = null;
  this._amqpExchange = null;
  this.exchangeName = 'orch';
  this._queues = {};
}