Search in sources :

Example 6 with Producer

use of com.swiftmq.amqp.v100.client.Producer in project swiftmq-client by iitsoftware.

the class SessionDispatcher method doSend.

private void doSend(POSendMessage po) {
    if (pTracer.isEnabled())
        pTracer.trace(toString(), ", doSend, po=" + po + ", dataLength=" + po.getPackager().getSize());
    try {
        Producer producer = po.getProducer();
        producer.verifyState();
        Packager packager = po.getPackager();
        if (remoteIncomingWindow > 0 && outgoingWindow > 0) {
            do {
                boolean wasFirstPacket = false;
                boolean isAtMostOnce = producer.getQoS() == QoS.AT_MOST_ONCE;
                packager.setMaxFrameSize(mySession.myConnection.connectionDispatcher.getMaxFrameSize());
                TransferFrame frame = new TransferFrame(mySession.getChannel());
                frame.setHandle(new Handle(producer.getHandle()));
                frame.setSettled(new AMQPBoolean(isAtMostOnce));
                if (packager.getCurrentPacketNumber() == 0) {
                    long dId = nextDeliveryId();
                    wasFirstPacket = true;
                    producer.incDeliveryCountSnd();
                    DeliveryTag deliveryTag = po.getDeliveryTag() != null ? po.getDeliveryTag() : producer.createDeliveryTag();
                    if (!isAtMostOnce) {
                        if (po.getTxnId() == null && !po.isRecovery())
                            producer.getDeliveryMemory().addUnsettledDelivery(new UnsettledDelivery(deliveryTag, null, po.getMessage()));
                        unsettledOutgoingDeliveries.put(dId, new DeliveryMapping(deliveryTag, producer));
                    }
                    frame.setDeliveryTag(deliveryTag);
                    frame.setDeliveryId(new DeliveryNumber(dId));
                    frame.setMessageFormat(new MessageFormat(0));
                    TxnIdIF txnId = po.getTxnId();
                    if (txnId != null) {
                        TransactionalState txState = new TransactionalState();
                        txState.setTxnId(txnId);
                        frame.setState(txState);
                    }
                }
                packager.setMessageFormat(0);
                packager.getNextPacket(frame);
                // We may increase the outgoing window and send a flow before
                if (wasFirstPacket && outgoingWindow - packager.getPredictedNumberPackets() < 0) {
                    outgoingWindow += packager.getPredictedNumberPackets();
                    sendFlow();
                    windowChanged = true;
                }
                if (pTracer.isEnabled())
                    pTracer.trace(toString(), ", doSend, remoteIncomingWindows=" + remoteIncomingWindow + ", outgoingWindow=" + outgoingWindow + ", sending message, wasFirstPacket=" + wasFirstPacket + ", maxSize=" + packager.getMaxPayloadLength() + ", packetSize=" + frame.getPayload().length + ", predictedNumberPackets=" + packager.getPredictedNumberPackets() + ", currentPacket=" + packager.getCurrentPacketNumber() + ", hasMore=" + packager.hasMore());
                outboundHandler.send(frame);
                nextOutgoingId++;
                remoteIncomingWindow--;
                if (!isAtMostOnce)
                    outgoingWindow--;
                if (!packager.hasMore()) {
                    // b) everything else: after the last packet has been sent
                    if (producer.isTransactionController() || po.getTxnId() != null)
                        producer.setWaitingPO(po);
                    else {
                        po.setSuccess(true);
                        if (po.getSemaphore() != null)
                            po.getSemaphore().notifySingleWaiter();
                    }
                    // If that was the last packet and outgoing window was increased for this message, we need to reset it and send another flow
                    if (windowChanged) {
                        outgoingWindow = mySession.getOutgoingWindowSize();
                        sendFlow();
                    }
                    break;
                }
            } while (remoteIncomingWindow > 0 && outgoingWindow > 0);
            if (packager.hasMore()) {
                if (pTracer.isEnabled())
                    pTracer.trace(toString(), ", doSend, remoteIncomingWindows=" + remoteIncomingWindow + ", outgoingWindow=" + outgoingWindow + ", has more but no window, storing message");
                outboundDeliveries.add(po);
            }
        } else {
            if (pTracer.isEnabled())
                pTracer.trace(toString(), ", doSend, po=" + po + ", remoteIncomingWindows=" + remoteIncomingWindow + ", outgoingWindow=" + outgoingWindow + ", no window, storing message");
            outboundDeliveries.add(po);
        }
    } catch (Exception e) {
        po.setSuccess(false);
        po.setException(e.getMessage());
        if (po.getSemaphore() != null)
            po.getSemaphore().notifySingleWaiter();
    }
}
Also used : TxnIdIF(com.swiftmq.amqp.v100.generated.transactions.coordination.TxnIdIF) IOException(java.io.IOException) TransactionalState(com.swiftmq.amqp.v100.generated.transactions.coordination.TransactionalState) Packager(com.swiftmq.amqp.v100.transport.Packager)

