org.apache.qpid.proton.engine.Event Java Examples

The following examples show how to use org.apache.qpid.proton.engine.Event. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source File: Server.java    From qpid-proton-j with Apache License 2.0 6 votes vote down vote up
@Override
public void onDelivery(Event evt) {
    Delivery dlv = evt.getDelivery();
    Link link = dlv.getLink();
    if (link instanceof Sender) {
        dlv.settle();
    } else {
        Receiver rcv = (Receiver) link;
        if (!dlv.isPartial()) {
            byte[] bytes = new byte[dlv.pending()];
            rcv.recv(bytes, 0, bytes.length);
            String address = router.getAddress(rcv);
            Message message = new Message(bytes);
            messages.put(address, message);
            dlv.disposition(Accepted.getInstance());
            dlv.settle();
            if (!quiet) {
                System.out.println(String.format("Got message(%s): %s", address, message));
            }
            send(address);
        }
    }
}
 
Example #2
Source File: Scheduling.java    From qpid-proton-j with Apache License 2.0 6 votes vote down vote up
@Override
public void onReactorInit(Event event) {
    startTime = System.currentTimeMillis();
    System.out.println("Hello, World!");

    // We can schedule a task event for some point in the future.
    // This will cause the reactor to stick around until it has a
    // chance to process the event.

    // The first argument is the delay. The second argument is the
    // handler for the event. We are just using self for now, but
    // we could pass in another object if we wanted.
    Task task = event.getReactor().schedule(1000, this);

    // We can ignore the task if we want to, but we can also use it
    // to pass stuff to the handler.
    task.attachments().set("key", String.class, "Yay");
}
 
Example #3
Source File: Drain.java    From qpid-proton-j with Apache License 2.0 6 votes vote down vote up
@Override
public void onDelivery(Event evt) {
    Delivery dlv = evt.getDelivery();
    if (dlv.getLink() instanceof Receiver) {
        Receiver receiver = (Receiver) dlv.getLink();

        if (!dlv.isPartial()) {
            byte[] bytes = new byte[dlv.pending()];
            receiver.recv(bytes, 0, bytes.length);
            Message msg = new Message(bytes);

            if (!quiet) {
                System.out.println(String.format("Got message: %s", msg));
            }
            received++;
            dlv.settle();
        }

        if ((received >= count) || (!block && !receiver.draining())) {
            receiver.getSession().getConnection().close();
        }
    }
}
 
Example #4
Source File: Spout.java    From qpid-proton-j with Apache License 2.0 6 votes vote down vote up
@Override
public void onLinkFlow(Event evt) {
    Link link = evt.getLink();
    if (link instanceof Sender) {
        Sender sender = (Sender) link;
        while ((sent < count) && sender.getCredit() > 0) {
            Delivery dlv = sender.delivery(String.format("spout-%s", sent).getBytes());

            Message msg = new Message(String.format("Hello World! [%s]", sent));
            byte[] bytes = msg.getBytes();
            sender.send(bytes, 0, bytes.length);
            sender.advance();

            if (!quiet) {
                System.out.println(String.format("Sent %s to %s: %s", new String(dlv.getTag()),
                                                 sender.getTarget().getAddress(), msg));
            }
            sent++;
        }
    }
}
 
Example #5
Source File: FlowController.java    From qpid-proton-j with Apache License 2.0 6 votes vote down vote up
@Override
public void onUnhandled(Event event) {
    int window = this.window;
    Link link = event.getLink();

    switch(event.getType()) {
    case LINK_LOCAL_OPEN:
    case LINK_REMOTE_OPEN:
    case LINK_FLOW:
    case DELIVERY:
        if (link instanceof Receiver) {
            this.drained += link.drained();
            if (this.drained == 0) {
                topup((Receiver)link, window);
            }
        }
        break;
    default:
        break;
    }
}
 
Example #6
Source File: TransportImplTest.java    From qpid-proton-j with Apache License 2.0 6 votes vote down vote up
private void assertEvents(Collector collector, Event.Type... expectedEventTypes)
{

    if(expectedEventTypes.length == 0)
    {
        assertNull("Expected no events, but at least one was present: " + collector.peek(), collector.peek());
    }
    else
    {
        ArrayList<Event.Type> eventTypesList = new ArrayList<Event.Type>();
        Event event = null;
        while ((event = collector.peek()) != null) {
            eventTypesList.add(event.getType());
            collector.pop();
        }

        assertArrayEquals("Unexpected event types: " + eventTypesList, expectedEventTypes, eventTypesList.toArray(new Event.Type[0]));
    }
}
 
