ARTEMIS-735 Refactoring of JUnit Tests in artemis-rest

This commit is contained in:
Bennet Schulz 2016-09-16 14:14:44 +02:00 committed by Clebert Suconic
parent af676d2081
commit 0cd84d96ba
12 changed files with 250 additions and 658 deletions

View File

@ -1,174 +0,0 @@
/*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You 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
*
* http://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.apache.activemq.artemis.rest;
import javax.jms.BytesMessage;
import javax.jms.JMSException;
import javax.jms.Message;
import javax.jms.ObjectMessage;
import javax.ws.rs.core.MediaType;
import javax.ws.rs.ext.MessageBodyReader;
import javax.ws.rs.ext.Providers;
import java.io.ByteArrayInputStream;
import java.lang.reflect.Type;
import org.apache.activemq.artemis.rest.util.HttpMessageHelper;
import org.jboss.resteasy.core.Headers;
import org.jboss.resteasy.spi.ResteasyProviderFactory;
import org.jboss.resteasy.util.GenericType;
public class Jms {
/**
* Set a JMS Message property to the value of an HTTP header
*
* @param message
* @param name
* @param value
*/
public static void setHttpHeader(Message message, String name, String value) {
try {
message.setStringProperty(HttpHeaderProperty.toPropertyName(name), value);
} catch (JMSException e) {
throw new RuntimeException(e);
}
}
/**
* Get an HTTP header value from a JMS Message
*
* @param message
* @param name
* @return the header or {@code null} if not present
*/
public static String getHttpHeader(Message message, String name) {
try {
return message.getStringProperty(HttpHeaderProperty.toPropertyName(name));
} catch (JMSException e) {
throw new RuntimeException(e);
}
}
/**
* Extract an object using a built-in RESTEasy JAX-RS MessageBodyReader
*
* @param message
* @param type
* @param <T>
* @return
*/
public static <T> T getEntity(Message message, Class<T> type) {
return getEntity(message, type, null, ResteasyProviderFactory.getInstance());
}
/**
* Extract an object using a built-in RESTEasy JAX-RS MessageBodyReader
*
* @param message
* @param type
* @param factory
* @param <T>
* @return
*/
public static <T> T getEntity(Message message, Class<T> type, ResteasyProviderFactory factory) {
return getEntity(message, type, null, factory);
}
/**
* Extract an object using a built-in RESTEasy JAX-RS MessageBodyReader
*
* @param message
* @param type
* @param factory
* @param <T>
* @return
* @throws UnknownMediaType
* @throws UnmarshalException
*/
public static <T> T getEntity(Message message,
GenericType<T> type,
ResteasyProviderFactory factory) throws UnknownMediaType {
return getEntity(message, type.getType(), type.getGenericType(), factory);
}
public static boolean isHttpMessage(Message message) {
try {
return message.getBooleanProperty(HttpMessageHelper.POSTED_AS_HTTP_MESSAGE);
} catch (JMSException e) {
return false;
}
}
/**
* Extract an object using a built-in RESTEasy JAX-RS MessageBodyReader
*
* @param message
* @param type
* @param genericType
* @param factory
* @param <T>
* @return
* @throws UnknownMediaType
* @throws UnmarshalException
*/
public static <T> T getEntity(Message message,
Class<T> type,
Type genericType,
ResteasyProviderFactory factory) throws UnknownMediaType {
if (!isHttpMessage(message)) {
try {
return (T) ((ObjectMessage) message).getObject();
} catch (JMSException e) {
throw new RuntimeException(e);
}
}
BytesMessage bytesMessage = (BytesMessage) message;
try {
long size = bytesMessage.getBodyLength();
if (size <= 0) {
return null;
}
byte[] body = new byte[(int) size];
bytesMessage.readBytes(body);
String contentType = message.getStringProperty(HttpHeaderProperty.CONTENT_TYPE);
if (contentType == null) {
throw new UnknownMediaType("Message did not have a Content-Type header cannot extract entity");
}
MediaType ct = MediaType.valueOf(contentType);
MessageBodyReader<T> reader = factory.getMessageBodyReader(type, genericType, null, ct);
if (reader == null) {
throw new UnmarshalException("Unable to find a JAX-RS reader for type " + type.getName() + " and media type " + contentType);
}
Providers current = ResteasyProviderFactory.getContextData(Providers.class);
ResteasyProviderFactory.pushContext(Providers.class, factory);
try {
return reader.readFrom(type, genericType, null, ct, new Headers<String>(), new ByteArrayInputStream(body));
} finally {
ResteasyProviderFactory.popContextData(Providers.class);
if (current != null)
ResteasyProviderFactory.pushContext(Providers.class, current);
}
} catch (Exception e) {
throw new RuntimeException(e);
}
}
}

