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

The following examples show how to use org.apache.qpid.proton.engine.Sender. 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: 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 #2
Source File: AmqpTransactionCoordinatorBuilder.java    From qpid-jms with Apache License 2.0 6 votes vote down vote up
@Override
protected Sender createEndpoint(JmsSessionInfo resourceInfo) {
    Coordinator coordinator = new Coordinator();
    coordinator.setCapabilities(TxnCapability.LOCAL_TXN);

    Symbol[] outcomes = new Symbol[]{ Accepted.DESCRIPTOR_SYMBOL, Rejected.DESCRIPTOR_SYMBOL, Released.DESCRIPTOR_SYMBOL, Modified.DESCRIPTOR_SYMBOL };

    Source source = new Source();
    source.setOutcomes(outcomes);

    String coordinatorName = "qpid-jms:coordinator:" + resourceInfo.getId().toString();

    Sender sender = getParent().getSession().getEndpoint().sender(coordinatorName);
    sender.setSource(source);
    sender.setTarget(coordinator);
    sender.setSenderSettleMode(SenderSettleMode.UNSETTLED);
    sender.setReceiverSettleMode(ReceiverSettleMode.FIRST);

    return sender;
}
 
Example #3
Source File: AmqpTransactionCoordinator.java    From qpid-jms with Apache License 2.0 6 votes vote down vote up
private void sendTxCommand(Message message) throws ProviderException {
    int encodedSize = 0;
    byte[] buffer = OUTBOUND_BUFFER;
    while (true) {
        try {
            encodedSize = message.encode(buffer, 0, buffer.length);
            break;
        } catch (BufferOverflowException e) {
            buffer = new byte[buffer.length * 2];
        }
    }

    Sender sender = getEndpoint();
    sender.send(buffer, 0, encodedSize);
    sender.advance();
}
 
Example #4
Source File: DeferredSettlementTest.java    From qpid-proton-j with Apache License 2.0 6 votes vote down vote up
private Delivery sendMessageToClient(String deliveryTag, int messageBody)
{
    byte[] tag = deliveryTag.getBytes(StandardCharsets.UTF_8);

    Message m = Proton.message();
    m.setBody(new AmqpValue(messageBody));

    byte[] encoded = new byte[BUFFER_SIZE];
    int len = m.encode(encoded, 0, BUFFER_SIZE);

    assertTrue("given array was too small", len < BUFFER_SIZE);

    Sender serverSender = getServer().getSender();
    Delivery serverDelivery = serverSender.delivery(tag);
    int sent = serverSender.send(encoded, 0, len);

    assertEquals("sender unable to send all data at once as assumed for simplicity", len, sent);

    boolean senderAdvanced = serverSender.advance();
    assertTrue("sender has not advanced", senderAdvanced);

    return serverDelivery;
}
 
Example #5
Source File: EventImplTest.java    From qpid-proton-j with Apache License 2.0 6 votes vote down vote up
@Test
public void testGetTransportWithDeliveryContext()
{
    Transport transport = Transport.Factory.create();
    Connection connection = Connection.Factory.create();
    transport.bind(connection);

    Session session = connection.session();
    Sender sender = session.sender("mySender");

    Delivery delivery = sender.delivery("tag".getBytes());

    EventImpl event = createEvent(delivery, Event.Type.DELIVERY);

    assertNotNull("No transport returned", event.getTransport());
    assertSame("Incorrect transport returned", transport, event.getTransport());
}
 
Example #6
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 #7
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 #8
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 #9
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 #10
Source File: ProtonServerSenderContextTest.java    From activemq-artemis with Apache License 2.0 6 votes vote down vote up
@Test(expected = ActiveMQAMQPNotFoundException.class)
public void testAcceptsNullSourceAddressWhenInitialising() throws Exception {
   ProtonProtocolManager mock = mock(ProtonProtocolManager.class);
   when(mock.getServer()).thenReturn(mock(ActiveMQServer.class));
   Sender mockSender = mock(Sender.class);
   AMQPConnectionContext mockConnContext = mock(AMQPConnectionContext.class);
   when(mockConnContext.getProtocolManager()).thenReturn(mock);

   AMQPSessionCallback mockSessionCallback = mock(AMQPSessionCallback.class);

   AddressQueryResult queryResult = new AddressQueryResult(null, Collections.emptySet(), 0, false, false, false, false, 0);
   when(mockSessionCallback.addressQuery(any(), any(), anyBoolean())).thenReturn(queryResult);
   ProtonServerSenderContext sc = new ProtonServerSenderContext( mockConnContext, mockSender, null, mockSessionCallback);

   Source source = new Source();
   source.setAddress(null);
   when(mockSender.getRemoteSource()).thenReturn(source);


   sc.initialise();
}
 
