Search in sources :

Example 1 with ZMQException

use of org.zeromq.ZMQException in project LogHub by fbacchella.

the class SmartContext method terminate.

public Future<Boolean> terminate() {
    synchronized (SmartContext.class) {
        if (!running) {
            return new FutureTask<Boolean>(() -> true);
        }
        running = false;
        try {
            controller.send("KILL", 0);
        } catch (ZMQException | zmq.ZError.IOException | zmq.ZError.CtxTerminatedException | zmq.ZError.InstantiationException e) {
            ZMQHelper.logZMQException(logger, "terminate", e);
        }
        SimplifiedThread<Boolean> terminator = new Helpers.SimplifiedThread<Boolean>(() -> {
            try {
                logger.trace("will terminate");
                instance.context.term();
            } catch (ZMQException | zmq.ZError.IOException | zmq.ZError.CtxTerminatedException | zmq.ZError.InstantiationException e) {
                ZMQHelper.logZMQException(logger, "terminate", e);
            } catch (final java.nio.channels.ClosedSelectorException e) {
                logger.error("closed selector:" + e.getMessage());
            } catch (final Exception e) {
                logger.error("Unexpected error:" + e.getMessage());
                return false;
            }
            logger.trace("done terminate");
            return true;
        }).setName("ZMQContextTerminator").setDaemon(false).start();
        // Now we've send termination signals, let other threads
        // some time to finish
        Thread.yield();
        logger.debug("sockets to close: {}", instance.sockets);
        instance.controller.setLinger(0);
        instance.controller.close();
        for (Socket s : new ArrayList<Socket>(instance.sockets.keySet())) {
            try {
                synchronized (s) {
                    // If someone close the socket meanwhile
                    if (!instance.sockets.containsKey(s)) {
                        continue;
                    }
                    logger.debug("forgotten socket: {}", () -> instance.sockets.get(s));
                    instance.close(s);
                }
            } catch (ZMQException | zmq.ZError.IOException | zmq.ZError.CtxTerminatedException | zmq.ZError.InstantiationException e) {
                ZMQHelper.logZMQException(logger, "close " + instance.sockets.get(s), e);
            } catch (java.nio.channels.ClosedSelectorException e) {
                logger.error("in close: " + e);
            } catch (Exception e) {
                logger.error("in close: " + e);
            }
        }
        return terminator.task;
    }
}
Also used : Helpers(loghub.Helpers) ArrayList(java.util.ArrayList) IOException(java.io.IOException) ZMQException(org.zeromq.ZMQException) ZMQException(org.zeromq.ZMQException) IOException(java.io.IOException) FutureTask(java.util.concurrent.FutureTask) Socket(org.zeromq.ZMQ.Socket)

Example 2 with ZMQException

use of org.zeromq.ZMQException in project jeromq by zeromq.

the class ZPicture method msgBinaryPicture.

/**
 * Creates a binary encoded 'picture' message to the socket (or actor), so it can be sent.
 * The arguments are encoded in a binary format that is compatible with zproto, and
 * is designed to reduce memory allocations.
 *
 * @param picture The picture argument is a string that defines the
 *                type of each argument. Supports these argument types:
 * <p>
 *                <table border="1">
 *                <caption><strong>Types of arguments</strong></caption>
 *                <tr><th style="text-align:left">pattern</th><th style="text-align:left">java type</th><th style="text-align:left">zproto type</th></tr>
 *                <tr><td>1</td><td>int</td><td>type = "number" size = "1"</td></tr>
 *                <tr><td>2</td><td>int</td><td>type = "number" size = "2"</td></tr>
 *                <tr><td>4</td><td>long</td><td>type = "number" size = "3"</td></tr>
 *                <tr><td>8</td><td>long</td><td>type = "number" size = "4"</td></tr>
 *                <tr><td>s</td><td>String, 0-255 chars</td><td>type = "string"</td></tr>
 *                <tr><td>S</td><td>String, 0-2^32-1 chars</td><td>type = "longstr"</td></tr>
 *                <tr><td>b</td><td>byte[], 0-2^32-1 bytes</td><td>type = "chunk"</td></tr>
 *                <tr><td>c</td><td>byte[], 0-2^32-1 bytes</td><td>type = "chunk"</td></tr>
 *                <tr><td>f</td><td>ZFrame</td><td>type = "frame"</td></tr>
 *                <tr><td>m</td><td>ZMsg</td><td>type = "msg" <b>Has to be the last element of the picture</b></td></tr>
 *                </table>
 * @param args    Arguments according to the picture
 * @return true when it has been queued on the socket and ØMQ has assumed responsibility for the message.
 * This does not indicate that the message has been transmitted to the network.
 * @api.note Does not change or take ownership of any arguments.
 */
