Search in sources :

Example 1 with TrivialTimeResponse

use of org.opennms.netmgt.provision.detector.simple.response.TrivialTimeResponse in project opennms by OpenNMS.

the class TrivialTimeClient method sendRequest.

@Override
public TrivialTimeResponse sendRequest(TrivialTimeRequest request) throws IOException, Exception {
    boolean gotTime = false;
    int remoteTime = 0;
    int localTime = 0;
    for (int i = 0; i < retries && !gotTime; i++) {
        // Try to read from the socket
        byte[] timeBytes = new byte[4];
        ByteBuffer timeByteBuffer = ByteBuffer.wrap(timeBytes);
        int bytesRead = 0;
        if (isTcp()) {
            bytesRead = tcpSocket.getInputStream().read(timeBytes);
        }
        if (isUdp()) {
            // Send an empty datagram per RFC868
            udpSocket.send(udpPacket);
            DatagramPacket timePacket = new DatagramPacket(timeBytes, timeBytes.length);
            // Try to receive a response from the remote socket
            udpSocket.receive(timePacket);
            bytesRead = timePacket.getLength();
        }
        if (bytesRead != 4) {
            continue;
        }
        LOG.debug("sendRequest: {} bytes read = {}", protocol, bytesRead);
        try {
            remoteTime = timeByteBuffer.getInt();
        } catch (BufferUnderflowException bue) {
            LOG.error("Encountered buffer underflow while reading time from remote socket.");
            remoteTime = 0;
            // to next iteration of for() loop
            continue;
        }
        localTime = (int) (System.currentTimeMillis() / 1000) - EPOCH_ADJ_FACTOR;
        gotTime = true;
    }
    return gotTime ? new TrivialTimeResponse(remoteTime, localTime, allowedSkew) : new TrivialTimeResponse();
}
Also used : TrivialTimeResponse(org.opennms.netmgt.provision.detector.simple.response.TrivialTimeResponse) DatagramPacket(java.net.DatagramPacket) ByteBuffer(java.nio.ByteBuffer) BufferUnderflowException(java.nio.BufferUnderflowException)

Aggregations

DatagramPacket (java.net.DatagramPacket)1 BufferUnderflowException (java.nio.BufferUnderflowException)1 ByteBuffer (java.nio.ByteBuffer)1 TrivialTimeResponse (org.opennms.netmgt.provision.detector.simple.response.TrivialTimeResponse)1