Example #11
Source File: AmqpTransactionCoordinator.java    From activemq-artemis with Apache License 2.0 6 votes vote down vote up
private void sendTxCommand(Message message) throws IOException {
   int encodedSize = 0;
   byte[] buffer = OUTBOUND_BUFFER;
   while (true) {
      try {
         encodedSize = message.encode(buffer, 0, buffer.length);
         break;
      } catch (BufferOverflowException e) {
         buffer = new byte[buffer.length * 2];
      }
   }

   Sender sender = getEndpoint();
   sender.send(buffer, 0, encodedSize);
   sender.advance();
}
 
Example #12
Source File: AmqpTransactionCoordinator.java    From activemq-artemis with Apache License 2.0 6 votes vote down vote up
@Override
protected void doOpen() {
   Coordinator coordinator = new Coordinator();
   coordinator.setCapabilities(TxnCapability.LOCAL_TXN);
   Source source = new Source();

   String coordinatorName = "qpid-jms:coordinator:" + session.getConnection().getConnectionId();

   Sender sender = session.getEndpoint().sender(coordinatorName);
   sender.setSource(source);
   sender.setTarget(coordinator);
   sender.setSenderSettleMode(SenderSettleMode.UNSETTLED);
   sender.setReceiverSettleMode(ReceiverSettleMode.FIRST);

   setEndpoint(sender);

   super.doOpen();
}
 
Example #13
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 #14
Source File: AmqpTemporaryDestinationBuilder.java    From qpid-jms with Apache License 2.0 5 votes vote down vote up
@Override
protected Sender createEndpoint(JmsTemporaryDestination resourceInfo) {
    // Form a link name, use the local generated name with a prefix to aid debugging
    String localDestinationName = resourceInfo.getAddress();
    String senderLinkName = null;
    if (resourceInfo.isQueue()) {
        senderLinkName = "qpid-jms:" + TEMP_QUEUE_CREATOR + localDestinationName;
    } else {
        senderLinkName = "qpid-jms:" + TEMP_TOPIC_CREATOR + localDestinationName;
    }

    // Just use a bare Source, this is a producer which
    // wont send anything and the link name is unique.
    Source source = new Source();

    Target target = new Target();
    target.setDynamic(true);
    target.setDurable(TerminusDurability.NONE);
    target.setExpiryPolicy(TerminusExpiryPolicy.LINK_DETACH);

    // Set the dynamic node lifetime-policy
    Map<Symbol, Object> dynamicNodeProperties = new HashMap<Symbol, Object>();
    dynamicNodeProperties.put(DYNAMIC_NODE_LIFETIME_POLICY, DeleteOnClose.getInstance());
    target.setDynamicNodeProperties(dynamicNodeProperties);

    // Set the capability to indicate the node type being created
    if (resourceInfo.isQueue()) {
        target.setCapabilities(AmqpDestinationHelper.TEMP_QUEUE_CAPABILITY);
    } else {
        target.setCapabilities(AmqpDestinationHelper.TEMP_TOPIC_CAPABILITY);
    }

    Sender sender = getParent().getEndpoint().sender(senderLinkName);
    sender.setSource(source);
    sender.setTarget(target);
    sender.setSenderSettleMode(SenderSettleMode.UNSETTLED);
    sender.setReceiverSettleMode(ReceiverSettleMode.FIRST);

    return sender;
}
 
Example #15
Source File: AmqpSecurityTest.java    From activemq-artemis with Apache License 2.0 5 votes vote down vote up
@Test(timeout = 60000)
public void testSendAndRejected() throws Exception {
   AmqpClient client = createAmqpClient(guestUser, guestPass);
   client.setValidator(new AmqpValidator() {

      @Override
      public void inspectOpenedResource(Sender sender) {
         ErrorCondition condition = sender.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("Sender should have been opened with an error");
         }
      }
   });

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

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

      connection.getStateInspector().assertValid();
   } finally {
      connection.close();
   }
}
 