@Draft
public ZMsg msgBinaryPicture(String picture, Object... args) {
    if (!BINARY_FORMAT.matcher(picture).matches()) {
        throw new ZMQException(picture + " is not in expected binary format " + BINARY_FORMAT.pattern(), ZError.EPROTO);
    }
    ZMsg msg = new ZMsg();
    // Pass 1: calculate total size of data frame
    int frameSize = 0;
    for (int index = 0; index < picture.length(); index++) {
        char pattern = picture.charAt(index);
        switch(pattern) {
            case '1':
                {
                    frameSize += 1;
                    break;
                }
            case '2':
                {
                    frameSize += 2;
                    break;
                }
            case '4':
                {
                    frameSize += 4;
                    break;
                }
            case '8':
                {
                    frameSize += 8;
                    break;
                }
            case 's':
                {
                    String string = (String) args[index];
                    frameSize += 1 + (string != null ? string.getBytes(ZMQ.CHARSET).length : 0);
                    break;
                }
            case 'S':
                {
                    String string = (String) args[index];
                    frameSize += 4 + (string != null ? string.getBytes(ZMQ.CHARSET).length : 0);
                    break;
                }
            case 'b':
            case 'c':
                {
                    byte[] block = (byte[]) args[index];
                    frameSize += 4 + block.length;
                    break;
                }
            case 'f':
                {
                    ZFrame frame = (ZFrame) args[index];
                    msg.add(frame);
                    break;
                }
            case 'm':
                {
                    ZMsg other = (ZMsg) args[index];
                    if (other == null) {
                        msg.add(new ZFrame((byte[]) null));
                    } else {
                        msg.addAll(other);
                    }
                    break;
                }
            default:
                assert (false) : "invalid picture element '" + pattern + "'";
        }
    }
    // Pass 2: encode data into data frame
    ZFrame frame = new ZFrame(new byte[frameSize]);
    ZNeedle needle = new ZNeedle(frame);
    for (int index = 0; index < picture.length(); index++) {
        char pattern = picture.charAt(index);
        switch(pattern) {
            case '1':
                {
                    needle.putNumber1((int) args[index]);
                    break;
                }
            case '2':
                {
                    needle.putNumber2((int) args[index]);
                    break;
                }
            case '4':
                {
                    needle.putNumber4((int) args[index]);
                    break;
                }
            case '8':
                {
                    needle.putNumber8((long) args[index]);
                    break;
                }
            case 's':
                {
                    needle.putString((String) args[index]);
                    break;
                }
            case 'S':
                {
                    needle.putLongString((String) args[index]);
                    break;
                }
            case 'b':
            case 'c':
                {
                    byte[] block = (byte[]) args[index];
                    needle.putNumber4(block.length);
                    needle.putBlock(block, block.length);
                    break;
                }
            case 'f':
            case 'm':
                break;
            default:
                assert (false) : "invalid picture element '" + pattern + "'";
        }
    }
    msg.addFirst(frame);
    return msg;
}
Also used : ZFrame(org.zeromq.ZFrame) ZMQException(org.zeromq.ZMQException) ZMsg(org.zeromq.ZMsg) Draft(zmq.util.Draft)

Example 3 with ZMQException

use of org.zeromq.ZMQException in project jeromq by zeromq.

the class interrupt method main.

public static void main(String[] args) {
    // Prepare our context and socket
    final ZContext context = new ZContext();
    final Thread zmqThread = new Thread() {

        @Override
        public void run() {
            ZMQ.Socket socket = context.createSocket(SocketType.REP);
            socket.bind("tcp://*:5555");
            while (!Thread.currentThread().isInterrupted()) {
                try {
                    socket.recv(0);
                } catch (ZMQException e) {
                    if (e.getErrorCode() == ZMQ.Error.ETERM.getCode()) {
                        break;
                    }
                }
            }
            socket.setLinger(0);
            socket.close();
        }
    };
    Runtime.getRuntime().addShutdownHook(new Thread() {

        @Override
        public void run() {
            System.out.println("W: interrupt received, killing server...");
            context.close();
            try {
                zmqThread.interrupt();
                zmqThread.join();
            } catch (InterruptedException e) {
            }
        }
    });
    zmqThread.start();
}
Also used : ZContext(org.zeromq.ZContext) ZMQException(org.zeromq.ZMQException) ZMQ(org.zeromq.ZMQ)

