[AMQ-6546] More refactoring of karaf itests

This commit is contained in:
Christian Schneider 2017-01-05 15:58:33 +01:00
parent 59f27aa483
commit 50ea30841e
16 changed files with 439 additions and 409 deletions

View File

@ -67,9 +67,8 @@
<scope>provided</scope>
</dependency>
<dependency>
<groupId>commons-httpclient</groupId>
<artifactId>commons-httpclient</artifactId>
<version>3.1</version>
<groupId>org.apache.httpcomponents</groupId>
<artifactId>httpclient</artifactId>
</dependency>
<dependency>
<groupId>org.ops4j.pax.exam</groupId>

View File

@ -16,6 +16,7 @@
*/
package org.apache.activemq.karaf.itest;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertTrue;
import static org.ops4j.pax.exam.CoreOptions.composite;
import static org.ops4j.pax.exam.CoreOptions.maven;
@ -26,47 +27,44 @@ import static org.ops4j.pax.exam.karaf.options.KarafDistributionOption.keepRunti
import static org.ops4j.pax.exam.karaf.options.KarafDistributionOption.logLevel;
import static org.ops4j.pax.exam.karaf.options.KarafDistributionOption.replaceConfigurationFile;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.PrintStream;
import java.security.PrivilegedAction;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.nio.channels.FileChannel;
import java.util.concurrent.Callable;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.FutureTask;
import java.util.concurrent.TimeUnit;
import javax.inject.Inject;
import javax.security.auth.Subject;
import org.apache.karaf.features.FeaturesService;
import org.apache.karaf.jaas.boot.principal.RolePrincipal;
import org.apache.karaf.jaas.boot.principal.UserPrincipal;
import org.apache.karaf.shell.api.console.Session;
import org.apache.karaf.shell.api.console.SessionFactory;
import org.junit.After;
import org.junit.Before;
import org.junit.runner.RunWith;
import org.ops4j.pax.exam.MavenUtils;
import org.ops4j.pax.exam.Option;
import org.ops4j.pax.exam.ProbeBuilder;
import org.ops4j.pax.exam.TestProbeBuilder;
import org.ops4j.pax.exam.junit.PaxExam;
import org.ops4j.pax.exam.karaf.options.LogLevelOption;
import org.ops4j.pax.exam.options.MavenUrlReference;
import org.ops4j.pax.exam.options.UrlReference;
import org.ops4j.pax.exam.spi.reactors.ExamReactorStrategy;
import org.ops4j.pax.exam.spi.reactors.PerClass;
import org.osgi.framework.Bundle;
import org.osgi.framework.BundleContext;
import org.osgi.framework.Constants;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
@RunWith(PaxExam.class)
@ExamReactorStrategy(PerClass.class)
public abstract class AbstractFeatureTest {
private static final String KARAF_MAJOR_VERSION = "4.0.0";
public static final Logger LOG = LoggerFactory.getLogger(AbstractFeatureTest.class);
public static final long ASSERTION_TIMEOUT = 30000L;
public static final long COMMAND_TIMEOUT = 30000L;
public static final String USER = "karaf";
public static final String PASSWORD = "karaf";
public static final String RESOURCE_BASE = "src/test/resources/org/apache/activemq/karaf/itest/";
@Inject
@ -75,6 +73,9 @@ public abstract class AbstractFeatureTest {
@Inject
FeaturesService featuresService;
@Inject
SessionFactory sessionFactory;
@Before
public void setUp() throws Exception {
}
@ -90,61 +91,6 @@ public abstract class AbstractFeatureTest {
return probe;
}
@Inject
SessionFactory sessionFactory;
ExecutorService executor = Executors.newCachedThreadPool();
private String executeCommand(final String command, final Long timeout, final Boolean silent) {
String response;
final ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
final PrintStream printStream = new PrintStream(byteArrayOutputStream);
final Session commandSession = sessionFactory.create(System.in, printStream, printStream);
commandSession.put("APPLICATION", System.getProperty("karaf.name", "root"));
commandSession.put("USER", USER);
FutureTask<String> commandFuture = new FutureTask<String>(
new Callable<String>() {
@Override
public String call() {
Subject subject = new Subject();
subject.getPrincipals().add(new UserPrincipal("admin"));
subject.getPrincipals().add(new RolePrincipal("admin"));
subject.getPrincipals().add(new RolePrincipal("manager"));
subject.getPrincipals().add(new RolePrincipal("viewer"));
return Subject.doAs(subject, new PrivilegedAction<String>() {
@Override
public String run() {
try {
if (!silent) {
System.out.println(command);
System.out.flush();
}
commandSession.execute(command);
} catch (Exception e) {
e.printStackTrace(System.err);
}
printStream.flush();
return byteArrayOutputStream.toString();
}
});
}});
try {
executor.submit(commandFuture);
response = commandFuture.get(timeout, TimeUnit.MILLISECONDS);
} catch (Exception e) {
e.printStackTrace(System.err);
response = "SHELL COMMAND TIMED OUT: ";
}
LOG.info("Execute: " + command + " - Response:" + response);
return response;
}
protected String executeCommand(final String command) {
return executeCommand(command, COMMAND_TIMEOUT, false);
}
/**
* Installs a feature and asserts that feature is properly installed.
*
@ -174,6 +120,19 @@ public abstract class AbstractFeatureTest {
throw new RuntimeException("Bundle " + symName + " not found");
}
protected String executeCommand(String command) {
return KarafShellHelper.executeCommand(sessionFactory, command);
}
protected void assertBrokerStarted() throws Exception {
withinReason(new Runnable() {
public void run() {
assertEquals("brokerName = amq-broker", executeCommand("activemq:list").trim());
assertTrue(executeCommand("activemq:bstat").trim().contains("BrokerName = amq-broker"));
}
});
}
public static Option configureBrokerStart(String xmlConfig) {
return composite(
replaceConfigurationFile("etc/activemq.xml", new File(RESOURCE_BASE + xmlConfig + ".xml")),
@ -209,7 +168,7 @@ public abstract class AbstractFeatureTest {
return MavenUtils.getArtifactVersion("org.apache.camel.karaf", "apache-camel");
}
protected boolean withinReason(Callable<Boolean> callable) throws Throwable {
public static boolean withinReason(Callable<Boolean> callable) throws Exception {
long max = System.currentTimeMillis() + ASSERTION_TIMEOUT;
while (true) {
try {
@ -225,7 +184,7 @@ public abstract class AbstractFeatureTest {
}
}
protected void withinReason(Runnable runable) throws Exception {
public static void withinReason(Runnable runable) {
long max = System.currentTimeMillis() + ASSERTION_TIMEOUT;
while (true) {
try {
@ -233,7 +192,11 @@ public abstract class AbstractFeatureTest {
return;
} catch (Throwable t) {
if (System.currentTimeMillis() < max) {
try {
TimeUnit.SECONDS.sleep(1);
} catch (InterruptedException e) {
throw new RuntimeException(e);
}
continue;
} else {
throw t;
@ -241,4 +204,30 @@ public abstract class AbstractFeatureTest {
}
}
}
@SuppressWarnings("resource")
public static void copyFile(File from, File to) throws IOException {
if (!to.exists()) {
System.err.println("Creating new file for: "+ to);
to.createNewFile();
}
FileChannel in = new FileInputStream(from).getChannel();
FileChannel out = new FileOutputStream(to).getChannel();
try {
long size = in.size();
long position = 0;
while (position < size) {
position += in.transferTo(position, 8192, out);
}
} finally {
try {
in.close();
out.force(true);
out.close();
} catch (Exception e) {
// ignore
}
}
}
}

View File

@ -1,80 +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.karaf.itest;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.nio.channels.FileChannel;
import javax.jms.Connection;
import javax.jms.MessageConsumer;
import javax.jms.Session;
import javax.jms.TextMessage;
import org.apache.activemq.ActiveMQConnectionFactory;
public abstract class AbstractJmsFeatureTest extends AbstractFeatureTest {
@SuppressWarnings("resource")
public static void copyFile(File from, File to) throws IOException {
if (!to.exists()) {
System.err.println("Creating new file for: "+ to);
to.createNewFile();
}
FileChannel in = new FileInputStream(from).getChannel();
FileChannel out = new FileOutputStream(to).getChannel();
try {
long size = in.size();
long position = 0;
while (position < size) {
position += in.transferTo(position, 8192, out);
}
} finally {
try {
in.close();
out.force(true);
out.close();
} catch (Exception e) {
// ignore
}
}
}
protected String consumeMessage(String nameAndPayload) throws Throwable {
Connection connection = getConnection();
Session session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE);
MessageConsumer consumer = session.createConsumer(session.createQueue(nameAndPayload));
TextMessage message = (TextMessage) consumer.receive(10000);
System.err.println("message: " + message);
connection.close();
return message.getText();
}
protected void produceMessage(String nameAndPayload) throws Throwable{
Connection connection = getConnection();
Session session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE);
session.createProducer(session.createQueue(nameAndPayload)).send(session.createTextMessage(nameAndPayload));
connection.close();
}
protected Connection getConnection() throws Exception {
ActiveMQConnectionFactory factory = new ActiveMQConnectionFactory();
Connection connection = factory.createConnection(AbstractFeatureTest.USER, AbstractFeatureTest.PASSWORD);
connection.start();
return connection;
}
}

View File

@ -19,18 +19,11 @@ package org.apache.activemq.karaf.itest;
import javax.jms.Connection;
import org.apache.qpid.jms.JmsConnectionFactory;
import org.junit.Ignore;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.ops4j.pax.exam.Configuration;
import org.ops4j.pax.exam.Option;
import org.ops4j.pax.exam.junit.PaxExam;
import org.ops4j.pax.exam.spi.reactors.ExamReactorStrategy;
import org.ops4j.pax.exam.spi.reactors.PerClass;
@RunWith(PaxExam.class)
@ExamReactorStrategy(PerClass.class)
public class ActiveMQAMQPBrokerFeatureTest extends ActiveMQBrokerFeatureTest {
public class ActiveMQAMQPBrokerFeatureTest extends AbstractFeatureTest {
private static final Integer AMQP_PORT = 61636;
@Configuration
@ -42,28 +35,30 @@ public class ActiveMQAMQPBrokerFeatureTest extends ActiveMQBrokerFeatureTest {
};
}
@Override
protected Connection getConnection() throws Exception {
@Test(timeout = 5 * 60 * 1000)
public void testProduceConsume() throws Throwable {
JMSTester tester = new JMSTester(getQPIDConnection());
tester.produceAndConsume(sessionFactory);
tester.close();
}
protected Connection getQPIDConnection() throws Exception {
assertBrokerStarted();
assertQpidClient();
JmsConnectionFactory factory = new JmsConnectionFactory("amqp://localhost:" + AMQP_PORT);
factory.setUsername(KarafShellHelper.USER);
factory.setPassword(KarafShellHelper.PASSWORD);
Connection connection = factory.createConnection();
connection.start();
return connection;
}
private void assertQpidClient() throws Exception {
withinReason(new Runnable() {
public void run() {
getBundle("org.apache.qpid.jms.client");
}
});
String amqpURI = "amqp://localhost:" + AMQP_PORT;
JmsConnectionFactory factory = new JmsConnectionFactory(amqpURI);
factory.setUsername(AbstractFeatureTest.USER);
factory.setPassword(AbstractFeatureTest.PASSWORD);
Connection connection = factory.createConnection();
connection.start();
return connection;
}
@Override
@Ignore
@Test(timeout = 5 * 60 * 1000)
public void testTemporaryDestinations() throws Throwable {
// ignore until we have temporary destination are working in amqp
}
}

View File

@ -20,9 +20,6 @@ import static org.ops4j.pax.exam.CoreOptions.composite;
import static org.ops4j.pax.exam.karaf.options.KarafDistributionOption.replaceConfigurationFile;
import java.io.File;
import java.util.concurrent.Callable;
import javax.jms.Connection;
import org.junit.Test;
import org.junit.runner.RunWith;
@ -31,7 +28,7 @@ import org.ops4j.pax.exam.Option;
import org.ops4j.pax.exam.junit.PaxExam;
@RunWith(PaxExam.class)
public class ActiveMQBrokerBlueprintTest extends AbstractJmsFeatureTest {
public class ActiveMQBrokerBlueprintTest extends AbstractFeatureTest {
@Configuration
public Option[] configure() {
@ -39,24 +36,17 @@ public class ActiveMQBrokerBlueprintTest extends AbstractJmsFeatureTest {
{
composite(super.configure("activemq", "activemq-blueprint")),
replaceConfigurationFile("deploy/activemq-blueprint.xml",
new File("src/test/resources/org/apache/activemq/karaf/itest/activemq-blueprint.xml"))
new File(RESOURCE_BASE + "activemq-blueprint.xml"))
};
}
@Test
public void test() throws Throwable {
withinReason(new Callable<Boolean>() {
@Override
public Boolean call() throws Exception {
Connection con;
try {
con = getConnection();
} catch (Throwable e) {
throw new RuntimeException(e);
}
con.close();
return true;
withinReason(() ->new Runnable() {
public void run() {
JMSTester jms = new JMSTester();
jms.produceAndConsume(sessionFactory);
jms.close();
}
});
}

View File

@ -16,30 +16,40 @@
*/
package org.apache.activemq.karaf.itest;
import static org.junit.Assert.assertEquals;
import static org.ops4j.pax.exam.CoreOptions.mavenBundle;
import java.io.IOException;
import java.net.URI;
import java.util.concurrent.Callable;
import org.apache.http.client.CredentialsProvider;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.client.utils.URIBuilder;
import org.apache.http.impl.client.BasicCredentialsProvider;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClientBuilder;
import org.apache.http.util.EntityUtils;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.ops4j.pax.exam.Option;
import org.ops4j.pax.exam.Configuration;
import org.ops4j.pax.exam.junit.PaxExam;
import org.ops4j.pax.exam.Option;
import org.ops4j.pax.exam.options.WrappedUrlProvisionOption;
import javax.jms.Connection;
import javax.jms.Message;
import javax.jms.Session;
import javax.jms.TemporaryQueue;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertNotNull;
import static org.junit.Assert.assertTrue;
@RunWith(PaxExam.class)
public class ActiveMQBrokerFeatureTest extends AbstractJmsFeatureTest {
public class ActiveMQBrokerFeatureTest extends AbstractFeatureTest {
static final String WEB_CONSOLE_URL = "http://localhost:8181/activemqweb/";
@Configuration
public static Option[] configure() {
return new Option[] //
{
configure("activemq"), //
configure("connector", "activemq-broker"), //
// To access web console
//mavenBundle("commons-codec", "commons-codec").versionAsInProject(),
mavenBundle("org.apache.httpcomponents", "httpcore-osgi").version("4.4.4"),
mavenBundle("org.apache.httpcomponents", "httpclient-osgi").version("4.5.2"),
configureBrokerStart()
};
}
@ -50,38 +60,69 @@ public class ActiveMQBrokerFeatureTest extends AbstractJmsFeatureTest {
@Test(timeout=5 * 60 * 1000)
public void test() throws Throwable {
assertBrokerStarted();
JMSTester jms = new JMSTester();
jms.produceAndConsume(sessionFactory);
jms.tempSendReceive();
jms.close();
}
withinReason(new Runnable() {
public void run() {
assertEquals("brokerName = amq-broker", executeCommand("activemq:list").trim());
assertTrue(executeCommand("activemq:bstat").trim().contains("BrokerName = amq-broker"));
private void produceMessageWebConsole(String nameAndPayload) throws Exception {
CredentialsProvider credsProvider = new BasicCredentialsProvider();
credsProvider.setCredentials(
new org.apache.http.auth.AuthScope("httpbin.org", 80),
new org.apache.http.auth.UsernamePasswordCredentials(KarafShellHelper.USER, KarafShellHelper.PASSWORD));
CloseableHttpClient client = HttpClientBuilder.create() //
.setDefaultCredentialsProvider(credsProvider)
.build();
System.err.println(executeCommand("activemq:bstat").trim());
System.err.println("attempting to access web console..");
withinReason(new Callable<Boolean>() {
public Boolean call() throws Exception {
CloseableHttpResponse response = client.execute(new HttpGet(WEB_CONSOLE_URL + "index.jsp"));
return response.getStatusLine().getStatusCode() != 200;
}
});
// produce and consume
System.err.println("attempting publish via web console..");
// need to first get the secret
CloseableHttpResponse response = client.execute(new HttpGet(WEB_CONSOLE_URL + "send.jsp"));
int code = response.getStatusLine().getStatusCode();
assertEquals("getting send succeeded", 200, code);
String secret = getSecret(EntityUtils.toString(response.getEntity()));
URI sendUri = new URIBuilder(WEB_CONSOLE_URL + "sendMessage.action") //
.addParameter("secret", secret) //
.addParameter("JMSText", nameAndPayload)
.addParameter("JMSDestination", nameAndPayload)
.addParameter("JMSDestinationType", "queue")
.build();
HttpPost post = new HttpPost(sendUri);
CloseableHttpResponse sendResponse = client.execute(post);
assertEquals("post succeeded, " + post, 302, sendResponse.getStatusLine().getStatusCode());
System.err.println(executeCommand("activemq:bstat").trim());
}
private String getSecret(String response) throws IOException {
final String secretMarker = "<input type=\"hidden\" name=\"secret\" value=\"";
String secret = response.substring(response.indexOf(secretMarker) + secretMarker.length());
secret = secret.substring(0, secret.indexOf("\"/>"));
return secret;
}
@Test
public void testSendReceiveWeb() throws Throwable {
assertBrokerStarted();
JMSTester jms = new JMSTester();
final String nameAndPayload = String.valueOf(System.currentTimeMillis());
produceMessage(nameAndPayload);
executeCommand("activemq:bstat").trim();
withinReason(new Runnable() {
public void run() {
assertEquals("JMS_BODY_FIELD:JMSText = " + nameAndPayload, executeCommand("activemq:browse --amqurl tcp://localhost:61616 --user karaf --password karaf -Vbody " + nameAndPayload).trim());
}
});
assertEquals("got our message", nameAndPayload, consumeMessage(nameAndPayload));
}
@Test(timeout = 5 * 60 * 1000)
public void testTemporaryDestinations() throws Throwable {
Connection connection = getConnection();
Session session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE);
TemporaryQueue temporaryQueue = session.createTemporaryQueue();
session.createProducer(temporaryQueue).send(session.createTextMessage("TEST"));
Message msg = session.createConsumer(temporaryQueue).receive(3000);
assertNotNull("Didn't receive the message", msg);
connection.close();
produceMessageWebConsole(nameAndPayload);
assertEquals("got our message", nameAndPayload, jms.consumeMessage(nameAndPayload));
jms.tempSendReceive();
jms.close();
}
}

View File

@ -31,7 +31,7 @@ import static org.ops4j.pax.exam.karaf.options.KarafDistributionOption.editConfi
import static org.ops4j.pax.exam.karaf.options.KarafDistributionOption.replaceConfigurationFile;
@RunWith(PaxExam.class)
public class ActiveMQBrokerNdCamelFeatureTest extends AbstractJmsFeatureTest {
public class ActiveMQBrokerNdCamelFeatureTest extends AbstractFeatureTest {
@Configuration
public static Option[] configure() {
@ -48,18 +48,18 @@ public class ActiveMQBrokerNdCamelFeatureTest extends AbstractJmsFeatureTest {
public void test() throws Throwable {
System.err.println(executeCommand("feature:list -i").trim());
assertFeatureInstalled("activemq");
assertBrokerStarted();
withinReason(new Runnable() {
public void run() {
getBundle("org.apache.activemq.activemq-camel");
assertEquals("brokerName = amq-broker", executeCommand("activemq:list").trim());
assertTrue(executeCommand("activemq:bstat").trim().contains("BrokerName = amq-broker"));
assertTrue("we have camel consumers", executeCommand("activemq:dstat").trim().contains("camel_in"));
}
});
// produce and consume
produceMessage("camel_in");
assertEquals("got our message", "camel_in", consumeMessage("camel_out"));
JMSTester jms = new JMSTester();
jms.produceMessage("camel_in");
assertEquals("got our message", "camel_in", jms.consumeMessage("camel_out"));
jms.close();
}
}

View File

@ -31,7 +31,7 @@ import org.ops4j.pax.exam.Option;
//@RunWith(PaxExam.class)
@Ignore
public class ActiveMQBrokerNdExternalCamelFeatureTest extends AbstractJmsFeatureTest {
public class ActiveMQBrokerNdExternalCamelFeatureTest extends AbstractFeatureTest {
@Configuration
public static Option[] configure() {
@ -51,16 +51,13 @@ public class ActiveMQBrokerNdExternalCamelFeatureTest extends AbstractJmsFeature
installAndAssertFeature("camel");
installAndAssertFeature("activemq-camel");
assertBrokerStarted();
withinReason(new Runnable() {
public void run() {
assertEquals("brokerName = amq-broker", executeCommand("activemq:list").trim());
assertTrue(executeCommand("activemq:bstat").trim().contains("BrokerName = amq-broker"));
getBundle("org.apache.activemq.activemq-camel");
}
});
System.err.println(executeCommand("activemq:bstat").trim());
// hot deploy the camel.xml file by copying it to the deploy directory
String karafDir = System.getProperty("karaf.base");
System.err.println("Karaf is running in dir: " + karafDir);
@ -76,8 +73,10 @@ public class ActiveMQBrokerNdExternalCamelFeatureTest extends AbstractJmsFeature
});
// produce and consume
produceMessage("camel_in");
assertEquals("got our message", "camel_in", consumeMessage("camel_out"));
JMSTester tester = new JMSTester();
tester.produceMessage("camel_in");
assertEquals("got our message", "camel_in", tester.consumeMessage("camel_out"));
tester.close();
}
}

View File

@ -1,112 +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.karaf.itest;
import java.util.concurrent.TimeUnit;
import org.apache.commons.httpclient.HttpClient;
import org.apache.commons.httpclient.UsernamePasswordCredentials;
import org.apache.commons.httpclient.auth.AuthScope;
import org.apache.commons.httpclient.methods.GetMethod;
import org.apache.commons.httpclient.methods.PostMethod;
import org.junit.Ignore;
import org.junit.runner.RunWith;
import org.ops4j.pax.exam.CoreOptions;
import org.ops4j.pax.exam.Option;
import org.ops4j.pax.exam.Configuration;
import org.ops4j.pax.exam.junit.PaxExam;
import static org.junit.Assert.assertEquals;
@RunWith(PaxExam.class)
@Ignore("Can fail sometimes. Old web-console is also @deprecated")
public class ActiveMQBrokerNdWebConsoleFeatureTest extends ActiveMQBrokerFeatureTest {
static final String WEB_CONSOLE_URL = "http://localhost:8181/activemqweb/";
@Configuration
public static Option[] configure() {
return new Option[] //
{
CoreOptions.mavenBundle("commons-codec", "commons-codec").versionAsInProject(),
CoreOptions.mavenBundle("commons-httpclient", "commons-httpclient").versionAsInProject(),
configure("activemq-broker")
};
}
@Override
protected void produceMessage(String nameAndPayload) throws Exception {
HttpClient client = new HttpClient();
client.getHttpConnectionManager().getParams().setConnectionTimeout(30000);
// set credentials
client.getState().setCredentials(
new AuthScope(AuthScope.ANY_HOST, AuthScope.ANY_PORT),
new UsernamePasswordCredentials(USER, PASSWORD)
);
System.err.println(executeCommand("activemq:bstat").trim());
System.err.println("attempting to access web console..");
GetMethod get = new GetMethod(WEB_CONSOLE_URL + "index.jsp");
get.setDoAuthentication(true);
// Give console some time to start
boolean done = false;
int loop = 0;
while (!done && loop < 30) {
loop++;
try {
int code = client.executeMethod(get);
if (code > 399 && code < 500) {
// code 4xx we should retry
System.err.println("web console not accessible yet - status code " + code);
TimeUnit.SECONDS.sleep(1);
} else {
done = true;
}
} catch (Exception ignored) {}
}
assertEquals("get succeeded on " + get, 200, get.getStatusCode());
System.err.println("attempting publish via web console..");
// need to first get the secret
get = new GetMethod(WEB_CONSOLE_URL + "send.jsp");
get.setDoAuthentication(true);
int code = client.executeMethod(get);
assertEquals("get succeeded on " + get, 200, code);
String response = get.getResponseBodyAsString();
final String secretMarker = "<input type=\"hidden\" name=\"secret\" value=\"";
String secret = response.substring(response.indexOf(secretMarker) + secretMarker.length());
secret = secret.substring(0, secret.indexOf("\"/>"));
PostMethod post = new PostMethod(WEB_CONSOLE_URL + "sendMessage.action");
post.setDoAuthentication(true);
post.addParameter("secret", secret);
post.addParameter("JMSText", nameAndPayload);
post.addParameter("JMSDestination", nameAndPayload);
post.addParameter("JMSDestinationType", "queue");
// execute the send
assertEquals("post succeeded, " + post, 302, client.executeMethod(post));
System.err.println(executeCommand("activemq:bstat").trim());
}
}

View File

@ -16,7 +16,6 @@
*/
package org.apache.activemq.karaf.itest;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertTrue;
import static org.ops4j.pax.exam.karaf.options.KarafDistributionOption.editConfigurationFilePut;
import static org.ops4j.pax.exam.karaf.options.KarafDistributionOption.replaceConfigurationFile;
@ -32,29 +31,23 @@ import org.ops4j.pax.exam.Option;
import org.ops4j.pax.exam.junit.PaxExam;
@RunWith(PaxExam.class)
public class ActiveMQBrokerRuntimeConfigTest extends AbstractJmsFeatureTest {
public class ActiveMQBrokerRuntimeConfigTest extends AbstractFeatureTest {
@Configuration
public static Option[] configure() {
return new Option[] //
{
configure("activemq"),
{ //
configure("activemq"), //
editConfigurationFilePut("etc/org.apache.activemq.server-default.cfg", "config.check", "false"),
replaceConfigurationFile("data/tmp/modified-config.xml",
new File(RESOURCE_BASE + "activemq-runtime-config-mod.xml")),
configureBrokerStart("activemq-runtime-config")
};
configureBrokerStart("activemq-runtime-config") };
}
@Test(timeout = 2 * 60 * 1000)
public void test() throws Throwable {
withinReason(new Runnable() {
public void run() {
assertEquals("brokerName = amq-broker", executeCommand("activemq:list").trim());
assertTrue("3MB limit", executeCommand("activemq:query").trim().contains("MemoryLimit = 3145728"));
}
});
assertBrokerStarted();
assertMemoryLimit("3145728");
// ensure update will be reflected in OS fs modified window
TimeUnit.SECONDS.sleep(4);
@ -66,11 +59,14 @@ public class ActiveMQBrokerRuntimeConfigTest extends AbstractJmsFeatureTest {
copyFile(new File(karafDir + "/data/tmp/modified-config.xml"), target);
System.err.println("new mod at: " + new Date(target.lastModified()));
assertMemoryLimit("4194304");
}
private void assertMemoryLimit(String limit) throws Exception {
withinReason(new Runnable() {
public void run() {
assertTrue("4MB limit", executeCommand("activemq:query").trim().contains("MemoryLimit = 4194304"));
assertTrue("3MB limit", executeCommand("activemq:query").trim().contains("MemoryLimit = "+ limit));
}
});
}
}

View File

@ -29,8 +29,8 @@ public class ActiveMQClientBundleTest extends AbstractFeatureTest {
@Configuration
public static Option[] configure() {
return new Option[] //
{
configure("activemq-client")
{ //
configure("activemq-client") //
};
}

View File

@ -32,7 +32,7 @@ import org.ops4j.pax.exam.Option;
import org.ops4j.pax.exam.junit.PaxExam;
@RunWith(PaxExam.class)
public class ActiveMQClientFactoryTest extends AbstractJmsFeatureTest {
public class ActiveMQClientFactoryTest extends AbstractFeatureTest {
@Inject
ConnectionFactory connectionFactory;
@ -45,7 +45,7 @@ public class ActiveMQClientFactoryTest extends AbstractJmsFeatureTest {
{
composite(super.configure("activemq", "activemq-broker", "activemq-cf")),
replaceConfigurationFile("etc/org.apache.activemq.cfg",
new File("src/test/resources/org/apache/activemq/karaf/itest/org.apache.activemq-local.cfg"))
new File(RESOURCE_BASE + "org.apache.activemq-local.cfg"))
};
}

View File

@ -0,0 +1,121 @@
/**
* 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.karaf.itest;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertNotNull;
import java.io.Closeable;
import javax.jms.Connection;
import javax.jms.JMSException;
import javax.jms.Message;
import javax.jms.MessageConsumer;
import javax.jms.Session;
import javax.jms.TemporaryQueue;
import javax.jms.TextMessage;
import org.apache.activemq.ActiveMQConnectionFactory;
import org.apache.karaf.shell.api.console.SessionFactory;
/**
* 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.
*/
public class JMSTester implements Closeable {
private Connection connection;
public JMSTester(Connection connection) {
this.connection = connection;
}
public JMSTester() {
try {
ActiveMQConnectionFactory factory = new ActiveMQConnectionFactory();
connection = factory.createConnection(KarafShellHelper.USER, KarafShellHelper.PASSWORD);
connection.start();
} catch (JMSException e) {
throw new RuntimeException(e);
}
}
public String consumeMessage(String nameAndPayload) {
try {
Session session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE);
MessageConsumer consumer = session.createConsumer(session.createQueue(nameAndPayload));
TextMessage message = (TextMessage) consumer.receive(10000);
System.err.println("message: " + message);
return message.getText();
} catch (JMSException e) {
throw new RuntimeException(e);
}
}
public void produceMessage(String nameAndPayload) {
try {
Session session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE);
session.createProducer(session.createQueue(nameAndPayload)).send(session.createTextMessage(nameAndPayload));
} catch (JMSException e) {
throw new RuntimeException(e);
}
}
public void produceAndConsume(SessionFactory sf) {
final String nameAndPayload = String.valueOf(System.currentTimeMillis());
produceMessage(nameAndPayload);
KarafShellHelper.executeCommand(sf, "activemq:bstat").trim();
AbstractFeatureTest.withinReason(new Runnable() {
public void run() {
assertEquals("JMS_BODY_FIELD:JMSText = " + nameAndPayload, KarafShellHelper.executeCommand(sf, "activemq:browse --amqurl tcp://localhost:61616 --user karaf --password karaf -Vbody " + nameAndPayload).trim());
}
});
assertEquals("got our message", nameAndPayload, consumeMessage(nameAndPayload));
}
public void tempSendReceive() throws JMSException {
Session session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE);
TemporaryQueue temporaryQueue = session.createTemporaryQueue();
session.createProducer(temporaryQueue).send(session.createTextMessage("TEST"));
Message msg = session.createConsumer(temporaryQueue).receive(3000);
assertNotNull("Didn't receive the message", msg);
}
public void close() {
try {
connection.close();
} catch (JMSException e) {
throw new RuntimeException(e);
}
}
}

View File

@ -0,0 +1,92 @@
/**
* 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.karaf.itest;
import java.io.ByteArrayOutputStream;
import java.io.PrintStream;
import java.security.PrivilegedAction;
import java.util.concurrent.Callable;
import java.util.concurrent.Executors;
import java.util.concurrent.FutureTask;
import java.util.concurrent.TimeUnit;
import javax.security.auth.Subject;
import org.apache.karaf.jaas.boot.principal.RolePrincipal;
import org.apache.karaf.jaas.boot.principal.UserPrincipal;
import org.apache.karaf.shell.api.console.Session;
import org.apache.karaf.shell.api.console.SessionFactory;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
public class KarafShellHelper {
public static final Logger LOG = LoggerFactory.getLogger(KarafShellHelper.class);
public static final String USER = "karaf";
public static final String PASSWORD = "karaf";
public static final long COMMAND_TIMEOUT = 30000L;
public static String executeCommand(SessionFactory sessionFactory, final String command, final Long timeout, final Boolean silent) {
String response;
final ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
final PrintStream printStream = new PrintStream(byteArrayOutputStream);
final Session commandSession = sessionFactory.create(System.in, printStream, printStream);
commandSession.put("APPLICATION", System.getProperty("karaf.name", "root"));
commandSession.put("USER", USER);
FutureTask<String> commandFuture = new FutureTask<String>(
new Callable<String>() {
@Override
public String call() {
Subject subject = new Subject();
subject.getPrincipals().add(new UserPrincipal("admin"));
subject.getPrincipals().add(new RolePrincipal("admin"));
subject.getPrincipals().add(new RolePrincipal("manager"));
subject.getPrincipals().add(new RolePrincipal("viewer"));
return Subject.doAs(subject, new PrivilegedAction<String>() {
@Override
public String run() {
try {
if (!silent) {
System.out.println(command);
System.out.flush();
}
commandSession.execute(command);
} catch (Exception e) {
e.printStackTrace(System.err);
}
printStream.flush();
return byteArrayOutputStream.toString();
}
});
}});
try {
Executors.newSingleThreadExecutor().submit(commandFuture);
response = commandFuture.get(timeout, TimeUnit.MILLISECONDS);
} catch (Exception e) {
e.printStackTrace(System.err);
response = "SHELL COMMAND TIMED OUT: ";
}
LOG.info("Execute: " + command + " - Response:" + response);
return response;
}
public static String executeCommand(SessionFactory sessionFactory, final String command) {
return executeCommand(sessionFactory, command, COMMAND_TIMEOUT, false);
}
}

View File

@ -68,7 +68,7 @@ public class ObrFeatureTest extends AbstractFeatureTest {
@Test(timeout = 5 * 60 * 1000)
public void testClientWithSpring32() throws Throwable {
testWithSpringVersion("3.2.14.RELEASE_1");
testWithSpringVersion("3.2.17.RELEASE_1");
}
@Test(timeout = 5 * 60 * 1000)
@ -78,12 +78,12 @@ public class ObrFeatureTest extends AbstractFeatureTest {
@Test(timeout = 5 * 60 * 1000)
public void testClientWithSpring41() throws Throwable {
testWithSpringVersion("4.1.7.RELEASE_2");
testWithSpringVersion("4.1.9.RELEASE_1");
}
@Test(timeout = 5 * 60 * 1000)
public void testClientWithSpring42() throws Throwable {
testWithSpringVersion("4.2.2.RELEASE_1");
testWithSpringVersion("4.2.8.RELEASE_1");
}
private void testWithSpringVersion(String version) throws Exception, Throwable {

View File

@ -89,7 +89,7 @@
<junit-version>4.12</junit-version>
<hamcrest-version>1.3</hamcrest-version>
<jxta-version>2.0</jxta-version>
<karaf-version>4.0.3</karaf-version>
<karaf-version>4.0.8</karaf-version>
<leveldb-api-version>0.9</leveldb-api-version>
<leveldb-version>0.9</leveldb-version>
<leveldbjni-version>1.8</leveldbjni-version>