Search in sources :

Example 11 with MessageListener

use of javax.jms.MessageListener in project microservice_framework by CJSCommonPlatform.

the class MessageListenerCodeGenerator method classSpecFrom.

/**
 * Generate the @link MessageListener} class implementation.
 *
 * @param subscriptionDescriptor    the subscription descriptor
 * @param subscription              the subscription
 * @param commonGeneratorProperties used to query the generator properties
 * @param classNameFactory          creates the class name for this generated class
 * @return the {@link TypeSpec.Builder} that defines the class
 */
private TypeSpec.Builder classSpecFrom(final SubscriptionDescriptor subscriptionDescriptor, final Subscription subscription, final CommonGeneratorProperties commonGeneratorProperties, final ClassNameFactory classNameFactory) {
    final String serviceComponent = subscriptionDescriptor.getServiceComponent().toUpperCase();
    if (componentDestinationType.isSupported(serviceComponent)) {
        final ClassName className = classNameFactory.classNameFor(JMS_LISTENER);
        String destination = destinationFromJmsUri(subscription.getEventsource().getLocation().getJmsUri());
        final TypeSpec.Builder typeSpecBuilder = classBuilder(className).addModifiers(PUBLIC).addSuperinterface(MessageListener.class).addField(FieldSpec.builder(ClassName.get(Logger.class), LOGGER_FIELD).addModifiers(PRIVATE, STATIC, FINAL).initializer("$T.getLogger($L.class)", LoggerFactory.class, className).build()).addField(FieldSpec.builder(ClassName.get(InterceptorChainProcessor.class), INTERCEPTOR_CHAIN_PROCESS).addAnnotation(Inject.class).build()).addField(FieldSpec.builder(ClassName.get(JmsProcessor.class), JMS_PROCESSOR_FIELD).addAnnotation(Inject.class).build()).addAnnotation(AnnotationSpec.builder(Adapter.class).addMember(DEFAULT_ANNOTATION_PARAMETER, "$S", serviceComponent).build()).addAnnotation(messageDrivenAnnotation(serviceComponent, subscriptionDescriptor.getService(), subscription));
        if (!subscription.getEvents().isEmpty()) {
            AnnotationSpec.Builder builder = AnnotationSpec.builder(Interceptors.class).addMember(DEFAULT_ANNOTATION_PARAMETER, CLASS_NAME, JmsLoggerMetadataInterceptor.class).addMember(DEFAULT_ANNOTATION_PARAMETER, CLASS_NAME, getValidationInterceptorClassName(classNameFactory, serviceComponent, subscription.getEvents()));
            typeSpecBuilder.addAnnotation(builder.build());
        }
        if (shouldAddCustomPoolConfiguration(commonGeneratorProperties)) {
            typeSpecBuilder.addAnnotation(AnnotationSpec.builder(Pool.class).addMember(DEFAULT_ANNOTATION_PARAMETER, "$S", poolNameFrom(destination, serviceComponent)).build());
        }
        return typeSpecBuilder;
    }
    throw new IllegalStateException(format("JMS Endpoint generation is unsupported for framework component type %s", serviceComponent));
}
Also used : Inject(javax.inject.Inject) JmsLoggerMetadataInterceptor(uk.gov.justice.services.adapter.messaging.JmsLoggerMetadataInterceptor) MessageListener(javax.jms.MessageListener) InterceptorChainProcessor(uk.gov.justice.services.core.interceptor.InterceptorChainProcessor) Logger(org.slf4j.Logger) AnnotationSpec(com.squareup.javapoet.AnnotationSpec) ClassName(com.squareup.javapoet.ClassName) Pool(org.jboss.ejb3.annotation.Pool) TypeSpec(com.squareup.javapoet.TypeSpec)

Example 12 with MessageListener

use of javax.jms.MessageListener in project microservice_framework by CJSCommonPlatform.

the class SubscriptionJmsEndpointGeneratorTest method shouldCallJmsProcessorWhenOnMessageIsInvoked.