Example 7 with Producer

use of com.swiftmq.amqp.v100.client.Producer in project swiftmq-client by iitsoftware.

the class SessionDispatcher method visit.

public void visit(POAttachProducer po) {
    if (pTracer.isEnabled())
        pTracer.trace(toString(), ", visit, po=" + po + " ...");
    String name = null;
    DeliveryMemory deliveryMemory = po.getDeliveryMemory();
    if (deliveryMemory.getLinkName() != null)
        name = deliveryMemory.getLinkName();
    else {
        name = uniqueSessionId + "/" + po.getTarget() + "/" + (nextLinkId++);
        deliveryMemory.setLinkName(name);
    }
    Producer producer = new Producer(mySession, po.getTarget(), name, po.getQoS(), deliveryMemory);
    int handle = ArrayListTool.setFirstFreeOrExpand(handles, producer);
    producer.setHandle(handle);
    po.setLink(producer);
    waitingPO.put(name, po);
    try {
        AttachFrame attachFrame = new AttachFrame(mySession.getChannel());
        attachFrame.setName(new AMQPString(name));
        attachFrame.setHandle(new Handle(handle));
        attachFrame.setRole(Role.SENDER);
        switch(producer.getQoS()) {
            case QoS.AT_LEAST_ONCE:
                attachFrame.setRcvSettleMode(ReceiverSettleMode.FIRST);
                break;
            case QoS.AT_MOST_ONCE:
                attachFrame.setSndSettleMode(SenderSettleMode.SETTLED);
                break;
            case QoS.EXACTLY_ONCE:
                attachFrame.setRcvSettleMode(ReceiverSettleMode.SECOND);
                break;
        }
        Source source = new Source();
        source.setAddress(new AddressString(name));
        source.setExpiryPolicy(TerminusExpiryPolicy.LINK_DETACH);
        source.setTimeout(new Seconds(0));
        attachFrame.setSource(source);
        String t = po.getTarget();
        if (t.equals(Coordinator.DESCRIPTOR_NAME)) {
            Coordinator coordinator = new Coordinator();
            coordinator.setCapabilities(new AMQPArray(AMQPTypeDecoder.SYM8, new AMQPType[] { TxnCapability.LOCAL_TRANSACTIONS }));
            attachFrame.setTarget(coordinator);
        } else {
            Target target = new Target();
            target.setAddress(new AddressString(t));
            target.setExpiryPolicy(TerminusExpiryPolicy.LINK_DETACH);
            target.setTimeout(new Seconds(0));
            attachFrame.setTarget(target);
        }
        attachFrame.setInitialDeliveryCount(new SequenceNo(producer.getDeliveryCountSnd()));
        attachFrame.setUnsettled(getUnsettledMap(producer.getDeliveryMemory()));
        outboundHandler.send(attachFrame);
    } catch (Exception e) {
        e.printStackTrace();
    }
    if (pTracer.isEnabled())
        pTracer.trace(toString(), ", visit, po=" + po + " done");
}
Also used : AddressString(com.swiftmq.amqp.v100.generated.messaging.message_format.AddressString) AddressString(com.swiftmq.amqp.v100.generated.messaging.message_format.AddressString) Coordinator(com.swiftmq.amqp.v100.generated.transactions.coordination.Coordinator) IOException(java.io.IOException)

Example 8 with Producer

use of com.swiftmq.amqp.v100.client.Producer in project swiftmq-client by iitsoftware.

the class TransactionController method createTxnId.

/**
 * Creates a new transaction id.
 *
 * @return transaction id
 * @throws AMQPException on error
 */
