Example usage for javax.jms Connection setClientID

List of usage examples for javax.jms Connection setClientID

Introduction

In this page you can find the example usage for javax.jms Connection setClientID.

Prototype

void setClientID(String clientID) throws JMSException;

Source Link

Document

Sets the client identifier for this connection.

Usage

From source file:org.apache.activemq.store.kahadb.SubscriptionRecoveryTest.java

private void tryConsumeExpectNone(Topic topic) throws Exception {
    Connection connection = cf.createConnection();
    connection.setClientID("Inactive");
    Session session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE);
    MessageConsumer consumer = session.createDurableSubscriber(topic, "Inactive");
    connection.start();// ww  w .j ava 2s .c  o m
    if (consumer.receive(TimeUnit.SECONDS.toMillis(10)) != null) {
        fail("Should be no messages for this durable.");
    }
    consumer.close();
    connection.close();
}

From source file:org.apache.activemq.store.kahadb.SubscriptionRecoveryTest.java

private int consumeFromInactiveDurableSub(Topic topic) throws Exception {
    Connection connection = cf.createConnection();
    connection.setClientID("Inactive");
    connection.start();//w  w  w. jav a  2 s  .c o m
    Session session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE);
    MessageConsumer consumer = session.createDurableSubscriber(topic, "Inactive");

    int count = 0;

    while (consumer.receive(10000) != null) {
        count++;
    }

    consumer.close();
    connection.close();

    return count;
}

From source file:org.apache.activemq.usecases.ConcurrentProducerDurableConsumerTest.java

protected TopicSubscriber createDurableSubscriber(Connection conn, Destination dest, String name)
        throws Exception {
    conn.setClientID(name);
    connections.add(conn);/*from w  w  w.jav a2 s  .co m*/
    conn.start();

    Session sess = conn.createSession(false, Session.AUTO_ACKNOWLEDGE);
    final TopicSubscriber consumer = sess.createDurableSubscriber((javax.jms.Topic) dest, name);

    return consumer;
}

From source file:org.apache.activemq.usecases.DurableSubscriberWithNetworkDisconnectTest.java

public void testSendOnAReceiveOnBWithTransportDisconnect() throws Exception {
    bridgeBrokers(SPOKE, HUB);/*  www  .j av  a 2 s.  c o m*/

    startAllBrokers();

    // Setup connection
    URI hubURI = brokers.get(HUB).broker.getVmConnectorURI();
    URI spokeURI = brokers.get(SPOKE).broker.getVmConnectorURI();
    ActiveMQConnectionFactory facHub = new ActiveMQConnectionFactory(hubURI);
    ActiveMQConnectionFactory facSpoke = new ActiveMQConnectionFactory(spokeURI);
    Connection conHub = facHub.createConnection();
    Connection conSpoke = facSpoke.createConnection();
    conHub.setClientID("clientHUB");
    conSpoke.setClientID("clientSPOKE");
    conHub.start();
    conSpoke.start();
    Session sesHub = conHub.createSession(false, Session.AUTO_ACKNOWLEDGE);
    Session sesSpoke = conSpoke.createSession(false, Session.AUTO_ACKNOWLEDGE);

    ActiveMQTopic topic = new ActiveMQTopic("TEST.FOO");
    String consumerName = "consumerName";

    // Setup consumers
    MessageConsumer remoteConsumer = sesSpoke.createDurableSubscriber(topic, consumerName);
    remoteConsumer.setMessageListener(new MessageListener() {
        public void onMessage(Message msg) {
            try {
                TextMessage textMsg = (TextMessage) msg;
                receivedMsgs++;
                LOG.info("Received messages (" + receivedMsgs + "): " + textMsg.getText());
            } catch (JMSException e) {
                e.printStackTrace();
            }
        }
    });

    // allow subscription information to flow back to Spoke
    sleep(1000);

    // Setup producer
    MessageProducer localProducer = sesHub.createProducer(topic);
    localProducer.setDeliveryMode(DeliveryMode.PERSISTENT);

    // Send messages
    for (int i = 0; i < MESSAGE_COUNT; i++) {
        sleep(50);
        if (i == 50 || i == 150) {
            if (simulateStalledNetwork) {
                socketProxy.pause();
            } else {
                socketProxy.close();
            }
            networkDownTimeStart = System.currentTimeMillis();
        } else if (networkDownTimeStart > 0) {
            // restart after NETWORK_DOWN_TIME seconds
            sleep(NETWORK_DOWN_TIME);
            networkDownTimeStart = 0;
            if (simulateStalledNetwork) {
                socketProxy.goOn();
            } else {
                socketProxy.reopen();
            }
        } else {
            // slow message production to allow bridge to recover and limit message duplication
            sleep(500);
        }
        Message test = sesHub.createTextMessage("test-" + i);
        localProducer.send(test);
    }

    LOG.info("waiting for messages to flow");
    Wait.waitFor(new Wait.Condition() {
        @Override
        public boolean isSatisified() throws Exception {
            return receivedMsgs >= MESSAGE_COUNT;
        }
    });

    assertTrue("At least message " + MESSAGE_COUNT + " must be received, count=" + receivedMsgs,
            MESSAGE_COUNT <= receivedMsgs);
    brokers.get(HUB).broker.deleteAllMessages();
    brokers.get(SPOKE).broker.deleteAllMessages();
    conHub.close();
    conSpoke.close();
}