View File

@ -46,14 +46,14 @@ import org.apache.activemq.artemis.utils.XMLUtil;
public class MessageServiceManager {
protected ExecutorService threadPool;
protected QueueServiceManager queueManager;
protected TopicServiceManager topicManager;
protected TimeoutTask timeoutTask;
protected int timeoutTaskInterval = 1;
private ExecutorService threadPool;
private QueueServiceManager queueManager;
private TopicServiceManager topicManager;
private TimeoutTask timeoutTask;
private int timeoutTaskInterval = 1;
protected MessageServiceConfiguration configuration = new MessageServiceConfiguration();
protected boolean configSet = false;
protected String configResourcePath;
private boolean configSet = false;
private String configResourcePath;
protected BindingRegistry registry;
private ClientSessionFactory consumerSessionFactory;
@ -116,14 +116,13 @@ public class MessageServiceManager {
}
public void start() throws Exception {
if (configuration == null || configSet == false) {
if (configuration == null || !configSet) {
if (configResourcePath == null) {
configuration = new MessageServiceConfiguration();
} else {
URL url = getClass().getClassLoader().getResource(configResourcePath);
if (url == null) {
// The URL is outside of the classloader. Trying a pure url now
if (isOutsideOfClassloader(url)) {
url = new URL(configResourcePath);
}
JAXBContext jaxb = JAXBContext.newInstance(MessageServiceConfiguration.class);
@ -161,7 +160,7 @@ public class MessageServiceManager {
ClientSessionFactory sessionFactory = defaultLocator.createSessionFactory();
LinkStrategy linkStrategy = new LinkHeaderLinkStrategy();
LinkStrategy linkStrategy;
if (configuration.isUseLinkHeaders()) {
linkStrategy = new LinkHeaderLinkStrategy();
} else {
@ -196,6 +195,10 @@ public class MessageServiceManager {
topicManager.start();
}
private boolean isOutsideOfClassloader(URL url) {
return url == null;
}
public void stop() {
if (queueManager != null)
queueManager.stop();

View File

@ -22,13 +22,13 @@ import org.apache.activemq.artemis.rest.MessageServiceManager;
import org.jboss.resteasy.plugins.server.tjws.TJWSEmbeddedJaxrsServer;
import org.jboss.resteasy.test.TestPortProvider;
public class EmbeddedRestActiveMQ {
class EmbeddedRestActiveMQ {
protected TJWSEmbeddedJaxrsServer tjws = new TJWSEmbeddedJaxrsServer();
protected EmbeddedActiveMQ embeddedActiveMQ;
protected MessageServiceManager manager = new MessageServiceManager(null);
private TJWSEmbeddedJaxrsServer tjws = new TJWSEmbeddedJaxrsServer();
EmbeddedActiveMQ embeddedActiveMQ;
private MessageServiceManager manager = new MessageServiceManager(null);
public EmbeddedRestActiveMQ(ConnectionFactoryOptions jmsOptions) {
EmbeddedRestActiveMQ(ConnectionFactoryOptions jmsOptions) {
int port = TestPortProvider.getPort();
tjws.setPort(port);
tjws.setRootResourcePath("");
@ -41,19 +41,7 @@ public class EmbeddedRestActiveMQ {
embeddedActiveMQ = new EmbeddedActiveMQ();
}
public TJWSEmbeddedJaxrsServer getTjws() {
return tjws;
}
public void setTjws(TJWSEmbeddedJaxrsServer tjws) {
this.tjws = tjws;
}
public EmbeddedActiveMQ getEmbeddedActiveMQ() {
return embeddedActiveMQ;
}
public MessageServiceManager getManager() {
MessageServiceManager getManager() {
return manager;
}

View File

@ -20,9 +20,9 @@ import org.apache.activemq.artemis.jms.client.ConnectionFactoryOptions;
import org.apache.activemq.artemis.jms.server.embedded.EmbeddedJMS;
import org.apache.activemq.artemis.spi.core.naming.BindingRegistry;
public class EmbeddedRestActiveMQJMS extends EmbeddedRestActiveMQ {
class EmbeddedRestActiveMQJMS extends EmbeddedRestActiveMQ {
public EmbeddedRestActiveMQJMS(ConnectionFactoryOptions jmsOptions) {
EmbeddedRestActiveMQJMS(ConnectionFactoryOptions jmsOptions) {
super(jmsOptions);
}
@ -31,13 +31,11 @@ public class EmbeddedRestActiveMQJMS extends EmbeddedRestActiveMQ {
embeddedActiveMQ = new EmbeddedJMS();
}
public BindingRegistry getRegistry() {
if (embeddedActiveMQ == null)
return null;
BindingRegistry getRegistry() {
return ((EmbeddedJMS) embeddedActiveMQ).getRegistry();
}
public EmbeddedJMS getEmbeddedJMS() {
EmbeddedJMS getEmbeddedJMS() {
return (EmbeddedJMS) embeddedActiveMQ;
}
}

View File

@ -22,9 +22,9 @@ import java.util.List;
import org.apache.activemq.artemis.rest.queue.push.FilePushStore;
import org.apache.activemq.artemis.rest.queue.push.xml.PushRegistration;
public class FileTopicPushStore extends FilePushStore implements TopicPushStore {
class FileTopicPushStore extends FilePushStore implements TopicPushStore {
public FileTopicPushStore(String dirname) throws Exception {
FileTopicPushStore(String dirname) throws Exception {
super(dirname);
}

View File

@ -0,0 +1,211 @@
/*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You 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
*
* http://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.apache.activemq.artemis.rest.integration;
import javax.jms.Connection;
import javax.jms.ConnectionFactory;
import javax.jms.Destination;
import javax.jms.JMSException;
import javax.jms.MessageProducer;
import javax.jms.ObjectMessage;
import javax.jms.Session;
import java.io.Serializable;
import java.util.ArrayList;
import java.util.List;
import org.apache.activemq.artemis.api.jms.JMSFactoryType;
import org.apache.activemq.artemis.core.config.impl.SecurityConfiguration;
import org.apache.activemq.artemis.rest.HttpHeaderProperty;
import org.apache.activemq.artemis.rest.test.TransformTest;
import org.apache.activemq.artemis.spi.core.naming.BindingRegistry;
import org.apache.activemq.artemis.spi.core.security.ActiveMQJAASSecurityManager;
import org.apache.activemq.artemis.spi.core.security.jaas.InVMLoginModule;
import org.jboss.resteasy.client.ClientRequest;
import org.jboss.resteasy.client.ClientResponse;
import org.jboss.resteasy.spi.Link;
import org.jboss.resteasy.test.TestPortProvider;
import org.apache.activemq.artemis.rest.test.Util;
import org.junit.AfterClass;
import org.junit.BeforeClass;
import org.junit.Test;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertNotNull;
public class EmbeddedRestActiveMQJMSTest {
private static EmbeddedRestActiveMQJMS server;
private static Link consumeNext;
@BeforeClass
public static void startEmbedded() throws Exception {
server = new EmbeddedRestActiveMQJMS(null);
assertNotNull(server.embeddedActiveMQ);
server.getManager().setConfigResourcePath("activemq-rest.xml");
SecurityConfiguration securityConfiguration = createDefaultSecurityConfiguration();
ActiveMQJAASSecurityManager securityManager = new ActiveMQJAASSecurityManager(InVMLoginModule.class.getName(), securityConfiguration);
server.getEmbeddedJMS().setSecurityManager(securityManager);
server.start();
List<String> connectors = createInVmConnector();
server.getEmbeddedJMS().getJMSServerManager().createConnectionFactory("ConnectionFactory", false, JMSFactoryType.CF, connectors, "ConnectionFactory");
ClientRequest request = new ClientRequest(TestPortProvider.generateURL("/queues/jms.queue.exampleQueue"));
ClientResponse<?> response = request.head();
response.releaseConnection();
assertEquals(200, response.getStatus());
Link sender = response.getLinkHeader().getLinkByTitle("create");
System.out.println("create: " + sender);
Link consumers = response.getLinkHeader().getLinkByTitle("pull-consumers");
System.out.println("pull: " + consumers);
response = Util.setAutoAck(consumers, true);
consumeNext = response.getLinkHeader().getLinkByTitle("consume-next");
System.out.println("consume-next: " + consumeNext);
}
private static List<String> createInVmConnector() {
List<String> connectors = new ArrayList<>();
connectors.add("in-vm");
return connectors;
}
@AfterClass
public static void stopEmbedded() throws Exception {
server.stop();
server = null;
}
@Test
public void shouldReturnStatusOK() throws Exception {
TransformTest.Order order = createTestOrder("1", "$5.00");
publish("exampleQueue", order, null);
ClientResponse<?> res = consumeNext.request().header("Accept-Wait", "2").accept("application/xml").post(String.class);
assertEquals(200, res.getStatus());
res.releaseConnection();
}
@Test
public void shouldReturnPublishedEntity() throws Exception {
TransformTest.Order order = createTestOrder("1", "$5.00");
publish("exampleQueue", order, null);
ClientResponse<?> res = consumeNext.request().header("Accept-Wait", "2").accept("application/xml").post(String.class);
TransformTest.Order order2 = res.getEntity(TransformTest.Order.class);
assertEquals(order, order2);
res.releaseConnection();
}
@Test
public void shouldReturnLink() throws Exception {
TransformTest.Order order = createTestOrder("1", "$5.00");
publish("exampleQueue", order, null);
ClientResponse<?> res = consumeNext.request().header("Accept-Wait", "2").accept("application/xml").post(String.class);
consumeNext = res.getLinkHeader().getLinkByTitle("consume-next");
res.releaseConnection();
assertNotNull(consumeNext);
}
@Test
public void shouldUseXmlAcceptHeaderToSetContentType() throws Exception {
TransformTest.Order order = createTestOrder("1", "$5.00");
publish("exampleQueue", order, null);
ClientResponse<?> res = consumeNext.request().header("Accept-Wait", "2").accept("application/xml").post(String.class);
assertEquals("application/xml", res.getHeaders().getFirst("Content-Type").toString().toLowerCase());
consumeNext = res.getLinkHeader().getLinkByTitle("consume-next");
res.releaseConnection();
assertNotNull(consumeNext);
}
@Test
public void shouldUseMessagePropertyToSetContentType() throws Exception {
TransformTest.Order order = createTestOrder("2", "$15.00");
publish("exampleQueue", order, "application/xml");
ClientResponse<?> res = consumeNext.request().header("Accept-Wait", "2").post(String.class);
assertEquals("application/xml", res.getHeaders().getFirst("Content-Type").toString().toLowerCase());
consumeNext = res.getLinkHeader().getLinkByTitle("consume-next");
res.releaseConnection();
assertNotNull(consumeNext);
}
@Test
public void shouldUseJsonAcceptHeaderToSetContentType() throws Exception {
TransformTest.Order order = createTestOrder("1", "$5.00");
publish("exampleQueue", order, null);
ClientResponse<?> res = consumeNext.request().header("Accept-Wait", "2").accept("application/json").post(String.class);
assertEquals("application/json", res.getHeaders().getFirst("Content-Type").toString().toLowerCase());
consumeNext = res.getLinkHeader().getLinkByTitle("consume-next");
res.releaseConnection();
assertNotNull(consumeNext);
}
private static Connection createConnection() throws JMSException {
BindingRegistry reg = server.getRegistry();
ConnectionFactory factory = (ConnectionFactory) reg.lookup("ConnectionFactory");
return factory.createConnection();
}
private static SecurityConfiguration createDefaultSecurityConfiguration() {
SecurityConfiguration securityConfiguration = new SecurityConfiguration();
securityConfiguration.addUser("guest", "guest");
securityConfiguration.addRole("guest", "guest");
securityConfiguration.setDefaultUser("guest");
return securityConfiguration;
}
private TransformTest.Order createTestOrder(String name, String amount) {
TransformTest.Order order = new TransformTest.Order();
order.setName(name);
order.setAmount(amount);
return order;
}
private static void publish(String destination, Serializable object, String contentType) throws Exception {
Connection conn = createConnection();
Session session = conn.createSession(false, Session.AUTO_ACKNOWLEDGE);
Destination dest = session.createQueue(destination);
try {
assertNotNull("Destination was null", dest);
MessageProducer producer = session.createProducer(dest);
ObjectMessage message = session.createObjectMessage();
if (contentType != null) {
message.setStringProperty(HttpHeaderProperty.CONTENT_TYPE, contentType);
}
message.setObject(object);
producer.send(message);
} finally {
conn.close();
}
}
}

View File

@ -1,161 +0,0 @@
/*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You 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
*
* http://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.apache.activemq.artemis.rest.test;
import javax.jms.Connection;
import javax.jms.ConnectionFactory;
import javax.jms.Destination;
import javax.jms.MessageProducer;
import javax.jms.ObjectMessage;
import javax.jms.Session;
import java.io.Serializable;
import java.util.ArrayList;
import java.util.List;
import org.apache.activemq.artemis.api.jms.JMSFactoryType;
import org.apache.activemq.artemis.core.config.impl.SecurityConfiguration;
import org.apache.activemq.artemis.rest.HttpHeaderProperty;
import org.apache.activemq.artemis.rest.integration.EmbeddedRestActiveMQJMS;
import org.apache.activemq.artemis.spi.core.naming.BindingRegistry;
import org.apache.activemq.artemis.spi.core.security.ActiveMQJAASSecurityManager;
import org.apache.activemq.artemis.spi.core.security.jaas.InVMLoginModule;
import org.jboss.resteasy.client.ClientRequest;
import org.jboss.resteasy.client.ClientResponse;
import org.jboss.resteasy.spi.Link;
import org.jboss.resteasy.test.TestPortProvider;
import org.junit.AfterClass;
import org.junit.Assert;
import org.junit.BeforeClass;
import org.junit.Test;
public class EmbeddedTest {
public static EmbeddedRestActiveMQJMS server;
@BeforeClass
public static void startEmbedded() throws Exception {
server = new EmbeddedRestActiveMQJMS(null);
server.getManager().setConfigResourcePath("activemq-rest.xml");
SecurityConfiguration securityConfiguration = new SecurityConfiguration();
securityConfiguration.addUser("guest", "guest");
securityConfiguration.addRole("guest", "guest");
securityConfiguration.setDefaultUser("guest");
ActiveMQJAASSecurityManager securityManager = new ActiveMQJAASSecurityManager(InVMLoginModule.class.getName(), securityConfiguration);
server.getEmbeddedJMS().setSecurityManager(securityManager);
server.start();
List<String> connectors = new ArrayList<>();
connectors.add("in-vm");
server.getEmbeddedJMS().getJMSServerManager().createConnectionFactory("ConnectionFactory", false, JMSFactoryType.CF, connectors, "ConnectionFactory");
}
@AfterClass
public static void stopEmbedded() throws Exception {
server.stop();
server = null;
}
public static void publish(String destination, Serializable object, String contentType) throws Exception {
BindingRegistry reg = server.getRegistry();
ConnectionFactory factory = (ConnectionFactory) reg.lookup("ConnectionFactory");
Connection conn = factory.createConnection();
Session session = conn.createSession(false, Session.AUTO_ACKNOWLEDGE);
Destination dest = session.createQueue(destination);
try {
Assert.assertNotNull("Destination was null", dest);
MessageProducer producer = session.createProducer(dest);
ObjectMessage message = session.createObjectMessage();
if (contentType != null) {
message.setStringProperty(HttpHeaderProperty.CONTENT_TYPE, contentType);
}
message.setObject(object);
producer.send(message);
} finally {
conn.close();
}
}
@Test
public void testTransform() throws Exception {
ClientRequest request = new ClientRequest(TestPortProvider.generateURL("/queues/jms.queue.exampleQueue"));
ClientResponse<?> response = request.head();
response.releaseConnection();
Assert.assertEquals(200, response.getStatus());
Link sender = response.getLinkHeader().getLinkByTitle("create");
System.out.println("create: " + sender);
Link consumers = response.getLinkHeader().getLinkByTitle("pull-consumers");
System.out.println("pull: " + consumers);
response = Util.setAutoAck(consumers, true);
Link consumeNext = response.getLinkHeader().getLinkByTitle("consume-next");
System.out.println("consume-next: " + consumeNext);
// test that Accept header is used to set content-type
{
TransformTest.Order order = new TransformTest.Order();
order.setName("1");
order.setAmount("$5.00");
publish("exampleQueue", order, null);
ClientResponse<?> res = consumeNext.request().header("Accept-Wait", "2").accept("application/xml").post(String.class);
Assert.assertEquals(200, res.getStatus());
Assert.assertEquals("application/xml", res.getHeaders().getFirst("Content-Type").toString().toLowerCase());
TransformTest.Order order2 = res.getEntity(TransformTest.Order.class);
Assert.assertEquals(order, order2);
consumeNext = res.getLinkHeader().getLinkByTitle("consume-next");
res.releaseConnection();
Assert.assertNotNull(consumeNext);
}
// test that Accept header is used to set content-type
{
TransformTest.Order order = new TransformTest.Order();
order.setName("1");
order.setAmount("$5.00");
publish("exampleQueue", order, null);
ClientResponse<?> res = consumeNext.request().header("Accept-Wait", "2").accept("application/json").post(String.class);
Assert.assertEquals(200, res.getStatus());
Assert.assertEquals("application/json", res.getHeaders().getFirst("Content-Type").toString().toLowerCase());
TransformTest.Order order2 = res.getEntity(TransformTest.Order.class);
Assert.assertEquals(order, order2);
consumeNext = res.getLinkHeader().getLinkByTitle("consume-next");
res.releaseConnection();
Assert.assertNotNull(consumeNext);
}
// test that message property is used to set content type
{
TransformTest.Order order = new TransformTest.Order();
order.setName("2");
order.setAmount("$15.00");
publish("exampleQueue", order, "application/xml");
ClientResponse<?> res = consumeNext.request().header("Accept-Wait", "2").post(String.class);
Assert.assertEquals(200, res.getStatus());
Assert.assertEquals("application/xml", res.getHeaders().getFirst("Content-Type").toString().toLowerCase());
TransformTest.Order order2 = res.getEntity(TransformTest.Order.class);
Assert.assertEquals(order, order2);
consumeNext = res.getLinkHeader().getLinkByTitle("consume-next");
res.releaseConnection();
Assert.assertNotNull(consumeNext);
}
}
}

View File

@ -27,14 +27,14 @@ import org.apache.activemq.artemis.rest.MessageServiceManager;
import org.jboss.resteasy.plugins.server.tjws.TJWSEmbeddedJaxrsServer;
import org.jboss.resteasy.test.TestPortProvider;
public class Embedded {
class EmbeddedTestServer {
protected MessageServiceManager manager = new MessageServiceManager(null);
protected MessageServiceConfiguration config = new MessageServiceConfiguration();
protected ActiveMQServer activeMQServer;
protected TJWSEmbeddedJaxrsServer tjws = new TJWSEmbeddedJaxrsServer();
private ActiveMQServer activeMQServer;
private TJWSEmbeddedJaxrsServer tjws = new TJWSEmbeddedJaxrsServer();
public Embedded() {
EmbeddedTestServer() {
int port = TestPortProvider.getPort();
System.out.println("default port is: " + port);
tjws.setPort(port);
@ -54,11 +54,7 @@ public class Embedded {
return activeMQServer;
}
public void setActiveMQServer(ActiveMQServer activeMQServer) {
this.activeMQServer = activeMQServer;
}
public TJWSEmbeddedJaxrsServer getJaxrsServer() {
TJWSEmbeddedJaxrsServer getJaxrsServer() {
return tjws;
}
@ -67,7 +63,7 @@ public class Embedded {
}
public void start() throws Exception {
System.out.println("\nStarting Embedded");
System.out.println("\nStarting EmbeddedTestServer");
if (activeMQServer == null) {
Configuration configuration = new ConfigurationImpl().setPersistenceEnabled(false).setSecurityEnabled(false).addAcceptorConfiguration(new TransportConfiguration(InVMAcceptorFactory.class.getName()));
@ -83,7 +79,7 @@ public class Embedded {
}
public void stop() throws Exception {
System.out.println("\nStopping Embedded");
System.out.println("\nStopping EmbeddedTestServer");
manager.stop();
tjws.stop();
activeMQServer.stop();

View File

@ -1,270 +0,0 @@
/*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You 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
*
* http://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.apache.activemq.artemis.rest.test;
import javax.jms.Connection;
import javax.jms.ConnectionFactory;
import javax.jms.Destination;
import javax.jms.Message;
import javax.jms.MessageConsumer;
import javax.jms.MessageListener;
import javax.jms.MessageProducer;
import javax.jms.ObjectMessage;
import javax.jms.Session;
import javax.xml.bind.annotation.XmlRootElement;
import java.io.Serializable;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.TimeUnit;
import org.apache.activemq.artemis.jms.client.ActiveMQDestination;
import org.apache.activemq.artemis.jms.client.ActiveMQJMSConnectionFactory;
import org.apache.activemq.artemis.rest.HttpHeaderProperty;
import org.apache.activemq.artemis.rest.Jms;
import org.apache.activemq.artemis.rest.queue.QueueDeployment;
import org.jboss.resteasy.client.ClientRequest;
import org.jboss.resteasy.client.ClientResponse;
import org.jboss.resteasy.spi.Link;
import org.junit.Assert;
import org.junit.BeforeClass;
import org.junit.Test;
import static org.jboss.resteasy.test.TestPortProvider.generateURL;
public class JMSTest extends MessageTestBase {
public static ConnectionFactory connectionFactory;
@BeforeClass
public static void setup() throws Exception {
connectionFactory = new ActiveMQJMSConnectionFactory(manager.getQueueManager().getServerLocator());
}
@XmlRootElement
public static class Order implements Serializable {
private static final long serialVersionUID = 1397854679589606480L;
private String name;
private String amount;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getAmount() {
return amount;
}
public void setAmount(String amount) {
this.amount = amount;
}
@Override
public boolean equals(Object o) {
if (this == o) {
return true;
}
if (o == null || getClass() != o.getClass()) {
return false;
}
Order order = (Order) o;
if (!amount.equals(order.amount)) {
return false;
}
if (!name.equals(order.name)) {
return false;
}
return true;
}
@Override
public int hashCode() {
int result = name.hashCode();
result = 31 * result + amount.hashCode();
return result;
}
}
public static Destination createDestination(String dest) {
ActiveMQDestination destination = (ActiveMQDestination) ActiveMQDestination.fromAddress(dest);
System.out.println("SimpleAddress: " + destination.getSimpleAddress());
return destination;
}
public static void publish(String dest, Serializable object, String contentType) throws Exception {
Connection conn = connectionFactory.createConnection();
try {
Session session = conn.createSession(false, Session.AUTO_ACKNOWLEDGE);
Destination destination = createDestination(dest);
MessageProducer producer = session.createProducer(destination);
ObjectMessage message = session.createObjectMessage();
if (contentType != null) {
message.setStringProperty(HttpHeaderProperty.CONTENT_TYPE, contentType);
}
message.setObject(object);
producer.send(message);
} finally {
conn.close();
}
}
public static class Listener implements MessageListener {
public static Order order;
public static String messageID = null;
public static CountDownLatch latch = new CountDownLatch(1);
@Override
public void onMessage(Message message) {
try {
order = Jms.getEntity(message, Order.class);
messageID = message.getJMSMessageID();
} catch (Exception e) {
e.printStackTrace();
}
latch.countDown();
}
}
@Test
public void testJmsConsumer() throws Exception {
String queueName = ActiveMQDestination.createQueueAddressFromName("testQueue2").toString();
System.out.println("Queue name: " + queueName);
QueueDeployment deployment = new QueueDeployment();
deployment.setDuplicatesAllowed(true);
deployment.setDurableSend(false);
deployment.setName(queueName);
manager.getQueueManager().deploy(deployment);
Connection conn = connectionFactory.createConnection();
try {
Session session = conn.createSession(false, Session.AUTO_ACKNOWLEDGE);
Destination destination = createDestination(queueName);
MessageConsumer consumer = session.createConsumer(destination);
consumer.setMessageListener(new Listener());
conn.start();
ClientRequest request = new ClientRequest(generateURL(Util.getUrlPath(queueName)));
ClientResponse<?> response = request.head();
response.releaseConnection();
Assert.assertEquals(200, response.getStatus());
Link sender = getLinkByTitle(manager.getQueueManager().getLinkStrategy(), response, "create");
System.out.println("create: " + sender);
Link consumeNext = getLinkByTitle(manager.getQueueManager().getLinkStrategy(), response, "consume-next");
System.out.println("consume-next: " + consumeNext);
// test that Accept header is used to set content-type
{
Order order = new Order();
order.setName("1");
order.setAmount("$5.00");
response = sender.request().body("application/xml", order).post();
response.releaseConnection();
Assert.assertEquals(201, response.getStatus());
Listener.latch.await(1, TimeUnit.SECONDS);
Assert.assertNotNull(Listener.order);
Assert.assertEquals(order, Listener.order);
Assert.assertNotNull(Listener.messageID);
}
} finally {
conn.close();
}
}
@Test
public void testJmsProducer() throws Exception {
String queueName = ActiveMQDestination.createQueueAddressFromName("testQueue").toString();
System.out.println("Queue name: " + queueName);
QueueDeployment deployment = new QueueDeployment();
deployment.setDuplicatesAllowed(true);
deployment.setDurableSend(false);
deployment.setName(queueName);
manager.getQueueManager().deploy(deployment);
ClientRequest request = new ClientRequest(generateURL(Util.getUrlPath(queueName)));
ClientResponse<?> response = request.head();
response.releaseConnection();
Assert.assertEquals(200, response.getStatus());
Link sender = getLinkByTitle(manager.getQueueManager().getLinkStrategy(), response, "create");
System.out.println("create: " + sender);
Link consumers = getLinkByTitle(manager.getQueueManager().getLinkStrategy(), response, "pull-consumers");
System.out.println("pull: " + consumers);
response = Util.setAutoAck(consumers, true);
Link consumeNext = getLinkByTitle(manager.getQueueManager().getLinkStrategy(), response, "consume-next");
System.out.println("consume-next: " + consumeNext);
// test that Accept header is used to set content-type
{
Order order = new Order();
order.setName("1");
order.setAmount("$5.00");
publish(queueName, order, null);
ClientResponse<?> res = consumeNext.request().header("Accept-Wait", "2").accept("application/xml").post(String.class);
Assert.assertEquals(200, res.getStatus());
Assert.assertEquals("application/xml", res.getHeaders().getFirst("Content-Type").toString().toLowerCase());
Order order2 = res.getEntity(Order.class);
res.releaseConnection();
Assert.assertEquals(order, order2);
consumeNext = getLinkByTitle(manager.getQueueManager().getLinkStrategy(), res, "consume-next");
Assert.assertNotNull(consumeNext);
}
// test that Accept header is used to set content-type
{
Order order = new Order();
order.setName("1");
order.setAmount("$5.00");
publish(queueName, order, null);
ClientResponse<?> res = consumeNext.request().header("Accept-Wait", "2").accept("application/json").post(String.class);
Assert.assertEquals(200, res.getStatus());
Assert.assertEquals("application/json", res.getHeaders().getFirst("Content-Type").toString().toLowerCase());
Order order2 = res.getEntity(Order.class);
res.releaseConnection();
Assert.assertEquals(order, order2);
consumeNext = getLinkByTitle(manager.getQueueManager().getLinkStrategy(), res, "consume-next");
Assert.assertNotNull(consumeNext);
}
// test that message property is used to set content type
{
Order order = new Order();
order.setName("2");
order.setAmount("$15.00");
publish(queueName, order, "application/xml");
ClientResponse<?> res = consumeNext.request().header("Accept-Wait", "2").post(String.class);
Assert.assertEquals(200, res.getStatus());
Assert.assertEquals("application/xml", res.getHeaders().getFirst("Content-Type").toString().toLowerCase());
Order order2 = res.getEntity(Order.class);
res.releaseConnection();
Assert.assertEquals(order, order2);
consumeNext = getLinkByTitle(manager.getQueueManager().getLinkStrategy(), res, "consume-next");
Assert.assertNotNull(consumeNext);
}
}
}

View File

@ -30,7 +30,7 @@ import org.junit.BeforeClass;
public class MessageTestBase {
public static Embedded server;
public static EmbeddedTestServer server;
public static MessageServiceManager manager;
private static Field executorField;
@ -45,7 +45,7 @@ public class MessageTestBase {
@BeforeClass
public static void setupActiveMQServerAndManager() throws Exception {
server = new Embedded();
server = new EmbeddedTestServer();
server.start();
manager = server.getManager();
}

View File

@ -39,7 +39,7 @@ public final class Util {
return Constants.PATH_FOR_QUEUES + "/" + queueName;
}
static ClientResponse setAutoAck(Link link, boolean ack) throws Exception {
public static ClientResponse setAutoAck(Link link, boolean ack) throws Exception {
ClientResponse response;
response = link.request().formParameter("autoAck", Boolean.toString(ack)).post();
response.releaseConnection();

View File

@ -14,9 +14,10 @@
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.activemq.artemis.rest.test;
package org.apache.activemq.artemis.rest.topic;
import org.apache.activemq.artemis.rest.topic.TopicDeployment;
import org.apache.activemq.artemis.rest.test.MessageTestBase;
import org.apache.activemq.artemis.rest.test.Util;
import org.apache.activemq.artemis.rest.util.Constants;
import org.jboss.resteasy.client.ClientRequest;
import org.jboss.resteasy.client.ClientResponse;