Process UDP messages
774205
def handle_message(self, message):
        """"""
        if self._yamaha:
            if 'power' in message:
                _LOGGER.debug("Power: %s", message.get('power'))
                self._yamaha.power = (
                    STATE_ON if message.get('power') == "on" else STATE_OFF)
            if 'input' in message:
                _LOGGER.debug("Input: %s", message.get('input'))
                self._yamaha._source = message.get('input')
            if 'volume' in message:
                volume = message.get('volume')

                if 'max_volume' in message:
                    volume_max = message.get('max_volume')
                else:
                    volume_max = self._yamaha.volume_max

                _LOGGER.debug("Volume: %d / Max: %d", volume, volume_max)

                self._yamaha.volume = volume / volume_max
                self._yamaha.volume_max = volume_max
            if 'mute' in message:
                _LOGGER.debug("Mute: %s", message.get('mute'))
                self._yamaha.mute = message.get('mute', False)
        else:
            _LOGGER.debug("No yamaha-obj found")
1284235
def from_raw_message(cls, rawmessage):
        """"""
        if (rawmessage[5] &
                MESSAGE_FLAG_EXTENDED_0X10) == MESSAGE_FLAG_EXTENDED_0X10:
            if len(rawmessage) >= ExtendedSend.receivedSize:
                msg = ExtendedSend.from_raw_message(rawmessage)
            else:
                msg = None
        else:
            msg = StandardSend(rawmessage[2:5],
                               {'cmd1': rawmessage[6],
                                'cmd2': rawmessage[7]},
                               flags=rawmessage[5],
                               acknak=rawmessage[8:9])
        return msg
612086
def process_npdu(self, npdu):
        """"""
        if _debug: RouterToRouterService._debug("process_npdu %r", npdu)

        # encode the npdu as if it was about to be delivered to the network
        pdu = PDU()
        npdu.encode(pdu)
        if _debug: RouterToRouterService._debug("    - pdu: %r", pdu)

        # broadcast messages go to everyone
        if pdu.pduDestination.addrType == Address.localBroadcastAddr:
            destList = self.connections.keys()
        else:
            conn = self.connections.get(pdu.pduDestination, None)
            if not conn:
                if _debug: RouterToRouterService._debug("    - not a connected client")

                # start a connection attempt
                conn = self.connect(pdu.pduDestination)
            if not conn.connected:
                # keep a reference to this pdu to send after the ack comes back
                conn.pendingNPDU.append(pdu)
                return

            destList = [pdu.pduDestination]
        if _debug: RouterToRouterService._debug("    - destList: %r", destList)

        for dest in destList:
            # make a router-to-router NPDU
            xpdu = RouterToRouterNPDU(pdu)
            xpdu.pduDestination = dest

            # send it to the multiplexer
            self.service_request(xpdu)
260707
def Process(self, fs_msg, context):
    """"""
    try:
      if fs_msg.message_type == "GrrMessage":
        grr_message = rdf_flows.GrrMessage.FromSerializedString(
            fs_msg.data.value)
        self._ProcessGRRMessages(fs_msg.source.client_id, [grr_message])
      elif fs_msg.message_type == "MessageList":
        packed_messages = rdf_flows.PackedMessageList.FromSerializedString(
            fs_msg.data.value)
        message_list = communicator.Communicator.DecompressMessageList(
            packed_messages)
        self._ProcessGRRMessages(fs_msg.source.client_id, message_list.job)
      else:
        logging.error("Received message with unrecognized message_type: %s",
                      fs_msg.message_type)
        context.set_code(grpc.StatusCode.INVALID_ARGUMENT)
    except Exception as e:
      logging.error("Exception processing message: %s", str(e))
      raise
420718
def _process(self, data_buffer):
        
        packet = json.loads(data_buffer.decode('utf-8'))

        if packet['cmd'] == 'out':
            # Call os.write manually. In Python2.6, sys.stdout.write doesn't use UTF-8.
            os.write(sys.stdout.fileno(), packet['data'].encode('utf-8'))

        elif packet['cmd'] == 'suspend':
            # Suspend client process to background.
            if hasattr(signal, 'SIGTSTP'):
                os.kill(os.getpid(), signal.SIGTSTP)

        elif packet['cmd'] == 'mode':
            # Set terminal to raw/cooked.
            action = packet['data']

            if action == 'raw':
                cm = raw_mode(sys.stdin.fileno())
                cm.__enter__()
                self._mode_context_managers.append(cm)

            elif action == 'cooked':
                cm = cooked_mode(sys.stdin.fileno())
                cm.__enter__()
                self._mode_context_managers.append(cm)

            elif action == 'restore' and self._mode_context_managers:
                cm = self._mode_context_managers.pop()
                cm.__exit__()
