JmsRequestProcessor.java

/*
 * Copyright (C) 2012-2024 RRiBbit.org
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 * https://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package org.rribbit.processing;

import java.io.Serializable;

import jakarta.jms.JMSException;
import jakarta.jms.Message;
import jakarta.jms.MessageListener;
import jakarta.jms.ObjectMessage;

import org.rribbit.Request;
import org.rribbit.execution.ListenerObjectExecutor;
import org.rribbit.retrieval.ListenerObjectRetriever;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

/**
 * This {@link RequestProcessor} handles {@link Request}s that are sent over JMS.
 *
 * @author G.J. Schouten
 *
 */
public class JmsRequestProcessor extends LocalRequestProcessor implements MessageListener {

	private static final Logger log = LoggerFactory.getLogger(JmsRequestProcessor.class);

	/**
	 * Whenever you use this constructor, be sure to set the {@link ListenerObjectRetriever} AND the {@link ListenerObjectExecutor} with the setters provided by
	 * {@link LocalRequestProcessor}. If you don't, runtime {@link NullPointerException}s will occur.
	 */
	public JmsRequestProcessor() {}

	/**
	 * This constructor is recommended, since it forces you to specify the {@link ListenerObjectRetriever} and {@link ListenerObjectExecutor}. Passing a null value for either
	 * of these will result in a runtime {@link NullPointerException} whenever the {@link JmsRequestProcessor} is used.
	 *
	 * @param listenerObjectRetriever
	 * @param listenerObjectExecutor
	 */
	public JmsRequestProcessor(ListenerObjectRetriever listenerObjectRetriever, ListenerObjectExecutor listenerObjectExecutor) {
		super(listenerObjectRetriever, listenerObjectExecutor);
	}

	@Override
	public void onMessage(Message message) {

		log.info("Received Message");
		if(message instanceof ObjectMessage) {
			try {
				Serializable object = ((ObjectMessage) message).getObject();
				if(object instanceof Request) {
					this.processRequest((Request) object); //Ignore the response, since JMS is one-direction only
				} else {
					throw new IllegalArgumentException("Object must be of type Request");
				}
			} catch(JMSException e) {
				throw new RuntimeException(e);
			}
		} else {
			throw new IllegalArgumentException("Message must be of type ObjectMessage");
		}
	}
}