From source file:org.apache.activemq.usecases.DurableSubscriberWithNetworkRestartTest.java

public void testSendOnAReceiveOnBWithTransportDisconnect() throws Exception {
    bridge(SPOKE, HUB);//from  www . ja  va2 s  .com
    startAllBrokers();

    verifyDuplexBridgeMbean();

    // Setup connection
    URI hubURI = brokers.get(HUB).broker.getTransportConnectors().get(0).getPublishableConnectURI();
    URI spokeURI = brokers.get(SPOKE).broker.getTransportConnectors().get(0).getPublishableConnectURI();
    ActiveMQConnectionFactory facHub = new ActiveMQConnectionFactory(hubURI);
    ActiveMQConnectionFactory facSpoke = new ActiveMQConnectionFactory(spokeURI);
    Connection conHub = facHub.createConnection();
    Connection conSpoke = facSpoke.createConnection();
    conHub.setClientID("clientHUB");
    conSpoke.setClientID("clientSPOKE");
    conHub.start();
    conSpoke.start();
    Session sesHub = conHub.createSession(false, Session.AUTO_ACKNOWLEDGE);
    Session sesSpoke = conSpoke.createSession(false, Session.AUTO_ACKNOWLEDGE);

    ActiveMQTopic topic = new ActiveMQTopic("TEST.FOO");
    String consumerName = "consumerName";

    // Setup consumers
    MessageConsumer remoteConsumer = sesHub.createDurableSubscriber(topic, consumerName);
    sleep(1000);
    remoteConsumer.close();

    // Setup producer
    MessageProducer localProducer = sesSpoke.createProducer(topic);
    localProducer.setDeliveryMode(DeliveryMode.PERSISTENT);

    final String payloadString = new String(new byte[10 * 1024]);
    // Send messages
    for (int i = 0; i < MESSAGE_COUNT; i++) {
        Message test = sesSpoke.createTextMessage("test-" + i);
        test.setStringProperty("payload", payloadString);
        localProducer.send(test);
    }
    localProducer.close();

    final String options = "?persistent=true&useJmx=true&deleteAllMessagesOnStartup=false";
    for (int i = 0; i < 2; i++) {
        brokers.get(SPOKE).broker.stop();
        sleep(1000);
        createBroker(new URI("broker:(tcp://localhost:61616)/" + SPOKE + options));
        bridge(SPOKE, HUB);
        brokers.get(SPOKE).broker.start();
        LOG.info("restarted spoke..:" + i);

        assertTrue("got mbeans on restart", Wait.waitFor(new Wait.Condition() {
            @Override
            public boolean isSatisified() throws Exception {
                return countMbeans(brokers.get(HUB).broker, "networkBridge", 20000) == (dynamicOnly ? 1 : 2);
            }
        }));
    }
}

From source file:org.apache.camel.component.sjms.jms.ConnectionFactoryResource.java

@Override
public Connection makeObject() throws Exception {
    Connection connection = null;
    if (connectionFactory != null) {
        if (getUsername() != null && getPassword() != null) {
            connection = connectionFactory.createConnection(getUsername(), getPassword());
        } else {/*  ww w  .java2s . c  o m*/
            connection = connectionFactory.createConnection();
        }
    }
    if (connection != null) {
        if (ObjectHelper.isNotEmpty(getClientId())) {
            connection.setClientID(getClientId());
        }
        connection.start();
    }
    return connection;
}

From source file:org.codehaus.stomp.jms.ProtocolConverter.java

protected void onStompConnect(StompFrame command) throws IOException, JMSException {
    if (noneXaSession != null) {
        throw new ProtocolException("Already connected.");
    }//from   www.  j  a  v a2 s.c o m

    Map<String, Object> headers = command.getHeaders();
    login = (String) headers.get(Stomp.Headers.Connect.LOGIN);
    passcode = (String) headers.get(Stomp.Headers.Connect.PASSCODE);
    clientId = (String) headers.get(Stomp.Headers.Connect.CLIENT_ID);

    Connection noneXaConnection;
    if (login != null) {
        noneXaConnection = noneXAConnectionFactory.createConnection(login, passcode);
    } else {
        noneXaConnection = noneXAConnectionFactory.createConnection();
    }
    if (clientId != null) {
        noneXaConnection.setClientID(clientId);
    }

    noneXaConnection.start();

    Session session = noneXaConnection.createSession(false, Session.CLIENT_ACKNOWLEDGE);
    if (log.isDebugEnabled()) {
        log.debug("Created session with ack mode: " + session.getAcknowledgeMode());
    }
    this.noneXaSession = new StompSession(initialContext, this, session, noneXaConnection);

    Map<String, Object> responseHeaders = new HashMap<String, Object>();

    responseHeaders.put(Stomp.Headers.Connected.SESSION, clientId);
    String requestId = (String) headers.get(Stomp.Headers.Connect.REQUEST_ID);
    if (requestId == null) {
        // TODO legacy
        requestId = (String) headers.get(Stomp.Headers.RECEIPT_REQUESTED);
    }
    if (requestId != null) {
        // TODO legacy
        responseHeaders.put(Stomp.Headers.Connected.RESPONSE_ID, requestId);
        responseHeaders.put(Stomp.Headers.Response.RECEIPT_ID, requestId);
    }

    StompFrame sc = new StompFrame();
    sc.setAction(Stomp.Responses.CONNECTED);
    sc.setHeaders(responseHeaders);
    sendToStomp(sc);
}