Example #7
Source File: Echo.java    From qpid-proton-j with Apache License 2.0 6 votes vote down vote up
@Override
public void onSelectableReadable(Event event) {
    Selectable selectable = event.getSelectable();

    // The onSelectableReadable event tells us that there is data
    // to be read, or the end of stream has been reached.
    SourceChannel channel = (SourceChannel)selectable.getChannel();
    ByteBuffer buffer = ByteBuffer.allocate(1024);
    try {
        while(true) {
            int amount = channel.read(buffer);
            if (amount < 0) {
                selectable.terminate();
                selectable.getReactor().update(selectable);
            }
            if (amount <= 0) break;
            System.out.write(buffer.array(), 0, buffer.position());
            buffer.clear();
        }
    } catch(IOException ioException) {
        ioException.printStackTrace();
        selectable.terminate();
        selectable.getReactor().update(selectable);
    }
}
 
Example #8
Source File: TransportImpl.java    From qpid-proton-j with Apache License 2.0 6 votes vote down vote up
@Override
public void handleClose(Close close, Binary payload, Integer channel)
{
    _closeReceived = true;
    _remoteIdleTimeout = 0;
    setRemoteState(EndpointState.CLOSED);
    if(_connectionEndpoint != null)
    {
        _connectionEndpoint.setRemoteState(EndpointState.CLOSED);
        if(close.getError() != null)
        {
            _connectionEndpoint.getRemoteCondition().copyFrom(close.getError());
        }

        _connectionEndpoint.put(Event.Type.CONNECTION_REMOTE_CLOSE, _connectionEndpoint);
    }

}
 
Example #9
Source File: Send.java    From qpid-proton-j with Apache License 2.0 6 votes vote down vote up
@Override
public void onConnectionInit(Event event) {
    Connection conn = event.getConnection();

    // Every session or link could have their own handler(s) if we
    // wanted simply by adding the handler to the given session
    // or link
    Session ssn = conn.session();

    // If a link doesn't have an event handler, the events go to
    // its parent session. If the session doesn't have a handler
    // the events go to its parent connection. If the connection
    // doesn't have a handler, the events go to the reactor.
    Sender snd = ssn.sender("sender");
    conn.open();
    ssn.open();
    snd.open();
}
 
Example #10
Source File: Send.java    From qpid-proton-j with Apache License 2.0 6 votes vote down vote up
@Override
public void onLinkFlow(Event event) {
    Sender snd = (Sender)event.getLink();
    if (snd.getCredit() > 0) {
        byte[] msgData = new byte[1024];
        int length;
        while(true) {
            try {
                length = message.encode(msgData, 0, msgData.length);
                break;
            } catch(BufferOverflowException e) {
                msgData = new byte[msgData.length * 2];
            }
        }
        byte[] tag = String.valueOf(nextTag++).getBytes();
        Delivery dlv = snd.delivery(tag);
        snd.send(msgData, 0, length);
        dlv.settle();
        snd.advance();
        snd.close();
        snd.getSession().close();
        snd.getSession().getConnection().close();
    }
}
 
Example #11
Source File: ReactorTest.java    From qpid-proton-j with Apache License 2.0 5 votes vote down vote up
@Test
public void scheduleWithEqualDeadline() throws IOException {
    final int count = 10;
    final ArrayList<Integer> taskRunOrder = new ArrayList<Integer>();

    class TaskHandler extends BaseHandler {
        private int _counter;

        private TaskHandler(int counter) {
            _counter = counter;
        }

        @Override
        public void onTimerTask(Event event) {
            taskRunOrder.add(_counter);
        }
    }

    final List<Integer> expectedOrder = new ArrayList<>();
    for(int i = 0 ; i < count; i++) {
        reactor.schedule(0, new TaskHandler(i));
        expectedOrder.add(i);
    }

    reactor.run();
    reactor.free();

    assertEquals(expectedOrder, taskRunOrder);
}
 