Example #16
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 #17
Source File: Server.java    From qpid-proton-j with Apache License 2.0 5 votes vote down vote up
private int send(String address, Sender snd) {
    if (snd == null) {
        Router.Routes<Sender> routes = router.getOutgoing(address);
        snd = routes.choose();
        if (snd == null) {
            return 0;
        }
    }

    int count = 0;
    while (snd.getCredit() > 0 && snd.getQueued() < 1024) {
        Message msg = messages.get(address);
        if (msg == null) {
            snd.drained();
            return count;
        }
        Delivery dlv = snd.delivery(nextTag());
        byte[] bytes = msg.getBytes();
        snd.send(bytes, 0, bytes.length);
        dlv.settle();
        count++;
        if (!quiet) {
            System.out.println(String.format("Sent message(%s): %s", address, msg));
        }
    }

    return count;
}
 
Example #18
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 #19
Source File: Router.java    From qpid-proton-j with Apache License 2.0 5 votes vote down vote up
private void remove(Link link) {
    if (link instanceof Sender) {
        remove((Sender) link);
    } else {
        remove((Receiver) link);
    }
}
 
Example #20
Source File: AmqpProducerBuilder.java    From qpid-jms with Apache License 2.0 5 votes vote down vote up
@Override
protected Sender createEndpoint(JmsProducerInfo resourceInfo) {
    JmsDestination destination = resourceInfo.getDestination();
    AmqpConnection connection = getParent().getConnection();

    String targetAddress = AmqpDestinationHelper.getDestinationAddress(destination, connection);

    Symbol[] outcomes = new Symbol[]{ Accepted.DESCRIPTOR_SYMBOL, Rejected.DESCRIPTOR_SYMBOL, Released.DESCRIPTOR_SYMBOL, Modified.DESCRIPTOR_SYMBOL };
    String sourceAddress = resourceInfo.getId().toString();
    Source source = new Source();
    source.setAddress(sourceAddress);
    source.setOutcomes(outcomes);
    // TODO: default outcome. Accepted normally, Rejected for transaction controller?

    Target target = new Target();
    target.setAddress(targetAddress);
    Symbol typeCapability =  AmqpDestinationHelper.toTypeCapability(destination);
    if (typeCapability != null) {
        target.setCapabilities(typeCapability);
    }

    String senderName = "qpid-jms:sender:" + sourceAddress + ":" + targetAddress;

    Sender sender = getParent().getEndpoint().sender(senderName);
    sender.setSource(source);
    sender.setTarget(target);
    if (resourceInfo.isPresettle()) {
        sender.setSenderSettleMode(SenderSettleMode.SETTLED);
    } else {
        sender.setSenderSettleMode(SenderSettleMode.UNSETTLED);
    }
    sender.setReceiverSettleMode(ReceiverSettleMode.FIRST);

    if (!connection.getProperties().isDelayedDeliverySupported()) {
        validateDelayedDeliveryLinkCapability = true;
        sender.setDesiredCapabilities(new Symbol[] { AmqpSupport.DELAYED_DELIVERY });
    }

    return sender;
}
 
Example #21
Source File: Pool.java    From qpid-proton-j with Apache License 2.0 5 votes vote down vote up
public Sender newOutgoing(Session ssn, String remote, String local) {
    Sender snd = ssn.sender(String.format("%s-%s", local, remote));
    Source src = new Source();
    src.setAddress(local);
    snd.setSource(src);
    Target tgt = new Target();
    tgt.setAddress(remote);
    snd.setTarget(tgt);
    return snd;
}
 
Example #22
Source File: Router.java    From qpid-proton-j with Apache License 2.0 5 votes vote down vote up
private void remove(Sender snd) {
    String address = getAddress(snd);
    Routes<Sender> routes = outgoing.get(address);
    if (routes != null) {
        routes.remove(snd);
        if (routes.size() == 0) {
            outgoing.remove(address);
        }
    }
}
 
Example #23
Source File: ProtonServerSenderContext.java    From activemq-artemis with Apache License 2.0 5 votes vote down vote up
public ProtonServerSenderContext(AMQPConnectionContext connection,
                                 Sender sender,
                                 AMQPSessionContext protonSession,
                                 AMQPSessionCallback server) {
   super();
   this.connection = connection;
   this.sender = sender;
   this.protonSession = protonSession;
   this.sessionSPI = server;
   this.executeDelivery = this::executeDelivery;
   amqpTreatRejectAsUnmodifiedDeliveryFailed = this.connection.getProtocolManager()
                                                              .isAmqpTreatRejectAsUnmodifiedDeliveryFailed();
}
 
