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

The following examples show how to use org.apache.qpid.proton.engine.Receiver. 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: AmqpReceiver.java    From activemq-artemis with Apache License 2.0 6 votes vote down vote up
@Override
public void processFlowUpdates(AmqpConnection connection) throws IOException {
   if (pullRequest != null || stopRequest != null) {
      Receiver receiver = getEndpoint();
      if (receiver.getRemoteCredit() <= 0 && receiver.getQueued() == 0) {
         if (pullRequest != null) {
            pullRequest.onSuccess();
            pullRequest = null;
         }

         if (stopRequest != null) {
            stopRequest.onSuccess();
            stopRequest = null;
         }
      }
   }

   LOG.trace("Consumer {} flow updated, remote credit = {}", getSubscriptionName(), getEndpoint().getRemoteCredit());

   super.processFlowUpdates(connection);
}
 
Example #2
Source File: Pool.java    From qpid-proton-j with Apache License 2.0 6 votes vote down vote up
public Pool(Collector collector, final Router router) {
    this.collector = collector;
    connections = new HashMap<String,Connection>();

    if (router != null) {
        outgoingResolver = new LinkResolver<Sender>() {
            public Sender resolve(String address) {
                return router.getOutgoing(address).choose();
            }
        };
        incomingResolver = new LinkResolver<Receiver>() {
            public Receiver resolve(String address) {
                return router.getIncoming(address).choose();
            }
        };
    } else {
        outgoingResolver = new LinkResolver<Sender>() {
            public Sender resolve(String address) { return null; }
        };
        incomingResolver = new LinkResolver<Receiver>() {
            public Receiver resolve(String address) { return null; }
        };
    }
}
 
Example #3
Source File: ProtonServerReceiverContext.java    From activemq-artemis with Apache License 2.0 6 votes vote down vote up
public ProtonServerReceiverContext(AMQPSessionCallback sessionSPI,
                                   AMQPConnectionContext connection,
                                   AMQPSessionContext protonSession,
                                   Receiver receiver) {
   this.connection = connection;
   this.routingContext = new RoutingContextImpl(null).setDuplicateDetection(connection.getProtocolManager().isAmqpDuplicateDetection());
   this.protonSession = protonSession;
   this.receiver = receiver;
   this.sessionSPI = sessionSPI;
   this.amqpCredits = connection.getAmqpCredits();
   this.minCreditRefresh = connection.getAmqpLowCredits();
   this.creditRunnable = createCreditRunnable(amqpCredits, minCreditRefresh, receiver, connection, this);
   useModified = this.connection.getProtocolManager().isUseModifiedForTransientDeliveryErrors();
   this.minLargeMessageSize = connection.getProtocolManager().getAmqpMinLargeMessageSize();

   if (sessionSPI != null) {
      sessionSPI.addCloseable((boolean failed) -> clearLargeMessage());
   }
}
 
Example #4
Source File: AMQPSessionContext.java    From activemq-artemis with Apache License 2.0 6 votes vote down vote up
public void addReceiver(Receiver receiver) throws Exception {
   try {
      ProtonServerReceiverContext protonReceiver = new ProtonServerReceiverContext(sessionSPI, connection, this, receiver);
      protonReceiver.initialise();
      receivers.put(receiver, protonReceiver);
      ServerProducer serverProducer = new ServerProducerImpl(receiver.getName(), "AMQP", receiver.getTarget().getAddress());
      sessionSPI.addProducer(serverProducer);
      receiver.setContext(protonReceiver);
      connection.runNow(() -> {
         receiver.open();
         connection.flush();
      });
   } catch (ActiveMQAMQPException e) {
      receivers.remove(receiver);
      receiver.setTarget(null);
      receiver.setCondition(new ErrorCondition(e.getAmqpError(), e.getMessage()));
      connection.runNow(() -> {
         receiver.close();
         connection.flush();
      });
   }
}
 