Example #12
Source File: ReactorTest.java    From qpid-proton-j with Apache License 2.0 5 votes vote down vote up
@Override
public void onDelivery(Event event) {
    Delivery dlv = event.getDelivery();
    if (!dlv.isPartial()) {
        dlv.settle();
        ++received;
    }
}
 
Example #13
Source File: Recv.java    From qpid-proton-j with Apache License 2.0 5 votes vote down vote up
@Override
public void onDelivery(Event event) {
    Receiver recv = (Receiver)event.getLink();
    Delivery delivery = recv.current();
    if (delivery.isReadable() && !delivery.isPartial()) {
        int size = delivery.pending();
        byte[] buffer = new byte[size];
        int read = recv.recv(buffer, 0, buffer.length);
        recv.advance();

        Message msg = Proton.message();
        msg.decode(buffer, 0, read);
        System.out.println(((AmqpValue)msg.getBody()).getValue());
    }
}
 
Example #14
Source File: Handshaker.java    From qpid-proton-j with Apache License 2.0 5 votes vote down vote up
@Override
public void onLinkRemoteOpen(Event event) {
    Link link = event.getLink();
    if (link.getLocalState() == EndpointState.UNINITIALIZED) {
        if (link.getRemoteSource() != null) {
            link.setSource(link.getRemoteSource().copy());
        }
        if (link.getRemoteTarget() != null) {
            link.setTarget(link.getRemoteTarget().copy());
        }
    }
    open(link);
}
 
Example #15
Source File: TransportSession.java    From qpid-proton-j with Apache License 2.0 5 votes vote down vote up
void handleDisposition(Disposition disposition)
{
    UnsignedInteger id = disposition.getFirst();
    UnsignedInteger last = disposition.getLast() == null ? id : disposition.getLast();
    final Map<UnsignedInteger, DeliveryImpl> unsettledDeliveries =
            disposition.getRole() == Role.RECEIVER ? _unsettledOutgoingDeliveriesById
                    : _unsettledIncomingDeliveriesById;

    while(id.compareTo(last)<=0)
    {
        DeliveryImpl delivery = unsettledDeliveries.get(id);
        if(delivery != null)
        {
            if(disposition.getState() != null)
            {
                delivery.setRemoteDeliveryState(disposition.getState());
            }
            if(Boolean.TRUE.equals(disposition.getSettled()))
            {
                delivery.setRemoteSettled(true);
                unsettledDeliveries.remove(id);
            }
            delivery.updateWork();

            getSession().getConnection().put(Event.Type.DELIVERY, delivery);
        }
        id = id.add(UnsignedInteger.ONE);
    }
    //TODO - Implement.
}
 
Example #16
Source File: TransportImpl.java    From qpid-proton-j with Apache License 2.0 5 votes vote down vote up
@Override
public void handleBegin(Begin begin, Binary payload, Integer channel)
{
    // TODO - check channel < max_channel
    TransportSession transportSession = _remoteSessions.get(channel);
    if(transportSession != null)
    {
        // TODO - fail due to begin on begun session
    }
    else
    {
        SessionImpl session;
        if(begin.getRemoteChannel() == null)
        {
            session = _connectionEndpoint.session();
            transportSession = getTransportState(session);
        }
        else
        {
            transportSession = _localSessions.get(begin.getRemoteChannel().intValue());
            if (transportSession == null) {
                // TODO handle failure rather than just throwing a nicer NPE
                throw new NullPointerException("uncorrelated channel: " + begin.getRemoteChannel());
            }
            session = transportSession.getSession();

        }
        transportSession.setRemoteChannel(channel);
        session.setRemoteState(EndpointState.ACTIVE);
        transportSession.setNextIncomingId(begin.getNextOutgoingId());
        session.setRemoteProperties(begin.getProperties());
        session.setRemoteDesiredCapabilities(begin.getDesiredCapabilities());
        session.setRemoteOfferedCapabilities(begin.getOfferedCapabilities());

        _remoteSessions.put(channel, transportSession);

        _connectionEndpoint.put(Event.Type.SESSION_REMOTE_OPEN, session);
    }

}
 