630029
def on_message(self, opcode, message):
		
		self.logger.debug("processing {0} (opcode: 0x{1:02x}) message".format(self._opcode_names.get(opcode, 'UNKNOWN'), opcode))
		if opcode == self._opcode_close:
			self.close()
		elif opcode == self._opcode_ping:
			if len(message) > 125:
				self.close()
				return
			self.send_message(self._opcode_pong, message)
		elif opcode == self._opcode_pong:
			pass
		elif opcode == self._opcode_binary:
			self.on_message_binary(message)
		elif opcode == self._opcode_text:
			try:
				message = self._decode_string(message)
			except UnicodeDecodeError:
				self.logger.warning('closing connection due to invalid unicode within a text message')
				self.close()
			else:
				self.on_message_text(message)
		elif opcode == self._opcode_continue:
			self.close()
		else:
			self.logger.warning("received unknown opcode: {0} (0x{0:02x})".format(opcode))
			self.close()
559011
def data_received(self, data):
        """"""
        data = data.decode()
        log.debug('received data: %s', data.strip())
        self.buffer += data
        self.handle_lines()
2658
def emit(self, batch):
        
        udp_socket = None
        try:
            self.client._seqid = 0
            #  truncate and reset the position of BytesIO object
            self.buffer._buffer.truncate(0)
            self.buffer._buffer.seek(0)
            self.client.emitBatch(batch)
            buff = self.buffer.getvalue()
            if len(buff) > self.max_packet_size:
                logging.warn('Data exceeds the max UDP packet size; size {},\
                        max {}'.format(len(buff), self.max_packet_size))
            else:
                udp_socket = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
                udp_socket.sendto(buff, self.address)

        except Exception as e:  # pragma: NO COVER
            logging.error(getattr(e, 'message', e))

        finally:
            if udp_socket is not None:
                udp_socket.close()
897666
def send_data_on_udp(ip_address, port, data):
    """"""
    sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
    try:
        sock.sendto(data.encode('utf-8'), (ip_address, port))
    except:
        LOGGER.exception('Failed to send trace to X-Ray Daemon')
    finally:
        sock.close()
1086248
def handle_message(received_message, control_plane_sockets, data_plane_sockets):
    
    logger.debug(u"Handling message #{0} ({1}) from {2}".format(received_message.message_nr,
                                                                received_message.message.__class__.__name__,
                                                                received_message.source[0]))

    try:
        if isinstance(received_message.message, MapRequestMessage):
            # A map-request message
            handle_map_request(received_message, control_plane_sockets, data_plane_sockets)

        elif isinstance(received_message.message, MapReplyMessage):
            # A map-reply message
            handle_map_reply(received_message, control_plane_sockets, data_plane_sockets)

        elif isinstance(received_message.message, MapNotifyMessage):
            # A map-notify message (subclass of MapRegisterMessage, so put above it!)
            handle_map_notify(received_message, control_plane_sockets, data_plane_sockets)

        elif isinstance(received_message.message, MapRegisterMessage):
            # A map-register message
            handle_map_register(received_message, control_plane_sockets, data_plane_sockets)

        elif isinstance(received_message.message, MapReferralMessage):
            # A map-referral message
            handle_map_referral(received_message, control_plane_sockets, data_plane_sockets)

        elif isinstance(received_message.message, EncapsulatedControlMessage):
            # Determine the type of ECM
            if isinstance(received_message.inner_message, MapRequestMessage):
                if received_message.message.ddt_originated:
                    # A DDT map-request message
                    handle_ddt_map_request(received_message, control_plane_sockets, data_plane_sockets)
                else:
                    # An encapsulated map-request message
                    handle_enc_map_request(received_message, control_plane_sockets, data_plane_sockets)
            else:
                logger.warning("ECM does not contain a map-request in message %d", received_message.message_nr)
        elif isinstance(received_message.message, InfoMessage):
            handle_info_message(received_message, control_plane_sockets, data_plane_sockets)
        else:
            logger.warning("Unknown content in message %d", received_message.message_nr)
    except:
        logger.exception("Unexpected exception while handling message %d", received_message.message_nr)
