Example usage for java.net DatagramPacket getData

List of usage examples for java.net DatagramPacket getData

Introduction

In this page you can find the example usage for java.net DatagramPacket getData.

Prototype

public synchronized byte[] getData() 

Source Link

Document

Returns the data buffer.

Usage

From source file:org.eredlab.g4.ccl.net.tftp.TFTPDataPacket.java

/***
 * Creates a data packet based from a received
 * datagram.  Assumes the datagram is at least length 4, else an
 * ArrayIndexOutOfBoundsException may be thrown.
 * <p>/*  ww  w. ja  v a 2s  . c  o  m*/
 * @param datagram  The datagram containing the received data.
 * @throws TFTPPacketException  If the datagram isn't a valid TFTP
 *         data packet.
 ***/
TFTPDataPacket(DatagramPacket datagram) throws TFTPPacketException {
    super(TFTPPacket.DATA, datagram.getAddress(), datagram.getPort());

    _data = datagram.getData();
    _offset = 4;

    if (getType() != _data[1])
        throw new TFTPPacketException("TFTP operator code does not match type.");

    _blockNumber = (((_data[2] & 0xff) << 8) | (_data[3] & 0xff));

    _length = datagram.getLength() - 4;

    if (_length > MAX_DATA_LENGTH)
        _length = MAX_DATA_LENGTH;
}

From source file:org.openhab.binding.hue.internal.tools.SsdpDiscovery.java

/**
 * Checks whether a packet does contain all given keywords case insensitive.
 * If all keywords are contained the IP address of the packet sender will be
 * returned./*from ww  w.  j a v  a 2  s.c om*/
 * 
 * @param packet
 *            The data packet to be analyzed.
 * @param keywords
 *            The keywords to be searched for.
 * @return The IP of the sender if all keywords have been found, null
 *         otherwise.
 * 
 * @throws IOException
 */
private String analyzePacket(DatagramPacket packet, String... keywords) throws IOException {

    logger.debug("Analyzing answer message.");

    InetAddress addr = packet.getAddress();
    ByteArrayInputStream in = new ByteArrayInputStream(packet.getData(), 0, packet.getLength());
    String response = IOUtils.toString(in);

    boolean foundAllKeywords = true;

    for (String keyword : keywords) {
        foundAllKeywords &= response.toUpperCase().contains(keyword.toUpperCase());
    }

    if (foundAllKeywords) {
        logger.debug("Found matching answer.");
        return addr.getHostAddress();
    }

    logger.debug("Answer did not match.");
    return null;
}

From source file:org.springframework.integration.ip.udp.UdpChannelAdapterTests.java