From source file:org.openhie.openempi.notification.impl.NotificationServiceImpl.java

public void registerListener(List<String> eventTypeNames, MessageHandler handler) {
    if (brokerService == null || !brokerInitialized) {
        log.debug("The broker service is not running in registerListener.");
        return;//ww w . j av  a 2  s . c  o m
    }

    if (!isValidHandler(handler)) {
        return;
    }

    ConnectionFactory connectionFactory = jmsTemplate.getConnectionFactory();
    Connection connection = null;
    try {
        connection = connectionFactory.createConnection();
        connection.setClientID(handler.getClientId());
    } catch (JMSException e) {
        log.error("Failed while setting up a registrant for notification events. Error: " + e, e);
        throw new RuntimeException("Unable to setup registration for event notification: " + e.getMessage());
    }

    for (String eventTypeName : eventTypeNames) {
        log.info("Registering handler for event " + eventTypeName);
        Topic topic = topicMap.get(eventTypeName);
        if (topic == null) {
            log.error("Caller attempted to register interest to events of unknown type " + eventTypeName);
            throw new RuntimeException("Unknown event type specified in registration request.");
        }

        if (isListenerRegistered(handler, eventTypeName)) {
            log.warn("Caller attempted to register interest for the same event again.");
            return;
        }

        try {
            Session topicSession = connection.createSession(false, Session.AUTO_ACKNOWLEDGE);
            TopicSubscriber subscriber = topicSession.createDurableSubscriber(topic, topic.getTopicName());
            MessageListenerImpl listener = new MessageListenerImpl(connection, topicSession, subscriber,
                    handler);
            saveListenerRegistration(listener, eventTypeName);
            subscriber.setMessageListener(listener);
        } catch (JMSException e) {
            log.error("Failed while setting up a registrant for notification events. Error: " + e, e);
            throw new RuntimeException(
                    "Unable to setup registration for event notification: " + e.getMessage());
        }
    }

    try {
        connection.start();
    } catch (JMSException e) {
        log.error("Failed while setting up a registrant for notification events. Error: " + e, e);
        throw new RuntimeException("Unable to setup registration for event notification: " + e.getMessage());
    }
}

From source file:org.sakaiproject.kernel.messaging.email.EmailMessagingService.java

@Inject
public EmailMessagingService(@Named(KernelConstants.JMS_BROKER_URL) String brokerUrl,
        @Named(KernelConstants.JMS_EMAIL_QUEUE) String emailQueueName,
        @Named(KernelConstants.JMS_EMAIL_TYPE) String emailJmsType, JCRNodeFactoryService jcrNodeFactory,
        MessageConverter msgConverter, Injector injector, UserFactoryService userFactory) {
    super(jcrNodeFactory, msgConverter, injector, userFactory);
    connectionFactory = new ActiveMQConnectionFactory(brokerUrl);
    try {/*from   www  .j  a v  a 2  s  .c  o m*/
        // prob want to use username,pw here
        Connection conn = connectionFactory.createTopicConnection();
        conn.setClientID("kernel.email1");
        connections.add(conn);
    } catch (JMSException e) {
        connectionFactory = null;
        try {
            throw e;
        } catch (JMSException e1) {
            e1.printStackTrace();
        }
    }

    startConnections();
    createSessions();

}

From source file:org.sakaiproject.kernel.messaging.email.EmailMessagingService.java

public String send(Email email) throws MessagingException, JMSException {
    try {/*from  w  ww  .  j a va 2  s.c om*/
        email.buildMimeMessage();
    } catch (Exception e) {
        // this is a lossy cast. This would be a commons EmailException
        // this up cast is to keep commons-email out of our direct bindings
        throw new MessagingException(e);
    }

    ByteArrayOutputStream os = new ByteArrayOutputStream();
    try {
        email.getMimeMessage().writeTo(os);
    } catch (javax.mail.MessagingException e) {
        throw new MessagingException(e);

    } catch (IOException e) {
        throw new MessagingException(e);
    }

    String content = os.toString();
    Connection conn = connectionFactory.createTopicConnection();
    conn.setClientID(getNextId());
    Session clientSession = conn.createSession(false, Session.AUTO_ACKNOWLEDGE);
    Destination emailTopic = clientSession.createTopic(emailQueueName);
    MessageProducer client = clientSession.createProducer(emailTopic);
    ObjectMessage mesg = clientSession.createObjectMessage(content);
    mesg.setJMSType(emailJmsType);
    client.send(mesg);
    // TODO finish this
    return null;

}