Example #5
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 #6
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 #7
Source File: AMQPConnectionContext.java    From activemq-artemis with Apache License 2.0 6 votes vote down vote up
protected void remoteLinkOpened(Link link) throws Exception {

      AMQPSessionContext protonSession = getSessionExtension(link.getSession());

      link.setSource(link.getRemoteSource());
      link.setTarget(link.getRemoteTarget());
      if (link instanceof Receiver) {
         Receiver receiver = (Receiver) link;
         if (link.getRemoteTarget() instanceof Coordinator) {
            Coordinator coordinator = (Coordinator) link.getRemoteTarget();
            protonSession.addTransactionHandler(coordinator, receiver);
         } else {
            protonSession.addReceiver(receiver);
         }
      } else {
         Sender sender = (Sender) link;
         protonSession.addSender(sender);
      }
   }
 
Example #8
Source File: ProtonServerReceiverContext.java    From activemq-artemis with Apache License 2.0 5 votes vote down vote up
public void deliveryFailed(Delivery delivery, Receiver receiver, Exception e) {
   connection.runNow(() -> {
      DeliveryState deliveryState = determineDeliveryState(((Source) receiver.getSource()),
                                                           useModified,
                                                           e);
      delivery.disposition(deliveryState);
      settle(delivery);
      connection.flush();
   });
}
 
Example #9
Source File: Drain.java    From qpid-proton-j with Apache License 2.0 5 votes vote down vote up
@Override
public void onLinkLocalOpen(Event evt) {
    Link link = evt.getLink();
    if (link instanceof Receiver) {
        Receiver receiver = (Receiver) link;

        if (block) {
            receiver.flow(count);
        } else {
            receiver.drain(count);
        }
    }
}
 
Example #10
Source File: AMQPSessionContext.java    From activemq-artemis with Apache License 2.0 5 votes vote down vote up
public void addTransactionHandler(Coordinator coordinator, Receiver receiver) {
   ProtonTransactionHandler transactionHandler = new ProtonTransactionHandler(sessionSPI, connection);

   coordinator.setCapabilities(Symbol.getSymbol("amqp:local-transactions"), Symbol.getSymbol("amqp:multi-txns-per-ssn"), Symbol.getSymbol("amqp:multi-ssns-per-txn"));

   receiver.setContext(transactionHandler);
   connection.runNow(() -> {
      receiver.open();
      receiver.flow(connection.getAmqpCredits());
      connection.flush();
   });
}
 
Example #11
Source File: TransportImplTest.java    From qpid-proton-j with Apache License 2.0 5 votes vote down vote up
@Test
public void testReceiverFlowBeforeOpenConnection()
{
    MockTransportImpl transport = new MockTransportImpl();
    Connection connection = Proton.connection();
    transport.bind(connection);

    Session session = connection.session();
    session.open();

    Receiver reciever = session.receiver("myReceiver");
    reciever.flow(5);

    pumpMockTransport(transport);

    assertEquals("Unexpected frames written: " + getFrameTypesWritten(transport), 0, transport.writes.size());

    // Now open the connection, expect the Open and Begin frames but
    // nothing else as we haven't opened the receiver itself yet.
    connection.open();

    pumpMockTransport(transport);

    assertEquals("Unexpected frames written: " + getFrameTypesWritten(transport), 2, transport.writes.size());

    assertTrue("Unexpected frame type", transport.writes.get(0) instanceof Open);
    assertTrue("Unexpected frame type", transport.writes.get(1) instanceof Begin);
}
 
Example #12
Source File: Router.java    From qpid-proton-j with Apache License 2.0 5 votes vote down vote up
private void add(Link link) {
    if (link instanceof Sender) {
        add((Sender) link);
    } else {
        add((Receiver) link);
    }
}
 
Example #13
Source File: FlowController.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 Receiver) {
        topUp((Receiver) link);
    }
}
 
Example #14
Source File: FlowController.java    From qpid-proton-j with Apache License 2.0 5 votes vote down vote up
@Override
public void onLinkRemoteOpen(Event evt) {
    Link link = evt.getLink();
    if (link instanceof Receiver) {
        topUp((Receiver) link);
    }
}
 
Example #15
Source File: FlowController.java    From qpid-proton-j with Apache License 2.0 5 votes vote down vote up
@Override
public void onLinkLocalOpen(Event evt) {
    Link link = evt.getLink();
    if (link instanceof Receiver) {
        topUp((Receiver) link);
    }
}
 