Example #17
Source File: TransportImpl.java    From qpid-proton-j with Apache License 2.0 5 votes vote down vote up
@Override
public void handleDetach(Detach detach, Binary payload, Integer channel)
{
    TransportSession transportSession = _remoteSessions.get(channel);
    if(transportSession == null)
    {
        // TODO - fail due to attach on non-begun session
    }
    else
    {
        TransportLink<?> transportLink = transportSession.getLinkFromRemoteHandle(detach.getHandle());

        if(transportLink != null)
        {
            LinkImpl link = transportLink.getLink();
            transportLink.receivedDetach();
            transportSession.freeRemoteHandle(transportLink.getRemoteHandle());
            if (detach.getClosed()) {
                _connectionEndpoint.put(Event.Type.LINK_REMOTE_CLOSE, link);
            } else {
                _connectionEndpoint.put(Event.Type.LINK_REMOTE_DETACH, link);
            }
            transportLink.clearRemoteHandle();
            link.setRemoteState(EndpointState.CLOSED);
            if(detach.getError() != null)
            {
                link.getRemoteCondition().copyFrom(detach.getError());
            }
        }
        else
        {
            // TODO - fail - attempt attach on a handle which is in use
        }
    }
}
 
Example #18
Source File: LinkImpl.java    From qpid-proton-j with Apache License 2.0 5 votes vote down vote up
LinkImpl(SessionImpl session, String name)
{
    _session = session;
    _session.incref();
    _name = name;
    ConnectionImpl conn = session.getConnectionImpl();
    _node = conn.addLinkEndpoint(this);
    conn.put(Event.Type.LINK_INIT, this);
}
 
Example #19
Source File: EventImplTest.java    From qpid-proton-j with Apache License 2.0 5 votes vote down vote up
@Test
public void testGetTransportWithLinkContext()
{
    Transport transport = Transport.Factory.create();
    Connection connection = Connection.Factory.create();
    transport.bind(connection);

    Session session = connection.session();
    Link link = session.receiver("myReceiver");

    EventImpl event = createEvent(link, Event.Type.LINK_INIT);

    assertNotNull("No transport returned", event.getTransport());
    assertSame("Incorrect transport returned", transport, event.getTransport());
}
 
Example #20
Source File: EventImplTest.java    From qpid-proton-j with Apache License 2.0 5 votes vote down vote up
@Test
public void testGetTransportWithConnectionContext()
{
    Transport transport = Transport.Factory.create();
    Connection connection = Connection.Factory.create();
    transport.bind(connection);

    EventImpl event = createEvent(connection, Event.Type.CONNECTION_BOUND);

    assertNotNull("No transport returned", event.getTransport());
    assertSame("Incorrect transport returned", transport, event.getTransport());
}
 
Example #21
Source File: IOHandler.java    From qpid-proton-j with Apache License 2.0 5 votes vote down vote up
private void handleOpen(Reactor reactor, Event event) {
    Connection connection = event.getConnection();
    if (connection.getRemoteState() != EndpointState.UNINITIALIZED) {
        return;
    }
    // Outgoing Reactor connections set the virtual host automatically using the
    // following rules:
    String vhost = connection.getHostname();
    if (vhost == null) {
        // setHostname never called, use the host from the connection's
        // socket address as the default virtual host:
        String conAddr = reactor.getConnectionAddress(connection);
        if (conAddr != null) {
            Address addr = new Address(conAddr);
            connection.setHostname(addr.getHost());
        }
    } else if (vhost.isEmpty()) {
        // setHostname called explictly with a null string. This allows
        // the application to completely avoid sending a virtual host
        // name
        connection.setHostname(null);
    } else {
        // setHostname set by application - use it.
    }
    Transport transport = Proton.transport();

    int maxFrameSizeOption = reactor.getOptions().getMaxFrameSize();
    if (maxFrameSizeOption != 0) {
        transport.setMaxFrameSize(maxFrameSizeOption);
    }

    if (reactor.getOptions().isEnableSaslByDefault()) {
        Sasl sasl = transport.sasl();
        sasl.client();
        sasl.setMechanisms("ANONYMOUS");
    }

    transport.bind(connection);
}
 
