Called when a message is received with decoded JSON content
509878
def recv(self, message, ref, pos):
        

        # Get action
        action = message.get('action', None)

        # Show the message we got
        if action != 'pingdog':
            self.debug("{} - Receive: {} (ref:{}) - {}".format(pos.name.encode('ascii', 'ignore'), message, ref, pos.uuid), color="cyan")

        # Check the action that it is requesting
        if action == 'get_config':
            # Get all the hardware connected to this POS
            answer = {}
            answer['action'] = 'config'
            answer['commit'] = pos.commit
            answer['hardware'] = []
            for hw in pos.hardwares.filter(enable=True):
                # Prepare to send back the config
                answer['hardware'].append({'kind': hw.kind, 'config': hw.get_config(), 'uuid': hw.uuid.hex})
            self.debug(u"{} - Send: {} - {}".format(pos.name.encode('ascii', 'ignore'), answer, pos.uuid), color='green')
            self.send(answer, ref, pos)
        elif action == 'subscribe':
            # Get UUID
            uid = message.get('uuid', None)
            # Check if we got a valid UUID
            if uid:
                uid = uuid.UUID(uid)
                poshw = POSHardware.objects.filter(uuid=uid).first()
                if poshw:
                    if poshw.enable:
                        # Suscribe this websocket to group
                        self.debug("{} - Subscribed to '{}' - {}".format(pos.name.encode('ascii', 'ignore'), uid.hex, pos.uuid), color="purple")
                        Group(uid.hex).add(self.message.reply_channel)
                        self.send({'action': 'subscribed', 'uuid': uid.hex, 'key': poshw.key}, ref, pos)
                    else:
                        self.send_error("You cannot subscribe to a disabled Hardware!", ref, pos)
                else:
                    self.send_error("You cannot subscribe to a Hardware that is not available, UUID not found!", ref, pos)
            else:
                self.send_error("You have tried to subscribe to a UUID but didn't specify any or is invalid", ref, pos)
        elif action == 'msg':
            uid = message.get('uuid', None)
            msg = message.get('msg', None)
            if uid:
                origin = POSHardware.objects.filter(uuid=uuid.UUID(uid)).first()
                if origin:
                    self.debug("{} - Got a message from {}: {} (ref:{}) - {}".format(pos.name.encode('ascii', 'ignore'), origin.uuid, msg, ref, pos.uuid), color='purple')
                    origin.recv(msg)
                else:
                    self.debug("{} - Got a message from UNKNOWN {}: {} (ref:{}) - {}".format(pos.name.encode('ascii', 'ignore'), uid, msg, ref, pos.uuid), color='purple')
            else:
                self.debug("{} - Got a message from NO-UUID: {} (ref:{}) - {}".format(pos.name.encode('ascii', 'ignore'), msg, ref, pos.uuid), color='purple')
        elif action == 'ping':
            super(POSConsumer, self).send({'message': json.dumps({'action': 'pong', 'ref': ref})})
        elif action == 'pong':
            self.debug("{} - Got PONG {} (ref:{}) - {}".format(pos.name.encode('ascii', 'ignore'), message.get('ref', '-'), ref, pos.uuid), color='white')
        elif action == 'pingdog':
            super(POSConsumer, self).send({'message': json.dumps({'action': 'pongdog', 'ref': ref})})
        elif action == 'error':
            uid = message.get('uuid', None)
            msg = message.get('error', 'No error')
            if uid:
                self.error("{} - Got an error from {}: {} (UUID:{}) (ref:{}) - {}".format(pos.name.encode('ascii', 'ignore'), pos.uuid, msg, uid, ref, pos.uuid))
            else:
                self.error("{} - Got an error from {}: {}) (ref:{}) - {}".format(pos.name.encode('ascii', 'ignore'), pos.uuid, msg, ref, pos.uuid))
            log = POSLog()
            log.pos = pos
            if uid:
                poshw = POSHardware.objects.filter(uuid=uid).first()
                if poshw:
                    log.poshw = poshw
                    log.uuid = poshw.uuid
            else:
                log.uuid = pos.uuid
            log.log = message.get('error', None)
            log.save()
        else:
            # Unknown action
            self.send_error("Unknown action '{}'".format(action), ref, pos)
517748
def _message_to_payload(cls, message):
        ''''''
        try:
            return json.loads(message.decode())
        except UnicodeDecodeError:
            message = 'messages must be encoded in UTF-8'
        except json.JSONDecodeError:
            message = 'invalid JSON'
        raise cls._error(cls.PARSE_ERROR, message, True, None)
404369
def _process_message(self, message: amqp.Message) -> None:
        """"""
        if self.shutdown_pending.is_set():
            return

        try:
            if isinstance(message.body, bytes):
                message.body = message.body.decode()
            description = json.loads(message.body)
        except Exception:
            logger.error("Cannot decode message. Dropping. Message: %r", message.body)
            traceback.print_exc()
            message.channel.basic_reject(message.delivery_tag, requeue=False)
        else:
            logger.info("Processing task: %r", description)
            self._process_description(message, description)