Example #16
Source File: Router.java    From qpid-proton-j with Apache License 2.0 5 votes vote down vote up
private void remove(Receiver rcv) {
    String address = getAddress(rcv);
    Routes<Receiver> routes = incoming.get(address);
    if (routes != null) {
        routes.remove(rcv);
        if (routes.size() == 0) {
            incoming.remove(address);
        }
    }
}
 
Example #17
Source File: Drain.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 Receiver) {
        Receiver receiver = (Receiver) link;

        if (!receiver.draining()) {
            receiver.getSession().getConnection().close();
        }
    }
}
 
Example #18
Source File: ProtonReceiverImpl.java    From vertx-proton with Apache License 2.0 5 votes vote down vote up
private void handleAborted(Receiver receiver, Delivery delivery) {
  splitContent = null;

  receiver.advance();
  delivery.settle();

  if(!receiver.getDrain()) {
    flow(1, false);
  } else {
    processForDrainCompletion();
  }
}
 
Example #19
Source File: ProtonServerReceiverContext.java    From activemq-artemis with Apache License 2.0 5 votes vote down vote up
private void actualDelivery(AMQPMessage message, Delivery delivery, Receiver receiver, Transaction tx) {
   try {
      sessionSPI.serverSend(this, tx, receiver, delivery, address, routingContext, message);
   } catch (Exception e) {
      log.warn(e.getMessage(), e);

      deliveryFailed(delivery, receiver, e);

   }
}
 
Example #20
Source File: ProtonServerReceiverContext.java    From activemq-artemis with Apache License 2.0 5 votes vote down vote up
private void initializeCurrentLargeMessage(Delivery delivery, Receiver receiver) throws Exception {
   long id = sessionSPI.getStorageManager().generateID();
   currentLargeMessage = new AMQPLargeMessage(id, delivery.getMessageFormat(), null, sessionSPI.getCoreMessageObjectPools(), sessionSPI.getStorageManager());

   ReadableBuffer dataBuffer = receiver.recv();
   currentLargeMessage.parseHeader(dataBuffer);

   sessionSPI.getStorageManager().largeMessageCreated(id, currentLargeMessage);
   currentLargeMessage.addBytes(dataBuffer);
}
 
Example #21
Source File: ProtonServerReceiverContext.java    From activemq-artemis with Apache License 2.0 5 votes vote down vote up
FlowControlRunner(int refill, int threshold, Receiver receiver, AMQPConnectionContext connection, ProtonServerReceiverContext context) {
   this.refill = refill;
   this.threshold = threshold;
   this.receiver = receiver;
   this.connection = connection;
   this.context = context;
}
 
Example #22
Source File: ProtonServerReceiverContext.java    From activemq-artemis with Apache License 2.0 5 votes vote down vote up
/**
 * This Credit Runnable may be used in Mock tests to simulate the credit semantic here
 */
public static Runnable createCreditRunnable(int refill,
                                            int threshold,
                                            Receiver receiver,
                                            AMQPConnectionContext connection) {
   return new FlowControlRunner(refill, threshold, receiver, connection, null);
}
 
Example #23
Source File: ProtonServerReceiverContext.java    From activemq-artemis with Apache License 2.0 5 votes vote down vote up
/**
 * This Credit Runnable may be used in Mock tests to simulate the credit semantic here
 */
public static Runnable createCreditRunnable(int refill,
                                            int threshold,
                                            Receiver receiver,
                                            AMQPConnectionContext connection,
                                            ProtonServerReceiverContext context) {
   return new FlowControlRunner(refill, threshold, receiver, connection, context);
}
 
Example #24
Source File: ProtonReceiverImpl.java    From vertx-proton with Apache License 2.0 5 votes vote down vote up
private void handlePartial(final Receiver receiver, final Delivery delivery) {
  if (sessionIncomingCapacity <= 0 || maxFrameSize <= 0 || session.getIncomingBytes() < windowFullThreshhold) {
    // No window, or there is still capacity, so do nothing.
  } else {
    // The session window could be effectively full, we need to
    // read part of the delivery content to ensure there is
    // room made for receiving more of the delivery.
    if(delivery.available() > 0) {
      ReadableBuffer buff = receiver.recv();

      if(splitContent == null && buff instanceof CompositeReadableBuffer) {
        // Its a composite and there is no prior partial content, use it.
        splitContent = (CompositeReadableBuffer) buff;
      } else {
        int remaining = buff.remaining();
        if(remaining > 0) {
          if (splitContent == null) {
            splitContent = new CompositeReadableBuffer();
          }

          byte[] chunk = new byte[remaining];
          buff.get(chunk);

          splitContent.append(chunk);
        }
      }
    }
  }
}
 