@Test
@SuppressWarnings("unchecked")
public void shouldCallJmsProcessorWhenOnMessageIsInvoked() throws Exception {
    SubscriptionDescriptor subscriptionDescriptor = setUpMessageSubscription("jms:topic:somecontext.controller.command", "somecontext.command1", serviceName, componentName);
    generator.run(subscriptionDescriptor, configurationWithBasePackage(BASE_PACKAGE, outputFolder, generatorProperties));
    Class<?> clazz = compiler.compiledClassOf(BASE_PACKAGE, "ContextEventProcessorSomecontextControllerCommandJmsListener");
    Object object = instantiate(clazz);
    assertThat(object, is(instanceOf(MessageListener.class)));
    MessageListener jmsListener = (MessageListener) object;
    Message message = mock(Message.class);
    jmsListener.onMessage(message);
    ArgumentCaptor<Consumer> consumerCaptor = ArgumentCaptor.forClass(Consumer.class);
    verify(jmsProcessor).process(consumerCaptor.capture(), eq(message));
    JsonEnvelope envelope = mock(JsonEnvelope.class);
    final InterceptorContext interceptorContext = interceptorContextWithInput(envelope);
    consumerCaptor.getValue().accept(interceptorContext);
    verify(interceptorChainProcessor).process(interceptorContext);
}
Also used : Message(javax.jms.Message) Consumer(java.util.function.Consumer) InterceptorContext(uk.gov.justice.services.core.interceptor.InterceptorContext) MessageListener(javax.jms.MessageListener) JsonEnvelope(uk.gov.justice.services.messaging.JsonEnvelope) SubscriptionDescriptor(uk.gov.justice.subscription.domain.SubscriptionDescriptor) Test(org.junit.Test)

Example 13 with MessageListener

use of javax.jms.MessageListener in project spring-integration by spring-projects.

the class SubscribableJmsChannel method onInit.

@Override
public void onInit() throws Exception {
    if (this.initialized) {
        return;
    }
    super.onInit();
    boolean isPubSub = this.container.isPubSubDomain();
    this.configureDispatcher(isPubSub);
    MessageListener listener = new DispatchingMessageListener(this.getJmsTemplate(), this.dispatcher, this, isPubSub, this.getMessageBuilderFactory());
    this.container.setMessageListener(listener);
    if (!this.container.isActive()) {
        this.container.afterPropertiesSet();
    }
    this.initialized = true;
}
Also used : MessageListener(javax.jms.MessageListener)

Example 14 with MessageListener

use of javax.jms.MessageListener in project activemq-artemis by apache.

the class ActiveMQMessageHandler method onMessage.

@Override
public void onMessage(final ClientMessage message) {
    if (logger.isTraceEnabled()) {
        logger.trace("onMessage(" + message + ")");
    }
    ActiveMQMessage msg = ActiveMQMessage.createMessage(message, session, options);
    boolean beforeDelivery = false;
    try {
        if (activation.getActivationSpec().getTransactionTimeout() > 0 && tm != null) {
            tm.setTransactionTimeout(activation.getActivationSpec().getTransactionTimeout());
        }
        if (logger.isTraceEnabled()) {
            logger.trace("HornetQMessageHandler::calling beforeDelivery on message " + message);
        }
        endpoint.beforeDelivery(ActiveMQActivation.ONMESSAGE);
        beforeDelivery = true;
        msg.doBeforeReceive();
        if (transacted) {
            message.individualAcknowledge();
        }
        ((MessageListener) endpoint).onMessage(msg);
        if (!transacted) {
            message.individualAcknowledge();
        }
        if (logger.isTraceEnabled()) {
            logger.trace("HornetQMessageHandler::calling afterDelivery on message " + message);
        }
        try {
            endpoint.afterDelivery();
        } catch (ResourceException e) {
            ActiveMQRALogger.LOGGER.unableToCallAfterDelivery(e);
            // If we get here, The TX was already rolled back
            // However we must do some stuff now to make sure the client message buffer is cleared
            // so we mark this as rollbackonly
            session.markRollbackOnly();
            return;
        }
        if (useLocalTx) {
            session.commit();
        }
        if (logger.isTraceEnabled()) {
            logger.trace("finished onMessage on " + message);
        }
    } catch (Throwable e) {
        ActiveMQRALogger.LOGGER.errorDeliveringMessage(e);
        // we need to call before/afterDelivery as a pair
        if (beforeDelivery) {
            if (useXA && tm != null) {
                // this is to avoid a scenario where afterDelivery would kick in
                try {
                    Transaction tx = tm.getTransaction();
                    if (tx != null) {
                        tx.setRollbackOnly();
                    }
                } catch (Exception e1) {
                    ActiveMQRALogger.LOGGER.unableToClearTheTransaction(e1);
                }
            }
            MessageEndpoint endToUse = endpoint;
            try {
                // to avoid a NPE that would happen while the RA is in tearDown
                if (endToUse != null) {
                    endToUse.afterDelivery();
                }
            } catch (ResourceException e1) {
                ActiveMQRALogger.LOGGER.unableToCallAfterDelivery(e1);
            }
        }
        if (useLocalTx || !activation.isDeliveryTransacted()) {
            try {
                session.rollback(true);
            } catch (ActiveMQException e1) {
                ActiveMQRALogger.LOGGER.unableToRollbackTX();
            }
        }
        // This is to make sure we will issue a rollback after failures
        // so that would cleanup consumer buffers among other things
        session.markRollbackOnly();
    } finally {
        try {
            session.resetIfNeeded();
        } catch (ActiveMQException e) {
            ActiveMQRALogger.LOGGER.unableToResetSession(activation.toString(), e);
            activation.startReconnectThread("Reset MessageHandler after Failure Thread");
        }
    }
}
Also used : MessageEndpoint(javax.resource.spi.endpoint.MessageEndpoint) Transaction(javax.transaction.Transaction) ActiveMQException(org.apache.activemq.artemis.api.core.ActiveMQException) MessageListener(javax.jms.MessageListener) ResourceException(javax.resource.ResourceException) ResourceException(javax.resource.ResourceException) ActiveMQException(org.apache.activemq.artemis.api.core.ActiveMQException) ActiveMQMessage(org.apache.activemq.artemis.jms.client.ActiveMQMessage)