public synchronized TxnIdIF createTxnId() throws AMQPException {
    if (producer == null) {
        producer = mySession.createProducer(Coordinator.DESCRIPTOR_NAME, QoS.AT_LEAST_ONCE);
        producer.setTransactionController(true);
        Set capa = producer.getDestinationCapabilities();
        if (capa != null) {
            if (capa.contains(TxnCapability.LOCAL_TRANSACTIONS.getValue()))
                supportLocalTransactions = true;
            supportDistributedTransactions = capa.contains(TxnCapability.DISTRIBUTED_TRANSACTIONS.getValue());
            supportPromotableTransactions = capa.contains(TxnCapability.PROMOTABLE_TRANSACTIONS.getValue());
            supportMultiTxnsPerSsn = capa.contains(TxnCapability.MULTI_TXNS_PER_SSN.getValue());
            supportMultiSsnsPerTxn = capa.contains(TxnCapability.MULTI_SSNS_PER_TXN.getValue());
        }
    }
    AMQPMessage msg = new AMQPMessage();
    msg.setAmqpValue(new AmqpValue(new Declare()));
    Declared declared = (Declared) producer.send(msg);
    return declared == null ? null : declared.getTxnId();
}
Also used : Set(java.util.Set) AMQPMessage(com.swiftmq.amqp.v100.messaging.AMQPMessage) AmqpValue(com.swiftmq.amqp.v100.generated.messaging.message_format.AmqpValue)

Example 9 with Producer

use of com.swiftmq.amqp.v100.client.Producer in project activemq by apache.

the class SwiftMQClientTest method testSendReceive.

@Test
public void testSendReceive() throws Exception {
    String queue = "testqueue";
    int nMsgs = 100;
    final String dataFormat = "%01024d";
    int qos = QoS.AT_MOST_ONCE;
    AMQPContext ctx = new AMQPContext(AMQPContext.CLIENT);
    try {
        Connection connection = new Connection(ctx, "127.0.0.1", port, false);
        connection.setContainerId("client");
        connection.setIdleTimeout(-1);
        connection.setMaxFrameSize(1024 * 4);
        connection.setExceptionListener(new ExceptionListener() {

            public void onException(Exception e) {
                e.printStackTrace();
            }
        });
        connection.connect();
        {
            Session session = connection.createSession(10, 10);
            Producer p = session.createProducer(queue, qos);
            for (int i = 0; i < nMsgs; i++) {
                AMQPMessage msg = new AMQPMessage();
                System.out.println("Sending " + i);
                msg.setAmqpValue(new AmqpValue(new AMQPString(String.format(dataFormat, i))));
                p.send(msg);
            }
            p.close();
            session.close();
        }
        System.out.println("=======================================================================================");
        System.out.println(" receiving ");
        System.out.println("=======================================================================================");
        {
            Session session = connection.createSession(10, 10);
            Consumer c = session.createConsumer(queue, 100, qos, true, null);
            // Receive messages non-transacted
            int i = 0;
            while (i < nMsgs) {
                AMQPMessage msg = c.receive();
                if (msg != null) {
                    final AMQPType value = msg.getAmqpValue().getValue();
                    if (value instanceof AMQPString) {
                        String s = ((AMQPString) value).getValue();
                        assertEquals(String.format(dataFormat, i), s);
                        System.out.println("Received: " + i);
                    }
                    if (!msg.isSettled())
                        msg.accept();
                    i++;
                }
            }
            c.close();
            session.close();
        }
        connection.close();
    } catch (Exception e) {
        e.printStackTrace();
    }
}
Also used : AMQPString(com.swiftmq.amqp.v100.types.AMQPString) AMQPMessage(com.swiftmq.amqp.v100.messaging.AMQPMessage) AmqpValue(com.swiftmq.amqp.v100.generated.messaging.message_format.AmqpValue) AMQPType(com.swiftmq.amqp.v100.types.AMQPType) AMQPContext(com.swiftmq.amqp.AMQPContext) AMQPString(com.swiftmq.amqp.v100.types.AMQPString) Test(org.junit.Test)

Example 10 with Producer

use of com.swiftmq.amqp.v100.client.Producer in project swiftmq-ce by iitsoftware.

the class RequestorNonTransacted method main.