Example #25
Source File: AmqpReceiverTest.java    From activemq-artemis with Apache License 2.0 5 votes vote down vote up
@Test(timeout = 60000)
public void testCreateQueueReceiverWithNoLocalSet() throws Exception {
   AmqpClient client = createAmqpClient();

   client.setValidator(new AmqpValidator() {

      @SuppressWarnings("unchecked")
      @Override
      public void inspectOpenedResource(Receiver receiver) {

         if (receiver.getRemoteSource() == null) {
            markAsInvalid("Link opened with null source.");
         }

         Source source = (Source) receiver.getRemoteSource();
         Map<Symbol, Object> filters = source.getFilter();

         // Currently don't support noLocal on a Queue
         if (findFilter(filters, NO_LOCAL_FILTER_IDS) != null) {
            markAsInvalid("Broker did not return the NoLocal Filter on Attach");
         }
      }
   });

   AmqpConnection connection = addConnection(client.connect());
   AmqpSession session = connection.createSession();

   session.createReceiver(getQueueName(), null, true);

   connection.getStateInspector().assertValid();
   connection.close();
}
 
Example #26
Source File: AmqpDurableReceiverTest.java    From activemq-artemis with Apache License 2.0 5 votes vote down vote up
@Test(timeout = 60000)
public void testLookupExistingSubscription() throws Exception {

   AmqpClient client = createAmqpClient();
   AmqpConnection connection = addConnection(client.createConnection());
   connection.setContainerId(getContainerID());
   connection.connect();

   AmqpSession session = connection.createSession();
   AmqpReceiver receiver = session.createDurableReceiver(getTopicName(), getSubscriptionName());

   receiver.detach();

   receiver = session.lookupSubscription(getSubscriptionName());

   assertNotNull(receiver);

   Receiver protonReceiver = receiver.getReceiver();
   assertNotNull(protonReceiver.getRemoteSource());
   Source remoteSource = (Source) protonReceiver.getRemoteSource();

   if (remoteSource.getFilter() != null) {
      assertFalse(remoteSource.getFilter().containsKey(NO_LOCAL_NAME));
      assertFalse(remoteSource.getFilter().containsKey(JMS_SELECTOR_NAME));
   }

   assertEquals(TerminusExpiryPolicy.NEVER, remoteSource.getExpiryPolicy());
   assertEquals(TerminusDurability.UNSETTLED_STATE, remoteSource.getDurable());
   assertEquals(COPY, remoteSource.getDistributionMode());

   receiver.close();

   try {
      receiver = session.lookupSubscription(getSubscriptionName());
      fail("Should not be able to lookup the subscription");
   } catch (Exception e) {
   }

   connection.close();
}
 
Example #27
Source File: AmqpDurableReceiverTest.java    From activemq-artemis with Apache License 2.0 5 votes vote down vote up
@Test(timeout = 60000)
public void testLookupExistingSubscriptionWithNoLocal() throws Exception {

   AmqpClient client = createAmqpClient();
   AmqpConnection connection = addConnection(client.createConnection());
   connection.setContainerId(getContainerID());
   connection.connect();

   AmqpSession session = connection.createSession();
   AmqpReceiver receiver = session.createDurableReceiver(getTopicName(), getSubscriptionName(), null, true);

   receiver.detach();

   receiver = session.lookupSubscription(getSubscriptionName());

   assertNotNull(receiver);

   Receiver protonReceiver = receiver.getReceiver();
   assertNotNull(protonReceiver.getRemoteSource());
   Source remoteSource = (Source) protonReceiver.getRemoteSource();

   assertNotNull(remoteSource.getFilter());
   assertTrue(remoteSource.getFilter().containsKey(NO_LOCAL_NAME));
   assertFalse(remoteSource.getFilter().containsKey(JMS_SELECTOR_NAME));

   assertEquals(TerminusExpiryPolicy.NEVER, remoteSource.getExpiryPolicy());
   assertEquals(TerminusDurability.UNSETTLED_STATE, remoteSource.getDurable());
   assertEquals(COPY, remoteSource.getDistributionMode());

   receiver.close();

   try {
      receiver = session.lookupSubscription(getSubscriptionName());
      fail("Should not be able to lookup the subscription");
   } catch (Exception e) {
   }

   connection.close();
}
 