Example 15 with MessageListener

use of javax.jms.MessageListener in project activemq-artemis by apache.

the class JmsSendWithAsyncCallbackTest method testAsyncCallbackIsFaster.

public void testAsyncCallbackIsFaster() throws JMSException, InterruptedException {
    connection.start();
    Session session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE);
    Queue queue = session.createQueue(getName());
    // setup a consumer to drain messages..
    MessageConsumer consumer = session.createConsumer(queue);
    consumer.setMessageListener(new MessageListener() {

        @Override
        public void onMessage(Message message) {
        }
    });
    // warmup...
    for (int i = 0; i < 10; i++) {
        benchmarkNonCallbackRate();
        benchmarkCallbackRate();
    }
    double callbackRate = benchmarkCallbackRate();
    double nonCallbackRate = benchmarkNonCallbackRate();
    LOG.info(String.format("AsyncCallback Send rate: %,.2f m/s", callbackRate));
    LOG.info(String.format("NonAsyncCallback Send rate: %,.2f m/s", nonCallbackRate));
    // The async style HAS to be faster than the non-async style..
    assertTrue("async rate[" + callbackRate + "] should beat non-async rate[" + nonCallbackRate + "]", callbackRate / nonCallbackRate > 1.5);
}
Also used : MessageConsumer(javax.jms.MessageConsumer) Message(javax.jms.Message) MessageListener(javax.jms.MessageListener) Queue(javax.jms.Queue) Session(javax.jms.Session)

Aggregations

MessageListener (javax.jms.MessageListener)146 Message (javax.jms.Message)128 MessageConsumer (javax.jms.MessageConsumer)103 Session (javax.jms.Session)97 TextMessage (javax.jms.TextMessage)95 CountDownLatch (java.util.concurrent.CountDownLatch)72 Test (org.junit.Test)71 Connection (javax.jms.Connection)60 MessageProducer (javax.jms.MessageProducer)58 JMSException (javax.jms.JMSException)57 Destination (javax.jms.Destination)32 AtomicInteger (java.util.concurrent.atomic.AtomicInteger)31 ActiveMQConnectionFactory (org.apache.activemq.ActiveMQConnectionFactory)26 BytesMessage (javax.jms.BytesMessage)22 Queue (javax.jms.Queue)21 ConnectionFactory (javax.jms.ConnectionFactory)16 ScheduledMessage (org.apache.activemq.ScheduledMessage)15 ArrayList (java.util.ArrayList)14 Topic (javax.jms.Topic)13 ActiveMQQueue (org.apache.activemq.command.ActiveMQQueue)13