272520
function parseMessage(msg, jsonEncode) {
    if (typeof msg === 'string') {
        msg = { data: msg };
    }

    var output = '';
    if (msg.event) {
        output += 'event: ' + msg.event + '\n';
    }

    if (msg.retry) {
        output += 'retry: ' + msg.retry + '\n';
    }

    if (msg.id) {
        output += 'id: ' + msg.id + '\n';
    }

    var data = msg.data || '';
    if (jsonEncode) {
        data = JSON.stringify(data);
    }

    output += parseTextData(data);

    return output;
}
906927
def on_request(self, msg):
        
        LOGGER.debug("natsd.Service.on_request - request " + str(msg) + " received")
        try:
            working_response = json.loads(msg.data.decode())
            working_properties = DriverTools.json2properties(working_response['properties'])
            working_body = b''+bytes(working_response['body'], 'utf8') if 'body' in working_response else None
            working_body_decoded = base64.b64decode(working_body) if working_body is not None else \
                bytes(json.dumps({}), 'utf8')
            self.cb(working_properties, working_body_decoded)
        except Exception as e:
            LOGGER.warn("natsd.Service.on_request - Exception raised while treating msg {"+str(msg)+","+str(msg)+"}")
        LOGGER.debug("natsd.Service.on_request - request " + str(msg) + " treated")
923613
def received(self, data):
        
        self.logger.debug('Data received: {}'.format(data))

        message_type = None

        if 'type' in data:
            message_type = data['type']

        if message_type == 'confirm_subscription':
            self._subscribed()
        elif message_type == 'reject_subscription':
            self._rejected()
        elif self.receive_callback is not None and 'message' in data:
            self.receive_callback(data['message'])
        else:
            self.logger.warning('Message type unknown. ({})'.format(message_type))
580070
private void doBatchMessage(final JsonObject message) {
    String batchID = message.getString("batch");
    if (currentBatch != null && currentBatch.id().equals(batchID)) {
      Object value = deserializer.deserialize(message);
      if (value != null) {
        if (log.isDebugEnabled()) {
          log.debug(String.format("%s - Batch received: Batch[batch=%s, id=%d, message=%s]", this, batchID, message.getLong("id"), value));
        }
        currentBatch.handleMessage(value);
      }
    }
  }
1192652
def from_json(json_string):
    
    # parse the provided json_message
    try:            
        parsed_msg = json.loads(json_string)            
    except ValueError as ex:            
        # if the provided json_message is not a valid JSON
        return None
    except TypeError as ex:
        # if json_message not string or buffer
        return None
    herald_version = None
    # check if it is a valid Herald JSON message
    if herald.MESSAGE_HEADERS in parsed_msg:
        if herald.MESSAGE_HERALD_VERSION in parsed_msg[herald.MESSAGE_HEADERS]:
            herald_version = parsed_msg[herald.MESSAGE_HEADERS].get(herald.MESSAGE_HERALD_VERSION)                         
    if herald_version is None or herald_version != herald.HERALD_SPECIFICATION_VERSION:
        _logger.error("Herald specification of the received message is not supported!")
        return None   
    # construct new Message object from the provided JSON object    
    msg = herald.beans.MessageReceived(uid=(parsed_msg[herald.MESSAGE_HEADERS].get(herald.MESSAGE_HEADER_UID) or None), 
                          subject=parsed_msg[herald.MESSAGE_SUBJECT], 
                          content=None, 
                          sender_uid=(parsed_msg[herald.MESSAGE_HEADERS].get(herald.MESSAGE_HEADER_SENDER_UID) or None), 
                          reply_to=(parsed_msg[herald.MESSAGE_HEADERS].get(herald.MESSAGE_HEADER_REPLIES_TO) or None), 
                          access=None,
                          timestamp=(parsed_msg[herald.MESSAGE_HEADERS].get(herald.MESSAGE_HEADER_TIMESTAMP) or None) 
                          )                           
    # set content
    try:
        if herald.MESSAGE_CONTENT in parsed_msg:
            parsed_content = parsed_msg[herald.MESSAGE_CONTENT]                              
            if parsed_content is not None:
                if isinstance(parsed_content, str):
                    msg.set_content(parsed_content)
                else:
                    msg.set_content(jabsorb.from_jabsorb(parsed_content))
    except KeyError as ex:
        _logger.error("Error retrieving message content! " + str(ex)) 
    # other headers
    if herald.MESSAGE_HEADERS in parsed_msg:
        for key in parsed_msg[herald.MESSAGE_HEADERS]:
            if key not in msg._headers:
                msg._headers[key] = parsed_msg[herald.MESSAGE_HEADERS][key]         
    # metadata
    if herald.MESSAGE_METADATA in parsed_msg:
        for key in parsed_msg[herald.MESSAGE_METADATA]:
            if key not in msg._metadata:
                msg._metadata[key] = parsed_msg[herald.MESSAGE_METADATA][key] 
                       
    return msg