Example 4 with ZMQException

use of org.zeromq.ZMQException in project jeromq by zeromq.

the class ZPicture method recvBinaryPicture.

/**
 * Receive a binary encoded 'picture' message from the socket (or actor).
 * This method is similar to {@link org.zeromq.ZMQ.Socket#recv()}, except the arguments are encoded
 * in a binary format that is compatible with zproto, and is designed to
 * reduce memory allocations.
 *
 * @param picture The picture argument is a string that defines
 *                the type of each argument. See {@link #sendBinaryPicture(Socket, String, Object...)}
 *                for the supported argument types.
 * @return the picture elements as object array
 */
@Draft
public Object[] recvBinaryPicture(Socket socket, final String picture) {
    if (!BINARY_FORMAT.matcher(picture).matches()) {
        throw new ZMQException(picture + " is not in expected binary format " + BINARY_FORMAT.pattern(), ZError.EPROTO);
    }
    ZFrame frame = ZFrame.recvFrame(socket);
    if (frame == null) {
        return null;
    }
    // Get the data frame
    ZNeedle needle = new ZNeedle(frame);
    Object[] results = new Object[picture.length()];
    for (int index = 0; index < picture.length(); index++) {
        char pattern = picture.charAt(index);
        switch(pattern) {
            case '1':
                {
                    results[index] = needle.getNumber1();
                    break;
                }
            case '2':
                {
                    results[index] = needle.getNumber2();
                    break;
                }
            case '4':
                {
                    results[index] = needle.getNumber4();
                    break;
                }
            case '8':
                {
                    results[index] = needle.getNumber8();
                    break;
                }
            case 's':
                {
                    results[index] = needle.getString();
                    break;
                }
            case 'S':
                {
                    results[index] = needle.getLongString();
                    break;
                }
            case 'b':
            case 'c':
                {
                    int size = needle.getNumber4();
                    results[index] = needle.getBlock(size);
                    break;
                }
            case 'f':
                {
                    // Get next frame off socket
                    results[index] = ZFrame.recvFrame(socket);
                    break;
                }
            case 'm':
                {
                    // Get zero or more remaining frames
                    results[index] = ZMsg.recvMsg(socket);
                    break;
                }
            default:
                assert (false) : "invalid picture element '" + pattern + "'";
        }
    }
    return results;
}
Also used : ZFrame(org.zeromq.ZFrame) ZMQException(org.zeromq.ZMQException) Draft(zmq.util.Draft)

Example 5 with ZMQException

use of org.zeromq.ZMQException in project jeromq by zeromq.

the class TcpAddressTest method testBad.

@Test
public void testBad() {
    try {
        Address addr = new Address(NetProtocol.tcp, "ggglocalhostxxx.google.com:80");
        addr.resolve(true);
        addr.resolved();
        Assert.fail();
    } catch (ZMQException e) {
        Assert.assertEquals(ZError.EADDRNOTAVAIL, e.getErrorCode());
        Assert.assertEquals(e.getCause().getMessage(), e.getMessage());
    }
}
Also used : Address(zmq.io.net.Address) Inet4Address(java.net.Inet4Address) InetSocketAddress(java.net.InetSocketAddress) Inet6Address(java.net.Inet6Address) ZMQException(org.zeromq.ZMQException) Test(org.junit.Test)

Aggregations

ZMQException (org.zeromq.ZMQException)8 Inet4Address (java.net.Inet4Address)3 Inet6Address (java.net.Inet6Address)3 InetSocketAddress (java.net.InetSocketAddress)3 IOException (java.io.IOException)2 Test (org.junit.Test)2 ZFrame (org.zeromq.ZFrame)2 Address (zmq.io.net.Address)2 Draft (zmq.util.Draft)2 InetAddress (java.net.InetAddress)1 UnknownHostException (java.net.UnknownHostException)1 ArrayList (java.util.ArrayList)1 FutureTask (java.util.concurrent.FutureTask)1 Helpers (loghub.Helpers)1 ZContext (org.zeromq.ZContext)1 ZMQ (org.zeromq.ZMQ)1 Socket (org.zeromq.ZMQ.Socket)1 ZMsg (org.zeromq.ZMsg)1 ZError (zmq.ZError)1