@SuppressWarnings("unchecked")
@Test/*from  ww w  . java 2s. com*/
public void testUnicastReceiverWithReply() throws Exception {
    QueueChannel channel = new QueueChannel(2);
    int port = SocketUtils.findAvailableUdpSocket();
    UnicastReceivingChannelAdapter adapter = new UnicastReceivingChannelAdapter(port);
    adapter.setOutputChannel(channel);
    adapter.start();
    SocketTestUtils.waitListening(adapter);

    Message<byte[]> message = MessageBuilder.withPayload("ABCD".getBytes()).build();
    DatagramPacketMessageMapper mapper = new DatagramPacketMessageMapper();
    DatagramPacket packet = mapper.fromMessage(message);
    packet.setSocketAddress(new InetSocketAddress("localhost", port));
    final DatagramSocket socket = new DatagramSocket(SocketUtils.findAvailableUdpSocket());
    socket.send(packet);
    final AtomicReference<DatagramPacket> theAnswer = new AtomicReference<DatagramPacket>();
    final CountDownLatch receiverReadyLatch = new CountDownLatch(1);
    final CountDownLatch replyReceivedLatch = new CountDownLatch(1);
    //main thread sends the reply using the headers, this thread will receive it
    Executors.newSingleThreadExecutor().execute(new Runnable() {
        public void run() {
            DatagramPacket answer = new DatagramPacket(new byte[2000], 2000);
            try {
                receiverReadyLatch.countDown();
                socket.receive(answer);
                theAnswer.set(answer);
                replyReceivedLatch.countDown();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    });
    Message<byte[]> receivedMessage = (Message<byte[]>) channel.receive(2000);
    assertEquals(new String(message.getPayload()), new String(receivedMessage.getPayload()));
    String replyString = "reply:" + System.currentTimeMillis();
    byte[] replyBytes = replyString.getBytes();
    DatagramPacket reply = new DatagramPacket(replyBytes, replyBytes.length);
    reply.setSocketAddress(
            new InetSocketAddress((String) receivedMessage.getHeaders().get(IpHeaders.IP_ADDRESS),
                    (Integer) receivedMessage.getHeaders().get(IpHeaders.PORT)));
    assertTrue(receiverReadyLatch.await(10, TimeUnit.SECONDS));
    new DatagramSocket().send(reply);
    assertTrue(replyReceivedLatch.await(10, TimeUnit.SECONDS));
    DatagramPacket answerPacket = theAnswer.get();
    assertNotNull(answerPacket);
    assertEquals(replyString, new String(answerPacket.getData(), 0, answerPacket.getLength()));
}

From source file:org.mule.test.firewall.FirewallTestCase.java

protected void doTestUdp(InetAddress address, int port) throws Exception {
    try {/*  ww  w.  j av  a 2s.  co m*/
        logger.debug("Testing UDP on " + addressToString(address, port));
        DatagramSocket server = openUdpServer(address, port);
        DatagramSocket client = openUdpClient();
        client.send(new DatagramPacket(new byte[] { 1 }, 1, address, port));
        DatagramPacket packet = new DatagramPacket(new byte[1], 1);
        server.receive(packet);
        assertEquals("Failed to send packet via " + addressToString(address, port), 1, packet.getData()[0]);
        client.close();
        server.close();
    } catch (Exception e) {
        logger.error("Error while attempting UDP message on " + addressToString(address, port));
        throw e;
    }
}

From source file:com.navercorp.pinpoint.profiler.sender.UdpDataSender.java

public boolean isNetworkAvailable() {
    final NetworkAvailabilityCheckPacket dto = new NetworkAvailabilityCheckPacket();
    try {//from  www.j  a  v a 2  s .  c  o  m
        final byte[] interBufferData = serialize(serializer, dto);
        final int interBufferSize = serializer.getInterBufferSize();
        reusePacket.setData(interBufferData, 0, interBufferSize);
        udpSocket.send(reusePacket);

        if (logger.isInfoEnabled()) {
            logger.info("Data sent. {}", dto);
        }

        final byte[] receiveData = new byte[NetworkAvailabilityCheckPacket.DATA_OK.length];
        final DatagramPacket receivePacket = new DatagramPacket(receiveData, receiveData.length);
        udpSocket.receive(receivePacket);

        if (logger.isInfoEnabled()) {
            logger.info("Data received. {}", Arrays.toString(receivePacket.getData()));
        }

        return Arrays.equals(NetworkAvailabilityCheckPacket.DATA_OK, receiveData);
    } catch (IOException e) {
        logger.warn("packet send error {}", dto, e);
        return false;
    }
}

From source file:net.sourceforge.vulcan.ant.receiver.UdpEventSource.java

@Override
public void run() {
    final DatagramSocket socket = openSocket();
    active = true;//from   w w w  .ja v  a2s.co  m

    synchronized (this) {
        notifyAll();
    }

    final byte[] buffer = new byte[8192];

    try {
        final DatagramPacket packet = new DatagramPacket(buffer, buffer.length);
        while (active) {
            try {
                socket.receive(packet);

                final AntEventSummary summary = deserialize(packet.getData());

                fireEvent(summary);
            } catch (SocketTimeoutException e) {
                continue;
            } catch (Exception e) {
                handleException(e);
            }
        }
    } finally {
        socket.close();
    }
}

From source file:com.springrts.springls.nat.NatHelpServer.java

/**
 * check UDP server for any new packets//www .j  a v  a 2s . c o  m
 */
private void checkForNewPackets() {

    DatagramPacket packet;
    while ((packet = fetchNextPackage()) != null) {
        InetAddress address = packet.getAddress();
        int clientPort = packet.getPort();
        String data = new String(packet.getData(), packet.getOffset(), packet.getLength());
        LOG.trace("*** UDP packet received from {} from port {}", address.getHostAddress(), clientPort);
        Client client = getContext().getClients().getClient(data);
        if (client == null) {
            continue;
        }
        client.setUdpSourcePort(clientPort);
        client.sendLine(String.format("UDPSOURCEPORT %d", clientPort));
    }
}

From source file:com.clearspring.metriccatcher.MetricCatcher.java

/**
 * Grab metric messages off the listening socket, creating and updating
 * them as needed.//from   w w  w. j a v  a2  s  .c o  m
 */
@Override
public void run() {
    // Arbitrary. One metric with a reasonable name is less than 200b
    // This (http://stackoverflow.com/q/3712151/17339) implies that 64 bit
    // leenuks will handle packets up to 24,258b, so let's assume we won't
    // get anything larger than that.  Note that this is a hard limit-you
    // can't accumulate from the socket so anything larger is truncated.
    byte[] data = new byte[24258];

    // Keep track of the last 1000 packets we've seen
    byte[] json = null;

    while (shutdown.get() == false) {
        DatagramPacket received = new DatagramPacket(data, data.length);
        try {
            // Pull in network data
            socket.receive(received);
            json = received.getData();
            if (logger.isDebugEnabled()) {
                logger.debug("Got packet from " + received.getAddress() + ":" + received.getPort());
                if (logger.isTraceEnabled()) {
                    String jsonString = new String(json);
                    logger.trace("JSON: " + jsonString);
                }
            }

            // Turn bytes of JSON into JSONMetric objects
            TypeReference<List<JSONMetric>> typeRef = new TypeReference<List<JSONMetric>>() {
            };
            List<JSONMetric> jsonMetrics = mapper.readValue(json, typeRef);

            // Parse all of the metrics in the message
            for (JSONMetric jsonMetric : jsonMetrics) {
                if (!metricCache.containsKey(jsonMetric.getName())) {
                    logger.info("Creating new " + jsonMetric.getType().name() + " metric for '"
                            + jsonMetric.getName() + "'");
                    Metric newMetric = createMetric(jsonMetric);
                    metricCache.put(jsonMetric.getName(), newMetric);
                }

                // Record the update
                logger.debug("Updating " + jsonMetric.getType() + " '" + jsonMetric.getName() + "' with <"
                        + jsonMetric.getValue() + ">");
                updateMetric(metricCache.get(jsonMetric.getName()), jsonMetric.getValue());
            }
        } catch (IOException e) {
            logger.warn("IO error: " + e);
            String jsonString = new String(json);
            logger.warn("JSON: " + jsonString);
        }
    }

    socket.close();
}

From source file:org.eredlab.g4.ccl.net.tftp.TFTPErrorPacket.java

/***
 * Creates an error packet based from a received
 * datagram.  Assumes the datagram is at least length 4, else an
 * ArrayIndexOutOfBoundsException may be thrown.
 * <p>//  w w w  . j a  v a 2 s. c o  m
 * @param datagram  The datagram containing the received error.
 * @throws TFTPPacketException  If the datagram isn't a valid TFTP
 *         error packet.
 ***/
TFTPErrorPacket(DatagramPacket datagram) throws TFTPPacketException {
    super(TFTPPacket.ERROR, datagram.getAddress(), datagram.getPort());
    int index, length;
    byte[] data;
    StringBuffer buffer;

    data = datagram.getData();
    length = datagram.getLength();

    if (getType() != data[1])
        throw new TFTPPacketException("TFTP operator code does not match type.");

    _error = (((data[2] & 0xff) << 8) | (data[3] & 0xff));

    if (length < 5)
        throw new TFTPPacketException("Bad error packet. No message.");

    index = 4;
    buffer = new StringBuffer();

    while (index < length && data[index] != 0) {
        buffer.append((char) data[index]);
        ++index;
    }

    _message = buffer.toString();
}

From source file:org.openhab.binding.tacmi.internal.TACmiBinding.java

/**
 * @{inheritDoc/*ww w . j a v a2  s  .  c o m*/
 */
@Override
protected void execute() {
    logger.trace("execute() method is called!");
    try {
        clientSocket.setBroadcast(true);
        clientSocket.setSoTimeout(10000);
        byte[] receiveData = new byte[14];
        DatagramPacket receivePacket = new DatagramPacket(receiveData, receiveData.length);
        clientSocket.receive(receivePacket);
        byte[] data = receivePacket.getData();
        Message message;
        if (data[1] > 0) {
            logger.debug("Processing analog message");
            message = new AnalogMessage(data);
        } else if (data[1] == 0) {
            logger.debug("Processing digital message");
            message = new DigitalMessage(data);
        } else {
            logger.debug("Invalid message received");
            return;
        }
        logger.debug(message.toString());
        for (TACmiBindingProvider provider : providers) {
            for (String itemName : provider.getItemNames()) {
                logger.debug("Processing item: " + itemName);
                int portNumber = provider.getPortNumber(itemName);
                if (provider.getCanNode(itemName) == message.canNode
                        && provider.getPortType(itemName).equals(message.getType().toString().toLowerCase())) {
                    if (message.hasPortnumber(portNumber)) {
                        if (message.getType() == MessageType.A) {
                            AnalogValue value = ((AnalogMessage) message).getAnalogValue(portNumber);
                            if (value.value != null) {
                                logger.debug("Updating item: " + itemName + " with value: " + value.value);
                                eventPublisher.postUpdate(itemName, new DecimalType(value.value));
                            }
                        } else {
                            OnOffType state = ((DigitalMessage) message).getPortStateAsOnOffType(portNumber);
                            logger.debug("Updating item {} with state {}", itemName, state);
                            eventPublisher.postUpdate(itemName, state);
                        }
                    } else {
                        logger.debug("Portnumber {} not included in message", portNumber);
                    }
                } else {
                    logger.debug("CAN Node does not match");
                }
            }
        }

    } catch (Exception e) {
        logger.warn("Error in execute: {}, Message: {}", e.getClass().getName(), e.getMessage());
    }
    logger.trace("TACmi execute() finished");

}