169441
def send_jsonified(self, msg, stats=True):
        
        msg = bytes_to_str(msg)

        if self._immediate_flush:
            if self.handler and self.handler.active and not self.send_queue:
                # Send message right away
                self.handler.send_pack('a[%s]' % msg)
            else:
                if self.send_queue:
                    self.send_queue += ','
                self.send_queue += msg

                self.flush()
        else:
            if self.send_queue:
                self.send_queue += ','
            self.send_queue += msg

            if not self._pending_flush:
                self.server.io_loop.add_callback(self.flush)
                self._pending_flush = True

        if stats:
            self.stats.on_pack_sent(1)
1324400
function(transport, message, info) {
        var e = message[0].replace('/', '');

        var data = null;
        if (message[1]) {
            try {
                data = JSON.parse(message[1]);
            } catch (e) {
                logger.warn('OSC messages should be JSON');
            }
        }

        transport.emit(e, data);
    }
564531
def _onMessage(self, ws, message):
        
        try:
            data = json.loads(message)['NotificationContainer']
            log.debug('Alert: %s %s %s', *data)
            if self._callback:
                self._callback(data)
        except Exception as err:  # pragma: no cover
            log.error('AlertListener Msg Error: %s', err)
1278584
@Override
    public void onMessage(StreamMessage received)
    {
        if (this.reloadConfig && this.watcher != null)
        {
            Map<String, Object> reloadedConfig = null;

            try
            {
                reloadedConfig = this.watcher.readIfUpdated();
            }
            catch (IOException ex)
            {
                String logFormat = "Config file reload failed. Skip reload config.";
                logger.warn(logFormat, ex);
            }

            if (reloadedConfig != null)
            {
                onUpdate(reloadedConfig);
            }
        }

        this.executingKeyHistory = received.getHeader().getHistory();
        this.responsed = false;

        // Execute message processing.
        // This class not handles exceptions.
        // Because if throws exception, this class not need ack.
        try
        {
            onExecute(received);
        }
        finally
        {
            clearExecuteStatus();
        }

        // If not responsed, auto ack
        if (this.responsed == false)
        {
            super.ack();
        }
    }
446389
function onMessage (subscription, fullMessage) {
  let msg = null
  try {
    msg = JSON.parse(fullMessage.body)
  } catch (fullMessage) {
    console.tron.error(`Error parsing : ${fullMessage}`)
  }
  if (msg) {
    return em({ subscription, msg })
  }
}
740420
def on_message(self, message):
        """"""
        json_rpc = json.loads(message)
        logging.log(logging.DEBUG, json_rpc)

        if self.pool is None:
            self.pool = multiprocessing.Pool(processes=args.workers)

        # Spawn a process to protect the server against segfaults
        async = self.pool.apply_async(_worker_process, [json_rpc])
        try:
            result = async.get(timeout=args.timeout)
            error = 0
        except multiprocessing.TimeoutError:
            result = ("File format conversion timed out! This is due "
                      "either to a large input file or a segmentation "
                      "fault in the underlying open babel library.")
            error = 1
            self.pool.terminate()
            self.pool = multiprocessing.Pool(processes=args.workers)
        except Exception:
            result = traceback.format_exc()
            error = 1
        logging.log(logging.DEBUG, result)

        self.write_message(json.dumps({'result': result, 'error': error,
                                       'id': json_rpc['id']},
                                      separators=(',', ':')))
759244
def onmessage(msg)
      msg = Oj.strict_load(msg)

      msg['data'] = Oj.strict_load(msg['data']) if msg['data'].is_a? String

      event = msg['event'].gsub(/\Apusher:/, 'pusher_')

      if event =~ /\Aclient-/
        msg['socket_id'] = connection.socket_id
        Channel.send_client_message msg
      elsif respond_to? event, true
        send event, msg
      end

    rescue JSON::ParserError
      error({ code: 5001, message: "Invalid JSON" })
    rescue Exception => e
      error({ code: 500, message: "#{e.message}\n #{e.backtrace.join "\n"}" })
    end
1021450
function onMessage(message) {
    if (message.type != "utf8") return

    DEBUGMSG("recv: " + message.utf8Data)
    message = JSON.parse(message.utf8Data)

    if      (message.type == "request")  session.onRequest(channel, message)
    else if (message.type == "response") session.onResponse(channel, message)
    else if (message.type == "event")    session.onEvent(channel, message)
  }
984853
function (message, encoding) {
    return module.exports.jsonToObject(
      module.exports.decodePayload(message, encoding))
  }