Example #28
Source File: AmqpReceiver.java    From activemq-artemis with Apache License 2.0 5 votes vote down vote up
private void stop(final AsyncResult request) {
   Receiver receiver = getEndpoint();
   if (receiver.getRemoteCredit() <= 0) {
      if (receiver.getQueued() == 0) {
         // We have no remote credit and all the deliveries have been processed.
         request.onSuccess();
      } else {
         // There are still deliveries to process, wait for them to be.
         stopRequest = request;
      }
   } else {
      // TODO: We don't actually want the additional messages that could be sent while
      // draining. We could explicitly reduce credit first, or possibly use 'echo' instead
      // of drain if it was supported. We would first need to understand what happens
      // if we reduce credit below the number of messages already in-flight before
      // the peer sees the update.
      stopRequest = request;
      receiver.drain(0);

      if (getDrainTimeout() > 0) {
         // If the remote doesn't respond we will close the consumer and break any
         // blocked receive or stop calls that are waiting.
         final ScheduledFuture<?> future = getSession().getScheduler().schedule(new Runnable() {
            @Override
            public void run() {
               LOG.trace("Consumer {} drain request timed out", this);
               Exception cause = new JmsOperationTimedOutException("Remote did not respond to a drain request in time");
               locallyClosed(session.getConnection(), cause);
               stopRequest.onFailure(cause);
               session.pumpToProtonTransport(stopRequest);
            }
         }, getDrainTimeout(), TimeUnit.MILLISECONDS);

         stopRequest = new ScheduledRequest(future, stopRequest);
      }
   }
}
 
Example #29
Source File: AmqpSecurityTest.java    From activemq-artemis with Apache License 2.0 5 votes vote down vote up
@Test(timeout = 30000)
public void testReceiverNotAuthorized() throws Exception {
   AmqpClient client = createAmqpClient(noprivUser, noprivPass);
   client.setValidator(new AmqpValidator() {

      @Override
      public void inspectOpenedResource(Receiver receiver) {
         ErrorCondition condition = receiver.getRemoteCondition();

         if (condition != null && condition.getCondition() != null) {
            if (!condition.getCondition().equals(AmqpError.UNAUTHORIZED_ACCESS)) {
               markAsInvalid("Should have been tagged with unauthorized access error");
            }
         } else {
            markAsInvalid("Receiver should have been opened with an error");
         }
      }
   });

   AmqpConnection connection = client.connect();

   try {
      AmqpSession session = connection.createSession();

      try {
         session.createReceiver(getQueueName());
         fail("Should not be able to consume here.");
      } catch (Exception ex) {
         instanceLog.debug("Caught expected exception");
      }

      connection.getStateInspector().assertValid();
   } finally {
      connection.close();
   }
}
 
Example #30
Source File: AmqpReceiverWithFiltersTest.java    From activemq-artemis with Apache License 2.0 5 votes vote down vote up
@Test(timeout = 60000)
public void testSupportedFiltersAreListedAsSupported() throws Exception {
   AmqpClient client = createAmqpClient();

   client.setValidator(new AmqpValidator() {

      @SuppressWarnings("unchecked")
      @Override
      public void inspectOpenedResource(Receiver receiver) {

         if (receiver.getRemoteSource() == null) {
            markAsInvalid("Link opened with null source.");
         }

         Source source = (Source) receiver.getRemoteSource();
         Map<Symbol, Object> filters = source.getFilter();

         if (findFilter(filters, AmqpSupport.JMS_SELECTOR_FILTER_IDS) == null) {
            markAsInvalid("Broker should return selector filter on attach.");
         }
      }
   });

   AmqpConnection connection = addConnection(client.connect());
   AmqpSession session = connection.createSession();

   session.createReceiver(getQueueName(), "color = red");

   connection.getStateInspector().assertValid();
   connection.close();
}