Example #22
Source File: Server.java    From qpid-proton-j with Apache License 2.0 5 votes vote down vote up
@Override
public void onLinkFlow(Event evt) {
    Link link = evt.getLink();
    if (link instanceof Sender) {
        Sender snd = (Sender) link;
        send(router.getAddress(snd), snd);
    }
}
 
Example #23
Source File: SessionImpl.java    From qpid-proton-j with Apache License 2.0 5 votes vote down vote up
SessionImpl(ConnectionImpl connection)
{
    _connection = connection;
    _connection.incref();
    _node = _connection.addSessionEndpoint(this);
    _connection.put(Event.Type.SESSION_INIT, this);
}
 
Example #24
Source File: TransportImpl.java    From qpid-proton-j with Apache License 2.0 5 votes vote down vote up
@Override
public void pop(int bytes)
{
    init();
    _outputProcessor.pop(bytes);
    _bytesOutput += bytes;

    int p = pending();
    if (p < 0 && !postedHeadClosed) {
        put(Event.Type.TRANSPORT_HEAD_CLOSED, this);
        postedHeadClosed = true;
        maybePostClosed();
    }
}
 
Example #25
Source File: Counter.java    From qpid-proton-j with Apache License 2.0 5 votes vote down vote up
@Override
public void onReactorInit(Event event) {
    startTime = System.currentTimeMillis();
    System.out.println("Hello, World!");

    // Note that unlike the previous scheduling example, we pass in
    // a separate object for the handler. This means that the timer
    // event we just scheduled will not be seen by the Counter
    // implementation of BaseHandler as it is being handled by the
    // CounterHandler instance we create.
    event.getReactor().schedule(250, new CounterHandler(10));
}
 
Example #26
Source File: TransportLink.java    From qpid-proton-j with Apache License 2.0 5 votes vote down vote up
void handleFlow(Flow flow)
{
    _remoteDeliveryCount = flow.getDeliveryCount();
    _remoteLinkCredit = flow.getLinkCredit();


    _link.getConnectionImpl().put(Event.Type.LINK_FLOW, _link);
}
 
Example #27
Source File: EventImpl.java    From qpid-proton-j with Apache License 2.0 5 votes vote down vote up
@Override
public Event copy()
{
   EventImpl newEvent = new EventImpl();
   newEvent.init(type, context);
   newEvent.attachments.copy(attachments);
   return newEvent;
}
 
Example #28
Source File: ReactorTest.java    From qpid-proton-j with Apache License 2.0 5 votes vote down vote up
@Override
public void onLinkFlow(Event event) {
    Sender link = (Sender)event.getLink();
    while (link.getCredit() > 0 && remaining > 0) {
        Delivery dlv = link.delivery(new byte[0]);
        assertNotNull(dlv);
        dlv.settle();
        link.advance();
        --remaining;
    }

    if (remaining == 0) {
        event.getConnection().close();
    }
}
 
Example #29
Source File: CountRandomly.java    From qpid-proton-j with Apache License 2.0 5 votes vote down vote up
@Override
public void onTimerTask(Event event) {
    // keep on shouting until we are done counting
    System.out.println("Yay, " + Math.round(Math.abs((Math.random() * 110) - 10)));
    if (!counter.done()) {
        event.getReactor().schedule(500, this);
    }
}
 
Example #30
Source File: TransportImpl.java    From qpid-proton-j with Apache License 2.0 5 votes vote down vote up
@Override
public void closed(TransportException error)
{
    if (!_closeReceived || error != null) {
        // Set an error condition, but only if one was not already set
        if(!_conditionSet) {
            if(error instanceof TransportDecodeException) {
                setCondition(new ErrorCondition(AmqpError.DECODE_ERROR, error.getMessage()));
            } else {
                String description =  error == null ? "connection aborted" : error.toString();

                setCondition(new ErrorCondition(ConnectionError.FRAMING_ERROR, description));
            }
        }

        _head_closed = true;
    }

    if (_conditionSet && !postedTransportError) {
        put(Event.Type.TRANSPORT_ERROR, this);
        postedTransportError = true;
    }

    if (!postedTailClosed) {
        put(Event.Type.TRANSPORT_TAIL_CLOSED, this);
        postedTailClosed = true;
        maybePostClosed();
    }
}