Example #24
Source File: AmqpFixedProducer.java    From qpid-jms with Apache License 2.0 5 votes vote down vote up
public AmqpFixedProducer(AmqpSession session, JmsProducerInfo info, Sender sender) {
    super(session, info, sender);

    connection = session.getConnection();
    tracer = connection.getResourceInfo().getTracer();

    delayedDeliverySupported = connection.getProperties().isDelayedDeliverySupported();
}
 
Example #25
Source File: AMQPSessionContext.java    From activemq-artemis with Apache License 2.0 5 votes vote down vote up
public void addSender(Sender sender) throws Exception {
   // TODO: Remove this check when we have support for global link names
   boolean outgoing = (sender.getContext() != null && sender.getContext().equals(true));
   ProtonServerSenderContext protonSender = outgoing ? new ProtonClientSenderContext(connection, sender, this, sessionSPI) : new ProtonServerSenderContext(connection, sender, this, sessionSPI);

   try {
      protonSender.initialise();
      senders.put(sender, protonSender);
      serverSenders.put(protonSender.getBrokerConsumer(), protonSender);
      sender.setContext(protonSender);
      connection.runNow(() -> {
         sender.open();
         connection.flush();
      });

      protonSender.start();
   } catch (ActiveMQAMQPException e) {
      senders.remove(sender);
      if (protonSender.getBrokerConsumer() != null) {
         serverSenders.remove(protonSender.getBrokerConsumer());
      }
      sender.setSource(null);
      sender.setCondition(new ErrorCondition(e.getAmqpError(), e.getMessage()));
      connection.runNow(() -> {
         sender.close();
         connection.flush();
      });
   }
}
 
Example #26
Source File: ProtonSessionImpl.java    From vertx-proton with Apache License 2.0 5 votes vote down vote up
@Override
public ProtonSender createSender(String address, ProtonLinkOptions senderOptions) {
  Sender sender = session.sender(getOrCreateLinkName(senderOptions));

  Symbol[] outcomes = new Symbol[] { Accepted.DESCRIPTOR_SYMBOL, Rejected.DESCRIPTOR_SYMBOL,
      Released.DESCRIPTOR_SYMBOL, Modified.DESCRIPTOR_SYMBOL };
  Source source = new Source();
  source.setOutcomes(outcomes);

  Target target = new Target();
  target.setAddress(address);
  if(senderOptions.isDynamic()) {
    target.setDynamic(true);
  }

  sender.setSource(source);
  sender.setTarget(target);

  ProtonSenderImpl s = new ProtonSenderImpl(sender);
  if (address == null) {
    s.setAnonymousSender(true);
  }

  s.openHandler((result) -> {
    LOG.trace("Sender open completed");
  });
  s.closeHandler((result) -> {
    if (result.succeeded()) {
      LOG.trace("Sender closed");
    } else {
      LOG.warn("Sender closed with error", result.cause());
    }
  });

  // Default to at-least-once
  s.setQoS(ProtonQoS.AT_LEAST_ONCE);

  return s;
}
 
Example #27
Source File: ProtonConnectionImpl.java    From vertx-proton with Apache License 2.0 5 votes vote down vote up
void fireRemoteLinkOpen(Link link) {
  if (link instanceof Sender) {
    if (senderOpenHandler != null) {
      senderOpenHandler.handle(new ProtonSenderImpl((Sender) link));
    }
  } else {
    if (receiverOpenHandler != null) {
      receiverOpenHandler.handle(new ProtonReceiverImpl((Receiver) link));
    }
  }
}
 
Example #28
Source File: ReactorTest.java    From qpid-proton-j with Apache License 2.0 5 votes vote down vote up
@Override
public void onConnectionInit(Event event) {
    Connection conn = event.getConnection();
    Session ssn = conn.session();
    Sender snd = ssn.sender("sender");
    conn.open();
    ssn.open();
    snd.open();
}
 
Example #29
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 #30
Source File: AmqpSecurityTest.java    From activemq-artemis with Apache License 2.0 5 votes vote down vote up
@Test(timeout = 30000)
public void testConsumerNotAuthorizedToCreateQueues() throws Exception {
   AmqpClient client = createAmqpClient(noprivUser, noprivPass);
   client.setValidator(new AmqpValidator() {

      @Override
      public void inspectOpenedResource(Sender sender) {
         ErrorCondition condition = sender.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("Sender should have been opened with an error");
         }
      }
   });

   AmqpConnection connection = client.connect();

   try {
      AmqpSession session = connection.createSession();

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

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