public static void main(String[] args) {
    if (args.length == 1 && args[0].equals("?")) {
        System.out.println();
        System.out.println("Usage: <host> <port> <target> <nreq> <qos> <authanon> [<username> <password>]");
        System.out.println("       <qos> ::= AT_LEAST_ONCE | AT_MOST_ONCE | EXACTLY_ONCE");
        System.out.println("       Suppress <username> <password> and set <authanon> to false to avoid SASL.");
        System.out.println();
        System.exit(0);
    }
    String host = "localhost";
    int port = 5672;
    String target = "testqueue";
    int nMsgs = 100;
    String qosS = "EXACTLY_ONCE";
    boolean authAnon = true;
    String user = null;
    String password = null;
    if (args.length >= 1)
        host = args[0];
    if (args.length >= 2)
        port = Integer.parseInt(args[1]);
    if (args.length >= 3)
        target = args[2];
    if (args.length >= 4)
        nMsgs = Integer.parseInt(args[3]);
    if (args.length >= 5)
        qosS = args[4];
    if (args.length >= 6)
        authAnon = Boolean.parseBoolean(args[5]);
    if (args.length >= 7)
        user = args[6];
    if (args.length >= 8)
        password = args[7];
    System.out.println();
    System.out.println("Host        : " + host);
    System.out.println("Port        : " + port);
    System.out.println("Target      : " + target);
    System.out.println("Number Req  : " + nMsgs);
    System.out.println("QoS         : " + qosS);
    System.out.println("Auth as Anon: " + authAnon);
    System.out.println("User        : " + user);
    System.out.println("Password    : " + password);
    System.out.println();
    try {
        // Create connection and connect
        AMQPContext ctx = new AMQPContext(AMQPContext.CLIENT);
        Connection connection = null;
        if (args.length < 7)
            connection = new Connection(ctx, host, port, authAnon);
        else
            connection = new Connection(ctx, host, port, user, password);
        if (port == 5671) {
            System.out.println("Using SSL on port 5671");
            connection.setSocketFactory(new JSSESocketFactory());
        }
        connection.connect();
        // Create session and producer
        Session session = connection.createSession(50, 50);
        Producer p = session.createProducer(target, toIntQoS(qosS));
        // Create a temp queue and a consumer
        Consumer c = session.createConsumer(100, toIntQoS(qosS));
        AddressIF tempDest = c.getRemoteAddress();
        // Do request / reply
        for (int i = 0; i < nMsgs; i++) {
            // Send the request
            AMQPMessage request = new AMQPMessage();
            Properties prop = new Properties();
            prop.setReplyTo(tempDest);
            request.setProperties(prop);
            String s = "Message #" + (i + 1);
            System.out.println("Sending " + s);
            request.setAmqpValue(new AmqpValue(new AMQPString(s)));
            p.send(request);
            // Receive the reply
            AMQPMessage reply = c.receive();
            if (reply == null)
                break;
            if (!reply.isSettled())
                reply.accept();
            AmqpValue value = reply.getAmqpValue();
            System.out.println("Received: " + ((AMQPString) value.getValue()).getValue());
        }
        Thread.sleep(2000);
        // Close everything down
        c.close();
        p.close();
        session.close();
        connection.close();
    } catch (Exception e) {
        e.printStackTrace();
    }
}
Also used : AddressIF(com.swiftmq.amqp.v100.generated.messaging.message_format.AddressIF) AMQPString(com.swiftmq.amqp.v100.types.AMQPString) Properties(com.swiftmq.amqp.v100.generated.messaging.message_format.Properties) AMQPMessage(com.swiftmq.amqp.v100.messaging.AMQPMessage) AmqpValue(com.swiftmq.amqp.v100.generated.messaging.message_format.AmqpValue) AMQPContext(com.swiftmq.amqp.AMQPContext) AMQPString(com.swiftmq.amqp.v100.types.AMQPString) JSSESocketFactory(com.swiftmq.net.JSSESocketFactory)

Aggregations

AMQPMessage (com.swiftmq.amqp.v100.messaging.AMQPMessage)13 AddressIF (com.swiftmq.amqp.v100.generated.messaging.message_format.AddressIF)7 Properties (com.swiftmq.amqp.v100.generated.messaging.message_format.Properties)7 AMQPString (com.swiftmq.amqp.v100.types.AMQPString)7 Producer (com.swiftmq.amqp.v100.client.Producer)6 AmqpValue (com.swiftmq.amqp.v100.generated.messaging.message_format.AmqpValue)6 TxnIdIF (com.swiftmq.amqp.v100.generated.transactions.coordination.TxnIdIF)6 AMQPContext (com.swiftmq.amqp.AMQPContext)5 JSSESocketFactory (com.swiftmq.net.JSSESocketFactory)4 ApplicationProperties (com.swiftmq.amqp.v100.generated.messaging.message_format.ApplicationProperties)2 AMQPInt (com.swiftmq.amqp.v100.types.AMQPInt)2 IOException (java.io.IOException)2 HashMap (java.util.HashMap)2 Map (java.util.Map)2 Connection (com.swiftmq.amqp.v100.client.Connection)1 Session (com.swiftmq.amqp.v100.client.Session)1 AddressString (com.swiftmq.amqp.v100.generated.messaging.message_format.AddressString)1 Coordinator (com.swiftmq.amqp.v100.generated.transactions.coordination.Coordinator)1 TransactionalState (com.swiftmq.amqp.v100.generated.transactions.coordination.TransactionalState)1 Packager (com.swiftmq.amqp.v100.transport.Packager)1