942634
def _batched_op_msg(
        operation, command, docs, check_keys, ack, opts, ctx):
    """"""
    buf = StringIO()

    # Save space for message length and request id
    buf.write(_ZERO_64)
    # responseTo, opCode
    buf.write(b"\x00\x00\x00\x00\xdd\x07\x00\x00")

    to_send, length = _batched_op_msg_impl(
        operation, command, docs, check_keys, ack, opts, ctx, buf)

    # Header - request id and message length
    buf.seek(4)
    request_id = _randint()
    buf.write(_pack_int(request_id))
    buf.seek(0)
    buf.write(_pack_int(length))

    return request_id, buf.getvalue(), to_send
177195
def _handle_eio_message(self, sid, data):
        """"""
        if sid in self._binary_packet:
            pkt = self._binary_packet[sid]
            if pkt.add_attachment(data):
                del self._binary_packet[sid]
                if pkt.packet_type == packet.BINARY_EVENT:
                    self._handle_event(sid, pkt.namespace, pkt.id, pkt.data)
                else:
                    self._handle_ack(sid, pkt.namespace, pkt.id, pkt.data)
        else:
            pkt = packet.Packet(encoded_packet=data)
            if pkt.packet_type == packet.CONNECT:
                self._handle_connect(sid, pkt.namespace)
            elif pkt.packet_type == packet.DISCONNECT:
                self._handle_disconnect(sid, pkt.namespace)
            elif pkt.packet_type == packet.EVENT:
                self._handle_event(sid, pkt.namespace, pkt.id, pkt.data)
            elif pkt.packet_type == packet.ACK:
                self._handle_ack(sid, pkt.namespace, pkt.id, pkt.data)
            elif pkt.packet_type == packet.BINARY_EVENT or \
                    pkt.packet_type == packet.BINARY_ACK:
                self._binary_packet[sid] = pkt
            elif pkt.packet_type == packet.ERROR:
                raise ValueError('Unexpected ERROR packet.')
            else:
                raise ValueError('Unknown packet type.')
1142895
def decode(self, pdu):
        """"""
        if _debug: NPCI._debug("decode %s", str(pdu))

        PCI.update(self, pdu)

        # check the length
        if len(pdu.pduData) < 2:
            raise DecodingError("invalid length")

        # only version 1 messages supported
        self.npduVersion = pdu.get()
        if (self.npduVersion != 0x01):
            raise DecodingError("only version 1 messages supported")

        # decode the control octet
        self.npduControl = control = pdu.get()
        netLayerMessage = control & 0x80
        dnetPresent = control & 0x20
        snetPresent = control & 0x08
        self.pduExpectingReply = (control & 0x04) != 0
        self.pduNetworkPriority = control & 0x03

        # extract the destination address
        if dnetPresent:
            dnet = pdu.get_short()
            dlen = pdu.get()
            dadr = pdu.get_data(dlen)

            if dnet == 0xFFFF:
                self.npduDADR = GlobalBroadcast()
            elif dlen == 0:
                self.npduDADR = RemoteBroadcast(dnet)
            else:
                self.npduDADR = RemoteStation(dnet, dadr)

        # extract the source address
        if snetPresent:
            snet = pdu.get_short()
            slen = pdu.get()
            sadr = pdu.get_data(slen)

            if snet == 0xFFFF:
                raise DecodingError("SADR can't be a global broadcast")
            elif slen == 0:
                raise DecodingError("SADR can't be a remote broadcast")

            self.npduSADR = RemoteStation(snet, sadr)

        # extract the hop count
        if dnetPresent:
            self.npduHopCount = pdu.get()

        # extract the network layer message type (if present)
        if netLayerMessage:
            self.npduNetMessage = pdu.get()
            if (self.npduNetMessage >= 0x80) and (self.npduNetMessage <= 0xFF):
                # extract the vendor ID
                self.npduVendorID = pdu.get_short()
        else:
            # application layer message
            self.npduNetMessage = None
682503
def echo(self, message, *, encoding=_NOTSET):
        """"""
        return self.execute('ECHO', message, encoding=encoding)
1272783
@Override
	public void processMessage(final WebSocketMessage webSocketData) {

		setDoTransactionNotifications(true);

		final SecurityContext securityContext = getWebSocket().getSecurityContext();

		try {

			final String uuid  = webSocketData.getId();
			int sequenceNumber = webSocketData.getNodeDataIntegerValue("chunkId");
			int chunkSize      = webSocketData.getNodeDataIntegerValue("chunkSize");
			int chunks         = webSocketData.getNodeDataIntegerValue("chunks");
			Object rawData     = webSocketData.getNodeData().get("chunk");

			byte[] data        = new byte[0];

			if (rawData != null) {

				if (rawData instanceof String) {

					logger.debug("Raw data: {}", rawData);

//                                        data = Base64.decodeBase64(((String)rawData).getBytes("UTF-8"));
					data = Base64.decode(((String) rawData));

					logger.debug("Decoded data: {}", data);

				}

			}

			final File file = (File) getNode(uuid);
			if (file.isTemplate()) {

				logger.warn("No write permission, file is in template mode: {}", new Object[] {file.toString()});
				getWebSocket().send(MessageBuilder.status().message("No write permission, file is in template mode").code(400).build(), true);
				return;

			}

			if (!file.isGranted(Permission.write, securityContext)) {

				logger.warn("No write permission for {} on {}", new Object[] {getWebSocket().getCurrentUser().toString(), file.toString()});
				getWebSocket().send(MessageBuilder.status().message("No write permission").code(400).build(), true);
				return;

			}

			getWebSocket().handleFileChunk(uuid, sequenceNumber, chunkSize, data, chunks);

			if (sequenceNumber+1 == chunks) {

				FileHelper.updateMetadata(file);

				file.increaseVersion();

				getWebSocket().removeFileUploadHandler(uuid);

				logger.debug("File upload finished. Checksum: {}, size: {}", new Object[]{ file.getChecksum(), file.getSize() });

			}

			final long currentSize = (long)(sequenceNumber * chunkSize) + data.length;

			// This should trigger setting of lastModifiedDate in any case
			getWebSocket().send(MessageBuilder.status().code(200).message("{\"id\":\"" + file.getUuid() + "\", \"name\":\"" + file.getName() + "\",\"size\":" + currentSize + "}").build(), true);

		} catch (IOException | FrameworkException ex) {

			String msg = ex.toString();

			// return error message
			getWebSocket().send(MessageBuilder.status().code(400).message("Could not process chunk data: ".concat((msg != null)
				? msg
				: "")).build(), true);
		}
	}
781485
def process_npdu(self, npdu):
        """"""
        if _debug: ProxyServiceNetworkAdapter._debug("process_npdu %r", npdu)

        # encode the npdu as if it was about to be delivered to the network
        pdu = PDU()
        npdu.encode(pdu)
        if _debug: ProxyServiceNetworkAdapter._debug("    - pdu: %r", pdu)

        # broadcast messages go to peers
        if pdu.pduDestination.addrType == Address.localBroadcastAddr:
            xpdu = ServerToProxyBroadcastNPDU(pdu)
        else:
            xpdu = ServerToProxyUnicastNPDU(pdu.pduDestination, pdu)

        # the connection has the correct address
        xpdu.pduDestination = self.conn.address

        # send it down to the multiplexer
        self.conn.service.service_request(xpdu)
65691
@Override
    public void processMessage() {
        VectorAggregation aggregation = new VectorAggregation(rowIndex, (short) voidConfiguration.getNumberOfShards(),
                        getShardIndex(), storage.getArray(key).getRow(rowIndex).dup());
        aggregation.setOriginatorId(this.getOriginatorId());

        clipboard.pin(aggregation);

        DistributedVectorMessage dvm = new DistributedVectorMessage(key, rowIndex);
        dvm.setOriginatorId(this.originatorId);

        if (voidConfiguration.getNumberOfShards() > 1)
            transport.sendMessageToAllShards(dvm);
        else {
            aggregation.extractContext(this);
            aggregation.processMessage();
        }
    }